-
-
Save akbng/0e6bff01dde6afcd7271d6026b634b15 to your computer and use it in GitHub Desktop.
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 { 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