### MerkleTree.js Quick Start Source: https://merkletree.js.org Demonstrates basic usage of MerkleTree.js, including creating leaves, building a tree, getting the root, generating a proof, and verifying it. ```javascript import { MerkleTree } from 'merkletreejs' import SHA256 from 'crypto-js/sha256' // Create leaves (typically hashed data) const leaves = ['a', 'b', 'c', 'd'].map(x => SHA256(x)) // Create tree const tree = new MerkleTree(leaves, SHA256) // Get root const root = tree.getRoot() const hexRoot = tree.getHexRoot() // Generate proof const leaf = SHA256('b') const proof = tree.getProof(leaf) // Verify proof const verified = tree.verify(proof, leaf, root) console.log('Proof verified:', verified) // true ``` -------------------------------- ### Install MerkleTree.js Source: https://merkletree.js.org Install the merkletreejs library using npm. ```bash npm install merkletreejs ``` -------------------------------- ### Basic Usage Example Source: https://merkletree.js.org A simple example demonstrating the creation of a Merkle tree, generation of a proof, and verification. ```APIDOC ## Basic Usage ### Description This example shows the fundamental workflow of creating a Merkle tree, retrieving the root, generating a proof for a specific leaf, and verifying that proof. ### Method N/A (Example) ### Endpoint N/A ### Parameters N/A ### Request Example ```javascript import { createMerkleTree, getHexRoot, getProof, verifyProof } from 'merkletreejs' // Create tree const leaves = ['a', 'b', 'c', 'd'] const tree = createMerkleTree(leaves) const root = getHexRoot(tree) // Generate proof const proof = getProof(tree, 'b') // Verify proof const isValid = verifyProof(proof, 'b', root) console.log('Valid:', isValid) // true ``` ### Response N/A ``` -------------------------------- ### Multi-Proof Usage Example Source: https://merkletree.js.org Example of generating and verifying a multi-proof with a complete tree. ```javascript const tree = new MerkleTree(leaves, SHA256, { complete: true }) const indices = [0, 2, 4] const multiProof = tree.getMultiProof(indices) const proofLeaves = indices.map(i => leaves[i]) const verified = tree.verifyMultiProof( tree.getRoot(), indices, proofLeaves, leaves.length, multiProof ) ``` -------------------------------- ### Get All Proofs Source: https://merkletree.js.org Retrieves proofs for all leaves in the tree. ```javascript const allProofs = getProofs(tree) ``` ```javascript const allHexProofs = getHexProofs(tree) ``` -------------------------------- ### Get Proofs Source: https://merkletree.js.org Retrieve proofs for all leaves in the tree. ```javascript const allProofs = tree.getProofs() ``` ```javascript const allHexProofs = tree.getHexProofs() ``` -------------------------------- ### Basic Usage Example Source: https://merkletree.js.org Standard workflow for creating a tree, generating a root, and verifying a proof. ```javascript import { MerkleTree } from 'merkletreejs' import SHA256 from 'crypto-js/sha256' // Prepare data const leaves = ['alice', 'bob', 'charlie', 'dave'].map(x => SHA256(x)) // Create tree const tree = new MerkleTree(leaves, SHA256) // Get root const root = tree.getHexRoot() console.log('Root:', root) // Generate and verify proof const leaf = SHA256('bob') const proof = tree.getProof(leaf) const verified = tree.verify(proof, leaf, tree.getRoot()) console.log('Proof verified:', verified) ``` -------------------------------- ### Get Hex Proof Source: https://merkletree.js.org Retrieves a proof as hex strings. ```javascript const hexProof = getHexProof(tree, 'targetLeaf') ``` -------------------------------- ### Quick Start Merkle Tree Source: https://merkletree.js.org Demonstrates basic tree creation, root retrieval, and proof verification. ```javascript import { createMerkleTree, getHexRoot, getProof, verifyProof } from 'merkletreejs' // Create a simple Merkle tree const leaves = ['a', 'b', 'c', 'd'] const tree = createMerkleTree(leaves) const root = getHexRoot(tree) // Generate and verify a proof const proof = getProof(tree, 'b') const isValid = verifyProof(proof, 'b', root) console.log('Proof valid:', isValid) // true ``` -------------------------------- ### Get MultiProof Source: https://merkletree.js.org Retrieves a multiproof for multiple indices. ```javascript const multiProof = getMultiProof(tree, [0, 2, 4]) ``` -------------------------------- ### Get Hex MultiProof Source: https://merkletree.js.org Retrieves a multiproof as hex strings. ```javascript const hexMultiProof = getHexMultiProof(tree, [0, 2, 4]) ``` -------------------------------- ### Merkle Tree API Comparison: Original vs. Functional Source: https://merkletree.js.org Compares the syntax and usage of the original class-based API with the new functional API for creating trees, getting roots, generating proofs, and verifying them. ```javascript const tree = new MerkleTree(leaves, hashFn, options) const root = tree.getHexRoot() const proof = tree.getProof(leaf) const isValid = tree.verify(proof, leaf, root) ``` ```javascript const tree = createMerkleTree(leaves, hashFn, options) const root = getHexRoot(tree) const proof = getProof(tree, leaf) const isValid = verifyProof(proof, leaf, root) ``` -------------------------------- ### Get Merkle Proof Source: https://merkletree.js.org Generates a proof for a specific leaf. ```javascript const proof = getProof(tree, 'targetLeaf') ``` -------------------------------- ### Get Merkle Tree Options Source: https://merkletree.js.org Retrieves the current configuration options of a Merkle tree. ```javascript const options = getOptions(tree) ``` -------------------------------- ### Get Proof Flags Source: https://merkletree.js.org Retrieve boolean flags required for multi-proof verification. ```javascript const flags = tree.getProofFlags([leaf0, leaf2], multiProof) ``` -------------------------------- ### Get All Leaves Source: https://merkletree.js.org Retrieve all leaves from the Merkle tree as Buffers. ```javascript const allLeaves = tree.getLeaves() ``` -------------------------------- ### Get Leaf Count Source: https://merkletree.js.org Get the total number of leaves currently in the Merkle tree. ```javascript const count = tree.getLeafCount() ``` -------------------------------- ### Get Tree Leaves Source: https://merkletree.js.org Retrieves all leaves as Buffers or hex strings. ```javascript const leaves = getLeaves(tree) ``` ```javascript const hexLeaves = getHexLeaves(tree) ``` -------------------------------- ### Get Tree Root Buffer Source: https://merkletree.js.org Retrieves the root hash as a Buffer. ```javascript const rootBuffer = getRoot(tree) ``` -------------------------------- ### Get Leaf Index Source: https://merkletree.js.org Retrieves the index of a specific leaf. ```javascript const index = getLeafIndex(tree, 'targetLeaf') ``` -------------------------------- ### Get Merkle Root Source: https://merkletree.js.org Retrieve the Merkle root of the tree as a Buffer. ```javascript const root = tree.getRoot() ``` -------------------------------- ### Get Merkle Root Source: https://merkletree.js.org Retrieves the root hash as a hex string. ```javascript const root = getHexRoot(tree) ``` -------------------------------- ### Get Leaves as Hex Strings Source: https://merkletree.js.org Retrieve all leaves from the Merkle tree as hex strings. ```javascript const hexLeaves = tree.getHexLeaves() ``` -------------------------------- ### Get Leaf Count Source: https://merkletree.js.org Retrieves the total number of leaves in the tree. ```javascript const count = getLeafCount(tree) ``` -------------------------------- ### Get Tree Layers Source: https://merkletree.js.org Retrieves tree layers as Buffers or hex strings, optionally flattened. ```javascript const layers = getLayers(tree) ``` ```javascript const hexLayers = getHexLayers(tree) ``` ```javascript const flatLayers = getLayersFlat(tree) ``` ```javascript const hexFlatLayers = getHexLayersFlat(tree) ``` -------------------------------- ### Get Leaf by Index Source: https://merkletree.js.org Retrieve a specific leaf from the tree using its index. ```javascript const leaf = tree.getLeaf(0) ``` -------------------------------- ### Get Specific Leaf Source: https://merkletree.js.org Retrieves a specific leaf by index as a Buffer or hex string. ```javascript const leaf = getLeaf(tree, 0) ``` ```javascript const hexLeaf = getHexLeaf(tree, 0) ``` -------------------------------- ### Get Merkle Root as Hex String Source: https://merkletree.js.org Retrieve the Merkle root of the tree as a hex string, prefixed with '0x'. ```javascript const hexRoot = tree.getHexRoot() ``` -------------------------------- ### Get Leaf as Hex String by Index Source: https://merkletree.js.org Retrieve a specific leaf from the tree as a hex string using its index. ```javascript const hexLeaf = tree.getHexLeaf(0) ``` -------------------------------- ### Basic Merkle Tree Usage with Functional API Source: https://merkletree.js.org Illustrates the basic workflow of creating a Merkle tree, generating a proof, and verifying it using the functional API. ```javascript import { createMerkleTree, getHexRoot, getProof, verifyProof } from 'merkletreejs' // Create tree const leaves = ['a', 'b', 'c', 'd'] const tree = createMerkleTree(leaves) const root = getHexRoot(tree) // Generate proof const proof = getProof(tree, 'b') // Verify proof const isValid = verifyProof(proof, 'b', root) console.log('Valid:', isValid) // true ``` -------------------------------- ### Get Tree Depth Source: https://merkletree.js.org Retrieves the depth of the tree. ```javascript const depth = getDepth(tree) ``` -------------------------------- ### Options Source: https://merkletree.js.org Configuration options for the MerkleTree constructor. ```APIDOC ## Options ```typescript interface Options { duplicateOdd?: boolean // Duplicate odd nodes (default: false) hashLeaves?: boolean // Hash leaves before adding (default: false) isBitcoinTree?: boolean // Use Bitcoin-style tree (default: false) sortLeaves?: boolean // Sort leaves (default: false) sortPairs?: boolean // Sort pairs (default: false) sort?: boolean // Sort leaves and pairs (default: false) fillDefaultHash?: Function // Fill function for odd layers complete?: boolean // Create complete tree (default: false) concatenator?: Function // Custom concatenation function } ``` ``` -------------------------------- ### Bitcoin-Style Tree Configuration Source: https://merkletree.js.org Initialize a tree with Bitcoin-specific tree behavior. ```javascript const tree = new MerkleTree(leaves, SHA256, { isBitcoinTree: true }) ``` -------------------------------- ### Constructor Source: https://merkletree.js.org Initializes a new MerkleTree instance with specified leaves, hash function, and options. ```APIDOC ## Constructor ### `new MerkleTree(leaves, hashFunction?, options?)` Creates a new Merkle tree instance. **Parameters:** * `leaves` (Buffer[]): Array of leaf nodes (should be pre-hashed) * `hashFunction` (Function): Hash function to use (defaults to SHA256) * `options` (Options): Configuration options ```javascript const tree = new MerkleTree(leaves, SHA256, { sortPairs: true, duplicateOdd: false }) ``` ``` -------------------------------- ### Create Merkle Tree with Custom Hash Functions Source: https://merkletree.js.org Demonstrates creating a Merkle tree using the default SHA256 hash function and custom keccak256 and SHA1 hash functions. ```javascript import { createMerkleTree } from 'merkletreejs' // Default SHA256 const tree = createMerkleTree(['a', 'b', 'c']) // Custom keccak256 const keccakTree = createMerkleTree(['a', 'b', 'c'], (data) => { const keccak256 = require('keccak256') return keccak256(Buffer.from(String(data))) }) // Custom SHA1 const sha1Tree = createMerkleTree(['a', 'b', 'c'], (data) => { const crypto = require('crypto') return crypto.createHash('sha1').update(data).digest() }) ``` -------------------------------- ### MerkleTree Constructor with Options Source: https://merkletree.js.org Instantiate a MerkleTree with custom options for sorting pairs and handling duplicate odd nodes. ```javascript const tree = new MerkleTree(leaves, SHA256, { sortPairs: true, duplicateOdd: false }) ``` -------------------------------- ### Core Methods - Proof Operations Source: https://merkletree.js.org Methods for generating and verifying Merkle proofs. ```APIDOC ## Core Methods - Proof Operations ### `getProof(leaf, index?)` Generates a proof for a leaf. ```javascript const proof = tree.getProof(leafHash) // For duplicate leaves, specify index const proof = tree.getProof(leafHash, 2) ``` ### `verify(proof, targetNode, root)` Verifies a proof against a root. ```javascript const isValid = tree.verify(proof, leafHash, root) ``` ### `getHexProof(leaf, index?)` Generates a proof as hex strings. ```javascript const hexProof = tree.getHexProof(leafHash) ``` ### `getPositionalHexProof(leaf, index?)` Generates a proof with positional information. ```javascript const positionalProof = tree.getPositionalHexProof(leafHash) // Returns: [[position, hash], [position, hash], ...] ``` ``` -------------------------------- ### Utility Methods Source: https://merkletree.js.org General tree management and inspection utilities. ```javascript tree.resetTree() ``` ```javascript console.log(tree.toString()) ``` ```javascript const options = tree.getOptions() ``` -------------------------------- ### Generate Multi-Proofs Source: https://merkletree.js.org Generate multi-proofs for multiple leaves, optionally as hex strings. ```javascript const multiProof = tree.getMultiProof([0, 2, 4]) ``` ```javascript const hexMultiProof = tree.getHexMultiProof(flatTree, [0, 2, 4]) ``` -------------------------------- ### Create Merkle Tree Source: https://merkletree.js.org Initializes a tree with default or custom hash functions and options. ```javascript const tree = createMerkleTree(['a', 'b', 'c']) // Using custom hash function const customHashFn = (data) => { const crypto = require('crypto') return crypto.createHash('sha256').update(data).digest() } const treeWithOptions = createMerkleTree(leaves, customHashFn, { sort: true }) ``` -------------------------------- ### Get Tree Depth Source: https://merkletree.js.org Determine the depth (number of layers) of the Merkle tree. ```javascript const depth = tree.getDepth() ``` -------------------------------- ### Utility Methods Source: https://merkletree.js.org General utility methods for interacting with the Merkle tree. ```APIDOC ## resetTree() ### Description Clears all leaves and layers from the tree, resetting it to an empty state. ### Method DELETE ### Endpoint /resetTree ### Parameters None ### Request Example ```javascript tree.resetTree() ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Tree has been reset." } ``` ``` ```APIDOC ## toString() ### Description Returns a visual string representation of the Merkle tree. ### Method GET ### Endpoint /toString ### Parameters None ### Request Example ```javascript console.log(tree.toString()) ``` ### Response #### Success Response (200) - **representation** (string) - The string representation of the tree. #### Response Example ```json { "representation": "Tree: [Layer1], [Layer2], ..." } ``` ``` ```APIDOC ## getOptions() ### Description Returns the current options configured for the Merkle tree. ### Method GET ### Endpoint /getOptions ### Parameters None ### Request Example ```javascript const options = tree.getOptions() ``` ### Response #### Success Response (200) - **options** (Object) - The current tree options. #### Response Example ```json { "options": { "isBitcoinTree": false, "hashLeaves": true } } ``` ``` -------------------------------- ### Verify Multi-Proofs Source: https://merkletree.js.org Verify multi-proofs using either standard parameters or boolean flags. ```javascript const isValid = tree.verifyMultiProof( root, [0, 2, 4], [leaf0, leaf2, leaf4], totalLeaves, multiProof ) ``` ```javascript const isValid = tree.verifyMultiProofWithFlags(root, leaves, proofs, flags) ``` -------------------------------- ### Static Multi-Proof Generation Source: https://merkletree.js.org A static method to generate a multi-proof from a flat tree representation. ```APIDOC ## static MerkleTree.getMultiProof(flatTree, indices) ### Description Static method to generate a multi-proof from a flat tree structure. ### Method POST ### Endpoint /getMultiProof ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **flatTree** (Array) - Required - The flat array representation of the tree. - **indices** (Array) - Required - The indices of the leaves for which to generate the multi-proof. ### Request Example ```json { "flatTree": [ ... ], "indices": [0, 2, 4] } ``` ### Response #### Success Response (200) - **multiProof** (Object) - The generated multi-proof. #### Response Example ```json { "multiProof": { ... } } ``` ``` -------------------------------- ### Proof Verification Methods Source: https://merkletree.js.org Methods for verifying Merkle proofs. ```APIDOC ## verifyMultiProof(root, proofIndices, proofLeaves, leavesCount, proof) ### Description Verifies a multi-proof against a given root. ### Method POST ### Endpoint /verifyMultiProof ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **root** (string) - Required - The Merkle root. - **proofIndices** (Array) - Required - The indices of the leaves included in the proof. - **proofLeaves** (Array) - Required - The leaves corresponding to the proof indices. - **leavesCount** (number) - Required - The total number of leaves in the tree. - **proof** (Object) - Required - The multi-proof data. ### Request Example ```json { "root": "0xroot", "proofIndices": [0, 2, 4], "proofLeaves": ["leaf0", "leaf2", "leaf4"], "leavesCount": 10, "proof": { ... } } ``` ### Response #### Success Response (200) - **isValid** (boolean) - True if the proof is valid, false otherwise. #### Response Example ```json { "isValid": true } ``` ``` ```APIDOC ## verifyMultiProofWithFlags(root, leaves, proofs, proofFlag) ### Description Verifies a multi-proof using boolean flags. ### Method POST ### Endpoint /verifyMultiProofWithFlags ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **root** (string) - Required - The Merkle root. - **leaves** (Array) - Required - The leaves to verify. - **proofs** (Array) - Required - The proofs associated with the leaves. - **proofFlag** (Array) - Required - Boolean flags indicating the inclusion of proofs. ### Request Example ```json { "root": "0xroot", "leaves": ["leaf1", "leaf3"], "proofs": [ { ... }, { ... } ], "proofFlag": [true, false] } ``` ### Response #### Success Response (200) - **isValid** (boolean) - True if the proof is valid, false otherwise. #### Response Example ```json { "isValid": true } ``` ``` -------------------------------- ### Static Verification Method Source: https://merkletree.js.org A static method to verify a proof without needing a tree instance. ```APIDOC ## static MerkleTree.verify(proof, targetNode, root, hashFn?, options?) ### Description Static method to verify a proof against a root, without requiring a tree instance. ### Method POST ### Endpoint /verify ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **proof** (Object) - Required - The proof data. - **targetNode** (string) - Required - The leaf or node to verify. - **root** (string) - Required - The Merkle root. - **hashFn** (Function) - Optional - The hash function used. - **options** (Object) - Optional - Verification options. ### Request Example ```json { "proof": { ... }, "targetNode": "leafValue", "root": "0xroot", "hashFn": "SHA256", "options": { "isBitcoinTree": true } } ``` ### Response #### Success Response (200) - **isValid** (boolean) - True if the proof is valid, false otherwise. #### Response Example ```json { "isValid": true } ``` ``` -------------------------------- ### Serialize and Deserialize Source: https://merkletree.js.org Methods for converting leaves, proofs, and the entire tree to and from JSON strings. ```javascript const jsonLeaves = MerkleTree.marshalLeaves(leaves) ``` ```javascript const leaves = MerkleTree.unmarshalLeaves(jsonLeaves) ``` ```javascript const jsonProof = MerkleTree.marshalProof(proof) ``` ```javascript const proof = MerkleTree.unmarshalProof(jsonProof) ``` ```javascript const jsonTree = MerkleTree.marshalTree(tree) ``` ```javascript const tree = MerkleTree.unmarshalTree(jsonTree, SHA256) ``` -------------------------------- ### Generate Merkle Proof as Hex Strings Source: https://merkletree.js.org Generate a Merkle proof for a leaf, with all hashes represented as hex strings. ```javascript const hexProof = tree.getHexProof(leafHash) ``` -------------------------------- ### Get Leaf Index Source: https://merkletree.js.org Find the index of a given leaf hash. Returns -1 if the leaf is not found. ```javascript const index = tree.getLeafIndex(leafHash) ``` -------------------------------- ### Proof Generation Methods Source: https://merkletree.js.org Methods for generating proofs for leaves in the Merkle tree. ```APIDOC ## getProofs() ### Description Gets proofs for all leaves. ### Method GET ### Endpoint /getProofs ### Parameters None ### Request Example ```javascript const allProofs = tree.getProofs() ``` ### Response #### Success Response (200) - **proofs** (Array) - An array of proofs for all leaves. #### Response Example ```json [ "proof1", "proof2", ... ] ``` ``` ```APIDOC ## getHexProofs() ### Description Gets proofs for all leaves as hex strings. ### Method GET ### Endpoint /getHexProofs ### Parameters None ### Request Example ```javascript const allHexProofs = tree.getHexProofs() ``` ### Response #### Success Response (200) - **hexProofs** (Array) - An array of proofs for all leaves as hex strings. #### Response Example ```json [ "0xhexproof1", "0xhexproof2", ... ] ``` ``` ```APIDOC ## getMultiProof(indices) ### Description Generates a multi-proof for multiple leaves specified by their indices. ### Method POST ### Endpoint /getMultiProof ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **indices** (Array) - Required - An array of indices for the leaves to include in the multi-proof. ### Request Example ```json { "indices": [0, 2, 4] } ``` ### Response #### Success Response (200) - **multiProof** (Object) - The generated multi-proof. #### Response Example ```json { "multiProof": { ... } } ``` ``` ```APIDOC ## getHexMultiProof(tree, indices) ### Description Generates a multi-proof as hex strings for multiple leaves. ### Method POST ### Endpoint /getHexMultiProof ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **tree** (Object) - Required - The Merkle tree instance. - **indices** (Array) - Required - An array of indices for the leaves to include in the multi-proof. ### Request Example ```json { "tree": { ... }, "indices": [0, 2, 4] } ``` ### Response #### Success Response (200) - **hexMultiProof** (Object) - The generated multi-proof as hex strings. #### Response Example ```json { "hexMultiProof": { ... } } ``` ``` -------------------------------- ### Get Filtered Leaves Source: https://merkletree.js.org Retrieve specific leaves from the Merkle tree by providing an array of their hash values. ```javascript const filteredLeaves = tree.getLeaves([specificHash1, specificHash2]) ``` -------------------------------- ### Proof Marshaling Source: https://merkletree.js.org Functions to convert Merkle proofs to and from JSON strings. ```APIDOC ## marshalProof(proof) ### Description Converts a proof to JSON string. ### Method N/A (Utility Function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript const proofJson = marshalProof(proof) ``` ### Response N/A ``` ```APIDOC ## unmarshalProof(jsonStr) ### Description Creates a proof from JSON string. ### Method N/A (Utility Function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript const proof = unmarshalProof(proofJson) ``` ### Response N/A ``` -------------------------------- ### Serialization Source: https://merkletree.js.org Functions for converting Merkle trees and proofs to and from JSON format. ```APIDOC ## marshalTree(tree) ### Description Converts a Merkle tree object into a JSON string representation. ### Method GET ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **tree** (object) - Required - The Merkle tree object to serialize. ### Request Example ```javascript const json = marshalTree(tree) ``` ### Response #### Success Response (200) - **json** (string) - The JSON string representation of the Merkle tree. #### Response Example ```json { "json": "{\"leaves\":[...], \"options\":{...}}" } ``` ``` ```APIDOC ## unmarshalTree(jsonStr, hashFn?, options?) ### Description Creates a Merkle tree object from a JSON string. ### Method POST ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **jsonStr** (string) - Required - The JSON string representing the Merkle tree. - **hashFn** (function) - Optional - The hash function to use when reconstructing the tree. - **options** (object) - Optional - Configuration options for the tree. ### Request Example ```javascript const tree = unmarshalTree(jsonStr) ``` ### Response #### Success Response (200) - **tree** (object) - The reconstructed Merkle tree object. #### Response Example ```json { "tree": {} } ``` ``` -------------------------------- ### Comparison with Original API Source: https://merkletree.js.org Compares the functional API usage with the original class-based API of MerkleTree.js. ```APIDOC ## Comparison with Original API ### Description This section highlights the differences in usage between the original class-based API and the newer functional API for common Merkle tree operations. ### Original MerkleTreeJS ```javascript const tree = new MerkleTree(leaves, hashFn, options) const root = tree.getHexRoot() const proof = tree.getProof(leaf) const isValid = tree.verify(proof, leaf, root) ``` ### Functional API ```javascript const tree = createMerkleTree(leaves, hashFn, options) const root = getHexRoot(tree) const proof = getProof(tree, leaf) const isValid = verifyProof(proof, leaf, root) ``` ### Method N/A (Comparison) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Core Methods - Tree Information Source: https://merkletree.js.org Methods for retrieving information about the Merkle Tree. ```APIDOC ## Core Methods - Tree Information ### `getRoot()` Returns the Merkle root as a Buffer. ```javascript const root = tree.getRoot() ``` ### `getHexRoot()` Returns the Merkle root as a hex string with '0x' prefix. ```javascript const hexRoot = tree.getHexRoot() ``` ### `getLeaves(values?)` Returns array of leaves. Optionally filter by specific values. ```javascript const allLeaves = tree.getLeaves() const filteredLeaves = tree.getLeaves([specificHash1, specificHash2]) ``` ### `getHexLeaves()` Returns array of leaves as hex strings. ```javascript const hexLeaves = tree.getHexLeaves() ``` ### `getLeafCount()` Returns the total number of leaves. ```javascript const count = tree.getLeafCount() ``` ### `getDepth()` Returns the tree depth (number of layers). ```javascript const depth = tree.getDepth() ``` ``` -------------------------------- ### Tree Utility Methods Source: https://merkletree.js.org Utility functions for managing and inspecting Merkle trees. ```APIDOC ## resetTree(tree) ### Description Clears all leaves and layers from the tree. ### Method N/A (Utility Function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript resetTree(tree) ``` ### Response N/A ``` ```APIDOC ## getOptions(tree) ### Description Gets the current tree options. ### Method N/A (Utility Function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript const options = getOptions(tree) ``` ### Response N/A ``` ```APIDOC ## treeToString(tree) ### Description Returns visual representation of the tree. ### Method N/A (Utility Function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript const treeString = treeToString(tree) console.log(treeString) ``` ### Response N/A ``` -------------------------------- ### Advanced and Static Methods Source: https://merkletree.js.org Advanced tree operations and static verification helpers. ```javascript const proofIndices = tree.getProofIndices([2,5,6], 4) ``` ```javascript const isValid = MerkleTree.verify(proof, leaf, root, SHA256) ``` ```javascript const multiProof = MerkleTree.getMultiProof(flatTree, [0, 2, 4]) ``` -------------------------------- ### Verify MultiProof Source: https://merkletree.js.org Validates a multiproof. ```javascript const isValid = verifyMultiProof(root, [0, 2], [leaf0, leaf2], 5, proof) ``` -------------------------------- ### Generate Positional Merkle Proof Source: https://merkletree.js.org Generate a Merkle proof that includes positional information for each hash in the proof. ```javascript const positionalProof = tree.getPositionalHexProof(leafHash) // Returns: [[position, hash], [position, hash], ...] ``` -------------------------------- ### Generate Merkle Proof Source: https://merkletree.js.org Create a Merkle proof for a given leaf hash. If duplicate leaves exist, specify the index. ```javascript const proof = tree.getProof(leafHash) ``` ```javascript // For duplicate leaves, specify index const proof = tree.getProof(leafHash, 2) ``` -------------------------------- ### Proof Flag Operations Source: https://merkletree.js.org Methods related to generating and using proof flags for verification. ```APIDOC ## getProofFlags(leaves, proofs) ### Description Gets boolean flags for multi-proof verification. ### Method POST ### Endpoint /getProofFlags ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **leaves** (Array) - Required - The leaves for which to generate flags. - **proofs** (Array) - Required - The proofs associated with the leaves. ### Request Example ```json { "leaves": ["leaf0", "leaf2"], "proofs": [ { ... }, { ... } ] } ``` ### Response #### Success Response (200) - **flags** (Array) - An array of boolean flags. #### Response Example ```json { "flags": [true, false] } ``` ``` -------------------------------- ### Core Functions Source: https://merkletree.js.org These functions are the fundamental building blocks for working with Merkle trees in the library. ```APIDOC ## createMerkleTree(leaves, hashFn?, options?) ### Description Creates a Merkle tree from an array of leaves. Uses SHA256 as the default hash function. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **leaves** (Array) - Required - The array of leaves to build the tree from. - **hashFn** (function) - Optional - A custom hash function to use. - **options** (object) - Optional - Configuration options for the tree. - **sort** (boolean) - Whether to sort leaves before hashing. - **isBitcoinTree** (boolean) - Whether to use Bitcoin-style tree construction. ### Request Example ```javascript const tree = createMerkleTree(['a', 'b', 'c']) const customHashFn = (data) => { const crypto = require('crypto') return crypto.createHash('sha256').update(data).digest() } const treeWithOptions = createMerkleTree(leaves, customHashFn, { sort: true }) ``` ### Response #### Success Response (200) - **tree** (object) - The created Merkle tree object. #### Response Example ```json { "tree": {} } ``` ``` ```APIDOC ## getHexRoot(tree) ### Description Gets the root hash of the Merkle tree as a hexadecimal string. ### Method GET ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **tree** (object) - Required - The Merkle tree object. ### Request Example ```javascript const root = getHexRoot(tree) ``` ### Response #### Success Response (200) - **root** (string) - The hexadecimal representation of the Merkle root. #### Response Example ```json { "root": "0x..." } ``` ``` ```APIDOC ## getProof(tree, leaf, index?) ### Description Generates a proof for a specific leaf in the Merkle tree. ### Method GET ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **tree** (object) - Required - The Merkle tree object. - **leaf** (string | Buffer | object | number) - Required - The leaf for which to generate the proof. - **index** (number) - Optional - The index of the leaf if duplicates exist. ### Request Example ```javascript const proof = getProof(tree, 'targetLeaf') ``` ### Response #### Success Response (200) - **proof** (Array) - An array representing the Merkle proof. #### Response Example ```json { "proof": ["0x...", "0x..."] } ``` ``` ```APIDOC ## verifyProof(proof, leaf, root, hashFn?, options?) ### Description Verifies a given Merkle proof against a leaf and the Merkle root. ### Method POST ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **proof** (Array) - Required - The Merkle proof. - **leaf** (string | Buffer | object | number) - Required - The leaf to verify. - **root** (string | Buffer) - Required - The Merkle root. - **hashFn** (function) - Optional - The hash function used to create the tree. - **options** (object) - Optional - Configuration options for verification. - **sort** (boolean) - Whether leaves were sorted during tree creation. - **isBitcoinTree** (boolean) - Whether the tree was constructed using Bitcoin-style rules. ### Request Example ```javascript const isValid = verifyProof(proof, 'targetLeaf', root) ``` ### Response #### Success Response (200) - **isValid** (boolean) - True if the proof is valid, false otherwise. #### Response Example ```json { "isValid": true } ``` ``` ```APIDOC ## getHexProof(tree, leaf, index?) ### Description Gets a proof for a specific leaf, with all hashes represented as hexadecimal strings. ### Method GET ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **tree** (object) - Required - The Merkle tree object. - **leaf** (string | Buffer | object | number) - Required - The leaf for which to generate the proof. - **index** (number) - Optional - The index of the leaf if duplicates exist. ### Request Example ```javascript const hexProof = getHexProof(tree, 'targetLeaf') ``` ### Response #### Success Response (200) - **hexProof** (Array) - An array of hexadecimal strings representing the Merkle proof. #### Response Example ```json { "hexProof": ["0x...", "0x..."] } ``` ``` ```APIDOC ## getMultiProof(tree, indices) ### Description Generates a multiproof for a given set of leaf indices. ### Method GET ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **tree** (object) - Required - The Merkle tree object. - **indices** (Array) - Required - An array of indices for which to generate the multiproof. ### Request Example ```javascript const multiProof = getMultiProof(tree, [0, 2, 4]) ``` ### Response #### Success Response (200) - **multiProof** (object) - An object containing the multiproof data. #### Response Example ```json { "multiProof": {} } ``` ``` ```APIDOC ## getHexMultiProof(tree, indices) ### Description Generates a multiproof for a given set of leaf indices, with all hashes represented as hexadecimal strings. ### Method GET ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **tree** (object) - Required - The Merkle tree object. - **indices** (Array) - Required - An array of indices for which to generate the multiproof. ### Request Example ```javascript const hexMultiProof = getHexMultiProof(tree, [0, 2, 4]) ``` ### Response #### Success Response (200) - **hexMultiProof** (object) - An object containing the multiproof data in hexadecimal format. #### Response Example ```json { "hexMultiProof": {} } ``` ``` ```APIDOC ## verifyMultiProof(root, proofIndices, proofLeaves, leavesCount, proof, hashFn?, options?) ### Description Verifies a multiproof against the Merkle root. ### Method POST ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **root** (string | Buffer) - Required - The Merkle root. - **proofIndices** (Array) - Required - The indices included in the multiproof. - **proofLeaves** (Array) - Required - The leaves corresponding to the proofIndices. - **leavesCount** (number) - Required - The total number of leaves in the original tree. - **proof** (object) - Required - The multiproof data. - **hashFn** (function) - Optional - The hash function used to create the tree. - **options** (object) - Optional - Configuration options for verification. - **sort** (boolean) - Whether leaves were sorted during tree creation. - **isBitcoinTree** (boolean) - Whether the tree was constructed using Bitcoin-style rules. ### Request Example ```javascript const isValid = verifyMultiProof(root, [0, 2], [leaf0, leaf2], 5, proof) ``` ### Response #### Success Response (200) - **isValid** (boolean) - True if the multiproof is valid, false otherwise. #### Response Example ```json { "isValid": true } ``` ``` ```APIDOC ## getProofs(tree) ### Description Generates proofs for all leaves in the Merkle tree. ### Method GET ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **tree** (object) - Required - The Merkle tree object. ### Request Example ```javascript const allProofs = getProofs(tree) ``` ### Response #### Success Response (200) - **allProofs** (Array>) - An array where each element is a proof for a corresponding leaf. #### Response Example ```json { "allProofs": [[ "0x..." ], [ "0x..." ]] } ``` ``` ```APIDOC ## getHexProofs(tree) ### Description Generates proofs for all leaves in the Merkle tree, with all hashes represented as hexadecimal strings. ### Method GET ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **tree** (object) - Required - The Merkle tree object. ### Request Example ```javascript const allHexProofs = getHexProofs(tree) ``` ### Response #### Success Response (200) - **allHexProofs** (Array>) - An array where each element is a proof (as hex strings) for a corresponding leaf. #### Response Example ```json { "allHexProofs": [[ "0x..." ], [ "0x..." ]] } ``` ``` -------------------------------- ### Marshal Proof to JSON String Source: https://merkletree.js.org Converts a proof object into a JSON string representation for serialization. ```javascript const proofJson = marshalProof(proof) ``` -------------------------------- ### Hash Functions Source: https://merkletree.js.org Information on using default and custom hash functions with MerkleTree.js. ```APIDOC ## Hash Functions ### Description The functional API uses **SHA256** as the default hash function. You can specify a custom hash function as the second parameter to `createMerkleTree`. ### Method `createMerkleTree(leaves, hashFn?, options?) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript // Default SHA256 const tree = createMerkleTree(['a', 'b', 'c']) // Custom keccak256 const keccakTree = createMerkleTree(['a', 'b', 'c'], (data) => { const keccak256 = require('keccak256') return keccak256(Buffer.from(String(data))) }) // Custom SHA1 const sha1Tree = createMerkleTree(['a', 'b', 'c'], (data) => { const crypto = require('crypto') return crypto.createHash('sha1').update(data).digest() }) ``` ### Response N/A ```