org.ethereum.core.AccountState Java Examples

The following examples show how to use org.ethereum.core.AccountState. 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: AccountsListWindow.java    From ethereumj with MIT License 6 votes vote down vote up
private void loadAccounts() {
	new Thread(){
		
		@Override
		public void run(){
			DBIterator i = WorldManager.getInstance().getRepository().getAccountsIterator();
			while(i.hasNext()) {
				DataClass dc = new DataClass();
				dc.address = i.next().getKey();
				
				AccountState state = WorldManager.getInstance().getRepository().getAccountState(dc.address);
				dc.accountState = state;
				
				adapter.addDataPiece(dc);
			}
		}
	}.start();
}
 
Example #2
Source File: ProgramExecutorImpl.java    From nuls-v2 with MIT License 6 votes vote down vote up
@Override
public ProgramResult stop(long blockNumber, byte[] address, byte[] sender) {
    checkThread();
    AccountState accountState = repository.getAccountState(address);
    if (accountState == null) {
        return revert("can't find contract");
    }
    if (!FastByteComparisons.equal(sender, accountState.getOwner())) {
        return revert("only the owner can stop the contract");
    }
    BigInteger balance = getTotalBalance(address, null);
    if (BigInteger.ZERO.compareTo(balance) != 0) {
        return revert("contract balance is not zero");
    }
    if (BigInteger.ZERO.compareTo(accountState.getNonce()) >= 0) {
        return revert("contract has stopped");
    }

    this.blockNumber = blockNumber;
    repository.setNonce(address, BigInteger.ZERO);

    ProgramResult programResult = new ProgramResult();

    return programResult;
}
 
Example #3
Source File: ProgramExecutorImpl.java    From nuls-v2 with MIT License 6 votes vote down vote up
@Override
public ProgramStatus status(byte[] address) {
    checkThread();
    this.revert = true;
    AccountState accountState = repository.getAccountState(address);
    if (accountState == null) {
        return ProgramStatus.not_found;
    } else {
        BigInteger nonce = repository.getNonce(address);
        if (BigInteger.ZERO.compareTo(nonce) >= 0) {
            return ProgramStatus.stop;
        } else {
            return ProgramStatus.normal;
        }
    }
}
 
Example #4
Source File: RepositoryImpl.java    From nuls with MIT License 6 votes vote down vote up
@Override
public synchronized RepositoryImpl startTracking() {
    Source<byte[], AccountState> trackAccountStateCache = new WriteCache.BytesKey<>(accountStateCache,
            WriteCache.CacheType.SIMPLE);
    Source<byte[], byte[]> trackCodeCache = new WriteCache.BytesKey<>(codeCache, WriteCache.CacheType.SIMPLE);
    MultiCache<CachedSource<DataWord, DataWord>> trackStorageCache = new MultiCache(storageCache) {
        @Override
        protected CachedSource create(byte[] key, CachedSource srcCache) {
            return new WriteCache<>(srcCache, WriteCache.CacheType.SIMPLE);
        }
    };

    RepositoryImpl ret = new RepositoryImpl(trackAccountStateCache, trackCodeCache, trackStorageCache);
    ret.parent = this;
    return ret;
}
 
Example #5
Source File: RepositoryRoot.java    From nuls-v2 with MIT License 6 votes vote down vote up
/**
 * Building the following structure for snapshot Repository:
 * <p>
 * stateDS --> trieCache --> stateTrie --> accountStateCodec --> accountStateCache
 * \                 \
 * \                 \-->>> storageKeyCompositor --> contractStorageTrie --> storageCodec --> storageCache
 * \--> codeCache
 *
 * @param stateDS
 * @param root
 */
public RepositoryRoot(final Source<byte[], byte[]> stateDS, byte[] root) {
    this.stateDS = stateDS;

    trieCache = new WriteCache.BytesKey<>(stateDS, WriteCache.CacheType.COUNTING);
    stateTrie = new SecureTrie(trieCache, root);

    SourceCodec.BytesKey<AccountState, byte[]> accountStateCodec = new SourceCodec.BytesKey<>(stateTrie, Serializers.AccountStateSerializer);
    final ReadWriteCache.BytesKey<AccountState> accountStateCache = new ReadWriteCache.BytesKey<>(accountStateCodec, WriteCache.CacheType.SIMPLE);

    final MultiCache<StorageCache> storageCache = new MultiStorageCache();

    // counting as there can be 2 contracts with the same code, 1 can suicide
    Source<byte[], byte[]> codeCache = new WriteCache.BytesKey<>(stateDS, WriteCache.CacheType.COUNTING);

    init(accountStateCache, codeCache, storageCache);
}
 
Example #6
Source File: RepositoryRoot.java    From nuls-v2 with MIT License 6 votes vote down vote up
@Override
protected synchronized boolean flushChild(byte[] key, StorageCache childCache) {
    if (super.flushChild(key, childCache)) {
        if (childCache != null) {
            AccountState storageOwnerAcct = accountStateCache.get(key);
            // need to update account storage root
            childCache.trie.flush();
            byte[] rootHash = childCache.trie.getRootHash();
            accountStateCache.put(key, storageOwnerAcct.withStateRoot(rootHash));
            return true;
        } else {
            // account was deleted
            return true;
        }
    } else {
        // no storage changes
        return false;
    }
}
 
Example #7
Source File: RepositoryRoot.java    From nuls with MIT License 6 votes vote down vote up
@Override
protected synchronized boolean flushChild(byte[] key, StorageCache childCache) {
    if (super.flushChild(key, childCache)) {
        if (childCache != null) {
            AccountState storageOwnerAcct = accountStateCache.get(key);
            // need to update account storage root
            childCache.trie.flush();
            byte[] rootHash = childCache.trie.getRootHash();
            accountStateCache.put(key, storageOwnerAcct.withStateRoot(rootHash));
            return true;
        } else {
            // account was deleted
            return true;
        }
    } else {
        // no storage changes
        return false;
    }
}
 
Example #8
Source File: RepositoryImpl.java    From nuls-v2 with MIT License 6 votes vote down vote up
@Override
public synchronized RepositoryImpl startTracking() {
    Source<byte[], AccountState> trackAccountStateCache = new WriteCache.BytesKey<>(accountStateCache,
            WriteCache.CacheType.SIMPLE);
    Source<byte[], byte[]> trackCodeCache = new WriteCache.BytesKey<>(codeCache, WriteCache.CacheType.SIMPLE);
    MultiCache<CachedSource<DataWord, DataWord>> trackStorageCache = new MultiCache(storageCache) {
        @Override
        protected CachedSource create(byte[] key, CachedSource srcCache) {
            return new WriteCache<>(srcCache, WriteCache.CacheType.SIMPLE);
        }
    };

    RepositoryImpl ret = new RepositoryImpl(trackAccountStateCache, trackCodeCache, trackStorageCache);
    ret.parent = this;
    return ret;
}
 
Example #9
Source File: RepositoryRoot.java    From nuls with MIT License 6 votes vote down vote up
/**
 * Building the following structure for snapshot Repository:
 * <p>
 * stateDS --> trieCache --> stateTrie --> accountStateCodec --> accountStateCache
 * \                 \
 * \                 \-->>> storageKeyCompositor --> contractStorageTrie --> storageCodec --> storageCache
 * \--> codeCache
 *
 * @param stateDS
 * @param root
 */
public RepositoryRoot(final Source<byte[], byte[]> stateDS, byte[] root) {
    this.stateDS = stateDS;

    trieCache = new WriteCache.BytesKey<>(stateDS, WriteCache.CacheType.COUNTING);
    stateTrie = new SecureTrie(trieCache, root);

    SourceCodec.BytesKey<AccountState, byte[]> accountStateCodec = new SourceCodec.BytesKey<>(stateTrie, Serializers.AccountStateSerializer);
    final ReadWriteCache.BytesKey<AccountState> accountStateCache = new ReadWriteCache.BytesKey<>(accountStateCodec, WriteCache.CacheType.SIMPLE);

    final MultiCache<StorageCache> storageCache = new MultiStorageCache();

    // counting as there can be 2 contracts with the same code, 1 can suicide
    Source<byte[], byte[]> codeCache = new WriteCache.BytesKey<>(stateDS, WriteCache.CacheType.COUNTING);

    init(accountStateCache, codeCache, storageCache);
}
 
Example #10
Source File: ProgramExecutorImpl.java    From nuls with MIT License 6 votes vote down vote up
@Override
public ProgramResult stop(byte[] address, byte[] sender) {
    checkThread();
    AccountState accountState = repository.getAccountState(address);
    if (accountState == null) {
        return revert("can't find contract");
    }
    if (!FastByteComparisons.equal(sender, accountState.getOwner())) {
        return revert("only the owner can stop the contract");
    }
    BigInteger balance = getTotalBalance(address, null);
    if (BigInteger.ZERO.compareTo(balance) != 0) {
        return revert("contract balance is not zero");
    }
    if (BigInteger.ZERO.compareTo(accountState.getNonce()) >= 0) {
        return revert("contract has stopped");
    }

    repository.setNonce(address, BigInteger.ZERO);

    ProgramResult programResult = new ProgramResult();

    return programResult;
}
 
Example #11
Source File: ProgramExecutorImpl.java    From nuls with MIT License 6 votes vote down vote up
@Override
public ProgramStatus status(byte[] address) {
    checkThread();
    this.revert = true;
    AccountState accountState = repository.getAccountState(address);
    if (accountState == null) {
        return ProgramStatus.not_found;
    } else {
        BigInteger nonce = repository.getNonce(address);
        if (BigInteger.ZERO.compareTo(nonce) >= 0) {
            return ProgramStatus.stop;
        } else {
            return ProgramStatus.normal;
        }
    }
}
 
Example #12
Source File: JSONHelper.java    From ethereumj with MIT License 6 votes vote down vote up
public static void dumpState(ObjectNode statesNode, String address, AccountState state, ContractDetails details) {  	

        List<DataWord> storageKeys = new ArrayList<>(details.getStorage().keySet());
		Collections.sort((List<DataWord>) storageKeys);

        ObjectNode account = statesNode.objectNode();
        ObjectNode storage = statesNode.objectNode();
                
        for (DataWord key : storageKeys) {
        	storage.put("0x" + Hex.toHexString(key.getData()),
					"0x" + Hex.toHexString(details.getStorage().get(key).getNoLeadZeroesData()));
        }
        account.put("balance", state.getBalance() == null ? "0" : state.getBalance().toString());
//        account.put("codeHash", details.getCodeHash() == null ? "0x" : "0x" + Hex.toHexString(details.getCodeHash()));
        account.put("code", details.getCode() == null ? "0x" : "0x" + Hex.toHexString(details.getCode()));
        account.put("nonce", state.getNonce() == null ? "0" : state.getNonce().toString());
        account.put("storage", storage);
        account.put("storage_root", state.getStateRoot() == null ? "" : Hex.toHexString(state.getStateRoot()));
        
        statesNode.put(address, account);
    }
 
Example #13
Source File: RepositoryImpl.java    From ethereumj with MIT License 6 votes vote down vote up
public AccountState createAccount(byte[] addr) {

        logger.trace("createAccount: [{}]", Hex.toHexString(addr)) ;
    	this.validateAddress(addr);
    	    	
        // 1. Save AccountState
        AccountState state =  new AccountState();
        accountStateDB.update(addr, state.getEncoded());
        
        ContractDetails details = new ContractDetails();
        contractDetailsDB.put(addr, details.getEncoded());
        
        if (logger.isDebugEnabled())
            logger.debug("New account created: [{}]", Hex.toHexString(addr));

        return state;
    }
 
Example #14
Source File: RepositoryImpl.java    From ethereumj with MIT License 6 votes vote down vote up
public void addStorageRow(byte[] addr, DataWord key, DataWord value) {

        if (key == null) return;
        AccountState      state = getAccountState(addr);
        ContractDetails   details = getContractDetails(addr);

        if (state == null || details == null) return;
        details.put(key, value);

        byte[] storageHash = details.getStorageHash();
        state.setStateRoot(storageHash);

        if (logger.isDebugEnabled())
            logger.debug("Storage key/value saved:\n account:\t [{}]\n key:\t\t [{}]\n value:\t\t [{}]\n new hash:\t [{}]",
                    Hex.toHexString(addr),
                    Hex.toHexString(key.getNoLeadZeroesData()),
                    Hex.toHexString(value.getNoLeadZeroesData()),
                    Hex.toHexString(storageHash));

        accountStateDB.update(addr, state.getEncoded());
        contractDetailsDB.put(addr, details.getEncoded());
    }
 
Example #15
Source File: RepositoryImpl.java    From ethereumj with MIT License 6 votes vote down vote up
public void saveCode(byte[] addr, byte[] code) {
	
	if (code == null) return;
    AccountState state = getAccountState(addr);
    if (state == null) return;
    
    if (logger.isDebugEnabled())
        logger.debug("Saving code: \n address:\t [{}], \n code:\t\t [{}]",
                Hex.toHexString(addr),
                Hex.toHexString(code));

    ContractDetails details = getContractDetails(addr);
    details.setCode(code);

    byte[] codeHash = HashUtil.sha3(code);
    state.setCodeHash(codeHash);

    accountStateDB.update(addr, state.getEncoded());
    contractDetailsDB.put(addr, details.getEncoded());
    
    if (logger.isDebugEnabled())
        logger.debug("Code saved: \n accountstate:\t [{}]\n codeHash:\t [{}]\n details RLP:\t [{}]",
                Hex.toHexString(state.getEncoded()),
                Hex.toHexString(codeHash),
                Hex.toHexString(details.getEncoded()));
}
 
Example #16
Source File: RepositoryTest.java    From ethereumj with MIT License 6 votes vote down vote up
@Test  // get/set code
public void test7() {

    String addr = "cd2a3d9f938e13cd947ec05abc7fe734df8dd826";
    String codeString = "7f60c860005461012c602054000000000000000000000000000000000000000000600060206000f200";
    String codeHash = "8f0d7fc8cc6fdd688fa58ae9256310069f5659ed2a8a3af994d80350fbf1e798";

    Repository repository = new RepositoryImpl();

    try {
        byte[] code0 = repository.getCode(Hex.decode(addr));
        repository.createAccount(Hex.decode(addr));
        repository.saveCode(Hex.decode(addr), Hex.decode(codeString));
        byte[] code1 = repository.getCode(Hex.decode(addr));
        AccountState accountState = repository.getAccountState(Hex.decode(addr));

        assertTrue(code0 == null);
        assertEquals(codeString, Hex.toHexString(code1));
        assertEquals(codeHash, Hex.toHexString(accountState.getCodeHash()));
    } finally {
        repository.close();
    }
}
 
Example #17
Source File: RepositoryTest.java    From ethereumj with MIT License 6 votes vote down vote up
@Test  // get/set code
public void test8() {

    byte[] addr = Hex.decode("cd2a3d9f938e13cd947ec05abc7fe734df8dd826");
    Repository repository = new RepositoryImpl();

    try {
        byte[] code0 = repository.getCode(addr);
        repository.createAccount(addr);
        byte[] code1 = repository.getCode(addr);
        AccountState accountState = repository.getAccountState(addr);
        assertTrue(code0 == null);
        assertNull(code1);
        assertNull(accountState.getCodeHash());
    } finally {
        repository.close();
    }
}
 
Example #18
Source File: StateExplorerWindow.java    From ethereumj with MIT License 6 votes vote down vote up
private String accountDetailsString(byte[] account, StateDataTableModel dataModel){	
	String ret = "";
	// 1) print account address
	ret = "Account: " + Hex.toHexString(account) + "\n";
	
	//2) print state 
	AccountState state = WorldManager.getInstance().getRepository().getAccountState(account);
	if(state != null)
		ret += state.toString() + "\n";
	
	//3) print storage
	ContractDetails contractDetails = WorldManager.getInstance().getRepository().getContractDetails(account);
	if(contractDetails != null) {
		Map<DataWord, DataWord> accountStorage = contractDetails.getStorage();
		dataModel.setData(accountStorage);
	}
	
	//4) code print
	byte[] code = WorldManager.getInstance().getRepository().getCode(account);
	if(code != null) {
		ret += "\n\nCode:\n";
		ret += Program.stringify(code, 0, "");
	}
	
	return ret;
}
 
Example #19
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 #20
Source File: RepositoryImpl.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Override
public synchronized AccountState createAccount(byte[] addr, byte[] creater) {
    AccountState state = new AccountState(config.getBlockchainConfig().getCommonConstants().getInitialNonce(),
            BigInteger.ZERO, creater);
    accountStateCache.put(addr, state);
    return state;
}
 
Example #21
Source File: RepositoryRoot.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Override
protected synchronized StorageCache create(byte[] key, StorageCache srcCache) {
    AccountState accountState = accountStateCache.get(key);
    Serializer<byte[], byte[]> keyCompositor = new NodeKeyCompositor(key);
    Source<byte[], byte[]> composingSrc = new SourceCodec.KeyOnly<>(trieCache, keyCompositor);
    TrieImpl storageTrie = createTrie(composingSrc, accountState == null ? null : accountState.getStateRoot());
    return new StorageCache(storageTrie);
}
 
Example #22
Source File: RepositoryImpl.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Override
public synchronized void saveCode(byte[] addr, byte[] code) {
    byte[] codeHash = HashUtil.sha3(code);
    codeCache.put(codeKey(codeHash, addr), code);
    AccountState accountState = getOrCreateAccountState(addr);
    accountStateCache.put(addr, accountState.withCodeHash(codeHash));
}
 
Example #23
Source File: RepositoryImpl.java    From nuls-v2 with MIT License 5 votes vote down vote up
synchronized AccountState getOrCreateAccountState(byte[] addr) {
    AccountState ret = accountStateCache.get(addr);
    if (ret == null) {
        ret = createAccount(addr, HashUtil.EMPTY_DATA_HASH);
    }
    return ret;
}
 
Example #24
Source File: RepositoryImpl.java    From nuls with MIT License 5 votes vote down vote up
@Override
public synchronized void saveCode(byte[] addr, byte[] code) {
    byte[] codeHash = HashUtil.sha3(code);
    codeCache.put(codeKey(codeHash, addr), code);
    AccountState accountState = getOrCreateAccountState(addr);
    accountStateCache.put(addr, accountState.withCodeHash(codeHash));
}
 
Example #25
Source File: RepositoryImpl.java    From nuls with MIT License 5 votes vote down vote up
@Override
public synchronized AccountState createAccount(byte[] addr, byte[] creater) {
    AccountState state = new AccountState(config.getBlockchainConfig().getCommonConstants().getInitialNonce(),
            BigInteger.ZERO, creater);
    accountStateCache.put(addr, state);
    return state;
}
 
Example #26
Source File: RepositoryImpl.java    From nuls with MIT License 5 votes vote down vote up
synchronized AccountState getOrCreateAccountState(byte[] addr) {
    AccountState ret = accountStateCache.get(addr);
    if (ret == null) {
        ret = createAccount(addr, HashUtil.EMPTY_DATA_HASH);
    }
    return ret;
}
 
Example #27
Source File: RepositoryTest.java    From ethereumj with MIT License 5 votes vote down vote up
@Test // create account, get account
public void test1() {

	String addr = "cd2a3d9f938e13cd947ec05abc7fe734df8dd826";
	Repository repository = new RepositoryImpl();

	try {
		AccountState createdState = repository.createAccount(Hex.decode(addr));
		AccountState fetchedState = repository.getAccountState(Hex.decode(addr));
		assertEquals(createdState.getEncoded(), fetchedState.getEncoded());
	} finally {
		repository.close();
	}
}
 
Example #28
Source File: RepositoryRoot.java    From nuls with MIT License 5 votes vote down vote up
@Override
protected synchronized StorageCache create(byte[] key, StorageCache srcCache) {
    AccountState accountState = accountStateCache.get(key);
    Serializer<byte[], byte[]> keyCompositor = new NodeKeyCompositor(key);
    Source<byte[], byte[]> composingSrc = new SourceCodec.KeyOnly<>(trieCache, keyCompositor);
    TrieImpl storageTrie = createTrie(composingSrc, accountState == null ? null : accountState.getStateRoot());
    return new StorageCache(storageTrie);
}
 
Example #29
Source File: RepositoryImpl.java    From ethereumj with MIT License 5 votes vote down vote up
public BigInteger increaseNonce(byte[] addr) {
    AccountState state = getAccountState(addr);
    if (state == null) return BigInteger.ZERO;
    state.incrementNonce();

    if (logger.isDebugEnabled())
        logger.debug("Increment nonce:\n account:\t [{}]\n new nonce:\t [{}]",
                Hex.toHexString(addr), state.getNonce().longValue());

    accountStateDB.update(addr, state.getEncoded());
    return state.getNonce();
}
 
Example #30
Source File: RepositoryImpl.java    From ethereumj with MIT License 4 votes vote down vote up
public BigInteger addBalance(byte[] addr, BigInteger value) {
   	
	AccountState state = getAccountState(addr);

       if (state == null)
           state = createAccount(addr);
       
	BigInteger newBalance = state.addToBalance(value);

	if (logger.isDebugEnabled())
		logger.debug("Changing balance: \n account:\t [{}]\n new balance:\t [{}]\n delta:\t\t [{}]",
				Hex.toHexString(addr), newBalance.toString(), value);

	accountStateDB.update(addr, state.getEncoded());
	return newBalance;
}