merkletreejs › Globals › "src/MerkleTree" › MerkleTree
Class reprensenting a Merkle Tree
namespace
MerkleTree
-
↳ MerkleTree
- addLeaf
- addLeaves
- bigNumberify
- binarySearch
- bufferIndexOf
- bufferToHex
- bufferify
- bufferifyFn
- getDepth
- getHexLayers
- getHexLayersFlat
- getHexLeaves
- getHexMultiProof
- getHexProof
- getHexProofs
- getHexRoot
- getLayerCount
- getLayers
- getLayersAsObject
- getLayersFlat
- getLeaf
- getLeafCount
- getLeafIndex
- getLeaves
- getMultiProof
- getOptions
- getPositionalHexProof
- getProof
- getProofFlags
- getProofIndices
- getProofs
- getProofsDFS
- getRoot
- isHexString
- isUnevenTree
- linearSearch
- log2
- resetTree
- toString
- toTreeString
- verify
- verifyMultiProof
- verifyMultiProofWithFlags
- zip
- bigNumberify
- binarySearch
- bufferToHex
- bufferify
- getMultiProof
- hexZeroPad
- isHexString
- linearSearch
- marshalLeaves
- marshalProof
- marshalTree
- unmarshalLeaves
- unmarshalProof
- unmarshalTree
- verify
+ new MerkleTree(leaves
: any[], hashFn
: any, options
: Options): MerkleTree
desc
Constructs a Merkle Tree.
All nodes and leaves are stored as Buffers.
Lonely leaf nodes are promoted to the next level up without being hashed again.
example
const MerkleTree = require('merkletreejs')
const crypto = require('crypto')
function sha256(data) {
// returns Buffer
return crypto.createHash('sha256').update(data).digest()
}
const leaves = ['a', 'b', 'c'].map(value => keccak(value))
const tree = new MerkleTree(leaves, sha256)
Parameters:
Name | Type | Default | Description |
---|---|---|---|
leaves |
any[] | - | Array of hashed leaves. Each leaf must be a Buffer. |
hashFn |
any | SHA256 | - |
options |
Options | {} | Additional options |
Returns: MerkleTree
▸ addLeaf(leaf
: TLeaf, shouldHash
: boolean): void
addLeaf
desc
Adds a leaf to the tree and re-calculates layers.
example
tree.addLeaf(newLeaf)
Parameters:
Name | Type | Default |
---|---|---|
leaf |
TLeaf | - |
shouldHash |
boolean | false |
Returns: void
▸ addLeaves(leaves
: TLeaf[], shouldHash
: boolean): void
addLeaves
desc
Adds multiple leaves to the tree and re-calculates layers.
example
tree.addLeaves(newLeaves)
Parameters:
Name | Type | Default |
---|---|---|
leaves |
TLeaf[] | - |
shouldHash |
boolean | false |
Returns: void
▸ bigNumberify(value
: any): BigInt
Inherited from Base.bigNumberify
Parameters:
Name | Type |
---|---|
value |
any |
Returns: BigInt
▸ binarySearch(array
: Buffer[], element
: Buffer, compareFunction
: function): number
Inherited from Base.binarySearch
binarySearch
desc
Returns the first index of which given item is found in array using binary search.
example
const index = tree.binarySearch(array, element, Buffer.compare)
Parameters:
▪ array: Buffer[]
Array of items.
▪ element: Buffer
Item to find.
▪ compareFunction: function
▸ (a
: unknown, b
: unknown): number
Parameters:
Name | Type |
---|---|
a |
unknown |
b |
unknown |
Returns: number
- Index number
▸ bufferIndexOf(array
: Buffer[], element
: Buffer, isSorted
: boolean): number
Inherited from Base.bufferIndexOf
bufferIndexOf
desc
Returns the first index of which given buffer is found in array.
example
const index = tree.bufferIndexOf(haystack, needle)
Parameters:
Name | Type | Default |
---|---|---|
array |
Buffer[] | - |
element |
Buffer | - |
isSorted |
boolean | false |
Returns: number
- Index number
▸ bufferToHex(value
: Buffer, withPrefix
: boolean): string
Inherited from Base.bufferToHex
bufferToHex
desc
Returns a hex string with 0x prefix for given buffer.
example
const hexStr = tree.bufferToHex(Buffer.from('A'))
Parameters:
Name | Type | Default |
---|---|---|
value |
Buffer | - |
withPrefix |
boolean | true |
Returns: string
▸ bufferify(value
: any): Buffer
bufferify
desc
Returns a buffer type for the given value.
example
const buf = tree.bufferify('0x1234')
Parameters:
Name | Type |
---|---|
value |
any |
Returns: Buffer
▸ bufferifyFn(f
: any): any
Inherited from Base.bufferifyFn
bufferifyFn
desc
Returns a function that will bufferify the return value.
example
const fn = tree.bufferifyFn((value) => sha256(value))
Parameters:
Name | Type |
---|---|
f |
any |
Returns: any
▸ getDepth(): number
getDepth
desc
Returns the tree depth (number of layers)
example
const depth = tree.getDepth()
Returns: number
▸ getHexLayers(): string[]
getHexLayers
desc
Returns multi-dimensional array of all layers of Merkle Tree, including leaves and root as hex strings.
example
const layers = tree.getHexLayers()
Returns: string[]
▸ getHexLayersFlat(): string[]
getHexLayersFlat
desc
Returns single flat array of all layers of Merkle Tree, including leaves and root as hex string.
example
const layers = tree.getHexLayersFlat()
Returns: string[]
▸ getHexLeaves(): string[]
getHexLeaves
desc
Returns array of leaves of Merkle Tree as hex strings.
example
const leaves = tree.getHexLeaves()
Returns: string[]
▸ getHexMultiProof(tree
: Buffer[] | string[], indices
: number[]): string[]
getHexMultiProof
desc
Returns the multiproof for given tree indices as hex strings.
example
const indices = [2, 5, 6]
const proof = tree.getHexMultiProof(indices)
Parameters:
Name | Type | Description |
---|---|---|
tree |
Buffer[] | string[] | - |
indices |
number[] | Tree indices. |
Returns: string[]
- Multiproofs as hex strings.
▸ getHexProof(leaf
: Buffer | string, index?
: number): string[]
getHexProof
desc
Returns the proof for a target leaf as hex strings.
example
const proof = tree.getHexProof(leaves[2])
Parameters:
Name | Type | Description |
---|---|---|
leaf |
Buffer | string | Target leaf |
index? |
number | - |
Returns: string[]
- Proof array as hex strings.
▸ getHexProofs(): string[]
getHexProofs
desc
Returns the proofs for all leaves as hex strings.
example
const proofs = tree.getHexProofs()
Returns: string[]
- Proofs array as hex strings.
▸ getHexRoot(): string
getHexRoot
desc
Returns the Merkle root hash as a hex string.
example
const root = tree.getHexRoot()
Returns: string
▸ getLayerCount(): number
getLayerCount
desc
Returns the total number of layers.
example
const count = tree.getLayerCount()
Returns: number
▸ getLayers(): Buffer[]
getLayers
desc
Returns multi-dimensional array of all layers of Merkle Tree, including leaves and root.
example
const layers = tree.getLayers()
Returns: Buffer[]
▸ getLayersAsObject(): any
getLayersAsObject
desc
Returns the layers as nested objects instead of an array.
example
const layersObj = tree.getLayersAsObject()
Returns: any
▸ getLayersFlat(): Buffer[]
getLayersFlat
desc
Returns single flat array of all layers of Merkle Tree, including leaves and root.
example
const layers = tree.getLayersFlat()
Returns: Buffer[]
▸ getLeaf(index
: number): Buffer
getLeaf
desc
Returns the leaf at the given index.
example
const leaf = tree.getLeaf(1)
Parameters:
Name | Type |
---|---|
index |
number |
Returns: Buffer
▸ getLeafCount(): number
getLeafCount
desc
Returns the total number of leaves.
example
const count = tree.getLeafCount()
Returns: number
▸ getLeafIndex(target
: TLeaf): number
getLeafIndex
desc
Returns the index of the given leaf, or -1 if the leaf is not found.
example
const leaf = Buffer.from('abc')
const index = tree.getLeafIndex(leaf)
Parameters:
Name | Type |
---|---|
target |
TLeaf |
Returns: number
▸ getLeaves(values?
: any[]): Buffer[]
getLeaves
desc
Returns array of leaves of Merkle Tree.
example
const leaves = tree.getLeaves()
Parameters:
Name | Type |
---|---|
values? |
any[] |
Returns: Buffer[]
▸ getMultiProof(tree?
: any[], indices?
: any[]): Buffer[]
getMultiProof
desc
Returns the multiproof for given tree indices.
example
const indices = [2, 5, 6]
const proof = tree.getMultiProof(indices)
Parameters:
Name | Type | Description |
---|---|---|
tree? |
any[] | - |
indices? |
any[] | Tree indices. |
Returns: Buffer[]
- Multiproofs
▸ getOptions(): object
Returns: object
-
complete: boolean = this.complete
-
duplicateOdd: boolean = this.duplicateOdd
-
fillDefaultHash: string = this.fillDefaultHash?.toString() ?? null
-
hashLeaves: boolean = this.hashLeaves
-
isBitcoinTree: boolean = this.isBitcoinTree
-
sort: boolean = this.sort
-
sortLeaves: boolean = this.sortLeaves
-
sortPairs: boolean = this.sortPairs
▸ getPositionalHexProof(leaf
: Buffer | string, index?
: number): (string | number)[][]
getPositionalHexProof
desc
Returns the proof for a target leaf as hex strings and the position in binary (left == 0).
example
const proof = tree.getPositionalHexProof(leaves[2])
Parameters:
Name | Type | Description |
---|---|---|
leaf |
Buffer | string | Target leaf |
index? |
number | - |
Returns: (string | number)[][]
- Proof array as hex strings. position at index 0
▸ getProof(leaf
: Buffer | string, index?
: number): object[]
getProof
desc
Returns the proof for a target leaf.
example
const proof = tree.getProof(leaves[2])
example
const leaves = ['a', 'b', 'a'].map(value => keccak(value))
const tree = new MerkleTree(leaves, keccak)
const proof = tree.getProof(leaves[2], 2)
Parameters:
Name | Type | Description |
---|---|---|
leaf |
Buffer | string | Target leaf |
index? |
number | - |
Returns: object[]
- Array of objects containing a position property of type string with values of 'left' or 'right' and a data property of type Buffer.
▸ getProofFlags(leaves
: any[], proofs
: Buffer[] | string[]): boolean[]
getProofFlags
desc
Returns list of booleans where proofs should be used instead of hashing.
Proof flags are used in the Solidity multiproof verifiers.
example
const indices = [2, 5, 6]
const proof = tree.getMultiProof(indices)
const proofFlags = tree.getProofFlags(leaves, proof)
Parameters:
Name | Type |
---|---|
leaves |
any[] |
proofs |
Buffer[] | string[] |
Returns: boolean[]
- Boolean flags
▸ getProofIndices(treeIndices
: number[], depth
: number): number[]
getProofIndices
desc
Returns the proof indices for given tree indices.
example
const proofIndices = tree.getProofIndices([2,5,6], 4)
console.log(proofIndices) // [ 23, 20, 19, 8, 3 ]
Parameters:
Name | Type | Description |
---|---|---|
treeIndices |
number[] | Tree indices |
depth |
number | Tree depth; number of layers. |
Returns: number[]
- Proof indices
▸ getProofs(): any[]
getProofs
desc
Returns the proofs for all leaves.
example
const proofs = tree.getProofs()
example
const leaves = ['a', 'b', 'a'].map(value => keccak(value))
const tree = new MerkleTree(leaves, keccak)
const proofs = tree.getProofs()
Returns: any[]
- Array of objects containing a position property of type string with values of 'left' or 'right' and a data property of type Buffer for all leaves.
▸ getProofsDFS(currentLayer
: any, index
: any, proof
: any, proofs
: any): any[]
getProofsDFS
desc
Get all proofs through single traverse
example
const layers = tree.getLayers()
const index = 0;
let proof = [];
let proofs = [];
const proof = tree.getProofsDFS(layers, index, proof, proofs)
Parameters:
Name | Type | Description |
---|---|---|
currentLayer |
any | Current layer index in traverse. |
index |
any | Current tarvese node index in traverse. |
proof |
any | Proof chain for single leaf. |
proofs |
any | Proofs for all leaves |
Returns: any[]
▸ getRoot(): Buffer
getRoot
desc
Returns the Merkle root hash as a Buffer.
example
const root = tree.getRoot()
Returns: Buffer
▸ isHexString(value
: string): boolean
Inherited from Base.isHexString
isHexString
desc
Returns true if value is a hex string.
example
console.log(MerkleTree.isHexString('0x1234'))
Parameters:
Name | Type |
---|---|
value |
string |
Returns: boolean
▸ isUnevenTree(treeLayers?
: any[]): boolean
Parameters:
Name | Type |
---|---|
treeLayers? |
any[] |
Returns: boolean
▸ linearSearch(array
: Buffer[], element
: Buffer, eqChecker
: function): number
Inherited from Base.linearSearch
linearSearch
desc
Returns the first index of which given item is found in array using linear search.
example
const index = tree.linearSearch(array, element, (a, b) => a === b)
Parameters:
▪ array: Buffer[]
Array of items.
▪ element: Buffer
Item to find.
▪ eqChecker: function
▸ (a
: unknown, b
: unknown): boolean
Parameters:
Name | Type |
---|---|
a |
unknown |
b |
unknown |
Returns: number
- Index number
▸ log2(n
: number): number
log2
desc
Returns the log2 of number.
Parameters:
Name | Type |
---|---|
n |
number |
Returns: number
▸ print(): void
desc
Prints out a visual representation of the merkle tree.
example
tree.print()
Returns: void
▸ resetTree(): void
resetTree
desc
Resets the tree by clearing the leaves and layers.
example
tree.resetTree()
Returns: void
▸ toString(): string
toString
desc
Returns a visual representation of the merkle tree as a string.
example
console.log(tree.toString())
Returns: string
▸ toTreeString(): string
toTreeString
desc
Returns a visual representation of the merkle tree as a string.
example
console.log(tree.toTreeString())
Returns: string
▸ verify(proof
: any[], targetNode
: Buffer | string, root
: Buffer | string): boolean
verify
desc
Returns true if the proof path (array of hashes) can connect the target node
to the Merkle root.
example
const root = tree.getRoot()
const proof = tree.getProof(leaves[2])
const verified = tree.verify(proof, leaves[2], root)
Parameters:
Name | Type | Description |
---|---|---|
proof |
any[] | Array of proof objects that should connect target node to Merkle root. |
targetNode |
Buffer | string | Target node Buffer |
root |
Buffer | string | Merkle root Buffer |
Returns: boolean
▸ verifyMultiProof(root
: Buffer | string, proofIndices
: number[], proofLeaves
: Buffer[] | string[], leavesCount
: number, proof
: Buffer[] | string[]): boolean
verifyMultiProof
desc
Returns true if the multiproofs can connect the leaves to the Merkle root.
example
const leaves = tree.getLeaves()
const root = tree.getRoot()
const treeFlat = tree.getLayersFlat()
const leavesCount = leaves.length
const proofIndices = [2, 5, 6]
const proofLeaves = proofIndices.map(i => leaves[i])
const proof = tree.getMultiProof(treeFlat, indices)
const verified = tree.verifyMultiProof(root, proofIndices, proofLeaves, leavesCount, proof)
Parameters:
Name | Type | Description |
---|---|---|
root |
Buffer | string | Merkle tree root |
proofIndices |
number[] | Leave indices for proof |
proofLeaves |
Buffer[] | string[] | Leaf values at indices for proof |
leavesCount |
number | Count of original leaves |
proof |
Buffer[] | string[] | Multiproofs given indices |
Returns: boolean
▸ verifyMultiProofWithFlags(root
: Buffer | string, leaves
: TLeaf[], proofs
: Buffer[] | string[], proofFlag
: boolean[]): boolean
Parameters:
Name | Type |
---|---|
root |
Buffer | string |
leaves |
TLeaf[] |
proofs |
Buffer[] | string[] |
proofFlag |
boolean[] |
Returns: boolean
▸ zip(a
: any[], b
: any[]): any[][]
zip
desc
Returns true if value is a hex string.
example
const zipped = tree.zip(['a', 'b'],['A', 'B'])
console.log(zipped) // [ [ 'a', 'A' ], [ 'b', 'B' ] ]
Parameters:
Name | Type | Description |
---|---|---|
a |
any[] | first array |
b |
any[] | second array |
Returns: any[][]
▸ bigNumberify(value
: any): BigInt
Inherited from Base.bigNumberify
Parameters:
Name | Type |
---|---|
value |
any |
Returns: BigInt
▸ binarySearch(array
: Buffer[], element
: Buffer, compareFunction
: function): number
Inherited from Base.binarySearch
binarySearch
desc
Returns the first index of which given item is found in array using binary search.
example
const index = MerkleTree.binarySearch(array, element, Buffer.compare)
Parameters:
▪ array: Buffer[]
Array of items.
▪ element: Buffer
Item to find.
▪ compareFunction: function
▸ (a
: unknown, b
: unknown): number
Parameters:
Name | Type |
---|---|
a |
unknown |
b |
unknown |
Returns: number
- Index number
▸ bufferToHex(value
: Buffer, withPrefix
: boolean): string
Inherited from Base.bufferToHex
bufferToHex
desc
Returns a hex string with 0x prefix for given buffer.
example
const hexStr = MerkleTree.bufferToHex(Buffer.from('A'))
Parameters:
Name | Type | Default |
---|---|---|
value |
Buffer | - |
withPrefix |
boolean | true |
Returns: string
▸ bufferify(value
: any): Buffer
bufferify
desc
Returns a buffer type for the given value.
example
const buf = MerkleTree.bufferify('0x1234')
Parameters:
Name | Type |
---|---|
value |
any |
Returns: Buffer
▸ getMultiProof(tree
: Buffer[] | string[], indices
: number[]): Buffer[]
getMultiProof
desc
Returns the multiproof for given tree indices.
example
const flatTree = tree.getLayersFlat()
const indices = [2, 5, 6]
const proof = MerkleTree.getMultiProof(flatTree, indices)
Parameters:
Name | Type | Description |
---|---|---|
tree |
Buffer[] | string[] | Tree as a flat array. |
indices |
number[] | Tree indices. |
Returns: Buffer[]
- Multiproofs
▸ hexZeroPad(hexStr
: string, length
: number): string
Inherited from Base.hexZeroPad
Parameters:
Name | Type |
---|---|
hexStr |
string |
length |
number |
Returns: string
▸ isHexString(v
: string): boolean
Inherited from Base.isHexString
isHexString
desc
Returns true if value is a hex string.
example
console.log(MerkleTree.isHexString('0x1234'))
Parameters:
Name | Type |
---|---|
v |
string |
Returns: boolean
▸ linearSearch(array
: Buffer[], element
: Buffer, eqChecker
: function): number
Inherited from Base.linearSearch
linearSearch
desc
Returns the first index of which given item is found in array using linear search.
example
const index = MerkleTree.linearSearch(array, element, (a, b) => a === b)
Parameters:
▪ array: Buffer[]
Array of items.
▪ element: Buffer
Item to find.
▪ eqChecker: function
▸ (a
: unknown, b
: unknown): boolean
Parameters:
Name | Type |
---|---|
a |
unknown |
b |
unknown |
Returns: number
- Index number
▸ marshalLeaves(leaves
: any[]): string
marshalLeaves
desc
Returns array of leaves of Merkle Tree as a JSON string.
example
const jsonStr = MerkleTree.marshalLeaves(leaves)
Parameters:
Name | Type |
---|---|
leaves |
any[] |
Returns: string
- List of leaves as JSON string
▸ marshalProof(proof
: any[]): string
marshalProof
desc
Returns proof array as JSON string.
example
const jsonStr = MerkleTree.marshalProof(proof)
Parameters:
Name | Type | Description |
---|---|---|
proof |
any[] | Merkle tree proof array |
Returns: string
- Proof array as JSON string.
▸ marshalTree(tree
: MerkleTree): string
Parameters:
Name | Type |
---|---|
tree |
MerkleTree |
Returns: string
▸ print(tree
: any): void
desc
Prints out a visual representation of the given merkle tree.
example
MerkleTree.print(tree)
Parameters:
Name | Type | Description |
---|---|---|
tree |
any | Merkle tree instance. |
Returns: void
▸ unmarshalLeaves(jsonStr
: string | object): Buffer[]
unmarshalLeaves
desc
Returns array of leaves of Merkle Tree as a Buffers.
example
const leaves = MerkleTree.unmarshalLeaves(jsonStr)
Parameters:
Name | Type |
---|---|
jsonStr |
string | object |
Returns: Buffer[]
- Unmarshalled list of leaves
▸ unmarshalProof(jsonStr
: string | object): any[]
unmarshalProof
desc
Returns the proof for a target leaf as a list of Buffers.
example
const proof = MerkleTree.unmarshalProof(jsonStr)
Parameters:
Name | Type |
---|---|
jsonStr |
string | object |
Returns: any[]
- Marshalled proof
▸ unmarshalTree(jsonStr
: string | object, hashFn
: any, options
: Options): MerkleTree
Parameters:
Name | Type | Default |
---|---|---|
jsonStr |
string | object | - |
hashFn |
any | SHA256 |
options |
Options | {} |
Returns: MerkleTree
▸ verify(proof
: any[], targetNode
: Buffer | string, root
: Buffer | string, hashFn
: any, options
: Options): boolean
verify
desc
Returns true if the proof path (array of hashes) can connect the target node
to the Merkle root.
example
const verified = MerkleTree.verify(proof, leaf, root, sha256, options)
Parameters:
Name | Type | Default | Description |
---|---|---|---|
proof |
any[] | - | Array of proof objects that should connect target node to Merkle root. |
targetNode |
Buffer | string | - | Target node Buffer |
root |
Buffer | string | - | Merkle root Buffer |
hashFn |
any | SHA256 | - |
options |
Options | {} | Additional options |
Returns: boolean