diff --git a/index.js b/index.js index e400979..70735ca 100644 --- a/index.js +++ b/index.js @@ -39,8 +39,7 @@ class MerkleTree { } createHashes(nodes) { - - while (nodes.length !== 1) { + while (nodes.length > 1) { const layerIndex = this.layers.length @@ -118,7 +117,7 @@ class MerkleTree { * const root = tree.getRoot() */ getRoot() { - return this.layers[this.layers.length-1][0] + return this.layers[this.layers.length-1][0] || Buffer.from([]) } /** diff --git a/package-lock.json b/package-lock.json index 3b5d7c4..45234e1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "merkletreejs", - "version": "0.0.9", + "version": "0.0.14", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 2ac6111..ea28799 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "merkletreejs", - "version": "0.0.14", + "version": "0.0.15", "description": "Construct Merkle Trees and verify proofs", "main": "index.js", "types": "index.d.ts", diff --git a/test/index.js b/test/index.js index 8ece5a8..47a5f33 100644 --- a/test/index.js +++ b/test/index.js @@ -222,3 +222,29 @@ test('sha-256 with option.isBitcoinTree', t => { t.equal(tree.verify(proof_0, leaves[0], root), true) }) + +test('sha256 - no leaves', t => { + t.plan(1) + + const leaves = [] + const tree = new MerkleTree(leaves, sha256) + + const root = '' + t.equal(tree.getRoot().toString('hex'), root) +}) + +test('sha256 - 1,000,000 leaves', t => { + t.plan(1) + + let values = [] + for (let i = 0; i < 1e6; i++) { + values.push(`${i}`) + } + + const leaves = values.map(x => sha256(x)) + + const tree = new MerkleTree(leaves, sha256) + + const root = '101dd357df60384d254330fe118e3046871767c2748ebd62ce031c117df483da' + t.equal(tree.getRoot().toString('hex'), root) +})