Search in sources :

Example 1 with ContractValidateException

use of org.tron.core.exception.ContractValidateException in project java-tron by tronprotocol.

the class Manager method generateBlock.

/**
 * Generate a block.
 */
public synchronized BlockCapsule generateBlock(final WitnessCapsule witnessCapsule, final long when, final byte[] privateKey) throws ValidateSignatureException, ContractValidateException, ContractExeException, UnLinkedBlockException {
    final long timestamp = this.dynamicPropertiesStore.getLatestBlockHeaderTimestamp();
    final long number = this.dynamicPropertiesStore.getLatestBlockHeaderNumber();
    final ByteString preHash = this.dynamicPropertiesStore.getLatestBlockHeaderHash();
    // judge create block time
    if (when < timestamp) {
        throw new IllegalArgumentException("generate block timestamp is invalid.");
    }
    long currentTrxSize = 0;
    long postponedTrxCount = 0;
    final BlockCapsule blockCapsule = new BlockCapsule(number + 1, preHash, when, witnessCapsule.getAddress());
    dialog.reset();
    dialog = DialogOptional.of(revokingStore.buildDialog());
    Iterator iterator = pendingTransactions.iterator();
    while (iterator.hasNext()) {
        TransactionCapsule trx = (TransactionCapsule) iterator.next();
        currentTrxSize += RamUsageEstimator.sizeOf(trx);
        // judge block size
        if (currentTrxSize > TRXS_SIZE) {
            postponedTrxCount++;
            continue;
        }
        // apply transaction
        try (Dialog tmpDialog = revokingStore.buildDialog()) {
            processTransaction(trx);
            tmpDialog.merge();
            // push into block
            blockCapsule.addTransaction(trx);
            iterator.remove();
        } catch (ContractExeException e) {
            logger.info("contract not processed during execute");
            logger.debug(e.getMessage(), e);
        } catch (ContractValidateException e) {
            logger.info("contract not processed during validate");
            logger.debug(e.getMessage(), e);
        } catch (RevokingStoreIllegalStateException e) {
            logger.debug(e.getMessage(), e);
        }
    }
    dialog.reset();
    if (postponedTrxCount > 0) {
        logger.info("{} transactions over the block size limit", postponedTrxCount);
    }
    logger.info("postponedTrxCount[" + postponedTrxCount + "],TrxLeft[" + pendingTransactions.size() + "]");
    blockCapsule.setMerkleRoot();
    blockCapsule.sign(privateKey);
    blockCapsule.generatedByMyself = true;
    this.pushBlock(blockCapsule);
    return blockCapsule;
}
Also used : TransactionCapsule(org.tron.core.capsule.TransactionCapsule) ByteString(com.google.protobuf.ByteString) Dialog(org.tron.core.db.AbstractRevokingStore.Dialog) ContractValidateException(org.tron.core.exception.ContractValidateException) Iterator(java.util.Iterator) BlockCapsule(org.tron.core.capsule.BlockCapsule) ContractExeException(org.tron.core.exception.ContractExeException) RevokingStoreIllegalStateException(org.tron.core.exception.RevokingStoreIllegalStateException)

Example 2 with ContractValidateException

use of org.tron.core.exception.ContractValidateException in project java-tron by tronprotocol.

the class Manager method pushBlock.

/**
 * save a block.
 */
public void pushBlock(final BlockCapsule block) throws ValidateSignatureException, ContractValidateException, ContractExeException, UnLinkedBlockException {
    try (PendingManager pm = new PendingManager(this)) {
        // todo: check block's validity
        if (!block.generatedByMyself) {
            if (!block.validateSignature()) {
                logger.info("The siganature is not validated.");
                // TODO: throw exception here.
                return;
            }
            if (!block.calcMerkleRoot().equals(block.getMerkleRoot())) {
                logger.info("The merkler root doesn't match, Calc result is " + block.calcMerkleRoot() + " , the headers is " + block.getMerkleRoot());
                // TODO:throw exception here.
                return;
            }
        }
        try {
            // direct return ,need test
            validateWitnessSchedule(block);
        } catch (Exception ex) {
            logger.error("validateWitnessSchedule error", ex);
        }
        BlockCapsule newBlock = this.khaosDb.push(block);
        // DB don't need lower block
        if (head == null) {
            if (newBlock.getNum() != 0) {
                return;
            }
        } else {
            if (newBlock.getNum() <= head.getNum()) {
                return;
            }
            // switch fork
            if (!newBlock.getParentHash().equals(head.getBlockId())) {
                switchFork(newBlock);
            }
            try (Dialog tmpDialog = revokingStore.buildDialog()) {
                this.processBlock(newBlock);
                tmpDialog.commit();
            } catch (RevokingStoreIllegalStateException e) {
                logger.debug(e.getMessage(), e);
            }
        }
        blockStore.put(block.getBlockId().getBytes(), block);
        this.numHashCache.putData(ByteArray.fromLong(block.getNum()), block.getBlockId().getBytes());
        // refreshHead(newBlock);
        logger.info("save block: " + newBlock);
    }
}
Also used : Dialog(org.tron.core.db.AbstractRevokingStore.Dialog) BlockCapsule(org.tron.core.capsule.BlockCapsule) BalanceInsufficientException(org.tron.core.exception.BalanceInsufficientException) HighFreqException(org.tron.core.exception.HighFreqException) ContractExeException(org.tron.core.exception.ContractExeException) ValidateSignatureException(org.tron.core.exception.ValidateSignatureException) ContractValidateException(org.tron.core.exception.ContractValidateException) RevokingStoreIllegalStateException(org.tron.core.exception.RevokingStoreIllegalStateException) UnLinkedBlockException(org.tron.core.exception.UnLinkedBlockException) RevokingStoreIllegalStateException(org.tron.core.exception.RevokingStoreIllegalStateException)

Example 3 with ContractValidateException

use of org.tron.core.exception.ContractValidateException in project java-tron by tronprotocol.

the class Manager method switchFork.

private void switchFork(BlockCapsule newHead) {
    Pair<LinkedList<BlockCapsule>, LinkedList<BlockCapsule>> binaryTree = khaosDb.getBranch(newHead.getBlockId(), head.getBlockId());
    if (CollectionUtils.isNotEmpty(binaryTree.getValue())) {
        while (!head.getBlockId().equals(binaryTree.getValue().peekLast().getParentHash())) {
            eraseBlock();
        }
    }
    if (CollectionUtils.isNotEmpty(binaryTree.getKey())) {
        LinkedList<BlockCapsule> branch = binaryTree.getKey();
        Collections.reverse(branch);
        branch.forEach(item -> {
            // todo  process the exception carefully later
            try (Dialog tmpDialog = revokingStore.buildDialog()) {
                processBlock(item);
                blockStore.put(item.getBlockId().getBytes(), item);
                this.numHashCache.putData(ByteArray.fromLong(item.getNum()), item.getBlockId().getBytes());
                tmpDialog.commit();
                head = item;
            } catch (ValidateSignatureException e) {
                logger.debug(e.getMessage(), e);
            } catch (ContractValidateException e) {
                logger.debug(e.getMessage(), e);
            } catch (ContractExeException e) {
                logger.debug(e.getMessage(), e);
            } catch (RevokingStoreIllegalStateException e) {
                logger.debug(e.getMessage(), e);
            }
        });
        return;
    }
}
Also used : Dialog(org.tron.core.db.AbstractRevokingStore.Dialog) ValidateSignatureException(org.tron.core.exception.ValidateSignatureException) ContractValidateException(org.tron.core.exception.ContractValidateException) BlockCapsule(org.tron.core.capsule.BlockCapsule) LinkedList(java.util.LinkedList) ContractExeException(org.tron.core.exception.ContractExeException) RevokingStoreIllegalStateException(org.tron.core.exception.RevokingStoreIllegalStateException)

Example 4 with ContractValidateException

use of org.tron.core.exception.ContractValidateException in project java-tron by tronprotocol.

the class TransferActuator method validate.

@Override
public boolean validate() throws ContractValidateException {
    try {
        if (!contract.is(TransferContract.class)) {
            throw new ContractValidateException("contract type error,expected type [TransferContract],real type[" + contract.getClass() + "]");
        }
        TransferContract transferContract = this.contract.unpack(TransferContract.class);
        Preconditions.checkNotNull(transferContract.getOwnerAddress(), "OwnerAddress is null");
        Preconditions.checkNotNull(transferContract.getToAddress(), "ToAddress is null");
        Preconditions.checkNotNull(transferContract.getAmount(), "Amount is null");
        if (transferContract.getOwnerAddress().equals(transferContract.getToAddress())) {
            throw new ContractValidateException("Cannot transfer trx to yourself.");
        }
        if (!dbManager.getAccountStore().has(transferContract.getOwnerAddress().toByteArray())) {
            throw new ContractValidateException("Validate TransferContract error, no OwnerAccount.");
        }
        AccountCapsule ownerAccount = dbManager.getAccountStore().get(transferContract.getOwnerAddress().toByteArray());
        long balance = ownerAccount.getBalance();
        long laststOperationTime = ownerAccount.getLatestOperationTime();
        long now = System.currentTimeMillis();
        // TODO:
        // if (now - laststOperationTime < balance) {
        // throw new ContractValidateException();
        // }
        // if account with to_address is not existed,  create it.
        ByteString toAddress = transferContract.getToAddress();
        if (!dbManager.getAccountStore().has(toAddress.toByteArray())) {
            AccountCapsule account = new AccountCapsule(toAddress, AccountType.Normal);
            dbManager.getAccountStore().put(toAddress.toByteArray(), account);
        }
        if (ownerAccount.getBalance() < calcFee()) {
            throw new ContractValidateException("Validate TransferContract error, insufficient fee.");
        }
        long amount = transferContract.getAmount();
        if (amount < 0) {
            throw new ContractValidateException("Amount is less than 0.");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new ContractValidateException(ex.getMessage());
    }
    return true;
}
Also used : AccountCapsule(org.tron.core.capsule.AccountCapsule) ByteString(com.google.protobuf.ByteString) ContractValidateException(org.tron.core.exception.ContractValidateException) TransferContract(org.tron.protos.Contract.TransferContract) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) ContractValidateException(org.tron.core.exception.ContractValidateException) BalanceInsufficientException(org.tron.core.exception.BalanceInsufficientException) ContractExeException(org.tron.core.exception.ContractExeException)

Example 5 with ContractValidateException

use of org.tron.core.exception.ContractValidateException in project java-tron by tronprotocol.

the class TransferAssetActuator method validate.

@Override
public boolean validate() throws ContractValidateException {
    try {
        TransferAssetContract transferAssetContract = this.contract.unpack(TransferAssetContract.class);
        Preconditions.checkNotNull(transferAssetContract.getOwnerAddress(), "OwnerAddress is null");
        Preconditions.checkNotNull(transferAssetContract.getToAddress(), "ToAddress is null");
        Preconditions.checkNotNull(transferAssetContract.getAssetName(), "AssetName is null");
        Preconditions.checkNotNull(transferAssetContract.getAmount(), "Amount is null");
        if (transferAssetContract.getOwnerAddress().equals(transferAssetContract.getToAddress())) {
            throw new ContractValidateException("Cannot transfer asset to yourself.");
        }
        byte[] ownerKey = transferAssetContract.getOwnerAddress().toByteArray();
        if (!this.dbManager.getAccountStore().has(ownerKey)) {
            throw new ContractValidateException();
        }
        // if account with to_address is not existed,  create it.
        ByteString toAddress = transferAssetContract.getToAddress();
        if (!dbManager.getAccountStore().has(toAddress.toByteArray())) {
            AccountCapsule account = new AccountCapsule(toAddress, AccountType.Normal);
            dbManager.getAccountStore().put(toAddress.toByteArray(), account);
        }
        byte[] nameKey = transferAssetContract.getAssetName().toByteArray();
        if (!this.dbManager.getAssetIssueStore().has(nameKey)) {
            throw new ContractValidateException();
        }
        long amount = transferAssetContract.getAmount();
        AccountCapsule ownerAccount = this.dbManager.getAccountStore().get(ownerKey);
        Map<String, Long> asset = ownerAccount.getAssetMap();
        if (asset.isEmpty()) {
            throw new ContractValidateException();
        }
        Long assetAmount = asset.get(ByteArray.toStr(nameKey));
        if (amount <= 0 || null == assetAmount || amount > assetAmount || assetAmount <= 0) {
            throw new ContractValidateException();
        }
    } catch (InvalidProtocolBufferException e) {
        throw new ContractValidateException();
    }
    return true;
}
Also used : AccountCapsule(org.tron.core.capsule.AccountCapsule) ByteString(com.google.protobuf.ByteString) ContractValidateException(org.tron.core.exception.ContractValidateException) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) ByteString(com.google.protobuf.ByteString) TransferAssetContract(org.tron.protos.Contract.TransferAssetContract)

Aggregations

ContractValidateException (org.tron.core.exception.ContractValidateException)28 ContractExeException (org.tron.core.exception.ContractExeException)25 AccountCapsule (org.tron.core.capsule.AccountCapsule)20 Test (org.junit.Test)16 TransactionResultCapsule (org.tron.core.capsule.TransactionResultCapsule)16 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)9 DateTime (org.joda.time.DateTime)6 ByteString (com.google.protobuf.ByteString)5 BlockCapsule (org.tron.core.capsule.BlockCapsule)4 ValidateSignatureException (org.tron.core.exception.ValidateSignatureException)4 AssetIssueCapsule (org.tron.core.capsule.AssetIssueCapsule)3 Dialog (org.tron.core.db.AbstractRevokingStore.Dialog)3 RevokingStoreIllegalStateException (org.tron.core.exception.RevokingStoreIllegalStateException)3 Iterator (java.util.Iterator)2 TransactionCapsule (org.tron.core.capsule.TransactionCapsule)2 BalanceInsufficientException (org.tron.core.exception.BalanceInsufficientException)2 UnLinkedBlockException (org.tron.core.exception.UnLinkedBlockException)2 Contract (org.tron.protos.Contract)2 Preconditions (com.google.common.base.Preconditions)1 Any (com.google.protobuf.Any)1