build method Null safety
- List<
TransactionModel> transactions, - Uint8List transactionRoot
Builds a new block from a List
of TransactionModel and a transactionRoot
.
It gets the last created block from the db
to extract BlockModel.previousHash
from it. If there are no blocks itmeans that it is the genesis block, i.e,
the first block created by the chain and the BlockModel.previousHash
will be 0.
This method returns the BlockModel
created in-memory. Its return should be used
to commit the TransactionModel. After commiting all the transactions,
commit needs to be called to persist the block into db
.
BlockModel blk = blockService.build(transactions, transactionRoot);
for (TransactionModel transaction in transactions) {
transaction.block = blk;
transaction.merkelProof = merkelTree.proofs[transaction.id];
transactionService.commit(transaction);
}
blockService.commit(blk);
Implementation
BlockModel build(
List<TransactionModel> transactions, Uint8List transactionRoot) {
BlockModel? lastBlock = _repository.getLast();
BlockModel block = BlockModel(
previousHash: lastBlock == null
? Uint8List(1)
: Digest("SHA3-256").process(lastBlock.header()),
transactionRoot: transactionRoot,
transactionCount: transactions.length);
block.id = Digest("SHA3-256").process(block.header());
return block;
}