Lean Incremental Merkle Tree
Lean Incremental Merkle tree implementation in TypeScript.
[!NOTE]
This library has been audited as part of the Semaphore V4 PSE audit: https://semaphore.pse.dev/Semaphore_4.0.0_Audit.pdf.
The LeanIMT is an optimized binary version of the IMT into binary-focused model, eliminating the need for zero values and allowing dynamic depth adjustment. Unlike the IMT, which uses a zero hash for incomplete nodes, the LeanIMT directly adopts the left child's value when a node lacks a right counterpart. The tree's depth dynamically adjusts to the count of leaves, enhancing efficiency by reducing the number of required hash calculations. To understand more about the LeanIMT, take a look at this visual explanation. For detailed insights into the implementation specifics, please refer to the technical documentation.
🛠 Install
npm or yarn
Install the @zk-kit/lean-imt
package with npm:
npm i @zk-kit/lean-imt --save
or yarn:
yarn add @zk-kit/lean-imt
CDN
You can also load it using a script
tag using unpkg:
<script src="https://unpkg.com/@zk-kit/lean-imt"></script>
or JSDelivr:
<script src="https://cdn.jsdelivr.net/npm/@zk-kit/lean-imt"></script>
📜 Usage
import { LeanIMT } from "@zk-kit/lean-imt"
import { poseidon2 } from "poseidon-lite"
const hash = (a, b) => poseidon2([a, b])
const tree = new LeanIMT(hash)
tree.insert(1n)
console.log(tree.leaves)
tree.insert(3n)
console.log(tree.root)
console.log(tree.depth)
console.log(tree.size)
console.log(tree.leaves)
const idx = tree.indexOf(3n)
console.log(idx)
const has = tree.has(4n)
console.log(tree.has(4n))
tree.update(1, 2n)
console.log(tree.leaves)
tree.update(1, 0n)
console.log(tree.leaves)
const proof = tree.generateProof(1)
console.log(tree.verifyProof(proof))
const nodes = tree.export()
const tree2 = LeanIMT.import(hash, nodes)
const tree3 = LeanIMT.import<number>(hash, nodes, Number)