SHARE
TWEET

Untitled

a guest Sep 17th, 2019 79 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class MerkleTree {
  2.     constructor(arr, concat) {
  3.         this.arr = arr
  4.         this.concat = concat
  5.     }
  6.     getProof(index, tempArr = this.arr, proof = []) {
  7.         if (tempArr.length === 1) {
  8.             return proof;
  9.         }
  10.         let newArr = [];
  11.         for (let i = 0; i < tempArr.length; i += 2) {
  12.             let left = tempArr[i];
  13.             let right = tempArr[i + 1];
  14.             if(index === i || index === i + 1) {
  15.                 // is the index referring to one of these two nodes
  16.                 const isLeft = !(index === i);
  17.                 const data = isLeft ? left : right;
  18.                 if (data) {
  19.                     proof.push({
  20.                         left: isLeft,
  21.                         data
  22.                     });
  23.                 }
  24.             }
  25.             if (right) {
  26.                 newArr.push(this.concat(left, right))
  27.             } else {
  28.                 newArr.push(left);
  29.             }
  30.         }
  31.         return this.getProof(Math.floor(index/2), newArr, proof);
  32.     }
  33.     getRoot(tempArr = this.arr, newArr = []) {
  34.         if (tempArr.length === 1) return tempArr[0];
  35.         for (let i = 0; i < tempArr.length; i += 2) {
  36.             if (tempArr[i + 1]) {
  37.                 newArr.push(this.concat(tempArr[i], tempArr[i + 1]))
  38.             } else {
  39.                 newArr.push(tempArr[i])
  40.             }
  41.         }
  42.         return this.getRoot(newArr)
  43.     }
  44. }
  45. module.exports = MerkleTree;
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top