From f6f94f60cff409915f6e443d6c822edc5e61c4ab Mon Sep 17 00:00:00 2001 From: theSatvik Date: Mon, 30 Aug 2021 16:04:18 +0530 Subject: [PATCH] Defined and declared class MerkleTree with constructor --- .../tree/merkle-tree/MerkleTree.js | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/data-structures/tree/merkle-tree/MerkleTree.js diff --git a/src/data-structures/tree/merkle-tree/MerkleTree.js b/src/data-structures/tree/merkle-tree/MerkleTree.js new file mode 100644 index 00000000..4b72e4b7 --- /dev/null +++ b/src/data-structures/tree/merkle-tree/MerkleTree.js @@ -0,0 +1,49 @@ +var crypto = require('crypto'); + +class MerkleTree { + /** + * @desc Constructs a Merkle Tree. + * If the number of nodes is odd, last node is duplicated while calculating next level up: + * Hash(LN) = Hash(LN+LN) + * @param {[]} array - Array of inputs. Each value must be a string/number/object. + * @param {Object} options - Additional options: {inputHash, hash} + * inputHash: - string + * ex: 'sha256' | 'md5' + * (*listOfSupportedHashes = crypto.getHashes()) + * + * - function + * ex: + * function sha256(data) { + * return crypto.createHash('sha256').update(data).digest('hex') + * } + * + * @example + * ```js + * const tree = new MerkleTree([1,2,3,4,5,6], {hash: 'md5'}) + * ``` + */ + + constructor (array, option = {}) { + if (!array) { + array = [] + } else { + if (!Array.isArray(array)) { + throw new Error('Input has to be an array') + } + } + + if (option.constructor !== Object) { + throw new Error('Invalid option object: has to be {hash, inputHash}') + } + + this.option = { + hash: option.hash || 'sha256', + inputHash: option.inputHash || 'sha256' + } + this.originalArray = array + this.buildTree() + } + +} + +module.exports = MerkleTree \ No newline at end of file