Search in sources :

Example 1 with BlockCapsule

use of org.tron.core.capsule.BlockCapsule 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 BlockCapsule

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

the class Manager method eraseBlock.

/**
 * when switch fork need erase blocks on fork branch.
 */
public void eraseBlock() {
    dialog.reset();
    BlockCapsule oldHeadBlock = getBlockStore().get(head.getBlockId().getBytes());
    try {
        revokingStore.pop();
        head = getBlockStore().get(getBlockIdByNum(oldHeadBlock.getNum() - 1).getBytes());
    } catch (RevokingStoreIllegalStateException e) {
        logger.debug(e.getMessage(), e);
    }
    khaosDb.pop();
    for (TransactionCapsule trx : oldHeadBlock.getTransactions()) {
        popedTransactions.add(trx);
    }
// todo process the trans in the poped block.
}
Also used : TransactionCapsule(org.tron.core.capsule.TransactionCapsule) BlockCapsule(org.tron.core.capsule.BlockCapsule) RevokingStoreIllegalStateException(org.tron.core.exception.RevokingStoreIllegalStateException)

Example 3 with BlockCapsule

use of org.tron.core.capsule.BlockCapsule 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 4 with BlockCapsule

use of org.tron.core.capsule.BlockCapsule 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 5 with BlockCapsule

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

the class KhaosDatabaseTest method testPushGetBlock.

@Test
public void testPushGetBlock() {
    BlockCapsule blockCapsule = new BlockCapsule(Block.newBuilder().setBlockHeader(BlockHeader.newBuilder().setRawData(raw.newBuilder().setParentHash(ByteString.copyFrom(ByteArray.fromHexString("0304f784e4e7bae517bcab94c3e0c9214fb4ac7ff9d7d5a937d1f40031f87b81"))))).build());
    BlockCapsule blockCapsule2 = new BlockCapsule(Block.newBuilder().setBlockHeader(BlockHeader.newBuilder().setRawData(raw.newBuilder().setParentHash(ByteString.copyFrom(ByteArray.fromHexString("9938a342238077182498b464ac029222ae169360e540d1fd6aee7c2ae9575a06"))))).build());
    khaosDatabase.start(blockCapsule);
    try {
        khaosDatabase.push(blockCapsule2);
    } catch (UnLinkedBlockException e) {
    }
    Assert.assertEquals(blockCapsule2, khaosDatabase.getBlock(blockCapsule2.getBlockId()));
    Assert.assertTrue("conatain is error", khaosDatabase.containBlock(blockCapsule2.getBlockId()));
    khaosDatabase.removeBlk(blockCapsule2.getBlockId());
    Assert.assertNull("removeBlk is error", khaosDatabase.getBlock(blockCapsule2.getBlockId()));
}
Also used : UnLinkedBlockException(org.tron.core.exception.UnLinkedBlockException) BlockCapsule(org.tron.core.capsule.BlockCapsule) Test(org.junit.Test)

Aggregations

BlockCapsule (org.tron.core.capsule.BlockCapsule)14 ByteString (com.google.protobuf.ByteString)4 Test (org.junit.Test)4 ContractExeException (org.tron.core.exception.ContractExeException)4 ContractValidateException (org.tron.core.exception.ContractValidateException)4 RevokingStoreIllegalStateException (org.tron.core.exception.RevokingStoreIllegalStateException)4 Dialog (org.tron.core.db.AbstractRevokingStore.Dialog)3 UnLinkedBlockException (org.tron.core.exception.UnLinkedBlockException)3 ValidateSignatureException (org.tron.core.exception.ValidateSignatureException)3 LinkedList (java.util.LinkedList)2 List (java.util.List)2 Message (org.tron.common.overlay.message.Message)2 Sha256Hash (org.tron.common.utils.Sha256Hash)2 TransactionCapsule (org.tron.core.capsule.TransactionCapsule)2 TronException (org.tron.core.exception.TronException)2 BlockInventoryMessage (org.tron.core.net.message.BlockInventoryMessage)2 BlockMessage (org.tron.core.net.message.BlockMessage)2 ChainInventoryMessage (org.tron.core.net.message.ChainInventoryMessage)2 FetchInvDataMessage (org.tron.core.net.message.FetchInvDataMessage)2 InventoryMessage (org.tron.core.net.message.InventoryMessage)2