#merkle-tree #tree #merkle

alloy-merkle-tree

Minimal Merkle Tree implementation

10 releases (6 breaking)

0.7.2 Dec 22, 2024
0.7.1 Oct 16, 2024
0.7.0 Sep 16, 2024
0.6.0 Jun 25, 2024
0.5.0 Feb 28, 2024

#48 in #merkle

Download history 32/week @ 2024-09-24 12/week @ 2024-10-01 2/week @ 2024-10-08 177/week @ 2024-10-15 11/week @ 2024-10-22 14/week @ 2024-10-29 25/week @ 2024-11-05 29/week @ 2024-11-12 76/week @ 2024-11-19 30/week @ 2024-11-26 18/week @ 2024-12-03 27/week @ 2024-12-10 134/week @ 2024-12-17 22/week @ 2024-12-24 4/week @ 2025-01-07

163 downloads per month
Used in 5 crates (4 directly)

Custom license

36KB
606 lines

alloy-merkle-tree

CI Crates.io Documentation

Minimal Merkle Tree implementation

  • various tree implementation
    • PerfectBinaryMerkleTree
    • IncrementalMerkleTree
    • StandardBinaryTree
  • type compatible with alloy-primitives
  • keccak hash as native hash
  • support features: insert, proof, verify

Install

 cargo add alloy-merkle-tree

Support

MerkleTree

Perfect Binary Merkle Tree

let mut tree = MerkleTree::new();
// Should be 2 ^ N leaves
let num_leaves = 16;
for i in 0..num_leaves {
    tree.insert(B256::from(U256::from(i)));
}
tree.finish();

for i in 0..num_leaves {
    let proof = tree.create_proof(&B256::from(U256::from(i))).unwrap();
    assert!(MerkleTree::verify_proof(&proof));
}

IncrementalMerkleTree

used in the ETH2 Deposit Contract

 let mut tree = IncrementalMerkleTree::<8>::new();
for i in 0..1 << (8 - 1) {
    tree.append([i as u8; 32].into()).unwrap();
}
for i in 0..1 << (8 - 1) {
    let leaf = [i as u8; 32].into();
    let proof = tree.proof_at_index(i).unwrap();
    assert!(tree.verify_proof(leaf, i, &proof));
}

StandardBinaryMerkleTree

StandardMerkleTree

let num_leaves = 1000;
let mut leaves = Vec::new();
for i in 0..num_leaves {
    leaves.push(i.to_string());
}
let tree = StandardMerkleTree::of_sorted(leaves.clone());

for leaf in leaves.iter() {
    let proof = tree.get_proof(leaf);
    let bool = tree.verify_proof(leaf.to_string(), proof);
    assert!(bool);
}

reference

Dependencies

~9.5MB
~173K SLoC