Class reprensenting a Merkle Tree MerkleTree

Hierarchy (view full)

Constructors

  • Parameters

    • leaves: any[]

      Array of hashed leaves. Each leaf must be a Buffer.

    • OptionalhashFn: any
    • Optionaloptions: Options

      Additional options

    Returns MerkleTree

    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.

    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)

Methods

  • addLeaf

    Parameters

    • leaf: Buffer
    • OptionalshouldHash: boolean

    Returns void

    Adds a leaf to the tree and re-calculates layers.

    tree.addLeaf(newLeaf)
    
  • addLeaves

    Parameters

    • leaves: Buffer[]
    • OptionalshouldHash: boolean

    Returns void

    Adds multiple leaves to the tree and re-calculates layers.

    tree.addLeaves(newLeaves)
    
  • Parameters

    • value: any

    Returns BigInt

  • binarySearch

    Parameters

    • array: Buffer[]

      Array of items.

    • element: Buffer

      Item to find.

    • compareFunction: ((a: unknown, b: unknown) => number)
        • (a, b): number
        • Parameters

          • a: unknown
          • b: unknown

          Returns number

    Returns number

    • Index number

    Returns the first index of which given item is found in array using binary search.

    const index = tree.binarySearch(array, element, Buffer.compare)
    
  • bufferToHex

    Parameters

    • value: Buffer
    • OptionalwithPrefix: boolean

    Returns string

    Returns a hex string with 0x prefix for given buffer.

    const hexStr = tree.bufferToHex(Buffer.from('A'))
    
  • bufferify

    Parameters

    • value: any

    Returns Buffer

    Returns a buffer type for the given value.

    const buf = tree.bufferify('0x1234')
    
  • bufferifyFn

    Parameters

    • f: any

    Returns any

    Returns a function that will bufferify the return value.

    const fn = tree.bufferifyFn((value) => sha256(value))
    
  • getDepth

    Returns number

    Returns the tree depth (number of layers)

    const depth = tree.getDepth()
    
  • getHexLayers

    Returns string[][]

    Returns multi-dimensional array of all layers of Merkle Tree, including leaves and root as hex strings.

    const layers = tree.getHexLayers()
    
  • getHexLayersFlat

    Returns string[]

    Returns single flat array of all layers of Merkle Tree, including leaves and root as hex string.

    const layers = tree.getHexLayersFlat()
    
  • getHexLeaves

    Returns string[]

    Returns array of leaves of Merkle Tree as hex strings.

    const leaves = tree.getHexLeaves()
    
  • getHexMultiProof

    Parameters

    • tree: string[] | Buffer[]
    • indices: number[]

      Tree indices.

    Returns string[]

    • Multiproofs as hex strings.

    Returns the multiproof for given tree indices as hex strings.

    const indices = [2, 5, 6]
    const proof = tree.getHexMultiProof(indices)
  • getHexProof

    Parameters

    • leaf: string | Buffer

      Target leaf

    • Optionalindex: number

      Target leaf index in leaves array. Use if there are leaves containing duplicate data in order to distinguish it.

    Returns string[]

    • Proof array as hex strings.

    Returns the proof for a target leaf as hex strings.

    const proof = tree.getHexProof(leaves[2])
    
  • getHexProofs

    Returns string[]

    • Proofs array as hex strings.

    Returns the proofs for all leaves as hex strings.

    const proofs = tree.getHexProofs()
    
  • getHexRoot

    Returns string

    Returns the Merkle root hash as a hex string.

    const root = tree.getHexRoot()
    
  • getLayerCount

    Returns number

    Returns the total number of layers.

    const count = tree.getLayerCount()
    
  • getLayers

    Returns Buffer[][]

    Returns multi-dimensional array of all layers of Merkle Tree, including leaves and root.

    const layers = tree.getLayers()
    
  • getLayersAsObject

    Returns any

    Returns the layers as nested objects instead of an array.

    const layersObj = tree.getLayersAsObject()
    
  • getLayersFlat

    Returns Buffer[]

    Returns single flat array of all layers of Merkle Tree, including leaves and root.

    const layers = tree.getLayersFlat()
    
  • getLeaf

    Parameters

    • index: number

    Returns Buffer

    Returns the leaf at the given index.

    const leaf = tree.getLeaf(1)
    
  • getLeafCount

    Returns number

    Returns the total number of leaves.

    const count = tree.getLeafCount()
    
  • getLeafIndex

    Parameters

    Returns number

    Returns the index of the given leaf, or -1 if the leaf is not found.

    const leaf = Buffer.from('abc')
    const index = tree.getLeafIndex(leaf)
  • getLeaves

    Parameters

    • Optionalvalues: any[]

    Returns Buffer[]

    Returns array of leaves of Merkle Tree.

    const leaves = tree.getLeaves()
    
  • getMultiProof

    Parameters

    • Optionaltree: any[]
    • Optionalindices: any[]

      Tree indices.

    Returns Buffer[]

    • Multiproofs

    Returns the multiproof for given tree indices.

    const indices = [2, 5, 6]
    const proof = tree.getMultiProof(indices)
  • Returns {
        complete: boolean;
        duplicateOdd: boolean;
        fillDefaultHash: string;
        hashLeaves: boolean;
        isBitcoinTree: boolean;
        sort: boolean;
        sortLeaves: boolean;
        sortPairs: boolean;
    }

    • complete: boolean
    • duplicateOdd: boolean
    • fillDefaultHash: string
    • hashLeaves: boolean
    • isBitcoinTree: boolean
    • sort: boolean
    • sortLeaves: boolean
    • sortPairs: boolean
  • getPositionalHexProof

    Parameters

    • leaf: string | Buffer

      Target leaf

    • Optionalindex: number

      Target leaf index in leaves array. Use if there are leaves containing duplicate data in order to distinguish it.

    Returns (string | number)[][]

    • Proof array as hex strings. position at index 0

    Returns the proof for a target leaf as hex strings and the position in binary (left == 0).

    const proof = tree.getPositionalHexProof(leaves[2])
    
  • getProof

    Parameters

    • leaf: string | Buffer

      Target leaf

    • Optionalindex: number

      Target leaf index in leaves array. Use if there are leaves containing duplicate data in order to distinguish it.

    Returns {
        data: Buffer;
        position: "left" | "right";
    }[]

    • Array of objects containing a position property of type string with values of 'left' or 'right' and a data property of type Buffer.

    Returns the proof for a target leaf.

    const proof = tree.getProof(leaves[2])
    
    const leaves = ['a', 'b', 'a'].map(value => keccak(value))
    const tree = new MerkleTree(leaves, keccak)
    const proof = tree.getProof(leaves[2], 2)
  • getProofFlags

    Parameters

    • leaves: any[]
    • proofs: string[] | Buffer[]

    Returns boolean[]

    • Boolean flags

    Returns list of booleans where proofs should be used instead of hashing. Proof flags are used in the Solidity multiproof verifiers.

    const indices = [2, 5, 6]
    const proof = tree.getMultiProof(indices)
    const proofFlags = tree.getProofFlags(leaves, proof)
  • getProofIndices

    Parameters

    • treeIndices: number[]

      Tree indices

    • depth: number

      Tree depth; number of layers.

    Returns number[]

    • Proof indices

    Returns the proof indices for given tree indices.

    const proofIndices = tree.getProofIndices([2,5,6], 4)
    console.log(proofIndices) // [ 23, 20, 19, 8, 3 ]
  • 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.

    Returns the proofs for all leaves.

    const proofs = tree.getProofs()
    
    const leaves = ['a', 'b', 'a'].map(value => keccak(value))
    const tree = new MerkleTree(leaves, keccak)
    const proofs = tree.getProofs()
  • getProofsDFS

    Parameters

    • 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[]

    Get all proofs through single traverse

    const layers = tree.getLayers()
    const index = 0;
    let proof = [];
    let proofs = [];
    const proof = tree.getProofsDFS(layers, index, proof, proofs)
  • getRoot

    Returns Buffer

    Returns the Merkle root hash as a Buffer.

    const root = tree.getRoot()
    
  • Parameters

    • OptionaltreeLayers: any[]

    Returns boolean

  • linearSearch

    Parameters

    • array: Buffer[]

      Array of items.

    • element: Buffer

      Item to find.

    • eqChecker: ((a: unknown, b: unknown) => boolean)
        • (a, b): boolean
        • Parameters

          • a: unknown
          • b: unknown

          Returns boolean

    Returns number

    • Index number

    Returns the first index of which given item is found in array using linear search.

    const index = tree.linearSearch(array, element, (a, b) => a === b)
    
  • print

    Returns void

    Prints out a visual representation of the merkle tree.

    tree.print()
    
  • resetTree

    Returns void

    Resets the tree by clearing the leaves and layers.

    tree.resetTree()
    
  • toString

    Returns string

    Returns a visual representation of the merkle tree as a string.

    console.log(tree.toString())
    
  • verify

    Parameters

    • proof: any[]

      Array of proof objects that should connect target node to Merkle root.

    • targetNode: string | Buffer

      Target node Buffer

    • root: string | Buffer

      Merkle root Buffer

    Returns boolean

    Returns true if the proof path (array of hashes) can connect the target node to the Merkle root.

    const root = tree.getRoot()
    const proof = tree.getProof(leaves[2])
    const verified = tree.verify(proof, leaves[2], root)
  • verifyMultiProof

    Parameters

    • root: string | Buffer

      Merkle tree root

    • proofIndices: number[]

      Leave indices for proof

    • proofLeaves: string[] | Buffer[]

      Leaf values at indices for proof

    • leavesCount: number

      Count of original leaves

    • proof: string[] | Buffer[]

      Multiproofs given indices

    Returns boolean

    Returns true if the multiproofs can connect the leaves to the Merkle root.

    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

    Returns boolean

  • Parameters

    • value: any

    Returns BigInt

  • binarySearch

    Parameters

    • array: Buffer[]

      Array of items.

    • element: Buffer

      Item to find.

    • compareFunction: ((a: unknown, b: unknown) => number)
        • (a, b): number
        • Parameters

          • a: unknown
          • b: unknown

          Returns number

    Returns number

    • Index number

    Returns the first index of which given item is found in array using binary search.

    const index = MerkleTree.binarySearch(array, element, Buffer.compare)
    
  • bufferToHex

    Parameters

    • value: Buffer
    • OptionalwithPrefix: boolean

    Returns string

    Returns a hex string with 0x prefix for given buffer.

    const hexStr = MerkleTree.bufferToHex(Buffer.from('A'))
    
  • bufferify

    Parameters

    • value: any

    Returns Buffer

    Returns a buffer type for the given value.

    const buf = MerkleTree.bufferify('0x1234')
    
  • getMultiProof

    Parameters

    • tree: string[] | Buffer[]

      Tree as a flat array.

    • indices: number[]

      Tree indices.

    Returns Buffer[]

    • Multiproofs

    Returns the multiproof for given tree indices.

    const flatTree = tree.getLayersFlat()
    const indices = [2, 5, 6]
    const proof = MerkleTree.getMultiProof(flatTree, indices)
  • Parameters

    • hexStr: string
    • length: number

    Returns string

  • isHexString

    Parameters

    • v: string

    Returns boolean

    Returns true if value is a hex string.

    console.log(MerkleTree.isHexString('0x1234'))
    
  • linearSearch

    Parameters

    • array: Buffer[]

      Array of items.

    • element: Buffer

      Item to find.

    • eqChecker: ((a: unknown, b: unknown) => boolean)
        • (a, b): boolean
        • Parameters

          • a: unknown
          • b: unknown

          Returns boolean

    Returns number

    • Index number

    Returns the first index of which given item is found in array using linear search.

    const index = MerkleTree.linearSearch(array, element, (a, b) => a === b)
    
  • marshalLeaves

    Parameters

    • leaves: any[]

    Returns string

    • List of leaves as JSON string

    Returns array of leaves of Merkle Tree as a JSON string.

    const jsonStr = MerkleTree.marshalLeaves(leaves)
    
  • marshalProof

    Parameters

    • proof: any[]

      Merkle tree proof array

    Returns string

    • Proof array as JSON string.

    Returns proof array as JSON string.

    const jsonStr = MerkleTree.marshalProof(proof)
    
  • Parameters

    Returns string

  • print

    Parameters

    • tree: any

      Merkle tree instance.

    Returns void

    Prints out a visual representation of the given merkle tree.

    MerkleTree.print(tree)
    
  • unmarshalLeaves

    Parameters

    • jsonStr: string | object

    Returns Buffer[]

    • Unmarshalled list of leaves

    Returns array of leaves of Merkle Tree as a Buffers.

    const leaves = MerkleTree.unmarshalLeaves(jsonStr)
    
  • unmarshalProof

    Parameters

    • jsonStr: string | object

    Returns any[]

    • Marshalled proof

    Returns the proof for a target leaf as a list of Buffers.

    const proof = MerkleTree.unmarshalProof(jsonStr)
    
  • Parameters

    • jsonStr: string | object
    • OptionalhashFn: any
    • Optionaloptions: Options

    Returns MerkleTree

  • verify

    Parameters

    • proof: any[]

      Array of proof objects that should connect target node to Merkle root.

    • targetNode: string | Buffer

      Target node Buffer

    • root: string | Buffer

      Merkle root Buffer

    • OptionalhashFn: any
    • Optionaloptions: Options

      Additional options

    Returns boolean

    Returns true if the proof path (array of hashes) can connect the target node to the Merkle root.

    const verified = MerkleTree.verify(proof, leaf, root, sha256, options)