Last active
February 12, 2020 16:43
-
-
Save dgarcia360/a34adc4b3bbc18d3edfa8bb86c308eb6 to your computer and use it in GitHub Desktop.
Build Transactions Merkle Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {QueryParams, RepositoryFactoryHttp, UInt64} from "nem2-sdk"; | |
import {MerkleTree} from "merkletreejs/index"; | |
import {sha3_256} from "js-sha3"; | |
const example = async () => { | |
const nodeUrl = 'http://api-xym-3-01.ap-northeast-1.nemtech.network:3000'; | |
const repositoryHttp = new RepositoryFactoryHttp(nodeUrl); | |
const blockHttp = repositoryHttp.createBlockRepository(); | |
// replace with block height | |
const height = UInt64.fromUint(1); | |
// 1. Obtain HRoot; in Symbol, this is stored in the block header. | |
const HRoot = (await blockHttp.getBlockByHeight(height).toPromise()).blockTransactionsHash; | |
// 2. Calculate HRoot0 creating a merkle tree with all the transactions within the block in natural order. | |
const transactions = await blockHttp.getBlockTransactions(height, new QueryParams(100)).toPromise(); | |
const leaves = transactions | |
.sort((n1,n2) => n1.transactionInfo.index - n2.transactionInfo.index) | |
.map(transaction => transaction.transactionInfo!.hash); | |
const tree = new MerkleTree(leaves, sha3_256, { | |
duplicateOdd: true, | |
hashLeaves: false, | |
sort: false, | |
sortLeaves: false, | |
sortPairs: false, | |
isBitcoinTree: false}); | |
const HRoot0 = tree.getRoot().toString('hex'); | |
// 3. Compare HRoot and HRoot0. | |
return HRoot.toUpperCase() === HRoot0.toUpperCase(); | |
} | |
example().then(result => console.log(result)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment