Skip to main content

ab_merkle_tree/
balanced.rs

1use crate::batching::{BATCH_NUM_LEAVES, PARALLEL_PAIRS, hash_pairs, perfect_subtree_root};
2use crate::{MerkleHasher, NewMerkleHasherForTreeSize};
3#[cfg(feature = "alloc")]
4use alloc::boxed::Box;
5use core::iter::TrustedLen;
6use core::mem::MaybeUninit;
7use core::num::NonZero;
8
9const TREE_SIZE_WITHOUT_LEAVES<const N: usize>: usize = {
10    // Ensuring only supported `N` can be specified for [`BalancedMerkleTree`]
11    assert!(
12        N.is_power_of_two(),
13        "Balanced Merkle Tree must have a number of leaves that is a power of 2"
14    );
15
16    assert!(
17        N > 1,
18        "This Balanced Merkle Tree must have more than one leaf"
19    );
20
21    N - 1
22};
23/// Number of elements in a proof for a tree with `N` leaves
24pub const PROOF_ELEMENTS<const N: usize>: usize = N.ilog2() as usize;
25const ROOT_ONLY_LARGE_STACK_SIZE<const N: usize, H: MerkleHasher>: usize = {
26    // For small trees the large stack is not used, so the returned value does not matter as long as
27    // it compiles
28    if N < BATCH_NUM_LEAVES::<H> {
29        1
30    } else {
31        (N / BATCH_NUM_LEAVES::<H>).ilog2() as usize + 1
32    }
33};
34
35/// Merkle Tree variant that has hash-sized leaves and is fully balanced according to configured
36/// generic parameter.
37///
38/// This can be considered a special case of [`UnbalancedMerkleTree`]. The root and proofs are
39/// identical for both in case the number of leaves is a power of two. For the number of leaves that
40/// is a power of two [`UnbalancedMerkleTree`] is useful when a single proof needs to be generated
41/// and the number of leaves is very large (it can generate proofs with very little RAM usage
42/// compared to this version).
43///
44/// [`UnbalancedMerkleTree`]: crate::unbalanced::UnbalancedMerkleTree
45///
46/// This Merkle Tree implementation is best suited for use cases when proofs for all (or most) of
47/// the elements need to be generated and the whole tree easily fits into memory. It can also be
48/// constructed and proofs can be generated efficiently without heap allocations.
49///
50/// With all parameters of the tree known statically, it results in the most efficient version of
51/// the code being generated for a given set of parameters.
52///
53/// Inner nodes are hashed with `H`.
54#[derive(Debug)]
55pub struct BalancedMerkleTree<'a, const N: usize, H>
56where
57    H: MerkleHasher,
58{
59    leaves: &'a [[u8; H::OUT_LEN]; N],
60    // This tree doesn't include leaves because we have them in `leaves` field
61    tree: [[u8; H::OUT_LEN]; TREE_SIZE_WITHOUT_LEAVES::<N>],
62}
63
64impl<'a, const N: usize, H> BalancedMerkleTree<'a, N, H>
65where
66    [(); TREE_SIZE_WITHOUT_LEAVES::<N>]:,
67    H: MerkleHasher + const NewMerkleHasherForTreeSize,
68{
69    /// Create a new tree from a fixed set of elements.
70    ///
71    /// The data structure is statically allocated and might be too large to fit on the stack!
72    /// If that is the case, use `new_boxed()` method.
73    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
74    pub fn new(leaves: &'a [[u8; H::OUT_LEN]; N]) -> Self {
75        // TODO: Technically redundant with the where-clause, which is not enforced in generic code
76        //  due to https://github.com/rust-lang/rust/issues/164019, remove once fixed
77        const { TREE_SIZE_WITHOUT_LEAVES::<N> };
78
79        let mut tree = [MaybeUninit::<[u8; H::OUT_LEN]>::uninit(); _];
80
81        Self::init_internal(leaves, &mut tree);
82
83        Self {
84            leaves,
85            // SAFETY: Statically guaranteed for all elements to be initialized
86            tree: unsafe { tree.transpose().assume_init() },
87        }
88    }
89
90    /// Like [`Self::new()`], but used pre-allocated memory for instantiation
91    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
92    pub fn new_in<'b>(
93        instance: &'b mut MaybeUninit<Self>,
94        leaves: &'a [[u8; H::OUT_LEN]; N],
95    ) -> &'b mut Self {
96        // TODO: Technically redundant with the where-clause, which is not enforced in generic code
97        //  due to https://github.com/rust-lang/rust/issues/164019, remove once fixed
98        const { TREE_SIZE_WITHOUT_LEAVES::<N> };
99
100        let instance_ptr = instance.as_mut_ptr();
101        // SAFETY: Valid and correctly aligned non-null pointer
102        unsafe {
103            (&raw mut (*instance_ptr).leaves).write(leaves);
104        }
105        let tree = {
106            // SAFETY: Valid and correctly aligned non-null pointer
107            let tree_ptr = unsafe { &raw mut (*instance_ptr).tree };
108            // SAFETY: Allocated and correctly aligned uninitialized data
109            unsafe {
110                tree_ptr
111                    .cast::<[MaybeUninit<[u8; H::OUT_LEN]>; TREE_SIZE_WITHOUT_LEAVES::<N>]>()
112                    .as_mut_unchecked()
113            }
114        };
115
116        Self::init_internal(leaves, tree);
117
118        // SAFETY: Initialized field by field above
119        unsafe { instance.assume_init_mut() }
120    }
121
122    /// Like [`Self::new()`], but creates heap-allocated instance, avoiding excessive stack usage
123    /// for large trees
124    #[cfg(feature = "alloc")]
125    pub fn new_boxed(leaves: &'a [[u8; H::OUT_LEN]; N]) -> Box<Self> {
126        let mut instance = Box::<Self>::new_uninit();
127
128        Self::new_in(&mut instance, leaves);
129
130        // SAFETY: Initialized by constructor above
131        unsafe { instance.assume_init() }
132    }
133
134    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
135    fn init_internal(
136        leaves: &[[u8; H::OUT_LEN]; N],
137        tree: &mut [MaybeUninit<[u8; H::OUT_LEN]>; TREE_SIZE_WITHOUT_LEAVES::<N>],
138    ) {
139        let hasher = const { H::new_for_tree_size(N as u64) };
140        let mut tree_hashes = tree.as_mut_slice();
141        let mut level_hashes = leaves.as_slice();
142
143        while level_hashes.len() > 1 {
144            let num_pairs = level_hashes.len() / 2;
145            let parent_hashes;
146            // SAFETY: The size of the tree is statically known to match the number of leaves and
147            // levels of hashes
148            (parent_hashes, tree_hashes) = unsafe { tree_hashes.split_at_mut_unchecked(num_pairs) };
149
150            let (parent_hashes_chunks, parent_hashes_remainder) =
151                parent_hashes.as_chunks_mut::<{ PARALLEL_PAIRS::<H> }>();
152            if parent_hashes_remainder.is_empty() {
153                for (pairs, hashes) in level_hashes
154                    .as_chunks::<{ BATCH_NUM_LEAVES::<H> }>()
155                    .0
156                    .iter()
157                    .zip(parent_hashes_chunks)
158                {
159                    // TODO: This memory copy is unfortunate, make hashing write into this memory
160                    //  directly once blake3 API improves
161                    *hashes = MaybeUninit::new(hash_pairs(&hasher, pairs)).into();
162                }
163            } else {
164                for (pair, parent_hash) in level_hashes
165                    .as_chunks::<2>()
166                    .0
167                    .iter()
168                    .zip(parent_hashes.iter_mut())
169                {
170                    parent_hash.write(hasher.hash_pair(pair));
171                }
172            }
173
174            // SAFETY: Just initialized
175            level_hashes = unsafe { parent_hashes.assume_init_ref() };
176        }
177    }
178
179    // TODO: Method that generates not only root, but also proof, like Unbalanced Merkle Tree
180    /// Compute Merkle Tree root.
181    ///
182    /// This is functionally equivalent to creating an instance first and calling [`Self::root()`]
183    /// method, but is faster and avoids heap allocation when root is the only thing that is needed.
184    #[inline]
185    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
186    pub fn compute_root_only(leaves: &[[u8; H::OUT_LEN]; N]) -> [u8; H::OUT_LEN] {
187        // TODO: Technically redundant with the where-clause, which is not enforced in generic code
188        //  due to https://github.com/rust-lang/rust/issues/164019, remove once fixed
189        const { TREE_SIZE_WITHOUT_LEAVES::<N> };
190
191        let hasher = const { H::new_for_tree_size(N as u64) };
192
193        // Trees smaller than a batch are hashed one level at a time
194        if N < BATCH_NUM_LEAVES::<H> {
195            let mut nodes = *leaves;
196            // SAFETY: `N` is a power of two, which `TREE_SIZE_WITHOUT_LEAVES` checks
197            return unsafe { perfect_subtree_root(&hasher, &mut nodes) };
198        }
199
200        // Stack of intermediate nodes per tree level. Each level holds a batch of hashes, the last
201        // one is collapsed into a single root hash at the very end.
202        let mut stack =
203            [[[0u8; H::OUT_LEN]; PARALLEL_PAIRS::<H>]; ROOT_ONLY_LARGE_STACK_SIZE::<N, H>];
204
205        // This variable allows reusing and reducing stack usage instead of having a separate
206        // `current` variable
207        let mut parent_current = [[0u8; H::OUT_LEN]; BATCH_NUM_LEAVES::<H>];
208        for (num_chunks, chunk_leaves) in leaves
209            .as_chunks::<{ BATCH_NUM_LEAVES::<H> }>()
210            .0
211            .iter()
212            .enumerate()
213        {
214            let current_half = &mut parent_current[PARALLEL_PAIRS::<H>..];
215
216            let current = hash_pairs::<{ PARALLEL_PAIRS::<H> }, _, _>(&hasher, chunk_leaves);
217            current_half.copy_from_slice(&current);
218
219            // Every bit set to `1` corresponds to an active Merkle Tree level
220            let lowest_active_levels = num_chunks.trailing_ones() as usize;
221            for parent in &mut stack[..lowest_active_levels] {
222                let parent_half = &mut parent_current[..PARALLEL_PAIRS::<H>];
223                parent_half.copy_from_slice(parent);
224
225                let current = hash_pairs::<{ PARALLEL_PAIRS::<H> }, _, _>(&hasher, &parent_current);
226
227                let current_half = &mut parent_current[PARALLEL_PAIRS::<H>..];
228                current_half.copy_from_slice(&current);
229            }
230
231            let current_half = &mut parent_current[PARALLEL_PAIRS::<H>..];
232
233            // Place a freshly computed batch of hashes into the first inactive level
234            stack[lowest_active_levels].copy_from_slice(current_half);
235        }
236
237        // SAFETY: Each level of the stack holds `MerkleHasher::PARALLEL_PAIRS` nodes, which is a
238        // power of two
239        unsafe { perfect_subtree_root(&hasher, &mut stack[ROOT_ONLY_LARGE_STACK_SIZE::<N, H> - 1]) }
240    }
241
242    /// Get the root of Merkle Tree
243    #[inline]
244    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
245    pub fn root(&self) -> [u8; H::OUT_LEN] {
246        *self
247            .tree
248            .last()
249            .or(self.leaves.last())
250            .expect("There is always at least one leaf hash; qed")
251    }
252
253    /// Iterator over proofs in the same order as provided leaf hashes
254    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
255    pub fn all_proofs(&self) -> ProofsIterator<'_, N, H> {
256        ProofsIterator {
257            leaves: self.leaves,
258            tree: &self.tree,
259            leaf_index: 0,
260        }
261    }
262
263    /// Verify previously generated proof
264    #[inline]
265    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
266    pub fn verify(
267        root: &[u8; H::OUT_LEN],
268        proof: &[[u8; H::OUT_LEN]; PROOF_ELEMENTS::<N>],
269        leaf_index: usize,
270        leaf: [u8; H::OUT_LEN],
271    ) -> bool {
272        // TODO: Technically redundant with the where-clause, which is not enforced in generic code
273        //  due to https://github.com/rust-lang/rust/issues/164019, remove once fixed
274        const { TREE_SIZE_WITHOUT_LEAVES::<N> };
275
276        if leaf_index >= N {
277            return false;
278        }
279
280        let hasher = const { H::new_for_tree_size(N as u64) };
281        let mut computed_root = leaf;
282
283        let mut position = leaf_index;
284        for hash in proof {
285            computed_root = if position.is_multiple_of(2) {
286                hasher.hash_pair(&[computed_root, *hash])
287            } else {
288                hasher.hash_pair(&[*hash, computed_root])
289            };
290
291            position /= 2;
292        }
293
294        root == &computed_root
295    }
296}
297
298/// Iterator over proofs for a balanced Merkle tree
299#[derive(Debug)]
300pub struct ProofsIterator<'a, const N: usize, H>
301where
302    H: MerkleHasher,
303{
304    leaves: &'a [[u8; H::OUT_LEN]; N],
305    tree: &'a [[u8; H::OUT_LEN]; TREE_SIZE_WITHOUT_LEAVES::<N>],
306    /// Index of the next leaf, the iterator is exhausted once it reaches `N`
307    leaf_index: usize,
308}
309
310impl<const N: usize, H> ProofsIterator<'_, N, H>
311where
312    H: MerkleHasher,
313{
314    #[inline(always)]
315    fn remaining(&self) -> usize {
316        N - self.leaf_index
317    }
318}
319
320impl<const N: usize, H> Iterator for ProofsIterator<'_, N, H>
321where
322    H: MerkleHasher,
323{
324    type Item = [[u8; H::OUT_LEN]; PROOF_ELEMENTS::<N>];
325
326    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
327    fn next(&mut self) -> Option<Self::Item> {
328        let index = self.leaf_index;
329
330        // The line below is a more efficient branchless version of this:
331        // let sibling_index = if index % 2 == 0 {
332        //     index + 1
333        // } else {
334        //     index - 1
335        // };
336        let sibling_index = index ^ 1;
337        // `N` is an even number, so the sibling is missing exactly when `index >= N`, meaning the
338        // iterator is exhausted
339        let sibling_hash = *self.leaves.get(sibling_index)?;
340        self.leaf_index += 1;
341
342        let mut proof = [MaybeUninit::<[u8; H::OUT_LEN]>::uninit(); _];
343        proof[0].write(sibling_hash);
344
345        // Part that is shared between left and right leaf proofs
346        let shared_proof = &mut proof[1..];
347
348        let mut tree_hashes = self.tree.as_slice();
349        let mut parent_position = index / 2;
350        let mut parent_level_size = N / 2;
351
352        for hash in shared_proof {
353            let parent_other_position = parent_position ^ 1;
354
355            let other_hash = tree_hashes.get(parent_other_position).expect(
356                "`parent_position` is within the current level of the tree, whose size is an \
357                    even number; qed",
358            );
359            hash.write(*other_hash);
360            tree_hashes = &tree_hashes[parent_level_size..];
361
362            parent_position /= 2;
363            parent_level_size /= 2;
364        }
365
366        // SAFETY: Just initialized
367        Some(unsafe { proof.transpose().assume_init() })
368    }
369
370    #[inline(always)]
371    fn size_hint(&self) -> (usize, Option<usize>) {
372        let remaining = self.remaining();
373        (remaining, Some(remaining))
374    }
375
376    #[inline(always)]
377    fn count(self) -> usize {
378        self.remaining()
379    }
380
381    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
382    fn last(mut self) -> Option<Self::Item> {
383        if self.leaf_index >= N {
384            return None;
385        }
386        self.leaf_index = N - 1;
387        self.next()
388    }
389
390    #[inline(always)]
391    fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
392        let advance = n.min(self.remaining());
393        self.leaf_index += advance;
394        NonZero::new(n - advance).map_or(Ok(()), Err)
395    }
396
397    #[inline(always)]
398    fn nth(&mut self, n: usize) -> Option<Self::Item> {
399        match self.advance_by(n) {
400            Ok(()) => self.next(),
401            Err(_) => None,
402        }
403    }
404}
405
406impl<const N: usize, H> ExactSizeIterator for ProofsIterator<'_, N, H>
407where
408    H: MerkleHasher,
409{
410    #[inline(always)]
411    fn len(&self) -> usize {
412        self.remaining()
413    }
414}
415
416// SAFETY: size_hint is always exact
417unsafe impl<const N: usize, H> TrustedLen for ProofsIterator<'_, N, H> where H: MerkleHasher {}