use of com.jd.blockchain.consensus.raft.consensus.BlockCommittedException 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;
}
Aggregations