Skip to content

Instantly share code, notes, and snippets.

@akbng

akbng/Merkle.js Secret

Last active March 29, 2022 14:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akbng/0e6bff01dde6afcd7271d6026b634b15 to your computer and use it in GitHub Desktop.
Save akbng/0e6bff01dde6afcd7271d6026b634b15 to your computer and use it in GitHub Desktop.
import { createHash } from "crypto";
function makeTree(arr) {
if (arr.length === 0) return null;
if (arr.length === 1) return arr[0];
const list = [];
const length = arr.length;
for (let i = 0; i < length; i += 2) {
const currentItem = arr[i];
if (i + 1 >= length) {
list.push(currentItem);
break;
}
const nextItem = arr[i + 1];
let value = currentItem.value + nextItem.value;
const node = new MerkleNode(getHash(value), currentItem, nextItem);
list.push(node);
}
return makeTree(list);
}
function getHash(data) {
return createHash("sha256").update(data.toString()).digest("hex");
}
class MerkleNode {
constructor(value, left = null, right = null) {
this.value = value;
this.left = left;
this.right = right;
}
}
class MerkleTree {
constructor(root, size) {
this.root = root;
this.size = size;
}
static create(transactions) {
const size = Math.ceil(Math.log2(transactions.length)) + 1;
const root = makeTree(transactions.map((trn) => new MerkleNode(trn.hash)));
return new MerkleTree(root, size);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment