/// <summary> /// Calculate merkle tree root of transaction. /// </summary> /// <returns></returns> public static Hash CalculateMerkleTreeRoot(this BlockBody blockBody) { if (blockBody.TransactionsCount == 0) { return(Hash.Empty); } var merkleTreeRoot = BinaryMerkleTree.FromLeafNodes(blockBody.TransactionIds).Root; return(merkleTreeRoot); }
/// <summary> /// Calculate the <see cref="BinaryMerkleTree.Root"/> with path and provided leaf. /// </summary> /// <param name="merklePath"></param> /// <param name="leaf"></param> /// <returns></returns> public static Hash ComputeRootWith(this MerklePath merklePath, Hash leaf) { Hash hash = leaf.Clone(); foreach (var node in merklePath.Path) { hash = BinaryMerkleTree.CalculateRootFromMultiHash(new[] { hash, node }); } return(hash); }
private Block GenerateBlock(BlockHeader blockHeader, IEnumerable <Hash> transactionIds) { var leafNodes = transactionIds as Hash[] ?? transactionIds.ToArray(); blockHeader.MerkleTreeRootOfTransactions = BinaryMerkleTree.FromLeafNodes(leafNodes).Root; blockHeader.MerkleTreeRootOfWorldState = Hash.Empty; blockHeader.MerkleTreeRootOfTransactionStatus = Hash.Empty; blockHeader.SignerPubkey = ByteString.CopyFromUtf8("SignerPubkey"); var block = new Block { Header = blockHeader, Body = new BlockBody() }; block.Body.TransactionIds.AddRange(leafNodes); return(block); }
/// <summary> /// Calculate merkle tree root of transaction and side chain block info. /// </summary> /// <returns></returns> public Hash CalculateMerkleTreeRoots() { // side chain info CalculateSideChainBlockHeadersRoot(); CalculateSideChainTransactionsRoot(); if (TransactionsCount == 0) { return(Hash.Default); } if (BinaryMerkleTree.Root != null) { return(BinaryMerkleTree.Root); } BinaryMerkleTree.AddNodes(Transactions); BinaryMerkleTree.ComputeRootHash(); return(BinaryMerkleTree.Root); }
public void BlockBody_Test() { var blockBody = new BlockBody(); blockBody.CalculateMerkleTreeRoot().ShouldBe(Hash.Empty); var transaction1 = _kernelTestHelper.GenerateTransaction(); var transaction2 = _kernelTestHelper.GenerateTransaction(); var transaction3 = _kernelTestHelper.GenerateTransaction(); blockBody.AddTransaction(transaction1); blockBody.TransactionIds.Count.ShouldBe(1); blockBody.TransactionIds.ShouldContain(transaction1.GetHash()); blockBody.AddTransactions(new[] { transaction2.GetHash(), transaction3.GetHash() }); blockBody.TransactionIds.Count.ShouldBe(3); blockBody.TransactionIds.ShouldContain(transaction2.GetHash()); blockBody.TransactionIds.ShouldContain(transaction3.GetHash()); blockBody.CalculateMerkleTreeRoot().ShouldBe(BinaryMerkleTree.FromLeafNodes(blockBody.TransactionIds).Root); }