fix infinite loop bug if no leaves

This commit is contained in:
Miguel Mota 2018-10-25 22:04:51 -07:00
parent 8d0092a0e0
commit a8bb50b50b
4 changed files with 30 additions and 5 deletions

View File

@ -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([])
}
/**

2
package-lock.json generated
View File

@ -1,6 +1,6 @@
{
"name": "merkletreejs",
"version": "0.0.9",
"version": "0.0.14",
"lockfileVersion": 1,
"requires": true,
"dependencies": {

View File

@ -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",

View File

@ -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)
})