Skip to content

Instantly share code, notes, and snippets.

@johnson86tw
Created June 14, 2021 05:22
Show Gist options
  • Save johnson86tw/c908cdf5b4b42c720eea60aace736a44 to your computer and use it in GitHub Desktop.
Save johnson86tw/c908cdf5b4b42c720eea60aace736a44 to your computer and use it in GitHub Desktop.
...
proof(indexOfLeaf: number) {
let pathElements: string[] = [];
let pathIndices: number[] = [];
const leaf = this.storage.get(MerkleTree.indexToKey(0, indexOfLeaf));
if (!leaf) throw new Error("leaf not found");
// store sibling into pathElements and target's indices into pathIndices
const handleIndex = (level: number, currentIndex: number, siblingIndex: number) => {
const siblingValue = this.storage.get(MerkleTree.indexToKey(level, siblingIndex)) || this.zeros[level];
pathElements.push(siblingValue);
pathIndices.push(currentIndex % 2);
};
this.traverse(indexOfLeaf, handleIndex);
return {
root: this.root(),
pathElements,
pathIndices,
leaf: leaf,
};
}
...
// traverse from leaf to root with handler for target node and sibling node
private traverse(indexOfLeaf: number, handler: (level: number, currentIndex: number, siblingIndex: number) => void) {
let currentIndex = indexOfLeaf;
for (let i = 0; i < this.levels; i++) {
let siblingIndex;
if (currentIndex % 2 === 0) {
siblingIndex = currentIndex + 1;
} else {
siblingIndex = currentIndex - 1;
}
handler(i, currentIndex, siblingIndex);
currentIndex = Math.floor(currentIndex / 2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment