Search in sources :

Example 11 with AccountState

use of org.aion.mcf.core.AccountState in project aion by aionnetwork.

the class AbstractRepositoryCache method getAccountState.

/**
 * Retrieves the current state of the account associated with the given
 * address.
 *
 * @param address
 *         the address of the account of interest
 * @return a {@link AccountState} object representing the account state as
 * is stored in the database or cache
 * @implNote If there is no account associated with the given address, it
 * will create it.
 */
@Override
public synchronized AccountState getAccountState(Address address) {
    // check if the account is cached locally
    AccountState accountState = this.cachedAccounts.get(address);
    // when the account is not cached load it from the repository
    if (accountState == null) {
        // note that the call below will create the account if never stored
        this.repository.loadAccountState(address, this.cachedAccounts, this.cachedDetails);
        accountState = this.cachedAccounts.get(address);
    }
    return accountState;
}
Also used : AccountState(org.aion.mcf.core.AccountState)

Example 12 with AccountState

use of org.aion.mcf.core.AccountState in project aion by aionnetwork.

the class GenesisBlockLoader method loadJSON.

/**
 * Loader function, ported from @chrislol's configuration class, will open a
 * file located at filePath. Load the JSON (not incrementally) and generate
 * a genesis object that defaults back to parameters specified in
 * {@link AionGenesis} if not specified.
 *
 * Alternatively, if the file cannot be loaded, then the default genesis
 * file is loaded
 *
 * Makes no assumptions about thread-safety.
 *
 * @param filePath
 *            filepath to the genesis JSON file
 * @return genesis file
 */
public static AionGenesis loadJSON(String filePath) {
    File genesisFile = new File(filePath);
    if (genesisFile.exists()) {
        try (InputStream is = new FileInputStream(genesisFile)) {
            String json = new String(ByteStreams.toByteArray(is));
            JSONObject mapper = new JSONObject(json);
            AionGenesis.Builder genesisBuilder = new AionGenesis.Builder();
            if (mapper.has("parentHash")) {
                genesisBuilder.withParentHash(ByteUtil.hexStringToBytes(mapper.getString("parentHash")));
            }
            if (mapper.has("coinbase")) {
                genesisBuilder.withCoinbase(Address.wrap(mapper.getString("coinbase")));
            }
            if (mapper.has("difficulty")) {
                String difficulty = mapper.getString("difficulty");
                if (difficulty.substring(0, 2).equals("0x"))
                    genesisBuilder.withDifficulty(ByteUtil.hexStringToBytes(mapper.getString("difficulty")));
                else
                    genesisBuilder.withDifficulty((new BigInteger(difficulty)).toByteArray());
            }
            if (mapper.has("timestamp")) {
                String timestamp = mapper.getString("timestamp");
                if (timestamp.substring(0, 2).equals("0x"))
                    genesisBuilder.withTimestamp((new BigInteger(1, ByteUtil.hexStringToBytes(timestamp)).longValueExact()));
                else
                    genesisBuilder.withTimestamp((new BigInteger(timestamp)).longValueExact());
            }
            if (mapper.has("extraData")) {
                String extraData = mapper.getString("extraData");
                if (extraData.substring(0, 2).equals("0x")) {
                    genesisBuilder.withExtraData(ByteUtil.hexStringToBytes(extraData));
                } else {
                    genesisBuilder.withExtraData(extraData.getBytes());
                }
            }
            if (mapper.has("energyLimit")) {
                String extraData = mapper.getString("energyLimit");
                if (extraData.substring(0, 2).equals("0x")) {
                    genesisBuilder.withEnergyLimit(new BigInteger(1, ByteUtil.hexStringToBytes(extraData)).longValueExact());
                } else {
                    genesisBuilder.withEnergyLimit(new BigInteger(extraData).longValueExact());
                }
            }
            if (mapper.has("networkBalanceAllocs")) {
                JSONObject networkBalanceAllocs = mapper.getJSONObject("networkBalanceAllocs");
                // BigInteger (decimal/string format)
                for (String key : networkBalanceAllocs.keySet()) {
                    Integer chainId = Integer.valueOf(key);
                    BigInteger value = new BigInteger(networkBalanceAllocs.getJSONObject(key).getString("balance"));
                    genesisBuilder.addNetworkBalance(chainId, value);
                }
            }
            // load premine accounts
            if (mapper.has("alloc")) {
                JSONObject accountAllocs = mapper.getJSONObject("alloc");
                for (String key : accountAllocs.keySet()) {
                    BigInteger balance = new BigInteger(accountAllocs.getJSONObject(key).getString("balance"));
                    AccountState acctState = new AccountState(BigInteger.ZERO, balance);
                    genesisBuilder.addPreminedAccount(Address.wrap(key), acctState);
                }
            }
            return genesisBuilder.build();
        } catch (IOException | JSONException e) {
            System.out.println(String.format("AION genesis format exception at %s, loading from defaults", filePath));
            AionGenesis.Builder genesisBuilder = new AionGenesis.Builder();
            return genesisBuilder.build();
        }
    } else {
        System.out.println(String.format("AION genesis not found at %s, loading from defaults", filePath));
        AionGenesis.Builder genesisBuilder = new AionGenesis.Builder();
        return genesisBuilder.build();
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JSONException(org.json.JSONException) AccountState(org.aion.mcf.core.AccountState) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) BigInteger(java.math.BigInteger) JSONObject(org.json.JSONObject) BigInteger(java.math.BigInteger) File(java.io.File)

Example 13 with AccountState

use of org.aion.mcf.core.AccountState in project aion by aionnetwork.

the class AionImpl method getAccountState.

// assumes a correctly formatted blockHash
@Override
public Optional<AccountState> getAccountState(Address address, byte[] blockHash) {
    try {
        byte[] stateRoot = this.aionHub.getBlockchain().getBlockByHash(blockHash).getStateRoot();
        AccountState account = (AccountState) this.aionHub.getRepository().getSnapshotTo(stateRoot).getAccountState(address);
        if (account == null)
            return Optional.empty();
        return Optional.of(account);
    } catch (Exception e) {
        LOG.debug("query request failed", e);
        return Optional.empty();
    }
}
Also used : AccountState(org.aion.mcf.core.AccountState)

Example 14 with AccountState

use of org.aion.mcf.core.AccountState in project aion by aionnetwork.

the class AionImpl method getAccountState.

// assumes a correctly formatted block number
@Override
public Optional<AccountState> getAccountState(Address address, long blockNumber) {
    try {
        byte[] stateRoot = this.aionHub.getBlockStore().getChainBlockByNumber(blockNumber).getStateRoot();
        AccountState account = (AccountState) this.aionHub.getRepository().getSnapshotTo(stateRoot).getAccountState(address);
        if (account == null)
            return Optional.empty();
        return Optional.of(account);
    } catch (Exception e) {
        LOG.debug("query request failed", e);
        return Optional.empty();
    }
}
Also used : AccountState(org.aion.mcf.core.AccountState)

Example 15 with AccountState

use of org.aion.mcf.core.AccountState in project aion by aionnetwork.

the class AionRepositoryDummy method updateBatch.

public void updateBatch(HashMap<ByteArrayWrapper, AccountState> stateCache, HashMap<ByteArrayWrapper, IContractDetails<DataWord>> detailsCache) {
    for (ByteArrayWrapper hash : stateCache.keySet()) {
        AccountState accountState = stateCache.get(hash);
        IContractDetails<DataWord> contractDetails = detailsCache.get(hash);
        if (accountState.isDeleted()) {
            worldState.remove(hash);
            detailsDB.remove(hash);
            logger.debug("delete: [{}]", Hex.toHexString(hash.getData()));
        } else {
            if (accountState.isDirty() || contractDetails.isDirty()) {
                detailsDB.put(hash, contractDetails);
                accountState.setStateRoot(contractDetails.getStorageHash());
                accountState.setCodeHash(h256(contractDetails.getCode()));
                worldState.put(hash, accountState);
                if (logger.isDebugEnabled()) {
                    logger.debug("update: [{}],nonce: [{}] balance: [{}] \n [{}]", Hex.toHexString(hash.getData()), accountState.getNonce(), accountState.getBalance(), contractDetails.getStorage());
                }
            }
        }
    }
    stateCache.clear();
    detailsCache.clear();
}
Also used : ByteArrayWrapper(org.aion.base.util.ByteArrayWrapper) DataWord(org.aion.mcf.vm.types.DataWord) AccountState(org.aion.mcf.core.AccountState)

Aggregations

AccountState (org.aion.mcf.core.AccountState)21 DataWord (org.aion.mcf.vm.types.DataWord)10 BigInteger (java.math.BigInteger)4 Address (org.aion.base.type.Address)4 ContractDetailsCacheImpl (org.aion.mcf.db.ContractDetailsCacheImpl)3 AionGenesis (org.aion.zero.impl.AionGenesis)2 Test (org.junit.Test)2 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Map (java.util.Map)1 IContractDetails (org.aion.base.db.IContractDetails)1 ByteArrayWrapper (org.aion.base.util.ByteArrayWrapper)1 JSONException (org.json.JSONException)1 JSONObject (org.json.JSONObject)1