Skip to main content

ab_merkle_tree/
sparse.rs

1//! Sparse Merkle Tree and related data structures.
2//!
3//! Sparse Merkle Tree is essentially a huge Balanced Merkle Tree, where most of the leaves are
4//! empty. By "empty" here we mean all zeroes. To optimize proofs and their verification, the
5//! hashing function is customized and returns all zeroes when both left and right branch are all
6//! zeroes, otherwise inner nodes are hashed like in a Balanced Merkle Tree.
7
8use crate::MerkleHasher;
9use crate::batching::{BUFFER_NUM_LEAVES, PARALLEL_PAIRS, perfect_subtree_root};
10use core::marker::PhantomCovariant;
11use core::mem::MaybeUninit;
12use core::num::NonZeroU128;
13
14/// Number of elements in a proof for a tree with `BITS`
15pub const PROOF_ELEMENTS<const BITS: u8>: usize = usize::from(BITS);
16const STACK_SIZE<const BITS: u8>: usize = usize::from(BITS) + 1;
17
18/// Ensuring only supported `NUM_BITS` can be specified for [`SparseMerkleTree`].
19///
20/// This is essentially a workaround for the current Rust type system constraints that do not allow
21/// a nicer way to do the same thing at compile time.
22const ENSURE_SUPPORTED_BITS<const BITS: u8>: usize = {
23    assert!(
24        BITS <= 128,
25        "This Sparse Merkle Tree doesn't support more than 2^128 leaves"
26    );
27
28    assert!(
29        BITS != 0,
30        "This Sparse Merkle Tree must have more than one leaf"
31    );
32
33    0
34};
35
36/// Sparse Merkle Tree Leaf
37#[derive(Debug)]
38pub enum Leaf<'a, H>
39where
40    H: MerkleHasher,
41{
42    /// Leaf contains a value
43    Occupied {
44        /// Leaf value
45        leaf: &'a [u8; H::OUT_LEN],
46    },
47    /// Leaf contains a value (owned)
48    OccupiedOwned {
49        /// Leaf value
50        leaf: [u8; H::OUT_LEN],
51    },
52    /// Leaf is empty
53    Empty {
54        /// Number of consecutive empty leaves
55        skip_count: NonZeroU128,
56    },
57}
58
59impl<'a, H> From<&'a [u8; H::OUT_LEN]> for Leaf<'a, H>
60where
61    H: MerkleHasher,
62{
63    #[inline(always)]
64    fn from(leaf: &'a [u8; H::OUT_LEN]) -> Self {
65        Self::Occupied { leaf }
66    }
67}
68
69/// Subtrees of buffered leaves that are lifted together before they are pushed into the stack of
70/// [`SparseMerkleTree::compute_root_only()`].
71///
72/// Each subtree is lifted to its target: the largest subtree that contains it and neither the
73/// previous nor the next subtree, below the whole tree. Subtrees with roots of all zeroes and the
74/// whole tree are not lifted. Paths of different subtrees are hashed together with
75/// [`MerkleHasher::hash_pairs()`].
76///
77/// Invariants:
78/// * subtrees are in order and start at or after `stack_leaves`, leaves between them are empty
79/// * `roots[i]` is the root of the subtree of `2^heights[i]` leaves that contains `first_leaves[i]`
80/// * `heights[i] <= targets[i]`, a target is capped by the previous subtree when its subtree is
81///   added and by the next subtree when that one is added, lanes are only pushed after that or at
82///   the end
83/// * `len <= MerkleHasher::PARALLEL_PAIRS`
84///
85/// Two consecutive subtrees are lifted to at most `2^limit` leaves, where `limit` is the highest
86/// bit in which their first leaves differ, so they end up in different halves of the subtree of
87/// `2^(limit + 1)` leaves that contains both. Lifted subtrees don't overlap, are in order and don't
88/// contain other occupied leaves. The same holds for the last subtree pushed into the stack, so
89/// they don't start before `stack_leaves`.
90struct Lanes<H>
91where
92    H: MerkleHasher,
93{
94    /// Root of the subtree of `2^height` leaves that contains the first leaf
95    roots: [[u8; H::OUT_LEN]; PARALLEL_PAIRS::<H>],
96    first_leaves: [u128; PARALLEL_PAIRS::<H>],
97    heights: [u8; PARALLEL_PAIRS::<H>],
98    /// Final once the next subtree is added
99    targets: [u8; PARALLEL_PAIRS::<H>],
100    len: usize,
101    /// First leaf of the last subtree added
102    previous_leaf: Option<u128>,
103    /// Leaves before this one are in the stack
104    stack_leaves: u128,
105}
106
107impl<H> Lanes<H>
108where
109    H: MerkleHasher,
110{
111    const EMPTY: Self = Self {
112        roots: [[0; H::OUT_LEN]; _],
113        first_leaves: [0; _],
114        heights: [0; _],
115        targets: [0; _],
116        len: 0,
117        previous_leaf: None,
118        stack_leaves: 0,
119    };
120
121    /// Root, first leaf, height and target of each subtree, in order
122    #[inline(always)]
123    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
124    fn iter(&self) -> impl Iterator<Item = (&[u8; H::OUT_LEN], u128, u8, u8)> {
125        self.roots
126            .iter()
127            .zip(&self.first_leaves)
128            .zip(self.heights.iter().zip(&self.targets))
129            .take(self.len)
130            .map(|((root, &first_leaf), (&height, &target))| (root, first_leaf, height, target))
131    }
132
133    /// Root, first leaf, height and target of each subtree, in order
134    #[inline(always)]
135    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
136    fn iter_mut(&mut self) -> impl Iterator<Item = (&mut [u8; H::OUT_LEN], u128, &mut u8, u8)> {
137        self.roots
138            .iter_mut()
139            .zip(&self.first_leaves)
140            .zip(self.heights.iter_mut().zip(&self.targets))
141            .take(self.len)
142            .map(|((root, &first_leaf), (height, &target))| (root, first_leaf, height, target))
143    }
144
145    /// Add a subtree after the subtrees in lanes, which must not be full
146    #[inline(always)]
147    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
148    fn push(&mut self, root: [u8; H::OUT_LEN], first_leaf: u128, height: u8, target: u8) {
149        if let (Some(lane_root), Some(lane_first_leaf), Some(lane_height), Some(lane_target)) = (
150            self.roots.get_mut(self.len),
151            self.first_leaves.get_mut(self.len),
152            self.heights.get_mut(self.len),
153            self.targets.get_mut(self.len),
154        ) {
155            *lane_root = root;
156            *lane_first_leaf = first_leaf;
157            *lane_height = height;
158            *lane_target = target;
159            self.len += 1;
160        }
161    }
162
163    /// Lift subtrees to their targets one level at a time
164    // Inlining is only prevented in normal builds, `no_panic` relies on it
165    #[cfg_attr(not(feature = "no-panic"), inline(never))]
166    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
167    fn lift(&mut self, hasher: &H) {
168        // Roots of subtrees below their targets next to their empty siblings, in order
169        let mut pairs = [[[0; H::OUT_LEN]; 2]; PARALLEL_PAIRS::<H>];
170        loop {
171            let mut num_pairs = 0;
172            for (root, first_leaf, height, target) in self.iter() {
173                if height < target
174                    && let Some(pair) = pairs.get_mut(num_pairs)
175                {
176                    *pair = if (first_leaf >> height).is_multiple_of(2) {
177                        [*root, [0; H::OUT_LEN]]
178                    } else {
179                        [[0; H::OUT_LEN], *root]
180                    };
181                    num_pairs += 1;
182                }
183            }
184
185            // The narrowest SIMD that hashes all pairs. There are at most
186            // `MerkleHasher::PARALLEL_PAIRS` of them, guards only keep arms with more pairs from
187            // being compiled.
188            match num_pairs {
189                1 => self.lift_level::<1>(hasher, &pairs),
190                2 if PARALLEL_PAIRS::<H> >= 2 => self.lift_level::<2>(hasher, &pairs),
191                3..=4 if PARALLEL_PAIRS::<H> >= 4 => self.lift_level::<4>(hasher, &pairs),
192                5..=8 if PARALLEL_PAIRS::<H> >= 8 => self.lift_level::<8>(hasher, &pairs),
193                9..=16 if PARALLEL_PAIRS::<H> >= 16 => self.lift_level::<16>(hasher, &pairs),
194                17..=32 if PARALLEL_PAIRS::<H> >= 32 => self.lift_level::<32>(hasher, &pairs),
195                33..=64 if PARALLEL_PAIRS::<H> >= 64 => self.lift_level::<64>(hasher, &pairs),
196                // All subtrees reached their targets
197                _ => break,
198            }
199        }
200    }
201
202    /// Hash the first `NUM_PAIRS` pairs, parents become roots of subtrees below their targets
203    #[inline(always)]
204    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
205    fn lift_level<const NUM_PAIRS: usize>(
206        &mut self,
207        hasher: &H,
208        pairs: &[[[u8; H::OUT_LEN]; 2]; PARALLEL_PAIRS::<H>],
209    ) {
210        if let Some(pairs) = pairs.first_chunk::<NUM_PAIRS>() {
211            let parents = hasher.hash_pairs(pairs);
212            // Pairs are in the order of subtrees below their targets, parents of the rest of the
213            // pairs are not used
214            let mut parents = parents.iter();
215            for (root, _, height, target) in self.iter_mut() {
216                if *height < target
217                    && let Some(parent) = parents.next()
218                {
219                    *root = *parent;
220                    *height += 1;
221                }
222            }
223        }
224    }
225}
226
227// TODO: A version that can hold intermediate nodes in memory, efficiently update leaves, etc.
228/// Sparse Merkle Tree variant that has hash-sized leaves, with most leaves being empty
229/// (all zeroes).
230///
231/// In contrast to a proper Balanced Merkle Tree, constant `BITS` here specifies the max number of
232/// leaves hypothetically possible in a tree (2^BITS, often intractable), rather than the number of
233/// non-empty leaves actually present.
234///
235/// Inner nodes are hashed with `H` (except when both children are empty), which is created with
236/// [`Default`] since the number of leaves is always `2^BITS`. Nodes of all zeroes are empty, so `H`
237/// must not hash nodes into all zeroes (cryptographic hashes practically never do), otherwise the
238/// root is ambiguous and may depend on [`MerkleHasher::PARALLEL_PAIRS`].
239#[derive(Debug)]
240pub struct SparseMerkleTree<const BITS: u8, H>(PhantomCovariant<H>);
241
242// TODO: Nodes in the stack are still hashed with empty siblings one pair at a time, paths of
243//  different nodes could be hashed in parallel with `MerkleHasher::hash_pairs()`
244impl<const BITS: u8, H> SparseMerkleTree<BITS, H>
245where
246    [(); ENSURE_SUPPORTED_BITS::<BITS>]:,
247    H: MerkleHasher + Default,
248{
249    const ZERO: [u8; H::OUT_LEN] = [0; H::OUT_LEN];
250
251    // TODO: Method that generates not only root, but also proof, like Unbalanced Merkle Tree
252    /// Compute Merkle Tree root.
253    ///
254    /// If provided iterator ends early, it means the rest of the leaves are empty.
255    ///
256    /// There must be no [`Leaf::Occupied`] for empty/unoccupied leaves or else they may result in
257    /// invalid root, [`Leaf::Empty`] must be used instead.
258    ///
259    /// Returns `None` if too many leaves were provided.
260    #[inline]
261    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
262    pub fn compute_root_only<'a, Iter>(leaves: Iter) -> Option<[u8; H::OUT_LEN]>
263    where
264        H: 'a,
265        Iter: IntoIterator<Item = Leaf<'a, H>> + 'a,
266    {
267        // TODO: Technically redundant with the where-clause, which is not enforced in generic code
268        //  due to https://github.com/rust-lang/rust/issues/164019, remove once fixed
269        const { ENSURE_SUPPORTED_BITS::<BITS> };
270
271        let hasher = H::default();
272
273        // Stack of intermediate nodes per tree level
274        let mut stack = [[0u8; H::OUT_LEN]; _];
275        let mut processed_some = false;
276        let mut num_leaves = 0u128;
277
278        if PARALLEL_PAIRS::<H> == 1 {
279            // Hashers that hash pairs one by one push each leaf into the stack right away, a loop
280            // doesn't need a frame for a closure like internal iteration below
281            for leaf in leaves {
282                if u32::from(BITS) < u128::BITS {
283                    // How many leaves were processed so far. Should have been
284                    // `num_leaves == 2^BITS`, but `>=` helps compiler with panic safety checks.
285                    // TODO: Use `==` once
286                    //  https://github.com/rust-lang/rust/issues/162834 is resolved
287                    if num_leaves >= 2u128.pow(u32::from(BITS)) {
288                        return None;
289                    }
290                } else {
291                    // For `BITS == u128::BITS` `num_leaves` will wrap around back to zero right at
292                    // the very end
293                    if processed_some && num_leaves == 0 {
294                        return None;
295                    }
296                    processed_some = true;
297                }
298
299                let mut current = match leaf {
300                    Leaf::Occupied { leaf } => *leaf,
301                    Leaf::OccupiedOwned { leaf } => leaf,
302                    Leaf::Empty { skip_count } => {
303                        num_leaves = Self::skip_leaves(
304                            &hasher,
305                            &mut stack,
306                            &mut processed_some,
307                            num_leaves,
308                            skip_count.get(),
309                        )?;
310                        continue;
311                    }
312                };
313
314                // Every bit set to `1` corresponds to an active Merkle Tree level
315                let lowest_active_levels = num_leaves.trailing_ones() as usize;
316                for item in stack.iter().take(lowest_active_levels) {
317                    current = hasher.hash_pair(&[*item, current]);
318                }
319
320                // Place the current hash at the first inactive level
321                *stack
322                    .get_mut(lowest_active_levels)
323                    .expect("Stack has `BITS + 1` levels, enough for `num_leaves < 2^BITS`; qed") =
324                    current;
325
326                // Wrapping is needed for `BITS == u128::BITS`, where number of leaves narrowly
327                // doesn't fit into `u128` itself
328                num_leaves = num_leaves.wrapping_add(1);
329            }
330
331            if u32::from(BITS) < u128::BITS {
332                Self::skip_leaves(
333                    &hasher,
334                    &mut stack,
335                    &mut processed_some,
336                    num_leaves,
337                    2u128.pow(u32::from(BITS)) - num_leaves,
338                )?;
339            } else if processed_some && num_leaves != 0 {
340                // For `BITS == u128::BITS` `num_leaves` will wrap around back to zero right at the
341                // very end, so we reverse the mechanism here
342                Self::skip_leaves(
343                    &hasher,
344                    &mut stack,
345                    &mut processed_some,
346                    num_leaves,
347                    0u128.wrapping_sub(num_leaves),
348                )?;
349            }
350        } else {
351            // Consecutive occupied leaves within a multiple of the buffer size, hashed together
352            // once the buffer is full, on the next empty leaf or at the end
353            let mut buffer = [MaybeUninit::<[u8; H::OUT_LEN]>::uninit(); BUFFER_NUM_LEAVES::<H>];
354            // Index of the first leaf in the buffer, which is empty if it is the index of the next
355            // leaf
356            let mut buffer_start = 0;
357            // Subtrees of buffered leaves are lifted in lanes before they are pushed into the stack
358            let mut lanes = Lanes::<H>::EMPTY;
359
360            // Adapters like `FlatMap` implement internal iteration as a loop over each inner
361            // iterator, which is much faster than pulling leaves with `Iterator::next()`
362            leaves.into_iter().try_for_each(|leaf| {
363                if u32::from(BITS) < u128::BITS {
364                    // How many leaves were processed so far. Should have been
365                    // `num_leaves == 2^BITS`, but `>=` helps compiler with panic safety checks.
366                    // TODO: Use `==` once
367                    //  https://github.com/rust-lang/rust/issues/162834 is resolved
368                    if num_leaves >= 2u128.pow(u32::from(BITS)) {
369                        return None;
370                    }
371                } else {
372                    // For `BITS == u128::BITS` `num_leaves` will wrap around back to zero right at
373                    // the very end
374                    if processed_some && num_leaves == 0 {
375                        return None;
376                    }
377                    processed_some = true;
378                }
379
380                let leaf = match leaf {
381                    Leaf::Occupied { leaf } => *leaf,
382                    Leaf::OccupiedOwned { leaf } => leaf,
383                    Leaf::Empty { skip_count } => {
384                        let buffer_end = num_leaves as usize % BUFFER_NUM_LEAVES::<H>;
385                        if buffer_start != buffer_end {
386                            // SAFETY: Leaves were written to the buffer from `buffer_start` up to
387                            // the index of the current leaf
388                            unsafe {
389                                Self::push_buffered_leaves(
390                                    &hasher,
391                                    &mut stack,
392                                    &mut lanes,
393                                    &mut buffer,
394                                    num_leaves,
395                                    buffer_start,
396                                    buffer_end,
397                                );
398                            }
399                        }
400                        // Empty leaves are pushed into the stack later, together with subtrees
401                        // after them
402                        num_leaves =
403                            Self::checked_skip(&mut processed_some, num_leaves, skip_count.get())?;
404                        // Truncation keeps the lowest bits, which are the index in the buffer
405                        buffer_start = num_leaves as usize % BUFFER_NUM_LEAVES::<H>;
406                        return Some(());
407                    }
408                };
409
410                // Truncation keeps the lowest bits, which are the index in the buffer
411                let buffer_index = num_leaves as usize % BUFFER_NUM_LEAVES::<H>;
412                buffer
413                    .get_mut(buffer_index)
414                    .expect("Index is a remainder of division by the buffer size; qed")
415                    .write(leaf);
416
417                if buffer_index == BUFFER_NUM_LEAVES::<H> - 1 {
418                    // SAFETY: Leaves were written to the buffer from `buffer_start` up to its end
419                    unsafe {
420                        Self::push_buffered_leaves(
421                            &hasher,
422                            &mut stack,
423                            &mut lanes,
424                            &mut buffer,
425                            num_leaves,
426                            buffer_start,
427                            BUFFER_NUM_LEAVES::<H>,
428                        );
429                    }
430                    buffer_start = 0;
431                }
432
433                // Wrapping is needed for `BITS == u128::BITS`, where number of leaves narrowly
434                // doesn't fit into `u128` itself
435                num_leaves = num_leaves.wrapping_add(1);
436                Some(())
437            })?;
438
439            let buffer_end = num_leaves as usize % BUFFER_NUM_LEAVES::<H>;
440            if buffer_start != buffer_end {
441                // SAFETY: Leaves were written to the buffer from `buffer_start` up to the index of
442                // the last leaf
443                unsafe {
444                    Self::push_buffered_leaves(
445                        &hasher,
446                        &mut stack,
447                        &mut lanes,
448                        &mut buffer,
449                        num_leaves,
450                        buffer_start,
451                        buffer_end,
452                    );
453                }
454            }
455
456            Self::push_lanes(&hasher, &mut stack, &mut lanes);
457            // For `BITS == u128::BITS` the number of leaves in the tree wraps around to zero just
458            // like `stack_leaves` does after the last leaf
459            let trailing_leaves = if u32::from(BITS) < u128::BITS {
460                2u128.pow(u32::from(BITS)) - lanes.stack_leaves
461            } else {
462                0u128.wrapping_sub(lanes.stack_leaves)
463            };
464            // Leaves in lanes and in the stack were checked to be within the tree already
465            Self::skip_leaves(
466                &hasher,
467                &mut stack,
468                &mut false,
469                lanes.stack_leaves,
470                trailing_leaves,
471            );
472        }
473
474        Some(stack[BITS as usize])
475    }
476
477    /// Push the root of a subtree of `2^height` leaves that starts at leaf `first_leaf`, merging it
478    /// with the nodes on the stack it completes
479    #[inline(always)]
480    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
481    fn push_subtree(
482        hasher: &H,
483        stack: &mut [[u8; H::OUT_LEN]; STACK_SIZE::<BITS>],
484        first_leaf: u128,
485        height: u32,
486        mut node: [u8; H::OUT_LEN],
487    ) {
488        // Every bit set to `1` corresponds to an active Merkle Tree level
489        let active_levels = (first_leaf >> height).trailing_ones() as usize;
490        for item in stack.iter().skip(height as usize).take(active_levels) {
491            node = hasher.hash_pair(&[*item, node]);
492        }
493
494        // Place the node at the first inactive level, which is within the stack for subtrees
495        // within the tree
496        if let Some(slot) = stack.get_mut(height as usize + active_levels) {
497            *slot = node;
498        }
499    }
500
501    /// Add leaves `buffer[start..end]` to lanes as the fewest perfect subtrees that start at
502    /// multiples of their sizes, `leaf_index` is the index of any leaf within the same multiple of
503    /// the buffer size.
504    ///
505    /// Contents of the buffer are meaningless afterward.
506    ///
507    /// # Safety
508    /// `end` must not be larger than the buffer size and leaves `buffer[start..end]` must be
509    /// initialized.
510    #[inline(always)]
511    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
512    unsafe fn push_buffered_leaves(
513        hasher: &H,
514        stack: &mut [[u8; H::OUT_LEN]; STACK_SIZE::<BITS>],
515        lanes: &mut Lanes<H>,
516        buffer: &mut [MaybeUninit<[u8; H::OUT_LEN]>; BUFFER_NUM_LEAVES::<H>],
517        leaf_index: u128,
518        mut start: usize,
519        end: usize,
520    ) {
521        // Truncation keeps the lowest bits, which are the index in the buffer
522        let buffer_first_leaf = leaf_index - (leaf_index as usize % BUFFER_NUM_LEAVES::<H>) as u128;
523
524        while start < end {
525            // The largest subtree that starts at a multiple of its size and ends within the range
526            let height = (end - start).ilog2().min(start.trailing_zeros());
527            // SAFETY: The subtree is within `buffer[start..end]`, which is within the buffer and
528            // initialized according to the function contract
529            let root = unsafe { Self::buffered_subtree_root(hasher, buffer, start, height) };
530            Self::add_subtree(
531                hasher,
532                stack,
533                lanes,
534                buffer_first_leaf + start as u128,
535                u8::try_from(height)
536                    .expect("Subtrees are within the buffer of 512 leaves at most; qed"),
537                root,
538            );
539            start += 2usize.pow(height);
540        }
541    }
542
543    /// Root of a perfect subtree of `2^height` leaves that starts at `buffer[start]`.
544    ///
545    /// Hashing needs more stack than anything else that processes leaves, a separate frame keeps
546    /// it off the stack while [`Self::push_lanes()`] runs. Leaves of the subtree in the buffer are
547    /// meaningless afterward.
548    ///
549    /// # Safety
550    /// `start + 2^height` must not be larger than the buffer size and leaves of the subtree must
551    /// be initialized.
552    // Inlining is only prevented in normal builds, `no_panic` relies on it
553    #[cfg_attr(not(feature = "no-panic"), inline(never))]
554    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
555    unsafe fn buffered_subtree_root(
556        hasher: &H,
557        buffer: &mut [MaybeUninit<[u8; H::OUT_LEN]>; BUFFER_NUM_LEAVES::<H>],
558        start: usize,
559        height: u32,
560    ) -> [u8; H::OUT_LEN] {
561        // SAFETY: Guaranteed by the function contract
562        let leaves = unsafe {
563            buffer
564                .get_unchecked_mut(start..start + 2usize.pow(height))
565                .assume_init_mut()
566        };
567        // SAFETY: Number of leaves is a power of two
568        unsafe { perfect_subtree_root(hasher, leaves) }
569    }
570
571    /// Add a subtree of `2^height` leaves that starts at leaf `first_leaf` after the subtrees that
572    /// were added before, pushing lanes into the stack first when they are full or when they hold a
573    /// single subtree that isn't lifted
574    #[inline(always)]
575    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
576    fn add_subtree(
577        hasher: &H,
578        stack: &mut [[u8; H::OUT_LEN]; STACK_SIZE::<BITS>],
579        lanes: &mut Lanes<H>,
580        first_leaf: u128,
581        height: u8,
582        root: [u8; H::OUT_LEN],
583    ) {
584        // Subtrees of up to `2^limit` leaves, where `limit` is the highest bit in which the first
585        // leaves of this and the previous subtree differ, contain only one of them. The whole tree
586        // is never needed either.
587        let limit = lanes
588            .previous_leaf
589            .replace(first_leaf)
590            .and_then(|previous_leaf| (previous_leaf ^ first_leaf).checked_ilog2())
591            .unwrap_or(u32::from(BITS) - 1);
592        let limit = u8::try_from(limit).expect("Smaller than `BITS`; qed");
593        if let Some(last) = lanes.len.checked_sub(1)
594            && let Some(target) = lanes.targets.get_mut(last)
595        {
596            *target = (*target).min(limit);
597        }
598
599        // Targets in lanes are final now. A single subtree that isn't lifted, like in runs of
600        // consecutive leaves and dense trees, is pushed right away instead of waiting for lanes to
601        // fill up.
602        if lanes.len == PARALLEL_PAIRS::<H>
603            || (lanes.len == 1 && lanes.heights.first() == lanes.targets.first())
604        {
605            Self::push_lanes(hasher, stack, lanes);
606        }
607
608        // The root of all zeroes isn't lifted, such that the stack hashes it with empty siblings
609        // like hashers that hash pairs one by one do. The target is lower than the subtree only
610        // for the whole tree.
611        let target = if root == Self::ZERO {
612            height
613        } else {
614            limit.max(height)
615        };
616        lanes.push(root, first_leaf, height, target);
617    }
618
619    /// Lift subtrees in lanes to their targets, then push them into the stack along with empty
620    /// leaves before them
621    #[inline(always)]
622    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
623    fn push_lanes(
624        hasher: &H,
625        stack: &mut [[u8; H::OUT_LEN]; STACK_SIZE::<BITS>],
626        lanes: &mut Lanes<H>,
627    ) {
628        // Lifting and pushing use separate frames, which don't need to be on the stack at the
629        // same time. Dense trees push subtrees that aren't lifted one at a time and skip lifting.
630        if lanes.iter().any(|(_, _, height, target)| height < target) {
631            lanes.lift(hasher);
632        }
633        Self::push_lifted_lanes(hasher, stack, lanes);
634    }
635
636    /// Push subtrees in lanes that reached their targets into the stack along with empty leaves
637    /// before them
638    // Inlining is only prevented in normal builds, `no_panic` relies on it
639    #[cfg_attr(not(feature = "no-panic"), inline(never))]
640    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
641    fn push_lifted_lanes(
642        hasher: &H,
643        stack: &mut [[u8; H::OUT_LEN]; STACK_SIZE::<BITS>],
644        lanes: &mut Lanes<H>,
645    ) {
646        let mut stack_leaves = lanes.stack_leaves;
647        for (root, first_leaf, height, _) in lanes.iter() {
648            let first_leaf = first_leaf >> height << height;
649            // Leaves in lanes and in the stack were checked to be within the tree already
650            Self::skip_leaves(
651                hasher,
652                stack,
653                &mut false,
654                stack_leaves,
655                first_leaf - stack_leaves,
656            );
657            Self::push_subtree(hasher, stack, first_leaf, u32::from(height), *root);
658            // Wrapping is needed for `BITS == u128::BITS`, where the last subtree may end with the
659            // last leaf of the tree
660            stack_leaves = first_leaf.wrapping_add(2u128.pow(u32::from(height)));
661        }
662        lanes.stack_leaves = stack_leaves;
663        lanes.len = 0;
664    }
665
666    /// Returns updated number of leaves
667    #[inline]
668    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
669    fn skip_leaves(
670        hasher: &H,
671        stack: &mut [[u8; H::OUT_LEN]; STACK_SIZE::<BITS>],
672        processed_some: &mut bool,
673        mut num_leaves: u128,
674        mut skip_count: u128,
675    ) -> Option<u128> {
676        Self::checked_skip(processed_some, num_leaves, skip_count)?;
677
678        while skip_count > 0 {
679            // Find the largest aligned chunk to skip for the current state of the tree
680            let max_levels_to_skip = skip_count.ilog2().min(num_leaves.trailing_zeros());
681            let chunk_size = 1u128 << max_levels_to_skip;
682
683            let mut level = max_levels_to_skip;
684            let mut current = Self::ZERO;
685            for item in stack.iter().skip(max_levels_to_skip as usize) {
686                // Check the active level for merging up the stack.
687                //
688                // `BITS == u128::BITS` condition is only added for better dead code elimination
689                // since that check is only relevant for 2^128 leaves case and nothing else.
690                if (u32::from(BITS) == u128::BITS && level == u128::BITS)
691                    || num_leaves & (1 << level) == 0
692                {
693                    // Level wasn't active before, stop here
694                    break;
695                }
696
697                // Hash together unless both are zero
698                if !(item == &Self::ZERO && current == Self::ZERO) {
699                    current = hasher.hash_pair(&[*item, current]);
700                }
701
702                level += 1;
703            }
704            // SAFETY: Level is limited by the number of leaves, which in turn is checked above to
705            // fit into 2^BITS, while `BITS` generic in turn ensured sufficient stack size. For
706            // `BITS == u128::BITS` the level is limited by the loop above instead.
707            *unsafe { stack.get_unchecked_mut(level as usize) } = current;
708
709            // Wrapping is needed for `BITS == u128::BITS`, where number of leaves narrowly
710            // doesn't fit into `u128` itself
711            num_leaves = num_leaves.wrapping_add(chunk_size);
712            skip_count -= chunk_size;
713        }
714
715        Some(num_leaves)
716    }
717
718    /// Returns updated number of leaves after `skip_count` empty leaves, `None` if there are too
719    /// many of them
720    #[inline(always)]
721    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
722    fn checked_skip(processed_some: &mut bool, num_leaves: u128, skip_count: u128) -> Option<u128> {
723        if u32::from(BITS) < u128::BITS {
724            // How many leaves were processed so far
725            if num_leaves.checked_add(skip_count)? > 2u128.pow(u32::from(BITS)) {
726                return None;
727            }
728        } else {
729            // For `BITS == u128::BITS` `num_leaves` will wrap around back to zero right at the
730            // very end
731            let (overflow_amount, overflowed) = num_leaves.overflowing_add(skip_count);
732            if *processed_some && overflowed && overflow_amount > 0 {
733                return None;
734            }
735            *processed_some = true;
736        }
737
738        // Wrapping is needed for `BITS == u128::BITS`, where number of leaves narrowly doesn't fit
739        // into `u128` itself
740        Some(num_leaves.wrapping_add(skip_count))
741    }
742
743    /// Verify previously generated proof.
744    ///
745    /// Leaf can either be leaf value for a leaf that is occupied or all zeroes for a leaf that is
746    /// supposed to be empty.
747    #[inline]
748    #[cfg_attr(feature = "no-panic", no_panic::no_panic)]
749    pub fn verify(
750        root: &[u8; H::OUT_LEN],
751        proof: &[[u8; H::OUT_LEN]; PROOF_ELEMENTS::<BITS>],
752        leaf_index: u128,
753        leaf: [u8; H::OUT_LEN],
754    ) -> bool {
755        // TODO: Technically redundant with the where-clause, which is not enforced in generic code
756        //  due to https://github.com/rust-lang/rust/issues/164019, remove once fixed
757        const { ENSURE_SUPPORTED_BITS::<BITS> };
758
759        // For `BITS == u128::BITS` any index is valid by definition
760        if u32::from(BITS) < u128::BITS && leaf_index >= 2u128.pow(u32::from(BITS)) {
761            return false;
762        }
763
764        let hasher = H::default();
765        let mut computed_root = leaf;
766
767        let mut position = leaf_index;
768        for hash in proof {
769            // Hash together unless both are zero
770            if !(computed_root == Self::ZERO && hash == &Self::ZERO) {
771                computed_root = if position.is_multiple_of(2) {
772                    hasher.hash_pair(&[computed_root, *hash])
773                } else {
774                    hasher.hash_pair(&[*hash, computed_root])
775                };
776            }
777
778            position /= 2;
779        }
780
781        root == &computed_root
782    }
783}