@zk-kit/merkle-tree
Version:
Merkle tree implementation in TypeScript.
79 lines (78 loc) • 2.7 kB
TypeScript
import { HashFunction, Proof, Node } from "./types";
/**
* A Merkle tree is a tree in which every leaf node is labelled with the cryptographic hash of a
* data block, and every non-leaf node is labelled with the cryptographic hash of the labels of its child nodes.
* It allows efficient and secure verification of the contents of large data structures.
* The MerkleTree class is a TypeScript implementation of Merkle tree and it provides all the functions to create
* efficient trees and to generate and verify proofs of membership.
*/
export default class MerkleTree {
static readonly maxDepth = 32;
private _root;
private readonly _nodes;
private readonly _zeroes;
private readonly _hash;
private readonly _depth;
/**
* Initializes the Merkle tree with the hash function, the depth and the zero value to use for zeroes.
* @param hash Hash function.
* @param depth Tree depth.
* @param zeroValue Zero values for zeroes.
*/
constructor(hash: HashFunction, depth: number, zeroValue: Node);
/**
* Returns the root hash of the tree.
* @returns Root hash.
*/
get root(): Node;
/**
* Returns the depth of the tree.
* @returns Tree depth.
*/
get depth(): number;
/**
* Returns the leaves of the tree.
* @returns List of leaves.
*/
get leaves(): Node[];
/**
* Returns the zeroes nodes of the tree.
* @returns List of zeroes.
*/
get zeroes(): Node[];
/**
* Inserts a new leaf in the tree.
* @param leaf New leaf.
*/
insert(leaf: Node): void;
/**
* Deletes a leaf from the tree. It does not remove the leaf from
* the data structure. It set the leaf to be deleted to a zero value.
* @param index Index of the leaf to be deleted.
*/
delete(index: number): void;
/**
* Creates a proof of membership.
* @param index Index of the proof's leaf.
* @returns Proof object.
*/
createProof(index: number): Proof;
/**
* Verifies a proof and return true or false.
* @param proof Proof to be verified.
* @returns True or false.
*/
verifyProof(proof: Proof): boolean;
/**
* Returns the index of a leaf. If the leaf does not exist it returns -1.
* @param leaf Tree leaf.
* @returns Index of the leaf.
*/
indexOf(leaf: Node): number;
/**
* Provides a bottom-up tree traversal where for each level it calls a callback.
* @param index Index of the leaf.
* @param callback Callback with tree level, index of node in that level and direction (left node: true, right node: false).
*/
private forEachLevel;
}