From 2992aafcc8dc013f2c6cc2942251aeba13a63264 Mon Sep 17 00:00:00 2001 From: theSatvik Date: Mon, 30 Aug 2021 16:05:14 +0530 Subject: [PATCH] added buildTree method --- .../tree/merkle-tree/MerkleTree.js | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/data-structures/tree/merkle-tree/MerkleTree.js b/src/data-structures/tree/merkle-tree/MerkleTree.js index 4b72e4b7..ce4efba3 100644 --- a/src/data-structures/tree/merkle-tree/MerkleTree.js +++ b/src/data-structures/tree/merkle-tree/MerkleTree.js @@ -43,6 +43,33 @@ class MerkleTree { this.originalArray = array this.buildTree() } + buildTree() { + // Hash all the inputs with inputHash() + this.hashedArray = this.originalArray.map(item => { + return this.inputHash(item) + }) + // Initiate a 2D map to store all the hash values + this.fullPath = [] + // Hash first row + let currentRow = this.hashedArray.map(item => { + return this.hash(item) + }) + while (currentRow.length > 1) { + let nextRow = [] + if ((currentRow.length % 2) !== 0) { + // Duplicate last node in the row if the node is alone + currentRow.push(currentRow[currentRow.length-1]) + } + for (let i = 0; i < currentRow.length; i += 2) { + nextRow.push(this.hash(currentRow[i]+currentRow[i+1])) + } + this.fullPath.unshift(currentRow) + currentRow = nextRow + } + this.fullPath.unshift(currentRow) + // Set the final hash as root + this.root = currentRow[0] + } }