ab_merkle_tree/lib.rs
1//! High-performance Merkle Tree and related data structures (Merkle Mountain Range, Sparse Merkle
2//! Tree).
3//!
4//! This crate contains several high-performance Merkle Tree implementations and related data
5//! structures, many of which are a subset of each other.
6//!
7//! These implementations can be an order of magnitude faster than traditional implementations by
8//! leveraging the ability of hash functions like BLAKE3 to hash multiple blocks at once with SIMD.
9//! Typical Merkle Tree crates only allow customizing a hash function of two leaves, which makes it
10//! impossible to benefit from the inherent strength of such hash functions.
11//!
12//! Currently [`BalancedMerkleTree`], [`UnbalancedMerkleTree`], [`MerkleMountainRange`] and
13//! [`SparseMerkleTree`] are available.
14//!
15//! [`BalancedMerkleTree`] is an optimized special case of [`UnbalancedMerkleTree`], which is in
16//! turn an optimized version of [`MerkleMountainRange`], and all 3 will return the same results for
17//! identical inputs and hasher.
18//!
19//! [`SparseMerkleTree`] is a special kind of Merkle Tree, usually of intractable size, where most
20//! of the leaves are empty (missing). It will also produce the same root as other trees in case the
21//! tree doesn't have any empty leaves, though it is unlikely to happen in practice.
22//!
23//! [`BalancedMerkleTree`]: balanced::BalancedMerkleTree
24//! [`MerkleMountainRange`]: mmr::MerkleMountainRange
25//! [`UnbalancedMerkleTree`]: unbalanced::UnbalancedMerkleTree
26//! [`SparseMerkleTree`]: sparse::SparseMerkleTree
27//!
28//! All trees are generic over [`MerkleHasher`], which can hash many pairs of nodes at once and
29//! defines the size of nodes. Hashers are created with [`Default`] when they don't depend on the
30//! number of leaves, otherwise with [`NewMerkleHasherForTreeSize`], which is implemented for all
31//! hashers that implement [`Default`]. Trees that don't know the number of leaves upfront, like
32//! [`MerkleMountainRange`], only support hashers that implement [`Default`].
33//!
34//! `blake3` module contains the BLAKE3 hasher and aliases of all trees that use it (requires
35//! `blake3` feature).
36//!
37//! Does not require a standard library (`no_std`), most APIs are usable without an allocator, never
38//! panics.
39
40#![expect(incomplete_features, reason = "generic_const_*")]
41#![feature(
42 const_block_items,
43 const_convert,
44 const_default,
45 const_trait_impl,
46 gca_const_items,
47 gca_macroless_args,
48 gca_min_const_items,
49 generic_const_items,
50 iter_advance_by,
51 maybe_uninit_uninit_array_transpose,
52 phantom_variance_markers,
53 trusted_len
54)]
55#![no_std]
56
57pub mod balanced;
58mod batching;
59#[cfg(feature = "blake3")]
60pub mod blake3;
61pub mod mmr;
62pub mod sparse;
63pub mod unbalanced;
64
65#[cfg(feature = "alloc")]
66extern crate alloc;
67
68/// Hash function for inner nodes of Merkle Trees.
69///
70/// Hashing of many pairs at once is a part of the API, such that hash functions like BLAKE3 can use
71/// SIMD to hash multiple pairs in parallel.
72///
73/// Hashers used with [`SparseMerkleTree`] must never hash nodes into all zeroes, see its docs for
74/// details.
75///
76/// [`SparseMerkleTree`]: sparse::SparseMerkleTree
77pub trait MerkleHasher {
78 /// Size of a node hash in bytes
79 const OUT_LEN: usize;
80 /// Number of pairs [`Self::hash_pairs()`] hashes in parallel, 1 for hashers that hash pairs one
81 /// by one.
82 ///
83 /// Trees size batches of pairs and buffers for them accordingly, such that hashers without
84 /// parallelism don't pay for batching. Must be a power of two that is not larger than 64.
85 const PARALLEL_PAIRS: usize = 1;
86
87 /// Hash a pair of nodes together
88 fn hash_pair(&self, pair: &[[u8; Self::OUT_LEN]; 2]) -> [u8; Self::OUT_LEN];
89
90 /// Similar to [`Self::hash_pair()`], but hashes multiple pairs at once.
91 ///
92 /// The default implementation hashes pairs one by one, hash functions that can do better
93 /// should override it. An override must return the same as [`Self::hash_pair()`] for each pair,
94 /// because trees mix both.
95 #[inline(always)]
96 fn hash_pairs<const NUM_PAIRS: usize>(
97 &self,
98 pairs: &[[[u8; Self::OUT_LEN]; 2]; NUM_PAIRS],
99 ) -> [[u8; Self::OUT_LEN]; NUM_PAIRS] {
100 pairs.each_ref().map(|pair| self.hash_pair(pair))
101 }
102
103 /// Root of an [`UnbalancedMerkleTree`] or [`MerkleMountainRange`] with a single leaf.
104 ///
105 /// The default implementation returns the leaf unchanged, which keeps a tree of trees the
106 /// same as a single larger tree. Hashers that depend on the tree size should hash the leaf
107 /// instead, otherwise the size isn't committed to when the tree has a single leaf and no inner
108 /// nodes.
109 ///
110 /// [`UnbalancedMerkleTree`]: unbalanced::UnbalancedMerkleTree
111 /// [`MerkleMountainRange`]: mmr::MerkleMountainRange
112 #[inline(always)]
113 fn hash_single_leaf(&self, leaf: &[u8; Self::OUT_LEN]) -> [u8; Self::OUT_LEN] {
114 *leaf
115 }
116}
117
118/// Creates hashers for trees with a known number of leaves.
119///
120/// A hasher either ignores the tree size, in which case it implements [`Default`] and gets this
121/// trait through the blanket implementation, or depends on it, in which case it implements this
122/// trait directly and must not implement [`Default`]. It can't be both: the two implementations
123/// would conflict.
124pub const trait NewMerkleHasherForTreeSize: Sized {
125 /// Create a hasher for a tree with `num_leaves` leaves
126 fn new_for_tree_size(num_leaves: u64) -> Self;
127}
128
129/// Hashers that implement [`Default`] ignore the tree size
130const impl<H> NewMerkleHasherForTreeSize for H
131where
132 H: [const] Default,
133{
134 #[inline(always)]
135 fn new_for_tree_size(_num_leaves: u64) -> Self {
136 H::default()
137 }
138}