merkl
A no_std + alloc sparse Merkle tree with a pluggable, namespaced key-value storage backend.
The initial version of this crate was vibe coded. Check it out on YouTube.
How it works
Each leaf is addressed by a key (a 32-byte hash). The key's bits, read MSB-first,
determine the path from root to leaf: bit 0 selects left (0) or right (1) at the root,
bit 1 at the next level, and so on. Internal nodes are stored in the backend keyed by
their own hash, holding a 64-byte serialised Node (left ‖ right child hashes).
The root lives outside the tree. MerkleTree holds no state beyond its backend and
hash-function marker. Every operation receives a root Hash and returns a new root —
making historical roots and independent sub-trees free.
root ──► Node{ left, right }
│ │
Node{…} leaf_hash ← terminal: no backend entry
│
leaf_hash ← terminal
An all-zero Hash (Hash::default()) is the canonical empty root.
Four ways to insert a leaf:
| Method | Key derivation | Use when |
|---|---|---|
insert(ns, root, data) |
H::hash(data) |
Natural content-addressing |
insert_leaf(ns, root, leaf_hash) |
leaf_hash (key = value) |
Pre-hashed leaf |
insert_indexed(ns, root, index, data) |
index bytes zero-padded to 32 bytes |
Array-like stable positions |
insert_indexed_leaf(ns, root, index, leaf_hash) |
index bytes zero-padded to 32 bytes |
Pre-hashed leaf at index |
Feature flags
| Feature | Default | Description |
|---|---|---|
std |
yes | Enables std-backed errors and the sha2 crate's std feature. Disable for no_std targets. |
sha2 |
no | Enables Sha256Hasher and the Sha256MerkleTree<B> alias. |
serde |
no | Derives Serialize/Deserialize for Node and MerkleOpening. |
redb |
no | Enables RedbBackend and RedbMerkleTree<H> backed by redb (requires std). |
fjall |
no | Enables FjallBackend backed by fjall (requires std). |
Quick start
SHA-256 hasher (sha2 feature)
[]
= { = "1.0", = ["sha2"] }
Index-keyed inserts
Useful for append-like structures where each element has a stable numeric position.
The index parameter is raw bytes (up to 32) zero-padded into a 32-byte key:
use ;
let tree = default;
// Use little-endian encoded integers as the index bytes.
let root = tree.insert_indexed.unwrap;
let root = tree.insert_indexed.unwrap;
The key for index is the raw bytes copied into a 32-byte zero-padded buffer, giving
each index a fixed, deterministic position in the tree.
Ephemeral forks
to_ephemeral() creates a short-lived view of a tree that reads from the
original backend but writes only into a temporary in-memory overlay. The
original backend is never mutated:
use ;
let tree = default;
let root = tree.insert.unwrap;
// Fork: all inserts go to the ephemeral overlay only.
let ephemeral = tree.to_ephemeral;
let _fork_root = ephemeral.insert.unwrap;
// The original backend is never modified by the ephemeral fork.
redb backend (redb feature)
[]
= { = "1.0", = ["redb", "sha2"] }
For a persistent file-backed database:
Cloning a RedbBackend is cheap — all clones share the same underlying Database
via Arc (or Rc on targets without atomics).
Each set call opens, writes, and commits its own write transaction. For bulk
tree construction, wrapping a single redb::WriteTransaction in a custom backend
will give better throughput.
fjall backend (fjall feature)
[]
= { = "1.0", = ["fjall"] }
Membership proofs
get_opening / get_opening_leaf / get_indexed_opening collect sibling
hashes bottom-up. Verification is a pure hash computation — it never touches
the backend:
use ;
let tree = default;
let root = tree.insert.unwrap;
// Verify membership by leaf data (convenience — hashes data internally).
let proof = tree.get_opening.unwrap;
assert_eq!;
// Or supply the leaf hash directly.
assert_eq!;
For indexed inserts, use get_indexed_opening and get_indexed:
use ;
let tree = default;
let root = tree.insert_indexed.unwrap;
// Retrieve the stored leaf hash by index.
let leaf = tree.get_indexed.unwrap;
// Build and verify an indexed opening.
let proof = tree.get_indexed_opening.unwrap;
assert_eq!;
Non-membership proofs
A sparse Merkle tree can also prove that a position is empty:
use ;
let = ;
// "carol" was never inserted; the path leads to an empty slot.
let proof = tree.get_opening.unwrap;
assert_eq!;
// Non-membership at an index position.
let proof = tree.get_indexed_opening.unwrap;
assert_eq!;
Traversal directions are derived from the key at verification time — never stored in the proof — so the proof cannot be forged by manipulating direction bits.
Path containment
MerkleOpening::contains checks whether one proof's path is a suffix of
another's — useful for verifying that a leaf proof lives inside a known
sub-tree proof:
use ;
// A deeper proof contains a shallower proof when their root-aligned
// siblings match.
let deep: = new;
let shallow: = new;
assert!;
Implementing KvsBackend
The KvsBackend trait is the only integration point:
use KvsBackend;
use Result;
Key facts:
- All methods take
&self— use interior mutability (RefCell,Mutex, etc.) for the write path. nsis used by the tree to separate node storage (ns) from its internal key-mapping namespace ("{ns}-key"). Your backend only needs to use it as an extra scope for isolation.- Tree node keys are 32-byte parent hashes; values are 64-byte
Nodeencodings (left ‖ right).
For bare-metal targets, wrap your store in RefCell (single-core) or a
critical_section::Mutex (multi-core / interrupt-driven):
License
MIT — see LICENSE.