Skip to content

Instantly share code, notes, and snippets.

@Dan-Nolan
Created July 9, 2020 20:22
Show Gist options
  • Save Dan-Nolan/968f80eab93b22b04bebe63393960e5e to your computer and use it in GitHub Desktop.
Save Dan-Nolan/968f80eab93b22b04bebe63393960e5e to your computer and use it in GitHub Desktop.
MerkleTree.js
class MerkleTree {
constructor(leaves, concat) {
this.leaves = leaves;
this.concat = concat;
}
getProof(index, leaves = this.leaves, proof = []) {
if (leaves.length === 1) {
return proof;
}
let newLayer = [];
for (let i = 0; i < leaves.length; i += 2) {
let left = leaves[i];
let right = leaves[i + 1];
if (right) {
if(index === i) {
proof.push({
data: right,
left: false,
});
}
if(index === i + 1) {
proof.push({
data: left,
left: true,
});
}
newLayer.push(this.concat(left, right));
}
else {
newLayer.push(left);
}
}
return this.getProof(Math.floor(index/2), newLayer, proof);
}
getRoot(leaves = this.leaves) {
if (leaves.length === 1) {
return leaves[0];
}
let newLayer = [];
for (let i = 0; i < leaves.length; i += 2) {
let left = leaves[i];
let right = leaves[i + 1];
if(right) {
newLayer.push(this.concat(left, right));
}
else {
newLayer.push(left);
}
}
return this.getRoot(newLayer);
}
}
module.exports = MerkleTree;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment