org.ethereum.db.ByteArrayWrapper Java Examples

The following examples show how to use org.ethereum.db.ByteArrayWrapper. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ByteArraySet.java    From nuls with MIT License 6 votes vote down vote up
@Override
public Iterator<byte[]> iterator() {
    return new Iterator<byte[]>() {

        Iterator<ByteArrayWrapper> it = delegate.iterator();

        @Override
        public boolean hasNext() {
            return it.hasNext();
        }

        @Override
        public byte[] next() {
            return it.next().getData();
        }

        @Override
        public void remove() {
            it.remove();
        }
    };
}
 
Example #2
Source File: Cache.java    From ethereumj with MIT License 6 votes vote down vote up
public void commit() {

        if (db == null) return;

		// Don't try to commit if it isn't dirty
		if (!this.isDirty) {
			return;
		}

		for (ByteArrayWrapper key : this.nodes.keySet()) {
			Node node = this.nodes.get(key);
			if (node.isDirty()) {
				this.db.put(key.getData(), node.getValue().encode());
				node.setDirty(false);
			}
		}
		this.isDirty = false;
		
		// TODO come up with a way to clean up this.nodes 
		// from memory without breaking consensus
	}
 
Example #3
Source File: ByteArraySet.java    From nuls-v2 with MIT License 6 votes vote down vote up
@Override
public Iterator<byte[]> iterator() {
    return new Iterator<byte[]>() {

        Iterator<ByteArrayWrapper> it = delegate.iterator();

        @Override
        public boolean hasNext() {
            return it.hasNext();
        }

        @Override
        public byte[] next() {
            return it.next().getData();
        }

        @Override
        public void remove() {
            it.remove();
        }
    };
}
 
Example #4
Source File: ProgramExecutorImpl.java    From nuls-v2 with MIT License 6 votes vote down vote up
public ProgramAccount getAccount(byte[] address) {
    ByteArrayWrapper addressWrapper = new ByteArrayWrapper(address);
    ProgramAccount account = accounts.get(addressWrapper);
    if (account == null) {
        BigInteger balance;
        BigInteger freeze;
        String nonce = null;
        ContractBalance contractBalance = getBalance(address);
        if (contractBalance != null) {
            balance = contractBalance.getBalance();
            freeze = contractBalance.getFreeze();
            nonce = contractBalance.getNonce();
        } else {
            balance = BigInteger.ZERO;
            freeze = BigInteger.ZERO;
        }
        account = new ProgramAccount(address, balance, nonce);
        account.setFreeze(freeze);
        accounts.put(addressWrapper, account);
    }
    return account;
}
 
Example #5
Source File: BlockchainImpl.java    From ethereumj with MIT License 6 votes vote down vote up
@Override
public List<byte[]> getListOfHashesStartFrom(byte[] hash, int qty){

    Long startIndex = blockCache.inverseBidiMap().get(new ByteArrayWrapper( hash ));
    if (startIndex == null) return null; // strange but no such hashes in our chain
    --startIndex;

    Long endIndex = startIndex - qty;
    if (endIndex < 0) endIndex = 0L;

    Vector<byte[]> result = new Vector<>();
    for (Long i = startIndex; i >= endIndex; --i){

        ByteArrayWrapper baw = blockCache.get(i);
        result.add(baw.getData());
    }

    return result;
}
 
Example #6
Source File: BlockchainImpl.java    From ethereumj with MIT License 6 votes vote down vote up
@Override
    public void storeBlock(Block block) {

        /* Debug check to see if the state is still as expected */
        if(logger.isWarnEnabled()) {
            String blockStateRootHash = Hex.toHexString(block.getStateRoot());
            String worldStateRootHash = Hex.toHexString(WorldManager.getInstance().getRepository().getWorldState().getRootHash());
            if(!blockStateRootHash.equals(worldStateRootHash)){
            	stateLogger.warn("BLOCK: STATE CONFLICT! block: {} worldstate {} mismatch", block.getNumber(), worldStateRootHash);
//                repository.close();
//                System.exit(-1); // Don't add block
            }
        }
    	
		this.repository.saveBlock(block);
		this.blockCache.put(block.getNumber(), new ByteArrayWrapper(block.getHash()));
		this.setLastBlock(block);
		
        if (logger.isDebugEnabled())
			logger.debug("block added to the blockChain: index: [{}]", block.getNumber());
        if (block.getNumber() % 100 == 0)
        	logger.info("*** Last block added [ #{} ]", block.getNumber());
    }
 
Example #7
Source File: ProgramExecutorImpl.java    From nuls with MIT License 5 votes vote down vote up
private ProgramExecutorImpl(VMContext vmContext, Source<byte[], byte[]> source, Repository repository, byte[] prevStateRoot,
                            Map<ByteArrayWrapper, ProgramAccount> accounts, Thread thread) {
    this.parent = this;
    this.vmContext = vmContext;
    this.source = source;
    this.repository = repository;
    this.prevStateRoot = prevStateRoot;
    this.beginTime = this.currentTime = System.currentTimeMillis();
    this.accounts = accounts;
    this.thread = thread;
}
 
Example #8
Source File: TrackTrie.java    From ethereumj with MIT License 5 votes vote down vote up
@Override
public void update(byte[] key, byte[] value) {
	if (trackingChanges)
		changes.put(new ByteArrayWrapper(key), value);
	else
		trie.update(key, value);
}
 
Example #9
Source File: TrackTrie.java    From ethereumj with MIT License 5 votes vote down vote up
@Override
public byte[] get(byte[] key) {
	if (trackingChanges) {
		ByteArrayWrapper wKey = new ByteArrayWrapper(key);
		if (deletes.contains(wKey))
			return null;
		if (changes.get(wKey) != null)
			return changes.get(wKey);
		return trie.get(key);
	}
	return trie.get(key);
}
 
Example #10
Source File: ByteArraySet.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Override
public Object[] toArray() {
    byte[][] ret = new byte[size()][];

    ByteArrayWrapper[] arr = delegate.toArray(new ByteArrayWrapper[size()]);
    for (int i = 0; i < arr.length; i++) {
        ret[i] = arr[i].getData();
    }
    return ret;
}
 
Example #11
Source File: TrackTrie.java    From ethereumj with MIT License 5 votes vote down vote up
@Override
public void delete(byte[] key) {
	if (trackingChanges) {
		ByteArrayWrapper wKey = new ByteArrayWrapper(key);
		deletes.add(wKey);
	} else
		trie.delete(key);
}
 
Example #12
Source File: JSONHelper.java    From ethereumj with MIT License 5 votes vote down vote up
public static void dumpBlock(ObjectNode blockNode, Block block,
			long gasUsed, byte[] state, List<ByteArrayWrapper> keys,
			Repository repository) {
    	
    	blockNode.put("coinbase", Hex.toHexString(block.getCoinbase()));
    	blockNode.put("difficulty", new BigInteger(1, block.calcDifficulty()).toString());
    	blockNode.put("extra_data", "0x");
    	blockNode.put("gas_limit", String.valueOf(block.calcGasLimit()));
    	blockNode.put("gas_used", String.valueOf(gasUsed));
    	blockNode.put("min_gas_price", String.valueOf(block.getMinGasPrice()));
    	blockNode.put("nonce", "0x" + Hex.toHexString(block.getNonce()));
    	blockNode.put("number", String.valueOf(block.getNumber()));
    	blockNode.put("prevhash", "0x" + Hex.toHexString(block.getParentHash()));
        
        ObjectNode statesNode = blockNode.objectNode();
        for (ByteArrayWrapper key : keys) {
            byte[] keyBytes = key.getData();
            AccountState    accountState    = repository.getAccountState(keyBytes);
            ContractDetails details  = repository.getContractDetails(keyBytes);
            JSONHelper.dumpState(statesNode, Hex.toHexString(keyBytes), accountState, details);
        }       
        blockNode.put("state", statesNode);
        
        blockNode.put("state_root", Hex.toHexString(state));
        blockNode.put("timestamp", String.valueOf(block.getTimestamp()));
        
        ArrayNode transactionsNode = blockNode.arrayNode();
        blockNode.put("transactions", transactionsNode);
        
        blockNode.put("tx_list_root", ByteUtil.toHexString(block.getTxTrieRoot()));
        blockNode.put("uncles_hash", "0x" + Hex.toHexString(block.getUnclesHash()));
        
//		JSONHelper.dumpTransactions(blockNode,
//				stateRoot, codeHash, code, storage);
    }
 
Example #13
Source File: HashUtil.java    From ethereumj with MIT License 5 votes vote down vote up
public static byte[] sha3(byte[] input) {
           ByteArrayWrapper inputByteArray = new ByteArrayWrapper(input);
           byte[] result = sha3Cache.get(inputByteArray);
           if(result != null)
                   return result;
           result = SHA3Helper.sha3(input);
           sha3Cache.put(inputByteArray, result);
           return result; 
}
 
Example #14
Source File: Wallet.java    From ethereumj with MIT License 5 votes vote down vote up
public void applyTransaction(Transaction transaction) {

        transactionMap.put(new ByteArrayWrapper(transaction.getHash()), transaction);

        byte[] senderAddress = transaction.getSender();
        Account sender =  rows.get(Hex.toHexString(senderAddress));
        if (sender != null) {
            sender.addPendingTransaction(transaction);

            logger.info("Pending transaction added to " +
                            "\n account: [{}], " +
                            "\n tx: [{}]",
                    Hex.toHexString(sender.getAddress()), Hex.toHexString(transaction.getHash()));
        }

        byte[] receiveAddress = transaction.getReceiveAddress();
        if(receiveAddress != null) {
	        Account receiver =  rows.get(Hex.toHexString(receiveAddress));
	        if (receiver != null) {
	            receiver.addPendingTransaction(transaction);
	
	            logger.info("Pending transaction added to " +
	                            "\n account: [{}], " +
	                            "\n tx: [{}]",
	                    Hex.toHexString(receiver.getAddress()), Hex.toHexString(transaction.getHash()));
	        }
        }
        this.notifyListeners();
    }
 
Example #15
Source File: BlockchainImpl.java    From ethereumj with MIT License 5 votes vote down vote up
@Override
public Block getBlockByHash(byte[] hash){

    Long index = blockCache.inverseBidiMap().get(new ByteArrayWrapper(hash));
    if (index == null) return null; // don't have such hash

    return repository.getBlock(index);
}
 
Example #16
Source File: LocalJSONTestSuiteTest.java    From ethereumj with MIT License 5 votes vote down vote up
@Test // AccountState parsing  //
public void test1() throws ParseException {

    String expectedNonce  = "01";
    String expectedBalance = "0de0b6b3a763ff6c";
    String expectedCode    = "6000600060006000604a3360c85c03f1";

    ByteArrayWrapper expectedKey1 = new ByteArrayWrapper(Hex.decode("ffaa"));
    ByteArrayWrapper expectedKey2 = new ByteArrayWrapper(Hex.decode("ffab"));

    ByteArrayWrapper expectedVal1 = new ByteArrayWrapper(Hex.decode("c8"));
    ByteArrayWrapper expectedVal2 = new ByteArrayWrapper(Hex.decode("b2b2b2"));

    JSONParser parser = new JSONParser();
    String accountString = "{'balance':999999999999999852,'nonce':1," +
            "'code':'0x6000600060006000604a3360c85c03f1'," +
            "'storage':{'0xffaa' : '0xc8', '0xffab' : '0xb2b2b2'}}";
    accountString = accountString.replace("'", "\"");

    JSONObject accountJSONObj = (JSONObject)parser.parse(accountString);

    AccountState state =
            new AccountState(Hex.decode("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6"),
                    accountJSONObj);

    Assert.assertEquals(expectedNonce, Hex.toHexString(state.nonce));
    Assert.assertEquals(expectedBalance, Hex.toHexString(state.balance));
    Assert.assertEquals(expectedCode, Hex.toHexString(state.code));

    Assert.assertTrue(state.storage.keySet().contains(expectedKey1));
    Assert.assertTrue(state.storage.keySet().contains(expectedKey2));

    Assert.assertTrue(state.storage.values().contains(expectedVal1));
    Assert.assertTrue(state.storage.values().contains(expectedVal2));
}
 
Example #17
Source File: Cache.java    From ethereumj with MIT License 5 votes vote down vote up
public void undo() {
	Iterator<Map.Entry<ByteArrayWrapper, Node>> iter = this.nodes.entrySet().iterator();
	while (iter.hasNext()) {
	    if(iter.next().getValue().isDirty()) {
	        iter.remove();
	    }
	}
	this.isDirty = false;
}
 
Example #18
Source File: Utils.java    From nuls-v2 with MIT License 5 votes vote down vote up
public static List<ByteArrayWrapper> dumpKeys(DbSource<byte[]> ds) {

        ArrayList<ByteArrayWrapper> keys = new ArrayList<>();

        for (byte[] key : ds.keys()) {
            keys.add(ByteUtil.wrap(key));
        }
        Collections.sort(keys);
        return keys;
    }
 
Example #19
Source File: ReadCache.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Override
public ReadCache.BytesKey<V> withMaxCapacity(int maxCapacity) {
    withCache(new ByteArrayMap<V>(new LRUMap<ByteArrayWrapper, V>(maxCapacity) {
        @Override
        protected boolean removeLRU(LinkEntry<ByteArrayWrapper, V> entry) {
            cacheRemoved(entry.getKey().getData(), entry.getValue());
            return super.removeLRU(entry);
        }
    }));
    return this;
}
 
Example #20
Source File: ByteArraySet.java    From nuls with MIT License 5 votes vote down vote up
@Override
public Object[] toArray() {
    byte[][] ret = new byte[size()][];

    ByteArrayWrapper[] arr = delegate.toArray(new ByteArrayWrapper[size()]);
    for (int i = 0; i < arr.length; i++) {
        ret[i] = arr[i].getData();
    }
    return ret;
}
 
Example #21
Source File: Cache.java    From ethereumj with MIT License 5 votes vote down vote up
public void delete(byte[] key) {
	ByteArrayWrapper keyObj = new ByteArrayWrapper(key);
	this.nodes.remove(keyObj);

       if (db == null) return;
	this.db.delete(key);
}
 
Example #22
Source File: Cache.java    From ethereumj with MIT License 5 votes vote down vote up
public Value get(byte[] key) {
	ByteArrayWrapper keyObj = new ByteArrayWrapper(key);
	// First check if the key is the cache
	if (this.nodes.get(keyObj) != null) {
		return this.nodes.get(keyObj).getValue();
	}

	// Get the key of the database instead and cache it
	byte[] data = this.db.get(key);
	Value value = Value.fromRlpEncoded(data);
	// Create caching node
	this.nodes.put(keyObj, new Node(value, false));

	return value;
}
 
Example #23
Source File: Cache.java    From ethereumj with MIT License 5 votes vote down vote up
/**
 * Put the node in the cache if RLP encoded value is longer than 32 bytes
 * 
 * @param o the Node which could be a pair-, multi-item Node or single Value  
 * @return sha3 hash of RLP encoded node if length &gt; 32 otherwise return node itself
 */
public Object put(Object o) {
	Value value = new Value(o);
	byte[] enc = value.encode();
	if (enc.length >= 32) {
		byte[] sha = HashUtil.sha3(enc);
		this.nodes.put(new ByteArrayWrapper(sha), new Node(value, true));
		this.isDirty = true;
		return sha;
	}
	return value;
}
 
Example #24
Source File: TrieImpl.java    From ethereumj with MIT License 5 votes vote down vote up
public TrieImpl copy() {
    TrieImpl trie = new TrieImpl(this.cache.getDb(), this.root);
    for (ByteArrayWrapper key : this.cache.getNodes().keySet()) {
        Node node = this.cache.getNodes().get(key);
        trie.cache.getNodes().put(key, node.copy());
    }
    return trie;
}
 
Example #25
Source File: ProgramExecutorImpl.java    From nuls-v2 with MIT License 5 votes vote down vote up
private ProgramExecutorImpl(ProgramExecutorImpl programExecutor, VMContext vmContext, Source<byte[], byte[]> source, Repository repository, byte[] prevStateRoot,
                            Map<ByteArrayWrapper, ProgramAccount> accounts, Thread thread) {
    this.parent = programExecutor;
    this.vmContext = vmContext;
    this.source = source;
    this.repository = repository;
    this.prevStateRoot = prevStateRoot;
    this.beginTime = this.currentTime = System.currentTimeMillis();
    this.accounts = accounts;
    this.thread = thread;
}
 
Example #26
Source File: Utils.java    From nuls with MIT License 5 votes vote down vote up
public static List<ByteArrayWrapper> dumpKeys(DbSource<byte[]> ds) {

        ArrayList<ByteArrayWrapper> keys = new ArrayList<>();

        for (byte[] key : ds.keys()) {
            keys.add(ByteUtil.wrap(key));
        }
        Collections.sort(keys);
        return keys;
    }
 
Example #27
Source File: ReadCache.java    From nuls with MIT License 5 votes vote down vote up
@Override
public ReadCache.BytesKey<V> withMaxCapacity(int maxCapacity) {
    withCache(new ByteArrayMap<V>(new LRUMap<ByteArrayWrapper, V>(maxCapacity) {
        @Override
        protected boolean removeLRU(LinkEntry<ByteArrayWrapper, V> entry) {
            cacheRemoved(entry.getKey().getData(), entry.getValue());
            return super.removeLRU(entry);
        }
    }));
    return this;
}
 
Example #28
Source File: ProgramExecutorImpl.java    From nuls with MIT License 5 votes vote down vote up
public ProgramAccount getAccount(byte[] address) {
    ByteArrayWrapper addressWrapper = new ByteArrayWrapper(address);
    ProgramAccount account = accounts.get(addressWrapper);
    if (account == null) {
        BigInteger balance = getBalance(address, blockNumber);
        account = new ProgramAccount(address, balance);
        accounts.put(addressWrapper, account);
    }
    return account;
}
 
Example #29
Source File: MockDB.java    From ethereumj with MIT License 4 votes vote down vote up
@Override
public byte[] get(byte[] arg0) throws DBException {

    return storage.get(new ByteArrayWrapper(arg0));
}
 
Example #30
Source File: ByteArraySet.java    From nuls with MIT License 4 votes vote down vote up
@Override
public boolean contains(Object o) {
    return delegate.contains(new ByteArrayWrapper((byte[]) o));
}