Skip to main content

ab_merkle_tree/
unbalanced.rs

1use crate::batching::{BUFFER_NUM_LEAVES, hash_buffered_leaves};
2use crate::{MerkleHasher, NewMerkleHasherForTreeSize};
3#[cfg(feature = "alloc")]
4use alloc::boxed::Box;
5#[cfg(feature = "alloc")]
6use alloc::vec::Vec;
7use core::cmp::Ordering;
8use core::iter::TrustedLen;
9use core::marker::PhantomCovariant;
10use core::mem::MaybeUninit;
11
12/// Number of elements in a proof for a tree with `MAX_N` leaves
13pub const PROOF_ELEMENTS<const MAX_N: u64>: usize = MAX_N.next_power_of_two().ilog2() as usize;
14const STACK_SIZE<const MAX_N: u64>: usize = MAX_N.next_power_of_two().ilog2() as usize + 1;
15/// Number of leaves in the buffer of [`UnbalancedMerkleTree::compute_root_only()`] and
16/// [`UnbalancedMerkleTree::compute_root_and_proof_in()`], which doesn't need to be larger than the
17/// largest perfect subtree of `MAX_N` leaves
18const BUFFER_NUM_LEAVES_FOR<const MAX_N: u64, H: MerkleHasher>: usize =
19    if MAX_N < BUFFER_NUM_LEAVES::<H> as u64 {
20        match MAX_N.checked_ilog2() {
21            Some(height) => 2usize.pow(height),
22            None => 1,
23        }
24    } else {
25        BUFFER_NUM_LEAVES::<H>
26    };
27const SUPPORTED_LEAVES_ARRAY_SIZE<const N: usize>: usize = {
28    assert!(N != 0, "Number of leaves must be greater than 0");
29    0
30};
31const USIZE_TO_U64<const N: usize>: u64 = N as u64;
32
33/// Merkle Tree variant that has pre-hashed leaves with arbitrary number of elements.
34///
35/// This can be considered a general case of [`BalancedMerkleTree`]. The root and proofs are
36/// identical for both in case the number of leaves is a power of two. [`BalancedMerkleTree`] is
37/// more efficient and should be preferred when possible.
38///
39/// [`BalancedMerkleTree`]: crate::balanced::BalancedMerkleTree
40///
41/// The unbalanced tree is not padded, it is created the same way Merkle Mountain Range would be:
42/// ```text
43///               Root
44///         /--------------\
45///        H3              H4
46///    /-------\         /----\
47///   H0       H1       H2     \
48///  /  \     /  \     /  \     \
49/// L0  L1   L2  L3   L4  L5    L6
50/// ```
51///
52/// Inner nodes are hashed with `H`, which is created from the number of leaves. That is why methods
53/// that take an iterator of leaves require a [`TrustedLen`] iterator. Variants with `dynamic_len`
54/// in their name accept any iterator instead, but only support hashers that implement [`Default`].
55#[derive(Debug)]
56pub struct UnbalancedMerkleTree<H>(PhantomCovariant<H>);
57
58impl<H> UnbalancedMerkleTree<H>
59where
60    H: MerkleHasher,
61{
62    /// Compute Merkle Tree Root.
63    ///
64    /// `MAX_N` generic constant defines the maximum number of elements supported and controls stack
65    /// usage.
66    ///
67    /// Returns `None` for an empty list of leaves, or if the number of leaves is larger than
68    /// `MAX_N`.
69    #[inline]
70    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
71    pub fn compute_root_only<'a, const MAX_N: u64, Item, Iter>(
72        leaves: Iter,
73    ) -> Option<[u8; H::OUT_LEN]>
74    where
75        H: NewMerkleHasherForTreeSize,
76        Item: Into<[u8; H::OUT_LEN]>,
77        Iter: IntoIterator<Item = Item, IntoIter: TrustedLen> + 'a,
78    {
79        let leaves = leaves.into_iter();
80        let hasher = Self::hasher_for_leaves(&leaves)?;
81
82        Self::compute_root_only_with::<MAX_N, _, _>(&hasher, leaves)
83    }
84
85    /// Similar to [`Self::compute_root_only()`], but for iterators that are not [`TrustedLen`]
86    #[inline]
87    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
88    pub fn compute_root_only_dynamic_len<'a, const MAX_N: u64, Item, Iter>(
89        leaves: Iter,
90    ) -> Option<[u8; H::OUT_LEN]>
91    where
92        H: Default,
93        Item: Into<[u8; H::OUT_LEN]>,
94        Iter: IntoIterator<Item = Item> + 'a,
95    {
96        let hasher = H::default();
97
98        Self::compute_root_only_with::<MAX_N, _, _>(&hasher, leaves)
99    }
100
101    #[inline]
102    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
103    fn compute_root_only_with<const MAX_N: u64, Item, Iter>(
104        hasher: &H,
105        leaves: Iter,
106    ) -> Option<[u8; H::OUT_LEN]>
107    where
108        Item: Into<[u8; H::OUT_LEN]>,
109        Iter: IntoIterator<Item = Item>,
110    {
111        if BUFFER_NUM_LEAVES_FOR::<MAX_N, H> > 1 {
112            return Self::compute_root_only_buffered::<MAX_N, _, _>(hasher, leaves);
113        }
114
115        // Stack of intermediate nodes per tree level
116        let mut stack = [[0u8; H::OUT_LEN]; STACK_SIZE::<MAX_N>];
117        let mut num_leaves = 0u64;
118
119        for hash in leaves {
120            // How many leaves were processed so far. Should have been `num_leaves == MAX_N`, but
121            // `>=` helps compiler with panic safety checks.
122            // TODO: Use `==` once https://github.com/rust-lang/rust/issues/162834 is resolved
123            if num_leaves >= MAX_N {
124                return None;
125            }
126
127            let mut current = hash.into();
128
129            // Every bit set to `1` corresponds to an active Merkle Tree level
130            let lowest_active_levels = num_leaves.trailing_ones() as usize;
131            for item in stack.iter().take(lowest_active_levels) {
132                current = hasher.hash_pair(&[*item, current]);
133            }
134
135            // Place the current hash at the first inactive level
136            stack[lowest_active_levels] = current;
137            num_leaves += 1;
138        }
139
140        if num_leaves == 0 {
141            // If no leaves were provided
142            return None;
143        }
144
145        // SAFETY: `num_leaves` is not zero, not larger than `MAX_N`, and peaks of all `num_leaves`
146        // leaves are on the stack
147        Some(unsafe { Self::root_from_peaks::<MAX_N>(hasher, &mut stack, num_leaves) })
148    }
149
150    /// Similar to [`Self::compute_root_only_with()`], but buffers leaves and hashes them as
151    /// perfect subtrees, which hashes many pairs at once
152    #[inline(always)]
153    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
154    fn compute_root_only_buffered<const MAX_N: u64, Item, Iter>(
155        hasher: &H,
156        leaves: Iter,
157    ) -> Option<[u8; H::OUT_LEN]>
158    where
159        Item: Into<[u8; H::OUT_LEN]>,
160        Iter: IntoIterator<Item = Item>,
161    {
162        // Stack of intermediate nodes per tree level
163        let mut stack = [[0u8; H::OUT_LEN]; STACK_SIZE::<MAX_N>];
164        let mut buffer =
165            [MaybeUninit::<[u8; H::OUT_LEN]>::uninit(); BUFFER_NUM_LEAVES_FOR::<MAX_N, H>];
166        let mut num_leaves = 0u64;
167
168        for hash in leaves {
169            // How many leaves were processed so far. Should have been `num_leaves == MAX_N`, but
170            // `>=` helps compiler with panic safety checks.
171            // TODO: Use `==` once https://github.com/rust-lang/rust/issues/162834 is resolved
172            if num_leaves >= MAX_N {
173                return None;
174            }
175
176            // Truncation keeps the lowest bits, which are the index in the buffer
177            let buffer_index = num_leaves as usize % BUFFER_NUM_LEAVES_FOR::<MAX_N, H>;
178            buffer
179                .get_mut(buffer_index)
180                .expect("Index is a remainder of division by the buffer size; qed")
181                .write(hash.into());
182            num_leaves += 1;
183
184            if buffer_index == BUFFER_NUM_LEAVES_FOR::<MAX_N, H> - 1 {
185                // SAFETY: Leaves were written to all indices of the buffer, which starts at a
186                // multiple of its size, and `num_leaves` is not larger than `MAX_N`
187                unsafe {
188                    Self::push_buffered_leaves::<MAX_N>(
189                        hasher,
190                        &mut stack,
191                        &mut buffer,
192                        num_leaves,
193                        BUFFER_NUM_LEAVES_FOR::<MAX_N, H>,
194                    );
195                }
196            }
197        }
198
199        if num_leaves == 0 {
200            // If no leaves were provided
201            return None;
202        }
203
204        // Truncation keeps the lowest bits, which are the number of leaves in the buffer
205        let num_buffered = num_leaves as usize % BUFFER_NUM_LEAVES_FOR::<MAX_N, H>;
206        // SAFETY: Leaves were written to the buffer up to `num_buffered`, it starts at a multiple
207        // of its size, and `num_leaves` is not larger than `MAX_N`
208        unsafe {
209            Self::push_buffered_leaves::<MAX_N>(
210                hasher,
211                &mut stack,
212                &mut buffer,
213                num_leaves,
214                num_buffered,
215            );
216        }
217
218        // SAFETY: `num_leaves` is not zero, not larger than `MAX_N`, and peaks of all `num_leaves`
219        // leaves are on the stack
220        Some(unsafe { Self::root_from_peaks::<MAX_N>(hasher, &mut stack, num_leaves) })
221    }
222
223    /// Push the last `num_buffered` leaves of `num_leaves` leaves, which are at the beginning of
224    /// the buffer, as perfect subtrees.
225    ///
226    /// # Safety
227    /// `num_buffered` leaves must be initialized, `num_leaves - num_buffered` must be a multiple of
228    /// the buffer size and `num_leaves` must not be larger than `MAX_N`.
229    #[inline(always)]
230    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
231    unsafe fn push_buffered_leaves<const MAX_N: u64>(
232        hasher: &H,
233        stack: &mut [[u8; H::OUT_LEN]; STACK_SIZE::<MAX_N>],
234        buffer: &mut [MaybeUninit<[u8; H::OUT_LEN]>; BUFFER_NUM_LEAVES_FOR::<MAX_N, H>],
235        num_leaves: u64,
236        num_buffered: usize,
237    ) {
238        let first_leaf = num_leaves - num_buffered as u64;
239        // SAFETY: `num_buffered` is not larger than the buffer, and these leaves are initialized.
240        // Subtrees start at multiples of their sizes because the buffer does, and end within
241        // `num_leaves`, which is not larger than `MAX_N`, as `Self::push_subtree()` requires.
242        unsafe {
243            hash_buffered_leaves(hasher, buffer, 0, num_buffered, |offset, height, root| {
244                Self::push_subtree::<MAX_N>(
245                    hasher,
246                    stack,
247                    first_leaf + offset as u64,
248                    height as usize,
249                    root,
250                );
251            });
252        }
253    }
254
255    /// Hash peaks of `num_leaves` leaves on the `stack` together into the root.
256    ///
257    /// # Safety
258    /// `num_leaves` must not be zero or larger than `MAX_N`, and peaks of all `num_leaves` leaves
259    /// must be on the `stack`.
260    #[inline(always)]
261    unsafe fn root_from_peaks<const MAX_N: u64>(
262        hasher: &H,
263        stack: &mut [[u8; H::OUT_LEN]; STACK_SIZE::<MAX_N>],
264        num_leaves: u64,
265    ) -> [u8; H::OUT_LEN] {
266        let mut stack_bits = num_leaves;
267
268        {
269            let lowest_active_level = stack_bits.trailing_zeros() as usize;
270            // Reuse `stack[0]` for resulting value
271            // SAFETY: Active level must have been set successfully before, hence it exists
272            stack[0] = *unsafe { stack.get_unchecked(lowest_active_level) };
273            // Clear lowest active level
274            stack_bits &= !(1 << lowest_active_level);
275        }
276
277        // Hash remaining peaks (if any) of the potentially unbalanced tree together
278        loop {
279            let lowest_active_level = stack_bits.trailing_zeros() as usize;
280
281            if lowest_active_level == u64::BITS as usize {
282                break;
283            }
284
285            // Clear lowest active level for next iteration
286            stack_bits &= !(1 << lowest_active_level);
287
288            // SAFETY: Active level must have been set successfully before, hence it exists
289            let lowest_active_level_item = unsafe { stack.get_unchecked(lowest_active_level) };
290
291            stack[0] = hasher.hash_pair(&[*lowest_active_level_item, stack[0]]);
292        }
293
294        if num_leaves == 1 {
295            stack[0] = hasher.hash_single_leaf(&stack[0]);
296        }
297
298        stack[0]
299    }
300
301    /// Compute Merkle Tree Root of `num_leaves` leaves, which are all zeroes except `leaves`.
302    ///
303    /// `leaves` are pairs of leaf index and leaf, with strictly increasing indices. Produces the
304    /// same root as [`Self::compute_root_only()`] with zeroes in all other positions, but hashes
305    /// runs of zero leaves as whole subtrees, so the number of hashes is proportional to the number
306    /// of `leaves` and the height of the tree rather than to `num_leaves`.
307    ///
308    /// `MAX_N` generic constant defines the maximum number of elements supported and controls stack
309    /// usage.
310    ///
311    /// Returns `None` if `num_leaves` is zero or larger than `MAX_N`, or if indices aren't strictly
312    /// increasing or not smaller than `num_leaves`.
313    #[inline]
314    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
315    pub fn compute_root_only_sparse<const MAX_N: u64, Item, Iter>(
316        num_leaves: u64,
317        leaves: Iter,
318    ) -> Option<[u8; H::OUT_LEN]>
319    where
320        H: NewMerkleHasherForTreeSize,
321        Item: Into<[u8; H::OUT_LEN]>,
322        Iter: IntoIterator<Item = (u64, Item)>,
323    {
324        // TODO: Runs of consecutive leaves could be buffered and hashed as perfect subtrees like
325        //  in `compute_root_only()`
326        if num_leaves == 0 || num_leaves > MAX_N {
327            return None;
328        }
329
330        let hasher = H::new_for_tree_size(num_leaves);
331        // Stack of intermediate nodes per tree level
332        let mut stack = [[0u8; H::OUT_LEN]; STACK_SIZE::<MAX_N>];
333        // Roots of perfect subtrees of zero leaves per height, filled up to `zeros_height`
334        let mut zeros = [[0u8; H::OUT_LEN]; STACK_SIZE::<MAX_N>];
335        let mut zeros_height = 0;
336        // Number of leaves processed so far, including zero leaves
337        let mut processed = 0u64;
338
339        for (index, leaf) in leaves {
340            if index < processed || index >= num_leaves {
341                return None;
342            }
343
344            // SAFETY: `processed <= index < num_leaves <= MAX_N`
345            unsafe {
346                Self::push_zero_leaves::<MAX_N>(
347                    &hasher,
348                    &mut stack,
349                    &mut zeros,
350                    &mut zeros_height,
351                    &mut processed,
352                    index,
353                );
354            }
355            // SAFETY: Any `processed` is a multiple of `2^0` and `processed + 1 <= num_leaves`,
356            // which is not larger than `MAX_N`
357            unsafe {
358                Self::push_subtree::<MAX_N>(&hasher, &mut stack, processed, 0, leaf.into());
359            }
360            processed += 1;
361        }
362
363        // SAFETY: `processed <= num_leaves <= MAX_N`
364        unsafe {
365            Self::push_zero_leaves::<MAX_N>(
366                &hasher,
367                &mut stack,
368                &mut zeros,
369                &mut zeros_height,
370                &mut processed,
371                num_leaves,
372            );
373        }
374
375        // SAFETY: `num_leaves` is not zero, not larger than `MAX_N`, and peaks of all `num_leaves`
376        // leaves are on the stack
377        Some(unsafe { Self::root_from_peaks::<MAX_N>(&hasher, &mut stack, num_leaves) })
378    }
379
380    /// Push zero leaves until `processed` reaches `target`, as perfect subtrees that are as large
381    /// as possible.
382    ///
383    /// # Safety
384    /// `processed` must not be larger than `target`, which must not be larger than `MAX_N`.
385    #[inline(always)]
386    unsafe fn push_zero_leaves<const MAX_N: u64>(
387        hasher: &H,
388        stack: &mut [[u8; H::OUT_LEN]; STACK_SIZE::<MAX_N>],
389        zeros: &mut [[u8; H::OUT_LEN]; STACK_SIZE::<MAX_N>],
390        zeros_height: &mut usize,
391        processed: &mut u64,
392        target: u64,
393    ) {
394        while let Some(height) = (target - *processed).checked_ilog2() {
395            // The largest subtree that fits into the remaining zero leaves and starts at a multiple
396            // of its size
397            let height = height.min(processed.trailing_zeros()) as usize;
398
399            while *zeros_height < height {
400                // SAFETY: `height` is at most `log2(MAX_N)`, which is within `STACK_SIZE`
401                let zero = unsafe { zeros.get_unchecked(*zeros_height) };
402                let zero = hasher.hash_pair(&[*zero, *zero]);
403                *zeros_height += 1;
404                // SAFETY: `height` is at most `log2(MAX_N)`, which is within `STACK_SIZE`
405                *unsafe { zeros.get_unchecked_mut(*zeros_height) } = zero;
406            }
407
408            // SAFETY: `height` is at most `log2(MAX_N)`, which is within `STACK_SIZE`
409            let zero = *unsafe { zeros.get_unchecked(height) };
410            // SAFETY: `processed` is a multiple of `2^height` and `processed + 2^height <= target`,
411            // which is not larger than `MAX_N`
412            unsafe {
413                Self::push_subtree::<MAX_N>(hasher, stack, *processed, height, zero);
414            }
415            *processed += 1 << height;
416        }
417    }
418
419    /// Push the root of a perfect subtree of height `height` after `processed` leaves, merging it
420    /// with the peaks it completes the same way as [`Self::compute_root_only()`] merges a leaf.
421    ///
422    /// # Safety
423    /// `processed` must be a multiple of `2^height`, and `processed + 2^height` must not be larger
424    /// than `MAX_N`.
425    #[inline(always)]
426    unsafe fn push_subtree<const MAX_N: u64>(
427        hasher: &H,
428        stack: &mut [[u8; H::OUT_LEN]; STACK_SIZE::<MAX_N>],
429        processed: u64,
430        height: usize,
431        mut node: [u8; H::OUT_LEN],
432    ) {
433        // Every bit set to `1` corresponds to an active Merkle Tree level
434        let active_levels = (processed >> height).trailing_ones() as usize;
435        for item in stack.iter().skip(height).take(active_levels) {
436            node = hasher.hash_pair(&[*item, node]);
437        }
438
439        // Place the node at the first inactive level.
440        //
441        // SAFETY: Bit `height + active_levels` is set in `processed + 2^height`, which is not
442        // larger than `MAX_N`, so the level is at most `log2(MAX_N)`, which is within `STACK_SIZE`
443        *unsafe { stack.get_unchecked_mut(height + active_levels) } = node;
444    }
445
446    /// Compute Merkle Tree Root for an array of leaves.
447    ///
448    /// Similar to [`Self::compute_root_only()`], but for inputs that are small arrays where `MAX_N`
449    /// is the same as the array length.
450    #[inline(always)]
451    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
452    pub fn compute_root_only_array<const N: usize, Item>(leaves: &[Item; N]) -> [u8; H::OUT_LEN]
453    where
454        H: const NewMerkleHasherForTreeSize,
455        [(); SUPPORTED_LEAVES_ARRAY_SIZE::<N>]:,
456        Item: Into<[u8; H::OUT_LEN]> + Copy,
457    {
458        // TODO: Technically redundant with the where-clause, which is not enforced in generic code
459        //  due to https://github.com/rust-lang/rust/issues/164019, remove once fixed
460        const { SUPPORTED_LEAVES_ARRAY_SIZE::<N> };
461
462        let hasher = const { H::new_for_tree_size(N as u64) };
463        // Iterating over indices rather than with `leaves.iter().copied()` allows the compiler to
464        // prove that the root always exists on aarch64 and riscv64 too
465        let leaves = (0..N).map(|index| *leaves.get(index).expect("Index is within array; qed"));
466        let maybe_root =
467            Self::compute_root_only_with::<{ USIZE_TO_U64::<N> }, _, _>(&hasher, leaves);
468        maybe_root.expect("Non-empty array with length matching `MAX_N` always has a root; qed")
469    }
470
471    /// Compute Merkle Tree root and generate a proof for the `leaf` at `target_index`.
472    ///
473    /// Returns `Some((root, proof))` on success, `None` if index is outside of list of leaves.
474    ///
475    /// `MAX_N` generic constant defines the maximum number of elements supported and controls stack
476    /// usage.
477    #[expect(clippy::type_complexity, reason = "Return type")]
478    #[inline]
479    #[cfg(feature = "alloc")]
480    pub fn compute_root_and_proof<'a, const MAX_N: u64, Item, Iter>(
481        leaves: Iter,
482        target_index: usize,
483    ) -> Option<([u8; H::OUT_LEN], Vec<[u8; H::OUT_LEN]>)>
484    where
485        H: NewMerkleHasherForTreeSize,
486        Item: Into<[u8; H::OUT_LEN]>,
487        Iter: IntoIterator<Item = Item, IntoIter: TrustedLen> + 'a,
488    {
489        let leaves = leaves.into_iter();
490        let hasher = Self::hasher_for_leaves(&leaves)?;
491
492        Self::compute_root_and_proof_with::<MAX_N, _, _>(&hasher, leaves, target_index)
493    }
494
495    /// Similar to [`Self::compute_root_and_proof()`], but for iterators that are not [`TrustedLen`]
496    #[expect(clippy::type_complexity, reason = "Return type")]
497    #[inline]
498    #[cfg(feature = "alloc")]
499    pub fn compute_root_and_proof_dynamic_len<'a, const MAX_N: u64, Item, Iter>(
500        leaves: Iter,
501        target_index: usize,
502    ) -> Option<([u8; H::OUT_LEN], Vec<[u8; H::OUT_LEN]>)>
503    where
504        H: Default,
505        Item: Into<[u8; H::OUT_LEN]>,
506        Iter: IntoIterator<Item = Item> + 'a,
507    {
508        let hasher = H::default();
509
510        Self::compute_root_and_proof_with::<MAX_N, _, _>(&hasher, leaves, target_index)
511    }
512
513    #[expect(clippy::type_complexity, reason = "Return type")]
514    #[inline(always)]
515    #[cfg(feature = "alloc")]
516    fn compute_root_and_proof_with<const MAX_N: u64, Item, Iter>(
517        hasher: &H,
518        leaves: Iter,
519        target_index: usize,
520    ) -> Option<([u8; H::OUT_LEN], Vec<[u8; H::OUT_LEN]>)>
521    where
522        Item: Into<[u8; H::OUT_LEN]>,
523        Iter: IntoIterator<Item = Item>,
524    {
525        // Stack of intermediate nodes per tree level
526        let mut stack = [[0u8; H::OUT_LEN]; _];
527        // SAFETY: Inner value is `MaybeUninit`
528        let mut proof =
529            unsafe { Box::<[MaybeUninit<[u8; H::OUT_LEN]>; _]>::new_uninit().assume_init() };
530
531        let (root, proof_length) = Self::compute_root_and_proof_inner::<MAX_N, _, _>(
532            hasher,
533            leaves,
534            target_index,
535            &mut stack,
536            &mut proof,
537        )?;
538
539        let proof_capacity = proof.len();
540        let proof = Box::into_raw(proof);
541        // SAFETY: Points to correctly allocated memory where `proof_length` elements were
542        // initialized
543        let proof = unsafe {
544            Vec::from_raw_parts(
545                proof.cast::<[u8; H::OUT_LEN]>(),
546                proof_length,
547                proof_capacity,
548            )
549        };
550
551        Some((root, proof))
552    }
553
554    /// Compute Merkle Tree root and generate a proof for the `leaf` at `target_index`.
555    ///
556    /// Returns `Some((root, proof))` on success, `None` if index is outside of list of leaves.
557    ///
558    /// `MAX_N` generic constant defines the maximum number of elements supported and controls stack
559    /// usage.
560    #[expect(clippy::type_complexity, reason = "Return type")]
561    #[inline]
562    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
563    pub fn compute_root_and_proof_in<'a, 'proof, const MAX_N: u64, Item, Iter>(
564        leaves: Iter,
565        target_index: usize,
566        proof: &'proof mut [MaybeUninit<[u8; H::OUT_LEN]>; PROOF_ELEMENTS::<MAX_N>],
567    ) -> Option<([u8; H::OUT_LEN], &'proof mut [[u8; H::OUT_LEN]])>
568    where
569        H: NewMerkleHasherForTreeSize,
570        Item: Into<[u8; H::OUT_LEN]>,
571        Iter: IntoIterator<Item = Item, IntoIter: TrustedLen> + 'a,
572    {
573        let leaves = leaves.into_iter();
574        let hasher = Self::hasher_for_leaves(&leaves)?;
575
576        Self::compute_root_and_proof_in_with::<MAX_N, _, _>(&hasher, leaves, target_index, proof)
577    }
578
579    /// Similar to [`Self::compute_root_and_proof_in()`], but for iterators that are not
580    /// [`TrustedLen`]
581    #[expect(clippy::type_complexity, reason = "Return type")]
582    #[inline]
583    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
584    pub fn compute_root_and_proof_dynamic_len_in<'a, 'proof, const MAX_N: u64, Item, Iter>(
585        leaves: Iter,
586        target_index: usize,
587        proof: &'proof mut [MaybeUninit<[u8; H::OUT_LEN]>; PROOF_ELEMENTS::<MAX_N>],
588    ) -> Option<([u8; H::OUT_LEN], &'proof mut [[u8; H::OUT_LEN]])>
589    where
590        H: Default,
591        Item: Into<[u8; H::OUT_LEN]>,
592        Iter: IntoIterator<Item = Item> + 'a,
593    {
594        let hasher = H::default();
595
596        Self::compute_root_and_proof_in_with::<MAX_N, _, _>(&hasher, leaves, target_index, proof)
597    }
598
599    #[expect(clippy::type_complexity, reason = "Return type")]
600    #[inline(always)]
601    fn compute_root_and_proof_in_with<'proof, const MAX_N: u64, Item, Iter>(
602        hasher: &H,
603        leaves: Iter,
604        target_index: usize,
605        proof: &'proof mut [MaybeUninit<[u8; H::OUT_LEN]>; PROOF_ELEMENTS::<MAX_N>],
606    ) -> Option<([u8; H::OUT_LEN], &'proof mut [[u8; H::OUT_LEN]])>
607    where
608        Item: Into<[u8; H::OUT_LEN]>,
609        Iter: IntoIterator<Item = Item>,
610    {
611        // Stack of intermediate nodes per tree level
612        let mut stack = [[0u8; H::OUT_LEN]; _];
613
614        let (root, proof_length) = Self::compute_root_and_proof_inner::<MAX_N, _, _>(
615            hasher,
616            leaves,
617            target_index,
618            &mut stack,
619            proof,
620        )?;
621        // SAFETY: Just correctly initialized `proof_length` elements
622        let proof = unsafe { proof.get_unchecked_mut(..proof_length).assume_init_mut() };
623
624        Some((root, proof))
625    }
626
627    /// Returns the root and the number of proof elements, which are initialized at the beginning
628    /// of `proof`
629    #[inline]
630    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
631    fn compute_root_and_proof_inner<const MAX_N: u64, Item, Iter>(
632        hasher: &H,
633        leaves: Iter,
634        target_index: usize,
635        stack: &mut [[u8; H::OUT_LEN]; STACK_SIZE::<MAX_N>],
636        proof: &mut [MaybeUninit<[u8; H::OUT_LEN]>; PROOF_ELEMENTS::<MAX_N>],
637    ) -> Option<([u8; H::OUT_LEN], usize)>
638    where
639        Item: Into<[u8; H::OUT_LEN]>,
640        Iter: IntoIterator<Item = Item>,
641    {
642        // The buffer that contains the target leaf is split at it, such that its perfect subtrees
643        // have at most half of its leaves, so buffers of fewer than 8 leaves hash at most one pair
644        // at once for it, which is slower than hashing pairs one by one
645        if BUFFER_NUM_LEAVES_FOR::<MAX_N, H> >= 8 {
646            return Self::compute_root_and_proof_buffered::<MAX_N, _, _>(
647                hasher,
648                leaves,
649                target_index,
650                stack,
651                proof,
652            );
653        }
654
655        let mut proof_length = 0;
656        let mut num_leaves = 0u64;
657
658        let mut current_target_level = None;
659        let mut position = target_index;
660
661        for (current_index, hash) in leaves.into_iter().enumerate() {
662            // How many leaves were processed so far. Should have been `num_leaves == MAX_N`, but
663            // `>=` helps compiler with panic safety checks.
664            // TODO: Use `==` once https://github.com/rust-lang/rust/issues/162834 is resolved
665            if num_leaves >= MAX_N {
666                return None;
667            }
668
669            let mut current = hash.into();
670
671            // Every bit set to `1` corresponds to an active Merkle Tree level
672            let lowest_active_levels = num_leaves.trailing_ones() as usize;
673
674            if current_index == target_index {
675                for item in stack.iter().take(lowest_active_levels) {
676                    // If at the target leaf index, need to collect the proof
677                    // SAFETY: Method signature guarantees upper bound of the proof length
678                    unsafe { proof.get_unchecked_mut(proof_length) }.write(*item);
679                    proof_length += 1;
680
681                    current = hasher.hash_pair(&[*item, current]);
682
683                    // Move up the tree
684                    position /= 2;
685                }
686
687                current_target_level = Some(lowest_active_levels);
688            } else {
689                for (level, item) in stack.iter().enumerate().take(lowest_active_levels) {
690                    if current_target_level == Some(level) {
691                        // SAFETY: Method signature guarantees upper bound of the proof length
692                        unsafe { proof.get_unchecked_mut(proof_length) }.write(
693                            if position.is_multiple_of(2) {
694                                current
695                            } else {
696                                *item
697                            },
698                        );
699                        proof_length += 1;
700
701                        current_target_level = Some(level + 1);
702
703                        // Move up the tree
704                        position /= 2;
705                    }
706
707                    current = hasher.hash_pair(&[*item, current]);
708                }
709            }
710
711            // Place the current hash at the first inactive level
712            stack[lowest_active_levels] = current;
713            num_leaves += 1;
714        }
715
716        // `active_levels` here contains the number of leaves after above loop
717        if target_index >= num_leaves as usize {
718            // If no leaves were provided
719            return None;
720        }
721
722        let Some(current_target_level) = current_target_level else {
723            // Index not found
724            return None;
725        };
726
727        let mut stack_bits = num_leaves;
728
729        {
730            let lowest_active_level = stack_bits.trailing_zeros() as usize;
731            // Reuse `stack[0]` for resulting value
732            // SAFETY: Active level must have been set successfully before, hence it exists
733            stack[0] = *unsafe { stack.get_unchecked(lowest_active_level) };
734            // Clear lowest active level
735            stack_bits &= !(1 << lowest_active_level);
736        }
737
738        // Hash remaining peaks (if any) of the potentially unbalanced tree together and collect
739        // proof hashes
740        let mut merged_peaks = false;
741        loop {
742            let lowest_active_level = stack_bits.trailing_zeros() as usize;
743
744            if lowest_active_level == u64::BITS as usize {
745                break;
746            }
747
748            // Clear lowest active level for next iteration
749            stack_bits &= !(1 << lowest_active_level);
750
751            // SAFETY: Active level must have been set successfully before, hence it exists
752            let lowest_active_level_item = unsafe { stack.get_unchecked(lowest_active_level) };
753
754            if lowest_active_level > current_target_level
755                || (lowest_active_level == current_target_level
756                    && !position.is_multiple_of(2)
757                    && !merged_peaks)
758            {
759                // SAFETY: Method signature guarantees upper bound of the proof length
760                unsafe { proof.get_unchecked_mut(proof_length) }.write(*lowest_active_level_item);
761                proof_length += 1;
762                merged_peaks = false;
763            } else if lowest_active_level == current_target_level {
764                // SAFETY: Method signature guarantees upper bound of the proof length
765                unsafe { proof.get_unchecked_mut(proof_length) }.write(stack[0]);
766                proof_length += 1;
767                merged_peaks = false;
768            } else {
769                // Not collecting proof because of the need to merge peaks of an unbalanced tree
770                merged_peaks = true;
771            }
772
773            // Collect the lowest peak into the proof
774            stack[0] = hasher.hash_pair(&[*lowest_active_level_item, stack[0]]);
775
776            position /= 2;
777        }
778
779        if num_leaves == 1 {
780            stack[0] = hasher.hash_single_leaf(&stack[0]);
781        }
782
783        Some((stack[0], proof_length))
784    }
785
786    /// Similar to [`Self::compute_root_and_proof_inner()`], but buffers leaves and hashes them as
787    /// perfect subtrees, which hashes many pairs at once
788    #[inline(always)]
789    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
790    fn compute_root_and_proof_buffered<const MAX_N: u64, Item, Iter>(
791        hasher: &H,
792        leaves: Iter,
793        target_index: usize,
794        stack: &mut [[u8; H::OUT_LEN]; STACK_SIZE::<MAX_N>],
795        proof: &mut [MaybeUninit<[u8; H::OUT_LEN]>; PROOF_ELEMENTS::<MAX_N>],
796    ) -> Option<([u8; H::OUT_LEN], usize)>
797    where
798        Item: Into<[u8; H::OUT_LEN]>,
799        Iter: IntoIterator<Item = Item>,
800    {
801        let target_index = target_index as u64;
802        let mut buffer =
803            [MaybeUninit::<[u8; H::OUT_LEN]>::uninit(); BUFFER_NUM_LEAVES_FOR::<MAX_N, H>];
804        let mut num_leaves = 0u64;
805
806        for hash in leaves {
807            // How many leaves were processed so far. Should have been `num_leaves == MAX_N`, but
808            // `>=` helps compiler with panic safety checks.
809            // TODO: Use `==` once https://github.com/rust-lang/rust/issues/162834 is resolved
810            if num_leaves >= MAX_N {
811                return None;
812            }
813
814            // Truncation keeps the lowest bits, which are the index in the buffer
815            let buffer_index = num_leaves as usize % BUFFER_NUM_LEAVES_FOR::<MAX_N, H>;
816            buffer
817                .get_mut(buffer_index)
818                .expect("Index is a remainder of division by the buffer size; qed")
819                .write(hash.into());
820            num_leaves += 1;
821
822            if buffer_index == BUFFER_NUM_LEAVES_FOR::<MAX_N, H> - 1 {
823                // SAFETY: Leaves were written to all indices of the buffer
824                unsafe {
825                    Self::push_buffered_leaves_with_proof::<MAX_N>(
826                        hasher,
827                        stack,
828                        proof,
829                        &mut buffer,
830                        target_index,
831                        num_leaves,
832                        BUFFER_NUM_LEAVES_FOR::<MAX_N, H>,
833                    );
834                }
835            }
836        }
837
838        if target_index >= num_leaves {
839            // If the target leaf was not provided
840            return None;
841        }
842
843        // Truncation keeps the lowest bits, which are the number of leaves in the buffer
844        let num_buffered = num_leaves as usize % BUFFER_NUM_LEAVES_FOR::<MAX_N, H>;
845        // SAFETY: Leaves were written to the buffer up to `num_buffered`
846        unsafe {
847            Self::push_buffered_leaves_with_proof::<MAX_N>(
848                hasher,
849                stack,
850                proof,
851                &mut buffer,
852                target_index,
853                num_leaves,
854                num_buffered,
855            );
856        }
857
858        // The peak that contains the target leaf is at the highest level in which its index and the
859        // number of leaves differ
860        let target_level = (target_index ^ num_leaves).ilog2();
861        // Proof elements below that level are initialized already. The target leaf was pushed
862        // alone, so every node that contains it below that level was created by merging two nodes
863        // in the stack, one of which contains it, and each of these merges wrote the other one into
864        // the proof at its level, which is within the proof because the merged node has at most
865        // `MAX_N` leaves.
866        let mut proof_length = target_level as usize;
867        // Peaks are at levels of bits set to `1` in the number of leaves and are hashed together
868        // from the lowest to the highest
869        let mut peaks = (0..u64::BITS)
870            .zip(stack.iter())
871            .filter(|&(level, _)| num_leaves & (1 << level) != 0);
872        // A tree with leaves has at least one peak
873        let (_, root) = peaks.next()?;
874        let mut root = *root;
875        for (level, peak) in peaks {
876            // Peaks below the peak that contains the target leaf are hashed into its sibling, peaks
877            // above it are siblings of nodes that contain it
878            if level >= target_level
879                && let Some(element) = proof.get_mut(proof_length)
880            {
881                element.write(if level == target_level { root } else { *peak });
882                proof_length += 1;
883            }
884
885            root = hasher.hash_pair(&[*peak, root]);
886        }
887
888        if num_leaves == 1 {
889            root = hasher.hash_single_leaf(&root);
890        }
891
892        Some((root, proof_length))
893    }
894
895    /// Push the last `num_buffered` leaves of `num_leaves` leaves, which are at the beginning of
896    /// the buffer, like [`Self::push_buffered_leaves()`], and collect the proof of the leaf at
897    /// `target_index` below the peak that contains it.
898    ///
899    /// `num_leaves - num_buffered` must be a multiple of the buffer size and `num_leaves` must not
900    /// be larger than `MAX_N`. Every merge of two nodes in the stack, one of which contains the
901    /// target leaf, writes the other one into the proof at their level. The target leaf is pushed
902    /// alone, such that the leaves before and after it are hashed as perfect subtrees that don't
903    /// contain it.
904    ///
905    /// # Safety
906    /// `num_buffered` leaves must be initialized.
907    #[inline(always)]
908    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
909    unsafe fn push_buffered_leaves_with_proof<const MAX_N: u64>(
910        hasher: &H,
911        stack: &mut [[u8; H::OUT_LEN]; STACK_SIZE::<MAX_N>],
912        proof: &mut [MaybeUninit<[u8; H::OUT_LEN]>; PROOF_ELEMENTS::<MAX_N>],
913        buffer: &mut [MaybeUninit<[u8; H::OUT_LEN]>; BUFFER_NUM_LEAVES_FOR::<MAX_N, H>],
914        target_index: u64,
915        num_leaves: u64,
916        num_buffered: usize,
917    ) {
918        let first_leaf = num_leaves - num_buffered as u64;
919        // Index of the target leaf in the buffer, or the number of buffered leaves if it is not
920        // there
921        let target_offset = target_index
922            .wrapping_sub(first_leaf)
923            .min(num_buffered as u64) as usize;
924        let mut start = 0;
925        while start < num_buffered {
926            let end = match start.cmp(&target_offset) {
927                Ordering::Less => target_offset,
928                Ordering::Equal => start + 1,
929                Ordering::Greater => num_buffered,
930            };
931            // SAFETY: `end` is not larger than `num_buffered`, and that many leaves are
932            // initialized according to the function contract. Hashing leaves before `start` didn't
933            // change the leaves after it.
934            unsafe {
935                hash_buffered_leaves(hasher, buffer, start, end, |offset, height, mut node| {
936                    // Subtrees are pushed the same way as in `Self::push_subtree()`
937                    let processed = first_leaf + offset as u64;
938                    let height = height as usize;
939
940                    // Every bit set to `1` corresponds to an active Merkle Tree level
941                    let active_levels = (processed >> height).trailing_ones() as usize;
942                    for (level, item) in stack.iter().enumerate().skip(height).take(active_levels) {
943                        // The node is at the odd position `processed >> level` of its level and
944                        // the one in the stack is right before it, so if one of them contains the
945                        // target leaf, the other one is a proof element
946                        let target_position = target_index >> level;
947                        if target_position | 1 == processed >> level
948                            && let Some(element) = proof.get_mut(level)
949                        {
950                            element.write(if target_position.is_multiple_of(2) {
951                                node
952                            } else {
953                                *item
954                            });
955                        }
956
957                        node = hasher.hash_pair(&[*item, node]);
958                    }
959
960                    // Place the node at the first inactive level, which is within the stack for
961                    // subtrees within `MAX_N` leaves
962                    if let Some(slot) = stack.get_mut(height + active_levels) {
963                        *slot = node;
964                    }
965                });
966            }
967            start = end;
968        }
969    }
970
971    /// Verify a Merkle proof for a leaf at the given index
972    #[inline]
973    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
974    pub fn verify(
975        root: &[u8; H::OUT_LEN],
976        proof: &[[u8; H::OUT_LEN]],
977        leaf_index: u64,
978        leaf: [u8; H::OUT_LEN],
979        num_leaves: u64,
980    ) -> bool
981    where
982        H: NewMerkleHasherForTreeSize,
983    {
984        if leaf_index >= num_leaves {
985            return false;
986        }
987
988        let hasher = H::new_for_tree_size(num_leaves);
989        let mut current = leaf;
990        let mut position = leaf_index;
991        let mut proof_pos = 0;
992        let mut level_size = num_leaves;
993
994        // Rebuild the path to the root
995        while level_size > 1 {
996            let is_left = position.is_multiple_of(2);
997            let is_last = position == level_size - 1;
998
999            if is_left && !is_last {
1000                // Left node with a right sibling
1001                if proof_pos >= proof.len() {
1002                    // Missing sibling
1003                    return false;
1004                }
1005                current = hasher.hash_pair(&[current, proof[proof_pos]]);
1006                proof_pos += 1;
1007            } else if !is_left {
1008                // Right node with a left sibling
1009                if proof_pos >= proof.len() {
1010                    // Missing sibling
1011                    return false;
1012                }
1013                current = hasher.hash_pair(&[proof[proof_pos], current]);
1014                proof_pos += 1;
1015            } else {
1016                // Last node, no sibling, keep current
1017            }
1018
1019            position /= 2;
1020            // Size of next level
1021            level_size = level_size.div_ceil(2);
1022        }
1023
1024        if num_leaves == 1 {
1025            current = hasher.hash_single_leaf(&current);
1026        }
1027
1028        // Check if proof is fully used and matches root
1029        proof_pos == proof.len() && current == *root
1030    }
1031
1032    /// Create a hasher for a tree with `leaves`.
1033    ///
1034    /// Returns `None` if there are more than `usize::MAX` leaves.
1035    #[inline(always)]
1036    fn hasher_for_leaves<Iter>(leaves: &Iter) -> Option<H>
1037    where
1038        H: NewMerkleHasherForTreeSize,
1039        Iter: TrustedLen,
1040    {
1041        // `TrustedLen` guarantees that the iterator yields exactly this many leaves. An empty list
1042        // or more than `MAX_N` leaves are rejected while iterating, which avoids extra checks for
1043        // hashers that ignore the number of leaves.
1044        let (_lower, upper) = leaves.size_hint();
1045
1046        Some(H::new_for_tree_size(upper? as u64))
1047    }
1048}