add proof leaf method

This commit is contained in:
Sergei SMART 2022-03-02 13:22:54 +10:00
parent 12f95d97ee
commit e0817b8389
5 changed files with 17 additions and 6 deletions

1
.gitignore vendored
View File

@ -4,3 +4,4 @@ lib
yarn-error.log
.idea
.nyc_output
.run

View File

@ -1,7 +1,6 @@
import {
Element,
HashFunction,
Index,
MerkleTreeOptions,
ProofPath,
SerializedTreeState,
@ -147,7 +146,7 @@ export default class MerkleTree {
* @param {number} index Leaf index to generate path for
* @returns {{pathElements: Object[], pathIndex: number[]}} An object containing adjacent elements and left-right index
*/
path(index: Index): ProofPath {
path(index: number): ProofPath {
if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) {
throw new Error('Index out of bounds: ' + index)
}
@ -194,8 +193,7 @@ export default class MerkleTree {
}
getTreeEdge(edgeElement: Element): TreeEdge {
const leaves = this._layers[0]
const edgeIndex = leaves.indexOf(edgeElement)
const edgeIndex = this.indexOf(edgeElement)
if (edgeIndex <= -1) {
throw new Error('Element not found')
}

View File

@ -167,7 +167,7 @@ export class PartialMerkleTree {
}
}
path(index: Element): ProofPath {
path(index: number): ProofPath {
if (isNaN(Number(index)) || index < 0 || index >= this._layers[0].length) {
throw new Error('Index out of bounds: ' + index)
}
@ -205,6 +205,11 @@ export class PartialMerkleTree {
}
}
proof(element: Element): ProofPath {
const index = this.indexOf(element)
return this.path(index)
}
serialize(): SerializedPartialTreeState {
const leaves = this.layers[0].slice(this._edgeLeaf.index)
return {

View File

@ -38,6 +38,5 @@ export type TreeEdge = {
edgePath: ProofPath;
edgeIndex: number
}
export type Index = Element
export type LeafWithIndex = { index: number, data: Element }

View File

@ -163,6 +163,13 @@ describe('PartialMerkleTree', () => {
})
})
describe('#proof', () => {
it('should return proof for known leaf', () => {
const { partialTree } = getTestTrees(10, [1, 2, 3, 4, 5], 3)
assert.deepEqual(partialTree.proof(4), partialTree.path(3))
})
})
describe('#getters', () => {
it('should return capacity', () => {
const levels = 10
@ -207,6 +214,7 @@ describe('PartialMerkleTree', () => {
const { partialTree } = getTestTrees(10, [1, 2, 3, 4, 5, 6, 7, 8, 9], 5)
should().throw((() => partialTree.path(-1)), 'Index out of bounds: -1')
should().throw((() => partialTree.path(10)), 'Index out of bounds: 10')
// @ts-ignore
should().throw((() => partialTree.path('qwe')), 'Index out of bounds: qwe')
})