Search in sources :

Example 1 with LedgerBlock

use of com.jd.blockchain.ledger.LedgerBlock in project jdchain-core by blockchain-jd-com.

the class BlockCommitService method commitBlock.

public boolean commitBlock(Block block, BlockClosure done) throws BlockCommittedException {
    boolean result = true;
    long latestBlockHeight = ledgerRepository.retrieveLatestBlockHeight();
    if (latestBlockHeight >= block.getHeight()) {
        throw new BlockCommittedException(block.getHeight());
    }
    if (latestBlockHeight + 1 != block.getHeight()) {
        notifyCatchUp(block.getHeight());
        LOGGER.error("commit block ignore. expect height:{}, latest block: {}", block.getHeight(), latestBlockHeight);
        return false;
    }
    RaftConsensusMessageContext context = RaftConsensusMessageContext.createContext(realmName);
    context.setTimestamp(block.getProposalTimestamp());
    String batch = messageHandle.beginBatch(context);
    context.setBatchId(batch);
    LoggerUtils.debugIfEnabled(LOGGER, "commit block start, batchId: {}", batch);
    Status status = Status.OK();
    try {
        int msgId = 0;
        for (byte[] tx : block.getTxs()) {
            AsyncFuture<byte[]> asyncFuture = messageHandle.processOrdered(msgId++, tx, context);
            Optional.ofNullable(done).ifPresent(d -> d.addFuture(asyncFuture));
        }
        messageHandle.completeBatch(context);
        // todo ?
        messageHandle.commitBatch(context);
        LedgerBlock repositoryLatestBlock = ledgerRepository.getLatestBlock();
        assert repositoryLatestBlock.getHeight() == block.getHeight();
        block.setPreBlockHash(repositoryLatestBlock.getPreviousHash());
        block.setCurrentBlockHash(repositoryLatestBlock.getHash());
        blockCommitCallbackList.forEach(c -> c.commitCallBack(block, true));
    } catch (Exception e) {
        LOGGER.error("commitBlock error", e);
        result = false;
        messageHandle.rollbackBatch(TransactionState.CONSENSUS_ERROR.CODE, context);
        status = new Status(TransactionState.CONSENSUS_ERROR.CODE, e.getMessage());
        blockCommitCallbackList.forEach(c -> c.commitCallBack(block, false));
    }
    LoggerUtils.debugIfEnabled(LOGGER, "commit block end, batchId: {}, blockHeight: {}, status: {}", batch, block.getHeight(), status);
    if (done != null) {
        done.run(status);
    }
    return result;
}
Also used : Status(com.alipay.sofa.jraft.Status) Longs(com.google.common.primitives.Longs) Logger(org.slf4j.Logger) MessageHandle(com.jd.blockchain.consensus.service.MessageHandle) TransactionState(com.jd.blockchain.ledger.TransactionState) BlockCommitCallback(com.jd.blockchain.consensus.raft.consensus.BlockCommitCallback) MessageBus(com.jd.blockchain.consensus.raft.msgbus.MessageBus) BlockCommittedException(com.jd.blockchain.consensus.raft.consensus.BlockCommittedException) LoggerFactory(org.slf4j.LoggerFactory) LedgerBlock(com.jd.blockchain.ledger.LedgerBlock) LedgerRepository(com.jd.blockchain.ledger.core.LedgerRepository) Status(com.alipay.sofa.jraft.Status) LoggerUtils(com.jd.blockchain.consensus.raft.util.LoggerUtils) ArrayList(java.util.ArrayList) List(java.util.List) AsyncFuture(utils.concurrent.AsyncFuture) BLOCK_CATCH_UP_TOPIC(com.jd.blockchain.consensus.raft.msgbus.MessageBus.BLOCK_CATCH_UP_TOPIC) Block(com.jd.blockchain.consensus.raft.consensus.Block) Optional(java.util.Optional) BlockCommitter(com.jd.blockchain.consensus.raft.consensus.BlockCommitter) LedgerBlock(com.jd.blockchain.ledger.LedgerBlock) BlockCommittedException(com.jd.blockchain.consensus.raft.consensus.BlockCommittedException) BlockCommittedException(com.jd.blockchain.consensus.raft.consensus.BlockCommittedException)

Example 2 with LedgerBlock

use of com.jd.blockchain.ledger.LedgerBlock in project jdchain-core by blockchain-jd-com.

the class RaftConsensusStateMachine method onStart.

public void onStart() {
    LedgerBlock ledgerBlock = ledgerRepository.retrieveLatestBlock();
    this.currentBlockHeight.set(ledgerBlock.getHeight());
}
Also used : LedgerBlock(com.jd.blockchain.ledger.LedgerBlock)

Example 3 with LedgerBlock

use of com.jd.blockchain.ledger.LedgerBlock in project jdchain-core by blockchain-jd-com.

the class LedgerEditorTest method testGennesisBlockCreation.

/**
 * 测试创建账本;
 */
@Test
public void testGennesisBlockCreation() {
    LedgerEditor ldgEdt = createLedgerInitEditor();
    LedgerTransactionContext genisisTxCtx = createGenisisTx(ldgEdt, participants);
    LedgerDataSetEditor ldgDS = (LedgerDataSetEditor) genisisTxCtx.getDataset();
    AsymmetricKeypair cryptoKeyPair = signatureFunction.generateKeypair();
    BlockchainKeypair userKP = new BlockchainKeypair(cryptoKeyPair.getPubKey(), cryptoKeyPair.getPrivKey());
    UserAccount userAccount = ldgDS.getUserAccountSet().register(userKP.getAddress(), userKP.getPubKey());
    userAccount.setProperty("Name", "孙悟空", -1);
    userAccount.setProperty("Age", "10000", -1);
    TransactionResult tx = genisisTxCtx.commit(TransactionState.SUCCESS);
    TransactionRequest genesisTxReq = genisisTxCtx.getTransactionRequest();
    assertEquals(genesisTxReq.getTransactionHash(), tx.getTransactionHash());
    assertEquals(0, tx.getBlockHeight());
    LedgerBlock block = ldgEdt.prepare();
    assertEquals(0, block.getHeight());
    assertNotNull(block.getHash());
    assertNull(block.getLedgerHash());
    assertNull(block.getPreviousHash());
    // 提交数据,写入存储;
    ldgEdt.commit();
}
Also used : LedgerBlock(com.jd.blockchain.ledger.LedgerBlock) AsymmetricKeypair(com.jd.blockchain.crypto.AsymmetricKeypair) TransactionResult(com.jd.blockchain.ledger.TransactionResult) LedgerDataSetEditor(com.jd.blockchain.ledger.core.LedgerDataSetEditor) LedgerEditor(com.jd.blockchain.ledger.core.LedgerEditor) BlockchainKeypair(com.jd.blockchain.ledger.BlockchainKeypair) LedgerTransactionContext(com.jd.blockchain.ledger.core.LedgerTransactionContext) UserAccount(com.jd.blockchain.ledger.core.UserAccount) TransactionRequest(com.jd.blockchain.ledger.TransactionRequest) Test(org.junit.Test)

Example 4 with LedgerBlock

use of com.jd.blockchain.ledger.LedgerBlock in project jdchain-core by blockchain-jd-com.

the class LedgerEditorTest method testWriteDataAccoutKvOp.

@SuppressWarnings("unused")
@Test
public void testWriteDataAccoutKvOp() {
    MemoryKVStorage storage = new MemoryKVStorage();
    LedgerEditor ldgEdt = createLedgerInitEditor(storage);
    LedgerTransactionContext genisisTxCtx = createGenisisTx(ldgEdt, participants);
    LedgerDataSetEditor ldgDS = (LedgerDataSetEditor) genisisTxCtx.getDataset();
    AsymmetricKeypair cryptoKeyPair = signatureFunction.generateKeypair();
    BlockchainKeypair dataKP = new BlockchainKeypair(cryptoKeyPair.getPubKey(), cryptoKeyPair.getPrivKey());
    DataAccount dataAccount = ldgDS.getDataAccountSet().register(dataKP.getAddress(), dataKP.getPubKey(), null);
    dataAccount.getDataset().setValue("A", TypedValue.fromText("abc"), -1);
    TransactionResult tx = genisisTxCtx.commit(TransactionState.SUCCESS);
    LedgerBlock block = ldgEdt.prepare();
    // 提交数据,写入存储;
    ldgEdt.commit();
    // 预期这是第1个区块;
    assertNotNull(block);
    assertNotNull(block.getHash());
    assertEquals(0, block.getHeight());
    // 验证数据读写的一致性;
    BytesValue bytes = dataAccount.getDataset().getValue("A");
    assertEquals(DataType.TEXT, bytes.getType());
    String textValue = bytes.getBytes().toUTF8String();
    assertEquals("abc", textValue);
    // 验证重新加载的正确性;
    LedgerManager manager = new LedgerManager();
    HashDigest ledgerHash = block.getHash();
    LedgerRepository repo = manager.register(ledgerHash, storage, LedgerDataStructure.MERKLE_TREE);
    dataAccount = repo.getDataAccountSet().getAccount(dataKP.getAddress());
    assertNotNull(dataAccount);
    bytes = dataAccount.getDataset().getValue("A");
    assertEquals(DataType.TEXT, bytes.getType());
    textValue = bytes.getBytes().toUTF8String();
    assertEquals("abc", textValue);
    LedgerTransaction tx_init = repo.getTransactionSet().getTransaction(tx.getTransactionHash());
    assertNotNull(tx_init);
}
Also used : LedgerBlock(com.jd.blockchain.ledger.LedgerBlock) LedgerManager(com.jd.blockchain.ledger.core.LedgerManager) TransactionResult(com.jd.blockchain.ledger.TransactionResult) LedgerDataSetEditor(com.jd.blockchain.ledger.core.LedgerDataSetEditor) LedgerEditor(com.jd.blockchain.ledger.core.LedgerEditor) BlockchainKeypair(com.jd.blockchain.ledger.BlockchainKeypair) LedgerTransactionContext(com.jd.blockchain.ledger.core.LedgerTransactionContext) BytesValue(com.jd.blockchain.ledger.BytesValue) LedgerRepository(com.jd.blockchain.ledger.core.LedgerRepository) DataAccount(com.jd.blockchain.ledger.core.DataAccount) AsymmetricKeypair(com.jd.blockchain.crypto.AsymmetricKeypair) HashDigest(com.jd.blockchain.crypto.HashDigest) LedgerTransaction(com.jd.blockchain.ledger.LedgerTransaction) MemoryKVStorage(com.jd.blockchain.storage.service.utils.MemoryKVStorage) Test(org.junit.Test)

Example 5 with LedgerBlock

use of com.jd.blockchain.ledger.LedgerBlock in project jdchain-core by blockchain-jd-com.

the class LedgerBlockImplTest method testSerialize_LedgerBlock.

@Test
public void testSerialize_LedgerBlock() throws Exception {
    byte[] serialBytes = BinaryProtocol.encode(data, LedgerBlock.class);
    LedgerBlock resolvedData1 = BinaryProtocol.decode(serialBytes);
    System.out.println("------Assert start ------");
    assertEquals(data.getHash(), resolvedData1.getHash());
    assertEquals(data.getHeight(), resolvedData1.getHeight());
    assertEquals(data.getLedgerHash(), resolvedData1.getLedgerHash());
    assertEquals(data.getPreviousHash(), resolvedData1.getPreviousHash());
    assertEquals(data.getTransactionSetHash(), resolvedData1.getTransactionSetHash());
    assertEquals(data.getAdminAccountHash(), resolvedData1.getAdminAccountHash());
    assertEquals(data.getContractAccountSetHash(), resolvedData1.getContractAccountSetHash());
    assertEquals(data.getDataAccountSetHash(), resolvedData1.getDataAccountSetHash());
    assertEquals(data.getUserAccountSetHash(), resolvedData1.getUserAccountSetHash());
    System.out.println("------Assert OK ------");
}
Also used : LedgerBlock(com.jd.blockchain.ledger.LedgerBlock) Test(org.junit.Test)

Aggregations

LedgerBlock (com.jd.blockchain.ledger.LedgerBlock)53 LedgerQuery (com.jd.blockchain.ledger.core.LedgerQuery)36 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)36 QueryArgs (utils.query.QueryArgs)10 LedgerTransaction (com.jd.blockchain.ledger.LedgerTransaction)9 DataAccountSet (com.jd.blockchain.ledger.core.DataAccountSet)9 LedgerEditor (com.jd.blockchain.ledger.core.LedgerEditor)9 Test (org.junit.Test)9 BlockchainKeypair (com.jd.blockchain.ledger.BlockchainKeypair)8 TransactionRequest (com.jd.blockchain.ledger.TransactionRequest)8 LedgerRepository (com.jd.blockchain.ledger.core.LedgerRepository)8 HashDigest (com.jd.blockchain.crypto.HashDigest)7 LedgerManager (com.jd.blockchain.ledger.core.LedgerManager)7 TransactionSet (com.jd.blockchain.ledger.core.TransactionSet)7 MemoryKVStorage (com.jd.blockchain.storage.service.utils.MemoryKVStorage)7 ContractAccountSet (com.jd.blockchain.ledger.core.ContractAccountSet)6 DataAccount (com.jd.blockchain.ledger.core.DataAccount)6 UserAccount (com.jd.blockchain.ledger.core.UserAccount)6 TransactionResponse (com.jd.blockchain.ledger.TransactionResponse)5 DefaultOperationHandleRegisteration (com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration)5