Search in sources :

Example 36 with AccountCapsule

use of org.tron.core.capsule.AccountCapsule in project java-tron by tronprotocol.

the class Manager method initAccount.

/**
 * save account into database.
 */
public void initAccount() {
    final Args args = Args.getInstance();
    final GenesisBlock genesisBlockArg = args.getGenesisBlock();
    genesisBlockArg.getAssets().forEach(account -> {
        // to be set in conf
        account.setAccountType("Normal");
        final AccountCapsule accountCapsule = new AccountCapsule(account.getAccountName(), ByteString.copyFrom(account.getAddressBytes()), account.getAccountType(), account.getBalance());
        this.accountStore.put(account.getAddressBytes(), accountCapsule);
    });
}
Also used : GenesisBlock(org.tron.core.config.args.GenesisBlock) AccountCapsule(org.tron.core.capsule.AccountCapsule) Args(org.tron.core.config.args.Args)

Example 37 with AccountCapsule

use of org.tron.core.capsule.AccountCapsule in project java-tron by tronprotocol.

the class Manager method updateWitness.

/**
 * update witness.
 */
public void updateWitness() {
    List<WitnessCapsule> currentWits = getWitnesses();
    final Map<ByteString, Long> countWitness = Maps.newHashMap();
    final List<AccountCapsule> accountList = this.accountStore.getAllAccounts();
    // logger.info("there is account List size is {}", accountList.size());
    accountList.forEach(account -> {
        // logger.info("there is account ,account address is {}",
        // account.createReadableString());
        Optional<Long> sum = account.getVotesList().stream().map(vote -> vote.getVoteCount()).reduce((a, b) -> a + b);
        if (sum.isPresent()) {
            if (sum.get() <= account.getShare()) {
                account.getVotesList().forEach(vote -> {
                    // TODO validate witness //active_witness
                    ByteString voteAddress = vote.getVoteAddress();
                    long voteCount = vote.getVoteCount();
                    if (countWitness.containsKey(voteAddress)) {
                        countWitness.put(voteAddress, countWitness.get(voteAddress) + voteCount);
                    } else {
                        countWitness.put(voteAddress, voteCount);
                    }
                });
            } else {
                logger.info("account" + account.createReadableString() + ",share[" + account.getShare() + "] > voteSum[" + sum.get() + "]");
            }
        }
    });
    witnessStore.getAllWitnesses().forEach(witnessCapsule -> {
        witnessCapsule.setVoteCount(0);
        witnessCapsule.setIsJobs(false);
        this.witnessStore.put(witnessCapsule.createDbKey(), witnessCapsule);
    });
    final List<WitnessCapsule> witnessCapsuleList = Lists.newArrayList();
    logger.info("countWitnessMap size is {}", countWitness.keySet().size());
    // Only possible during the initialization phase
    if (countWitness.size() == 0) {
        witnessCapsuleList.addAll(this.witnessStore.getAllWitnesses());
    }
    countWitness.forEach((address, voteCount) -> {
        final WitnessCapsule witnessCapsule = this.witnessStore.get(createDbKey(address));
        if (null == witnessCapsule) {
            logger.warn("witnessCapsule is null.address is {}", createReadableString(address));
            return;
        }
        ByteString witnessAddress = witnessCapsule.getInstance().getAddress();
        AccountCapsule witnessAccountCapsule = accountStore.get(createDbKey(witnessAddress));
        if (witnessAccountCapsule == null) {
            logger.warn("witnessAccount[" + createReadableString(witnessAddress) + "] not exists");
        } else {
            if (witnessAccountCapsule.getBalance() < WitnessCapsule.MIN_BALANCE) {
                logger.warn("witnessAccount[" + createReadableString(witnessAddress) + "] has balance[" + witnessAccountCapsule.getBalance() + "] < MIN_BALANCE[" + WitnessCapsule.MIN_BALANCE + "]");
            } else {
                witnessCapsule.setVoteCount(witnessCapsule.getVoteCount() + voteCount);
                witnessCapsule.setIsJobs(false);
                witnessCapsuleList.add(witnessCapsule);
                this.witnessStore.put(witnessCapsule.createDbKey(), witnessCapsule);
                logger.info("address is {}  ,countVote is {}", witnessCapsule.createReadableString(), witnessCapsule.getVoteCount());
            }
        }
    });
    sortWitness(witnessCapsuleList);
    if (witnessCapsuleList.size() > MAX_ACTIVE_WITNESS_NUM) {
        setWitnesses(witnessCapsuleList.subList(0, MAX_ACTIVE_WITNESS_NUM));
    } else {
        setWitnesses(witnessCapsuleList);
    }
    getWitnesses().forEach(witnessCapsule -> {
        witnessCapsule.setIsJobs(true);
        this.witnessStore.put(witnessCapsule.createDbKey(), witnessCapsule);
    });
    logger.info("updateWitness,before:{} ", getWitnessStringList(currentWits) + ",\nafter:{} " + getWitnessStringList(getWitnesses()));
}
Also used : AccountCapsule(org.tron.core.capsule.AccountCapsule) GenesisBlock(org.tron.core.config.args.GenesisBlock) SOLIDIFIED_THRESHOLD(org.tron.core.config.Parameter.ChainConstant.SOLIDIFIED_THRESHOLD) WitnessCapsule(org.tron.core.capsule.WitnessCapsule) BalanceInsufficientException(org.tron.core.exception.BalanceInsufficientException) Autowired(org.springframework.beans.factory.annotation.Autowired) AccountType(org.tron.protos.Protocol.AccountType) HighFreqException(org.tron.core.exception.HighFreqException) BlockCapsule(org.tron.core.capsule.BlockCapsule) ContractExeException(org.tron.core.exception.ContractExeException) BlockId(org.tron.core.capsule.BlockCapsule.BlockId) Args(org.tron.core.config.args.Args) RamUsageEstimator(com.carrotsearch.sizeof.RamUsageEstimator) Map(java.util.Map) TransactionResultCapsule(org.tron.core.capsule.TransactionResultCapsule) AccountCapsule(org.tron.core.capsule.AccountCapsule) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) Transaction(org.tron.protos.Protocol.Transaction) Pair(javafx.util.Pair) ECKey(org.tron.common.crypto.ECKey) Set(java.util.Set) WITNESS_PAY_PER_BLOCK(org.tron.core.config.Parameter.ChainConstant.WITNESS_PAY_PER_BLOCK) Collectors(java.util.stream.Collectors) ByteString(com.google.protobuf.ByteString) TransactionCapsule(org.tron.core.capsule.TransactionCapsule) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) ValidateSignatureException(org.tron.core.exception.ValidateSignatureException) LevelDbDataSourceImpl(org.tron.common.storage.leveldb.LevelDbDataSourceImpl) TransferContract(org.tron.protos.Protocol.Transaction.Contract.ContractType.TransferContract) Actuator(org.tron.core.actuator.Actuator) Optional(java.util.Optional) DialogOptional(org.tron.common.utils.DialogOptional) RandomGenerator(org.tron.common.utils.RandomGenerator) Setter(lombok.Setter) ContractValidateException(org.tron.core.exception.ContractValidateException) Getter(lombok.Getter) ActuatorFactory(org.tron.core.actuator.ActuatorFactory) ArrayUtils(org.apache.commons.lang3.ArrayUtils) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) CollectionUtils(org.apache.commons.collections4.CollectionUtils) ArrayList(java.util.ArrayList) Lists(com.google.common.collect.Lists) ByteArray(org.tron.common.utils.ByteArray) RevokingStoreIllegalStateException(org.tron.core.exception.RevokingStoreIllegalStateException) LinkedList(java.util.LinkedList) Sha256Hash(org.tron.common.utils.Sha256Hash) TransferAssetContract(org.tron.protos.Protocol.Transaction.Contract.ContractType.TransferAssetContract) Iterator(java.util.Iterator) DateTime(org.joda.time.DateTime) Dialog(org.tron.core.db.AbstractRevokingStore.Dialog) Maps(com.google.common.collect.Maps) Lock(java.util.concurrent.locks.Lock) Component(org.springframework.stereotype.Component) BlockUtil(org.tron.core.capsule.utils.BlockUtil) Time(org.tron.common.utils.Time) Collections(java.util.Collections) UnLinkedBlockException(org.tron.core.exception.UnLinkedBlockException) Node(org.tron.common.overlay.discover.Node) WitnessCapsule(org.tron.core.capsule.WitnessCapsule) ByteString(com.google.protobuf.ByteString)

Example 38 with AccountCapsule

use of org.tron.core.capsule.AccountCapsule in project java-tron by tronprotocol.

the class Manager method adjustBalance.

/**
 * judge balance.
 */
public void adjustBalance(byte[] accountAddress, long amount) throws BalanceInsufficientException {
    AccountCapsule account = getAccountStore().get(accountAddress);
    long balance = account.getBalance();
    if (amount == 0) {
        return;
    }
    if (amount < 0 && balance < -amount) {
        throw new BalanceInsufficientException(accountAddress + " Insufficient");
    }
    account.setBalance(balance + amount);
    this.getAccountStore().put(account.getAddress().toByteArray(), account);
}
Also used : AccountCapsule(org.tron.core.capsule.AccountCapsule) BalanceInsufficientException(org.tron.core.exception.BalanceInsufficientException)

Example 39 with AccountCapsule

use of org.tron.core.capsule.AccountCapsule in project java-tron by tronprotocol.

the class WitnessCreateActuator method validate.

@Override
public boolean validate() throws ContractValidateException {
    try {
        if (!this.contract.is(WitnessCreateContract.class)) {
            throw new ContractValidateException("contract type error,expected type [AccountCreateContract],real type[" + this.contract.getClass() + "]");
        }
        final WitnessCreateContract contract = this.contract.unpack(WitnessCreateContract.class);
        Preconditions.checkNotNull(contract.getOwnerAddress(), "OwnerAddress is null");
        Preconditions.checkArgument(this.dbManager.getAccountStore().has(contract.getOwnerAddress().toByteArray()), "account not exists");
        AccountCapsule accountCapsule = this.dbManager.getAccountStore().get(contract.getOwnerAddress().toByteArray());
        Preconditions.checkArgument(accountCapsule.getShare() >= WitnessCapsule.MIN_BALANCE, "witnessAccount  has balance[" + accountCapsule.getShare() + "] < MIN_BALANCE[" + WitnessCapsule.MIN_BALANCE + "]");
        Preconditions.checkArgument(!this.dbManager.getWitnessStore().has(contract.getOwnerAddress().toByteArray()), "Witness has existed");
    } catch (final Exception ex) {
        ex.printStackTrace();
        throw new ContractValidateException(ex.getMessage());
    }
    return true;
}
Also used : AccountCapsule(org.tron.core.capsule.AccountCapsule) WitnessCreateContract(org.tron.protos.Contract.WitnessCreateContract) ContractValidateException(org.tron.core.exception.ContractValidateException) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) ContractValidateException(org.tron.core.exception.ContractValidateException) ContractExeException(org.tron.core.exception.ContractExeException)

Example 40 with AccountCapsule

use of org.tron.core.capsule.AccountCapsule in project java-tron by tronprotocol.

the class CreateAccountActuator method execute.

@Override
public boolean execute(TransactionResultCapsule ret) throws ContractExeException {
    long fee = calcFee();
    try {
        AccountCreateContract accountCreateContract = contract.unpack(AccountCreateContract.class);
        AccountCapsule accountCapsule = new AccountCapsule(accountCreateContract);
        dbManager.getAccountStore().put(accountCreateContract.getOwnerAddress().toByteArray(), accountCapsule);
        ret.setStatus(fee, code.SUCESS);
        return true;
    } catch (InvalidProtocolBufferException e) {
        ret.setStatus(fee, code.FAILED);
        logger.debug(e.getMessage(), e);
        throw new ContractExeException(e.getMessage());
    }
}
Also used : AccountCapsule(org.tron.core.capsule.AccountCapsule) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) AccountCreateContract(org.tron.protos.Contract.AccountCreateContract) ContractExeException(org.tron.core.exception.ContractExeException)

Aggregations

AccountCapsule (org.tron.core.capsule.AccountCapsule)42 ContractExeException (org.tron.core.exception.ContractExeException)22 ContractValidateException (org.tron.core.exception.ContractValidateException)20 TransactionResultCapsule (org.tron.core.capsule.TransactionResultCapsule)16 Test (org.junit.Test)15 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)9 DateTime (org.joda.time.DateTime)7 ByteString (com.google.protobuf.ByteString)5 Before (org.junit.Before)5 AssetIssueCapsule (org.tron.core.capsule.AssetIssueCapsule)5 BalanceInsufficientException (org.tron.core.exception.BalanceInsufficientException)5 WitnessCapsule (org.tron.core.capsule.WitnessCapsule)3 Args (org.tron.core.config.args.Args)3 GenesisBlock (org.tron.core.config.args.GenesisBlock)3 Contract (org.tron.protos.Contract)3 AccountStore (org.tron.core.db.AccountStore)2 TransferAssetContract (org.tron.protos.Contract.TransferAssetContract)2 RamUsageEstimator (com.carrotsearch.sizeof.RamUsageEstimator)1 Lists (com.google.common.collect.Lists)1 Maps (com.google.common.collect.Maps)1