diff --git a/index.ts b/index.ts index 7a59013..5242654 100644 --- a/index.ts +++ b/index.ts @@ -765,7 +765,11 @@ export class MerkleTree { while (i < indexqueue.length) { const index = indexqueue[i] if (index >= 2 && ({}).hasOwnProperty.call(tree, index ^ 1)) { - tree[(index / 2) | 0] = this.hashAlgo(Buffer.concat([tree[index - (index % 2)], tree[index - (index % 2) + 1]])) + let pair = [tree[index - (index % 2)], tree[index - (index % 2) + 1]] + if (this.sortPairs) { + pair = pair.sort(Buffer.compare) + } + tree[(index / 2) | 0] = this.hashAlgo(Buffer.concat(pair)) indexqueue.push((index / 2) | 0) } i += 1 diff --git a/test/merkletree.test.js b/test/merkletree.test.js index ed3291c..f8d14d3 100644 --- a/test/merkletree.test.js +++ b/test/merkletree.test.js @@ -696,6 +696,30 @@ test('sha256 getMultiProof', t => { t.equal(tree.verifyMultiProof(root, indices, tLeaves, depth, proof), true) }) +test('sha256 getMultiProof with pairs sorted', t => { + t.plan(1) + + const leaves = Array(16).fill(0).map((x, i) => { + const b = Buffer.alloc(32) + b.writeUIntLE(i, 31, 1) + return b + }) + + const tree = new MerkleTree(leaves, sha256, { sortPairs: true }) + + const root = tree.getHexRoot() + + const i = 100 + const indices = Array(16).fill(0).map((x, j) => j).filter(j => (i >> j) % 2 === 1) + + const proof = tree.getMultiProof(indices) + + const depth = tree.getDepth() + + const tLeaves = indices.map(i => leaves[i]) + t.equal(tree.verifyMultiProof(root, indices, tLeaves, depth, proof), true) +}) + test('sha256 getMultiProof using tree array', t => { t.plan(5)