Created
April 14, 2022 21:03
-
-
Save joselvelez/2e2ebd7bd5f95d3641f0c71f3b279036 to your computer and use it in GitHub Desktop.
Generate 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 keccak256 from "keccak256"; | |
import { MerkleTree } from "merkletreejs"; | |
import fs from "fs"; | |
const leafValues = []; | |
let tree; | |
let root; | |
/** | |
* Creates a new file called 'MerkleTree.txt' that contains | |
* the generated Merkle tree from the 'MerkleLeaves.json' file | |
*/ | |
export async function generateMerkleTree(data) { | |
try { | |
console.log(`\nGenerating a Merkle Tree...`); | |
tree = new MerkleTree(data, keccak256, {sortPairs: true, sortLeaves: true, sort: true, hashLeaves: true}); | |
root = tree.getHexRoot(); | |
// For a short list, you can log it out, but not recommended for large lists | |
console.log('\nTree:', tree.toString()); | |
fs.writeFileSync('../example/MerkleTree.txt', tree.toString()); | |
console.log(`Merkle tree generated. | |
\nRoot hash is ${tree.getHexRoot()} | |
\nTree Summary: | |
\n Leaf Count: ${tree.getLeafCount()} | |
\n Layer Count: ${tree.getLayerCount()} | |
\n Tree Depth: ${tree.getDepth()} | |
\nSaving to MerkleTree.txt | |
`); | |
} catch (e) { | |
console.log(e); | |
} | |
} | |
/* | |
* Save the root hash to a file 'MerkleRoot.json' | |
*/ | |
async function saveMerkleRoot() { | |
fs.writeFileSync('../example/MerkleRoot.json', JSON.stringify(root)); | |
console.log(`Saving the Merkle Root '${root}' to 'MerkleRoot.json'`); | |
} | |
/* | |
* Main function that is called. It will run the sequence of | |
* of calls to generate the leaves array, the Merkle tree | |
* and the root hash. | |
*/ | |
export async function generate(data) { | |
try { | |
for (let i = 0; i < data.length; i ++) { | |
let currentHash; | |
let currentValue; | |
currentValue = data[i]; | |
currentHash = `0x${keccak256(data[i]).toString('hex')}`; | |
/* | |
* Create an object for each gene containing: | |
* gene symbol, keccak256 hash, leaf index | |
*/ | |
leafValues.push({ "Leaf": currentValue, "Hash": currentHash}) | |
} | |
} catch (err) { | |
console.log(err); | |
} | |
// Generate a file containing a summary of the Merkle Tree | |
fs.writeFileSync("../example/MerkleTreeSummary.json", JSON.stringify(leafValues)); | |
generateMerkleTree(data) | |
.then(saveMerkleRoot()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment