Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class MerkleTree {
- constructor(arr, concat) {
- this.arr = arr
- this.concat = concat
- }
- getProof(index, tempArr = this.arr, proof = []) {
- if (tempArr.length === 1) {
- return proof;
- }
- let newArr = [];
- for (let i = 0; i < tempArr.length; i += 2) {
- let left = tempArr[i];
- let right = tempArr[i + 1];
- if(index === i || index === i + 1) {
- // is the index referring to one of these two nodes
- const isLeft = !(index === i);
- const data = isLeft ? left : right;
- if (data) {
- proof.push({
- left: isLeft,
- data
- });
- }
- }
- if (right) {
- newArr.push(this.concat(left, right))
- } else {
- newArr.push(left);
- }
- }
- return this.getProof(Math.floor(index/2), newArr, proof);
- }
- getRoot(tempArr = this.arr, newArr = []) {
- if (tempArr.length === 1) return tempArr[0];
- for (let i = 0; i < tempArr.length; i += 2) {
- if (tempArr[i + 1]) {
- newArr.push(this.concat(tempArr[i], tempArr[i + 1]))
- } else {
- newArr.push(tempArr[i])
- }
- }
- return this.getRoot(newArr)
- }
- }
- module.exports = MerkleTree;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement