Skip to main content

snarkvm_console_collections/merkle_tree/
mod.rs

1// Copyright (c) 2019-2026 Provable Inc.
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16mod helpers;
17pub use helpers::*;
18
19mod path;
20pub use path::*;
21
22#[cfg(test)]
23mod tests;
24
25use snarkvm_console_types::prelude::*;
26
27use aleo_std::prelude::*;
28
29#[cfg(feature = "locktick")]
30use locktick::parking_lot::Mutex;
31#[cfg(not(feature = "locktick"))]
32use parking_lot::Mutex;
33use serde::{Deserialize, Serialize};
34use std::{borrow::Cow, collections::BTreeMap, mem};
35
36#[cfg(not(feature = "serial"))]
37use rayon::prelude::*;
38
39/// A binary Merkle tree constructed with a leaf-digest hash function and a
40/// two-to-one compressing hash function.
41///
42/// If the number of leaves is less than `2**DEPTH`, the leaf layer is first
43/// padded to the next power of 2 with the empty-hash value `e` returned by the
44/// implementation of `PathHash::hash_empty()` for `PH`, then a balanced binary
45/// tree is built. In concrete terms, at most one `e` leaf is added: the rest
46/// are only virtual in that instead nodes with the value `PH::hash_children(e,
47/// e)` are added to the next level, which is indeed full of size equal to a
48/// power of 2.
49///
50/// Padding levels are then added as needed to reach the full `DEPTH`, each of
51/// which is constructed by hashing the root of the previous level together with
52/// `e`.
53pub struct MerkleTree<E: Environment, LH: LeafHash<Hash = PH::Hash>, PH: PathHash<Hash = Field<E>>, const DEPTH: u8> {
54    /// The leaf hasher for the Merkle tree.
55    leaf_hasher: LH,
56    /// The path hasher for the Merkle tree.
57    path_hasher: PH,
58    /// The computed root of the full Merkle tree.
59    root: PH::Hash,
60    /// The internal hashes, from root to hashed leaves, of the full Merkle tree.
61    tree: Vec<PH::Hash>,
62    /// The canonical empty hash.
63    empty_hash: Field<E>,
64    /// The number of hashed leaves in the tree.
65    number_of_leaves: usize,
66    /// An optimization: the previous tree allocation reused in prepare_append.
67    preserved_tree_allocation: Mutex<Option<Vec<PH::Hash>>>,
68}
69
70/// The contents of a [`MerkleTree`], sans its hashers.
71///
72/// This is the serializable form of a Merkle tree, intended for caching one on
73/// disk. Note that a [`MerkleTree`] itself is deliberately **not** serializable:
74/// its hashers hold precomputed bases (tens of MiBs of group elements for the
75/// BHP hashers), and deserializing those is orders of magnitude more expensive
76/// than setting them up from scratch - each group element costs a subgroup check,
77/// i.e. a full scalar multiplication.
78#[derive(Clone, Debug, Deserialize, Serialize)]
79#[serde(bound = "E: Serialize + DeserializeOwned")]
80pub struct MerkleTreeState<'a, E: Environment> {
81    /// The computed root of the full Merkle tree.
82    root: Field<E>,
83    /// The internal hashes, from root to hashed leaves, of the full Merkle tree.
84    tree: Cow<'a, [Field<E>]>,
85    /// The canonical empty hash.
86    empty_hash: Field<E>,
87    /// The number of hashed leaves in the tree.
88    number_of_leaves: usize,
89}
90
91impl<E: Environment> MerkleTreeState<'_, E> {
92    /// Converts the state into one that borrows nothing, cloning the tree's nodes if needed.
93    ///
94    /// This is what allows a state taken from a [`MerkleTree`] behind a lock to be used after the
95    /// lock is released - most importantly, to be serialized without holding it for the duration of
96    /// the write. It is a no-op for a state that already owns its nodes, such as a deserialized one.
97    pub fn into_owned(self) -> MerkleTreeState<'static, E> {
98        MerkleTreeState {
99            root: self.root,
100            tree: Cow::Owned(self.tree.into_owned()),
101            empty_hash: self.empty_hash,
102            number_of_leaves: self.number_of_leaves,
103        }
104    }
105}
106
107impl<E: Environment, LH: LeafHash<Hash = PH::Hash>, PH: PathHash<Hash = Field<E>>, const DEPTH: u8> Clone
108    for MerkleTree<E, LH, PH, DEPTH>
109{
110    fn clone(&self) -> Self {
111        Self {
112            leaf_hasher: self.leaf_hasher.clone(),
113            path_hasher: self.path_hasher.clone(),
114            root: self.root,
115            tree: self.tree.clone(),
116            empty_hash: self.empty_hash,
117            number_of_leaves: self.number_of_leaves,
118            preserved_tree_allocation: Default::default(),
119        }
120    }
121}
122
123impl<E: Environment, LH: LeafHash<Hash = PH::Hash>, PH: PathHash<Hash = Field<E>>, const DEPTH: u8>
124    MerkleTree<E, LH, PH, DEPTH>
125{
126    #[inline]
127    /// Initializes a new Merkle tree with the given leaves.
128    pub fn new(leaf_hasher: &LH, path_hasher: &PH, leaves: &[LH::Leaf]) -> Result<Self> {
129        let timer = timer!("MerkleTree::new");
130
131        // Ensure the Merkle tree depth is greater than 0.
132        ensure!(DEPTH > 0, "Merkle tree depth must be greater than 0");
133        // Ensure the Merkle tree depth is less than or equal to 64.
134        ensure!(DEPTH <= 64u8, "Merkle tree depth must be less than or equal to 64");
135
136        // Compute the maximum number of leaves.
137        let max_leaves = match leaves.len().checked_next_power_of_two() {
138            Some(num_leaves) => num_leaves,
139            None => bail!("Integer overflow when computing the maximum number of leaves in the Merkle tree"),
140        };
141
142        // Compute the number of nodes.
143        let num_nodes = max_leaves - 1;
144        // Compute the tree size as the maximum number of leaves plus the number of nodes.
145        let tree_size = max_leaves + num_nodes;
146        // Compute the number of levels in the Merkle tree (i.e. log2(tree_size)).
147        let tree_depth = tree_depth::<DEPTH>(tree_size)?;
148        // Compute the number of padded levels.
149        let padding_depth = DEPTH - tree_depth;
150
151        // Compute the empty hash.
152        let empty_hash = path_hasher.hash_empty()?;
153
154        // Calculate the size of the tree which excludes leafless nodes.
155        // The minimum tree size is either a single root node or the calculated number of nodes plus
156        // the supplied leaves; if the number of leaves is odd, an empty hash is added for padding.
157        let minimum_tree_size =
158            std::cmp::max(1, num_nodes + leaves.len() + if leaves.len() > 1 { leaves.len() % 2 } else { 0 });
159
160        // Initialize the Merkle tree.
161        let mut tree = vec![empty_hash; minimum_tree_size];
162
163        // Compute and store each leaf hash.
164        tree[num_nodes..num_nodes + leaves.len()].copy_from_slice(&leaf_hasher.hash_leaves(leaves)?);
165        lap!(timer, "Hashed {} leaves", leaves.len());
166
167        // Compute and store the hashes for each level, iterating from the penultimate level to the root level.
168        let mut start_index = num_nodes;
169        // Compute the start index of the current level.
170        while let Some(start) = parent(start_index) {
171            // Compute the end index of the current level.
172            let end = left_child(start);
173            // Construct the children for each node in the current level; the leaves are padded, which means
174            // that there either are 2 children, or there are none, at which point we may stop iterating.
175            let tuples = (start..end)
176                .take_while(|&i| tree.get(left_child(i)).is_some())
177                .map(|i| (tree[left_child(i)], tree[right_child(i)]))
178                .collect::<Vec<_>>();
179            // Compute and store the hashes for each node in the current level.
180            let num_full_nodes = tuples.len();
181            tree[start..][..num_full_nodes].copy_from_slice(&path_hasher.hash_all_children(&tuples)?);
182            // Use the precomputed empty node hash for every empty node, if there are any.
183            if start + num_full_nodes < end {
184                let empty_node_hash = path_hasher.hash_children(&empty_hash, &empty_hash)?;
185                for node in tree.iter_mut().take(end).skip(start + num_full_nodes) {
186                    *node = empty_node_hash;
187                }
188            }
189            // Update the start index for the next level.
190            start_index = start;
191        }
192        lap!(timer, "Hashed {} levels", tree_depth);
193
194        // Compute the root hash, by iterating from the root level up to `DEPTH`.
195        let mut root_hash = tree[0];
196        for _ in 0..padding_depth {
197            // Update the root hash, by hashing the current root hash with the empty hash.
198            root_hash = path_hasher.hash_children(&root_hash, &empty_hash)?;
199        }
200        lap!(timer, "Hashed {} padding levels", padding_depth);
201
202        finish!(timer);
203
204        Ok(Self {
205            leaf_hasher: leaf_hasher.clone(),
206            path_hasher: path_hasher.clone(),
207            root: root_hash,
208            tree,
209            empty_hash,
210            number_of_leaves: leaves.len(),
211            preserved_tree_allocation: Default::default(),
212        })
213    }
214
215    /// Returns the contents of the Merkle tree, sans its hashers.
216    ///
217    /// This borrows from the tree, so it is cheap even for very large trees; use
218    /// [`Self::from_state`] to recreate the tree from the returned state.
219    ///
220    /// note: The borrow lasts as long as the state does, so a state obtained through a lock guard
221    /// keeps that guard alive. Serializing such a state therefore holds the lock for the entire
222    /// write, which for a large tree is far longer than taking it; [`MerkleTreeState::into_owned`]
223    /// trades a copy of the tree for the ability to release the lock first.
224    pub fn to_state(&self) -> MerkleTreeState<'_, E> {
225        MerkleTreeState {
226            root: self.root,
227            tree: Cow::Borrowed(&self.tree),
228            empty_hash: self.empty_hash,
229            number_of_leaves: self.number_of_leaves,
230        }
231    }
232
233    /// Recreates a Merkle tree from the given state, using the given hashers.
234    ///
235    /// The state is checked for internal consistency, which includes recomputing
236    /// the root from the topmost node; since only the padding levels are hashed,
237    /// this is cheap. Note that this cannot attest that the tree corresponds to
238    /// any particular set of leaves, so the caller is still expected to check the
239    /// resulting root against a trusted value.
240    pub fn from_state(leaf_hasher: &LH, path_hasher: &PH, state: MerkleTreeState<'_, E>) -> Result<Self> {
241        // Ensure the Merkle tree depth is greater than 0.
242        ensure!(DEPTH > 0, "Merkle tree depth must be greater than 0");
243        // Ensure the Merkle tree depth is less than or equal to 64.
244        ensure!(DEPTH <= 64u8, "Merkle tree depth must be less than or equal to 64");
245
246        let MerkleTreeState { root, tree, empty_hash, number_of_leaves } = state;
247        // Note: this is a no-op if the state was deserialized, as opposed to borrowed.
248        let tree = tree.into_owned();
249
250        // Ensure the empty hash matches the one produced by the given path hasher; a
251        // mismatch means that the state was produced for a different network or hasher.
252        ensure!(empty_hash == path_hasher.hash_empty()?, "The Merkle tree state has an invalid empty hash");
253
254        // Compute the maximum number of leaves.
255        let max_leaves = match number_of_leaves.checked_next_power_of_two() {
256            Some(num_leaves) => num_leaves,
257            None => bail!("Integer overflow when computing the maximum number of leaves in the Merkle tree"),
258        };
259        // Compute the number of nodes.
260        let num_nodes = max_leaves - 1;
261        // Compute the number of padded levels.
262        let padding_depth = DEPTH - tree_depth::<DEPTH>(max_leaves + num_nodes)?;
263
264        // Ensure the tree contains exactly as many nodes as its number of leaves implies.
265        let minimum_tree_size = std::cmp::max(
266            1,
267            num_nodes + number_of_leaves + if number_of_leaves > 1 { number_of_leaves % 2 } else { 0 },
268        );
269        ensure!(
270            tree.len() == minimum_tree_size,
271            "The Merkle tree state contains {} nodes, expected {minimum_tree_size} for {number_of_leaves} leaves",
272            tree.len()
273        );
274
275        // Recompute the root hash, by iterating from the root level up to `DEPTH`.
276        let mut root_hash = tree[0];
277        for _ in 0..padding_depth {
278            // Update the root hash, by hashing the current root hash with the empty hash.
279            root_hash = path_hasher.hash_children(&root_hash, &empty_hash)?;
280        }
281        ensure!(root_hash == root, "The Merkle tree state has an invalid root");
282
283        Ok(Self {
284            leaf_hasher: leaf_hasher.clone(),
285            path_hasher: path_hasher.clone(),
286            root,
287            tree,
288            empty_hash,
289            number_of_leaves,
290            preserved_tree_allocation: Default::default(),
291        })
292    }
293
294    #[inline]
295    /// Returns a new Merkle tree with the given new leaves appended to it.
296    pub fn prepare_append(&self, new_leaves: &[LH::Leaf]) -> Result<Self> {
297        let timer = timer!("MerkleTree::prepare_append");
298
299        // Compute the maximum number of leaves.
300        let max_leaves = match (self.number_of_leaves + new_leaves.len()).checked_next_power_of_two() {
301            Some(num_leaves) => num_leaves,
302            None => bail!("Integer overflow when computing the maximum number of leaves in the Merkle tree"),
303        };
304        // Compute the number of nodes.
305        let num_nodes = max_leaves - 1;
306        // Compute the tree size as the maximum number of leaves plus the number of nodes.
307        let tree_size = num_nodes + max_leaves;
308        // Compute the number of levels in the Merkle tree (i.e. log2(tree_size)).
309        let tree_depth = tree_depth::<DEPTH>(tree_size)?;
310        // Compute the number of padded levels.
311        let padding_depth = DEPTH - tree_depth;
312
313        // Reuse the previous Merkle tree, or initialize it if missing.
314        // All the (inner) nodes are rewritten, so their current values are irrelevant.
315        // The slowest part is populating the values, but large allocations are also slow.
316        let mut tree = self.preserved_tree_allocation.lock().take().unwrap_or_else(|| vec![self.empty_hash; num_nodes]);
317        // The number of nodes in the preserved allocation is too small if the depth increases.
318        // This is basically a noop if there are sufficient nodes already.
319        tree.resize(num_nodes, self.empty_hash);
320
321        // Extend the new Merkle tree with the existing leaf hashes.
322        tree.extend(self.leaf_hashes()?);
323        // Extend the new Merkle tree with the new leaf hashes.
324        tree.extend(&self.leaf_hasher.hash_leaves(new_leaves)?);
325
326        // Calculate the size of the tree which excludes leafless nodes.
327        let new_number_of_leaves = self.number_of_leaves + new_leaves.len();
328        let minimum_tree_size = std::cmp::max(
329            1,
330            num_nodes + new_number_of_leaves + if new_number_of_leaves > 1 { new_number_of_leaves % 2 } else { 0 },
331        );
332
333        // Resize the new Merkle tree with empty hashes to pad up to `tree_size`.
334        tree.resize(minimum_tree_size, self.empty_hash);
335        lap!(timer, "Hashed {} new leaves", new_leaves.len());
336
337        // Initialize a start index to track the starting index of the current level.
338        let start_index = num_nodes;
339        // Initialize a middle index to separate the precomputed indices from the new indices that need to be computed.
340        let middle_index = num_nodes + self.number_of_leaves;
341        // Initialize a precompute index to track the starting index of each precomputed level.
342        let start_precompute_index = match self.number_of_leaves.checked_next_power_of_two() {
343            Some(num_leaves) => num_leaves - 1,
344            None => bail!("Integer overflow when computing the Merkle tree precompute index"),
345        };
346        // Initialize a precompute index to track the middle index of each precomputed level.
347        let middle_precompute_index = match num_nodes == start_precompute_index {
348            // If the old tree and new tree are of the same size, then we can copy over the right half of the old tree.
349            true => Some(start_precompute_index + self.number_of_leaves + new_leaves.len() + 1),
350            // Otherwise, we need to compute the right half of the new tree.
351            false => None,
352        };
353
354        // Compute and store the hashes for each level, iterating from the penultimate level to the root level.
355        self.compute_updated_tree(
356            &mut tree,
357            start_index,
358            middle_index,
359            start_precompute_index,
360            middle_precompute_index,
361        )?;
362
363        // Compute the root hash, by iterating from the root level up to `DEPTH`.
364        let mut root_hash = tree[0];
365        for _ in 0..padding_depth {
366            // Update the root hash, by hashing the current root hash with the empty hash.
367            root_hash = self.path_hasher.hash_children(&root_hash, &self.empty_hash)?;
368        }
369        lap!(timer, "Hashed {} padding levels", padding_depth);
370
371        finish!(timer);
372
373        Ok(Self {
374            leaf_hasher: self.leaf_hasher.clone(),
375            path_hasher: self.path_hasher.clone(),
376            root: root_hash,
377            tree,
378            empty_hash: self.empty_hash,
379            number_of_leaves: self.number_of_leaves + new_leaves.len(),
380            preserved_tree_allocation: Default::default(), // Placeholder; will be updated at the callsite using Self::preserve_tree_allocation
381        })
382    }
383
384    #[inline]
385    /// Updates the Merkle tree with the given new leaves appended to it.
386    pub fn append(&mut self, new_leaves: &[LH::Leaf]) -> Result<()> {
387        let timer = timer!("MerkleTree::append");
388
389        // Compute the updated Merkle tree with the new leaves.
390        let updated_tree = self.prepare_append(new_leaves)?;
391        // Update the tree at the very end, so the original tree is not altered in case of failure.
392        *self = updated_tree;
393
394        finish!(timer);
395        Ok(())
396    }
397
398    #[inline]
399    /// Updates the Merkle tree at the location of the given leaf index with the new leaf.
400    pub fn update(&mut self, leaf_index: usize, new_leaf: &LH::Leaf) -> Result<()> {
401        let timer = timer!("MerkleTree::update");
402
403        // Compute the updated Merkle tree with the new leaves.
404        let updated_tree = self.prepare_update(leaf_index, new_leaf)?;
405        // Update the tree at the very end, so the original tree is not altered in case of failure.
406        *self = updated_tree;
407
408        finish!(timer);
409        Ok(())
410    }
411
412    #[inline]
413    /// Returns a new Merkle tree with updates at the location of the given leaf index with the new leaf.
414    pub fn prepare_update(&self, leaf_index: usize, new_leaf: &LH::Leaf) -> Result<Self> {
415        let timer = timer!("MerkleTree::prepare_update");
416
417        // Check that the leaf index is within the bounds of the Merkle tree.
418        ensure!(
419            leaf_index < self.number_of_leaves,
420            "Leaf index must be less than the number of leaves in the Merkle tree {leaf_index} , {}",
421            self.number_of_leaves
422        );
423
424        // Allocate a vector to store the path hashes.
425        let mut path_hashes = Vec::with_capacity(DEPTH as usize);
426
427        // Compute and add the new leaf hash to the path hashes.
428        path_hashes.push(self.leaf_hasher.hash_leaf(new_leaf)?);
429        lap!(timer, "Hashed 1 new leaf");
430
431        // Compute the start index (on the left) for the leaf hashes level in the Merkle tree.
432        let start = match self.number_of_leaves.checked_next_power_of_two() {
433            Some(num_leaves) => num_leaves - 1,
434            None => bail!("Integer overflow when computing the Merkle tree start index"),
435        };
436
437        // Compute the new hashes for the path from the leaf to the root.
438        let mut index = start + leaf_index;
439        while let Some(parent) = parent(index) {
440            // Get the left and right child hashes of the parent.
441            let (left, right) = match is_left_child(index) {
442                true => (path_hashes.last().unwrap(), &self.tree[right_child(parent)]),
443                false => (&self.tree[left_child(parent)], path_hashes.last().unwrap()),
444            };
445            // Compute and add the new parent hash to the path hashes.
446            path_hashes.push(self.path_hasher.hash_children(left, right)?);
447            // Update the index to the parent.
448            index = parent;
449        }
450
451        // Compute the number of levels in the Merkle tree (i.e. log2(tree_size)).
452        let tree_depth = tree_depth::<DEPTH>(self.tree.len())?;
453        // Compute the padding depth.
454        let padding_depth = DEPTH - tree_depth;
455
456        // Update the root hash.
457        // This unwrap is safe, as the path hashes vector is guaranteed to have at least one element.
458        let mut root_hash = *path_hashes.last().unwrap();
459        for _ in 0..padding_depth {
460            // Update the root hash, by hashing the current root hash with the empty hash.
461            root_hash = self.path_hasher.hash_children(&root_hash, &self.empty_hash)?;
462        }
463        lap!(timer, "Hashed {} padding levels", padding_depth);
464
465        // Initialize the Merkle tree.
466        let mut tree = Vec::with_capacity(self.tree.len());
467        // Extend the new Merkle tree with the existing leaf hashes.
468        tree.extend(&self.tree);
469
470        // Update the rest of the tree with the new path hashes.
471        let mut index = Some(start + leaf_index);
472        for path_hash in path_hashes {
473            tree[index.unwrap()] = path_hash;
474            index = parent(index.unwrap());
475        }
476
477        finish!(timer);
478
479        Ok(Self {
480            leaf_hasher: self.leaf_hasher.clone(),
481            path_hasher: self.path_hasher.clone(),
482            root: root_hash,
483            tree,
484            empty_hash: self.empty_hash,
485            number_of_leaves: self.number_of_leaves,
486            preserved_tree_allocation: Default::default(),
487        })
488    }
489
490    #[inline]
491    /// Updates the Merkle tree at the location of the given leaf indices with the new leaves.
492    pub fn update_many(&mut self, updates: &BTreeMap<usize, LH::Leaf>) -> Result<()> {
493        let timer = timer!("MerkleTree::update_many");
494
495        // Check that there are updates to perform.
496        ensure!(!updates.is_empty(), "There must be at least one leaf to update in the Merkle tree");
497
498        // Check that the latest leaf index is less than number of leaves in the Merkle tree.
499        // Note: This unwrap is safe since updates is guaranteed to be non-empty.
500        ensure!(
501            *updates.last_key_value().unwrap().0 < self.number_of_leaves,
502            "Leaf index must be less than the number of leaves in the Merkle tree"
503        );
504
505        // Compute the start index (on the left) for the leaf hashes level in the Merkle tree.
506        let start = match self.number_of_leaves.checked_next_power_of_two() {
507            Some(num_leaves) => num_leaves - 1,
508            None => bail!("Integer overflow when computing the Merkle tree start index"),
509        };
510
511        // A helper to compute the leaf hash.
512        let hash_update = |(leaf_index, leaf): &(&usize, &LH::Leaf)| {
513            self.leaf_hasher.hash_leaf(leaf).map(|hash| (start + **leaf_index, hash))
514        };
515
516        // Hash the leaves and add them to the updated hashes.
517        let leaf_hashes: Vec<(usize, LH::Hash)> = match updates.len() {
518            0..=100 => updates.iter().map(|update| hash_update(&update)).collect::<Result<Vec<_>>>()?,
519            _ => cfg_iter!(updates).map(|update| hash_update(&update)).collect::<Result<Vec<_>>>()?,
520        };
521        lap!(timer, "Hashed {} new leaves", leaf_hashes.len());
522
523        // Store the updated hashes by level.
524        let mut updated_hashes = Vec::new();
525        updated_hashes.push(leaf_hashes);
526
527        // A helper function to compute the path hashes for a given level.
528        type Update<PH> = (usize, (<PH as PathHash>::Hash, <PH as PathHash>::Hash));
529        let compute_path_hashes = |inputs: &[Update<PH>]| match inputs.len() {
530            0..=100 => inputs
531                .iter()
532                .map(|(index, (left, right))| self.path_hasher.hash_children(left, right).map(|hash| (*index, hash)))
533                .collect::<Result<Vec<_>>>(),
534            _ => cfg_iter!(inputs)
535                .map(|(index, (left, right))| self.path_hasher.hash_children(left, right).map(|hash| (*index, hash)))
536                .collect::<Result<Vec<_>>>(),
537        };
538
539        // Compute the depth of the tree. This corresponds to the number of levels of hashes in the tree.
540        let tree_depth = tree_depth::<DEPTH>(self.tree.len())?;
541        // Allocate a vector to store the inputs to the path hasher.
542        let mut inputs = Vec::with_capacity(updated_hashes[0].len());
543        // For each level in the tree, compute the path hashes.
544        // In the first iteration, we compute the path hashes for the updated leaf hashes.
545        // In the subsequent iterations, we compute the path hashes for the updated path hashes, until we reach the root.
546        for level in 0..tree_depth as usize {
547            let mut current = 0;
548            while current < updated_hashes[level].len() {
549                let (current_leaf_index, current_leaf_hash) = updated_hashes[level][current];
550                // Get the sibling of the current leaf.
551                let sibling_leaf_index = match sibling(current_leaf_index) {
552                    Some(sibling_index) => sibling_index,
553                    // If there is no sibling, then we have reached the root.
554                    None => break,
555                };
556                // Check if the sibling hash is the next hash in the vector.
557                let sibling_is_next_hash = match current + 1 < updated_hashes[level].len() {
558                    true => updated_hashes[level][current + 1].0 == sibling_leaf_index,
559                    false => false,
560                };
561                // Get the sibling hash.
562                // Note: This algorithm assumes that the sibling hash is either the next hash in the vector,
563                // or in the original Merkle tree. Consequently, updates need to be provided in sequential order.
564                // This is enforced by the type of `updates: `BTreeMap<usize, LH::Leaf>`.
565                // If this assumption is violated, then the algorithm will compute incorrect path hashes in the Merkle tree.
566                let sibling_leaf_hash = match sibling_is_next_hash {
567                    true => updated_hashes[level][current + 1].1,
568                    false => self.tree[sibling_leaf_index],
569                };
570                // Order the current and sibling hashes.
571                let (left, right) = match is_left_child(current_leaf_index) {
572                    true => (current_leaf_hash, sibling_leaf_hash),
573                    false => (sibling_leaf_hash, current_leaf_hash),
574                };
575                // Compute the parent index.
576                // Note that this unwrap is safe, since we check that the `current_leaf_index` is not the root.
577                let parent_index = parent(current_leaf_index).unwrap();
578                // Add the parent hash to the updated hashes.
579                inputs.push((parent_index, (left, right)));
580                // Update the current index.
581                match sibling_is_next_hash {
582                    true => current += 2,
583                    false => current += 1,
584                }
585            }
586            // Compute the path hashes for the current level.
587            let path_hashes = compute_path_hashes(&inputs)?;
588            // Add the path hashes to the updated hashes.
589            updated_hashes.push(path_hashes);
590            // Clear the inputs.
591            inputs.clear();
592        }
593
594        // Compute the padding depth.
595        let padding_depth = DEPTH - tree_depth;
596
597        // Update the root hash.
598        // This unwrap is safe, as the updated hashes is guaranteed to have at least one element.
599        let mut root_hash = updated_hashes.last().unwrap()[0].1;
600        for _ in 0..padding_depth {
601            // Update the root hash, by hashing the current root hash with the empty hash.
602            root_hash = self.path_hasher.hash_children(&root_hash, &self.empty_hash)?;
603        }
604        lap!(timer, "Hashed {} padding levels", padding_depth);
605
606        // Update the root hash.
607        self.root = root_hash;
608
609        // Update the rest of the tree with the updated hashes.
610        for (index, hash) in updated_hashes.into_iter().flatten() {
611            self.tree[index] = hash;
612        }
613
614        finish!(timer);
615        Ok(())
616    }
617
618    #[inline]
619    /// Returns a new Merkle tree with the last 'n' leaves removed from it.
620    pub fn prepare_remove_last_n(&self, n: usize) -> Result<Self> {
621        let timer = timer!("MerkleTree::prepare_remove_last_n");
622
623        ensure!(n > 0, "Cannot remove zero leaves from the Merkle tree");
624
625        // Determine the updated number of leaves, after removing the last 'n' leaves.
626        let updated_number_of_leaves = self.number_of_leaves.checked_sub(n).ok_or_else(|| {
627            anyhow!("Failed to remove '{n}' leaves from the Merkle tree, as it only contains {}", self.number_of_leaves)
628        })?;
629
630        // Compute the maximum number of leaves.
631        let max_leaves = match (updated_number_of_leaves).checked_next_power_of_two() {
632            Some(num_leaves) => num_leaves,
633            None => bail!("Integer overflow when computing the maximum number of leaves in the Merkle tree"),
634        };
635        // Compute the number of nodes.
636        let num_nodes = max_leaves - 1;
637        // Compute the tree size as the maximum number of leaves plus the number of nodes.
638        let tree_size = num_nodes + max_leaves;
639        // Compute the number of levels in the Merkle tree (i.e. log2(tree_size)).
640        let tree_depth = tree_depth::<DEPTH>(tree_size)?;
641        // Compute the number of padded levels.
642        let padding_depth = DEPTH - tree_depth;
643
644        // Calculate the size of the tree which excludes leafless nodes.
645        let minimum_tree_size = std::cmp::max(
646            1,
647            num_nodes
648                + updated_number_of_leaves
649                + if updated_number_of_leaves > 1 { updated_number_of_leaves % 2 } else { 0 },
650        );
651
652        // Initialize the Merkle tree.
653        let mut tree = vec![self.empty_hash; num_nodes];
654        // Extend the new Merkle tree with the existing leaf hashes, excluding the last 'n' leaves.
655        tree.extend(&self.leaf_hashes()?[..updated_number_of_leaves]);
656        // Resize the new Merkle tree with empty hashes to pad up to `tree_size`.
657        tree.resize(minimum_tree_size, self.empty_hash);
658        lap!(timer, "Resizing to {} leaves", updated_number_of_leaves);
659
660        // Initialize a start index to track the starting index of the current level.
661        let start_index = num_nodes;
662        // Initialize a middle index to separate the precomputed indices from the new indices that need to be computed.
663        let middle_index = num_nodes + updated_number_of_leaves;
664        // Initialize a precompute index to track the starting index of each precomputed level.
665        let start_precompute_index = match self.number_of_leaves.checked_next_power_of_two() {
666            Some(num_leaves) => num_leaves - 1,
667            None => bail!("Integer overflow when computing the Merkle tree precompute index"),
668        };
669        // Initialize a precompute index to track the middle index of each precomputed level.
670        let middle_precompute_index = match num_nodes == start_precompute_index {
671            // If the old tree and new tree are of the same size, then we can copy over the right half of the old tree.
672            true => Some(start_precompute_index + self.number_of_leaves + 1),
673            // true => None,
674            // Otherwise, do nothing, since shrinking the tree is already free.
675            false => None,
676        };
677
678        // Compute and store the hashes for each level, iterating from the penultimate level to the root level.
679        self.compute_updated_tree(
680            &mut tree,
681            start_index,
682            middle_index,
683            start_precompute_index,
684            middle_precompute_index,
685        )?;
686
687        // Compute the root hash, by iterating from the root level up to `DEPTH`.
688        let mut root_hash = tree[0];
689        for _ in 0..padding_depth {
690            // Update the root hash, by hashing the current root hash with the empty hash.
691            root_hash = self.path_hasher.hash_children(&root_hash, &self.empty_hash)?;
692        }
693        lap!(timer, "Hashed {} padding levels", padding_depth);
694
695        finish!(timer);
696
697        Ok(Self {
698            leaf_hasher: self.leaf_hasher.clone(),
699            path_hasher: self.path_hasher.clone(),
700            root: root_hash,
701            tree,
702            empty_hash: self.empty_hash,
703            number_of_leaves: updated_number_of_leaves,
704            preserved_tree_allocation: Default::default(),
705        })
706    }
707
708    #[inline]
709    /// Updates the Merkle tree with the last 'n' leaves removed from it.
710    pub fn remove_last_n(&mut self, n: usize) -> Result<()> {
711        let timer = timer!("MerkleTree::remove_last_n");
712
713        // Compute the updated Merkle tree with the last 'n' leaves removed.
714        let updated_tree = self.prepare_remove_last_n(n)?;
715        // Update the tree at the very end, so the original tree is not altered in case of failure.
716        *self = updated_tree;
717
718        finish!(timer);
719        Ok(())
720    }
721
722    #[inline]
723    /// Returns the Merkle path for the given leaf index and leaf.
724    pub fn prove(&self, leaf_index: usize, leaf: &LH::Leaf) -> Result<MerklePath<E, DEPTH>> {
725        // Ensure the leaf index is valid.
726        ensure!(leaf_index < self.number_of_leaves, "The given Merkle leaf index is out of bounds");
727
728        // Compute the leaf hash.
729        let leaf_hash = self.leaf_hasher.hash_leaf(leaf)?;
730
731        // Compute the start index (on the left) for the leaf hashes level in the Merkle tree.
732        let start = match self.number_of_leaves.checked_next_power_of_two() {
733            Some(num_leaves) => num_leaves - 1,
734            None => bail!("Integer overflow when computing the Merkle tree start index"),
735        };
736
737        // Compute the absolute index of the leaf in the Merkle tree.
738        let mut index = start + leaf_index;
739        // Ensure the leaf index is valid.
740        ensure!(index < self.tree.len(), "The given Merkle leaf index is out of bounds");
741        // Ensure the leaf hash matches the one in the tree.
742        ensure!(self.tree[index] == leaf_hash, "The given Merkle leaf does not match the one in the Merkle tree");
743
744        // Initialize a vector for the Merkle path.
745        let mut path = Vec::with_capacity(DEPTH as usize);
746
747        // Iterate from the leaf hash to the root level, storing the sibling hashes along the path.
748        for _ in 0..DEPTH {
749            // Compute the index of the sibling hash, if it exists.
750            if let Some(sibling) = sibling(index) {
751                // Append the sibling hash to the path.
752                path.push(self.tree[sibling]);
753                // Compute the index of the parent hash, if it exists.
754                match parent(index) {
755                    // Update the index to the parent index.
756                    Some(parent) => index = parent,
757                    // If the parent does not exist, the path is complete.
758                    None => break,
759                }
760            }
761        }
762
763        // If the Merkle path length is not equal to `DEPTH`, pad the path with the empty hash.
764        path.resize(DEPTH as usize, self.empty_hash);
765
766        // Return the Merkle path.
767        MerklePath::try_from((U64::new(leaf_index as u64), path))
768    }
769
770    /// Returns `true` if the given Merkle path is valid for the given root and leaf.
771    pub fn verify(&self, path: &MerklePath<E, DEPTH>, root: &PH::Hash, leaf: &LH::Leaf) -> bool {
772        path.verify(&self.leaf_hasher, &self.path_hasher, root, leaf)
773    }
774
775    /// Returns the Merkle root of the tree.
776    pub const fn root(&self) -> &PH::Hash {
777        &self.root
778    }
779
780    /// Returns the Merkle tree (excluding the hashes of the leaves).
781    pub fn tree(&self) -> &[PH::Hash] {
782        &self.tree
783    }
784
785    /// Returns the empty hash.
786    pub const fn empty_hash(&self) -> &PH::Hash {
787        &self.empty_hash
788    }
789
790    /// Returns the leaf hashes from the Merkle tree.
791    pub fn leaf_hashes(&self) -> Result<&[LH::Hash]> {
792        // Compute the start index (on the left) for the leaf hashes level in the Merkle tree.
793        let start = match self.number_of_leaves.checked_next_power_of_two() {
794            Some(num_leaves) => num_leaves - 1,
795            None => bail!("Integer overflow when computing the Merkle tree start index"),
796        };
797        // Compute the end index (on the right) for the leaf hashes level in the Merkle tree.
798        let end = start + self.number_of_leaves;
799        // Return the leaf hashes.
800        Ok(&self.tree[start..end])
801    }
802
803    /// Returns the number of leaves in the Merkle tree.
804    pub const fn number_of_leaves(&self) -> usize {
805        self.number_of_leaves
806    }
807
808    /// Compute and store the hashes for each level, iterating from the penultimate level to the root level.
809    ///
810    /// ```ignore
811    ///  start_index      middle_index                              end_index
812    ///  start_precompute_index         middle_precompute_index     end_index
813    /// ```
814    #[inline]
815    fn compute_updated_tree(
816        &self,
817        tree: &mut [Field<E>],
818        mut start_index: usize,
819        mut middle_index: usize,
820        mut start_precompute_index: usize,
821        mut middle_precompute_index: Option<usize>,
822    ) -> Result<()> {
823        // Initialize a timer for the while loop.
824        let timer = timer!("MerkleTree::compute_updated_tree");
825
826        // Compute and store the hashes for each level, iterating from the penultimate level to the root level.
827        let empty_hash = self.path_hasher.hash_empty()?;
828        while let (Some(start), Some(middle)) = (parent(start_index), parent(middle_index)) {
829            // Compute the end index of the current level.
830            let end = left_child(start);
831
832            // If the current level has precomputed indices, copy them instead of recomputing them.
833            if let Some(start_precompute) = parent(start_precompute_index) {
834                // Compute the end index of the precomputed level.
835                let end_precompute = start_precompute + (middle - start);
836                // Copy the hashes for each node in the current level.
837                tree[start..middle].copy_from_slice(&self.tree[start_precompute..end_precompute]);
838                // Update the precompute index for the next level.
839                start_precompute_index = start_precompute;
840            } else {
841                // Ensure the start index is equal to the middle index, as all precomputed indices have been processed.
842                ensure!(start == middle, "Failed to process all left precomputed indices in the Merkle tree");
843            }
844            lap!(timer, "Precompute (Left): {start} -> {middle}");
845
846            // If the current level has precomputed indices, copy them instead of recomputing them.
847            // Note: This logic works because the old tree and new tree are the same power of two.
848            if let Some(middle_precompute) = middle_precompute_index {
849                if let Some(middle_precompute) = parent(middle_precompute) {
850                    // Construct the children for the new indices in the current level.
851                    let tuples = (middle..middle_precompute)
852                        .map(|i| {
853                            (
854                                tree.get(left_child(i)).copied().unwrap_or(empty_hash),
855                                tree.get(right_child(i)).copied().unwrap_or(empty_hash),
856                            )
857                        })
858                        .collect::<Vec<_>>();
859                    // Process the indices that need to be computed for the current level.
860                    // If any level requires computing more than 100 nodes, borrow the tree for performance.
861                    match tuples.len() >= 100 {
862                        // Option 1: Borrow the tree to compute and store the hashes for the new indices in the current level.
863                        true => cfg_iter_mut!(tree[middle..middle_precompute]).zip_eq(cfg_iter!(tuples)).try_for_each(
864                            |(node, (left, right))| {
865                                *node = self.path_hasher.hash_children(left, right)?;
866                                Ok::<_, Error>(())
867                            },
868                        )?,
869                        // Option 2: Compute and store the hashes for the new indices in the current level.
870                        false => tree[middle..middle_precompute].iter_mut().zip_eq(&tuples).try_for_each(
871                            |(node, (left, right))| {
872                                *node = self.path_hasher.hash_children(left, right)?;
873                                Ok::<_, Error>(())
874                            },
875                        )?,
876                    }
877                    lap!(timer, "Compute: {middle} -> {middle_precompute}");
878
879                    // Copy the hashes for each node in the current level.
880                    tree[middle_precompute..end].copy_from_slice(&self.tree[middle_precompute..end]);
881                    // Update the precompute index for the next level.
882                    middle_precompute_index = Some(middle_precompute + 1);
883                    lap!(timer, "Precompute (Right): {middle_precompute} -> {end}");
884                } else {
885                    // Ensure the middle precompute index is equal to the end index, as all precomputed indices have been processed.
886                    ensure!(
887                        middle_precompute == end,
888                        "Failed to process all right precomputed indices in the Merkle tree"
889                    );
890                }
891            } else {
892                // Construct the children for the new indices in the current level.
893                let tuples = (middle..end)
894                    .map(|i| {
895                        (
896                            tree.get(left_child(i)).copied().unwrap_or(empty_hash),
897                            tree.get(right_child(i)).copied().unwrap_or(empty_hash),
898                        )
899                    })
900                    .collect::<Vec<_>>();
901                // Process the indices that need to be computed for the current level.
902                // If any level requires computing more than 100 nodes, borrow the tree for performance.
903                match tuples.len() >= 100 {
904                    // Option 1: Borrow the tree to compute and store the hashes for the new indices in the current level.
905                    true => cfg_iter_mut!(tree[middle..end]).zip_eq(cfg_iter!(tuples)).try_for_each(
906                        |(node, (left, right))| {
907                            *node = self.path_hasher.hash_children(left, right)?;
908                            Ok::<_, Error>(())
909                        },
910                    )?,
911                    // Option 2: Compute and store the hashes for the new indices in the current level.
912                    false => tree[middle..end].iter_mut().zip_eq(&tuples).try_for_each(|(node, (left, right))| {
913                        *node = self.path_hasher.hash_children(left, right)?;
914                        Ok::<_, Error>(())
915                    })?,
916                }
917                lap!(timer, "Compute: {middle} -> {end}");
918            }
919
920            // Update the start index for the next level.
921            start_index = start;
922            // Update the middle index for the next level.
923            middle_index = middle;
924        }
925
926        // End the timer for the while loop.
927        finish!(timer);
928
929        Ok(())
930    }
931
932    /// Save the previous tree in order to reuse its allocation later on.
933    pub fn preserve_tree_allocation(&self, previous: &mut Self) {
934        *self.preserved_tree_allocation.lock() = Some(mem::take(&mut previous.tree));
935    }
936}
937
938/// Returns the depth of the tree, given the size of the tree.
939#[inline]
940fn tree_depth<const DEPTH: u8>(tree_size: usize) -> Result<u8> {
941    let tree_size = u64::try_from(tree_size)?;
942    // Since we only allow tree sizes up to u64::MAX, the maximum possible depth is 63.
943    let tree_depth = u8::try_from(tree_size.checked_ilog2().unwrap_or(0))?;
944    // Ensure the tree depth is within the depth bound.
945    match tree_depth <= DEPTH {
946        // Return the tree depth.
947        true => Ok(tree_depth),
948        false => bail!("Merkle tree cannot exceed depth {DEPTH}: attempted to reach depth {tree_depth}"),
949    }
950}
951
952/// Returns the index of the left child, given an index.
953#[inline]
954const fn left_child(index: usize) -> usize {
955    2 * index + 1
956}
957
958/// Returns the index of the right child, given an index.
959#[inline]
960const fn right_child(index: usize) -> usize {
961    2 * index + 2
962}
963
964/// Returns the index of the sibling, given an index.
965#[inline]
966const fn sibling(index: usize) -> Option<usize> {
967    if is_root(index) {
968        None
969    } else if is_left_child(index) {
970        Some(index + 1)
971    } else {
972        Some(index - 1)
973    }
974}
975
976/// Returns true iff the index represents the root.
977#[inline]
978const fn is_root(index: usize) -> bool {
979    index == 0
980}
981
982/// Returns true iff the given index represents a left child.
983#[inline]
984const fn is_left_child(index: usize) -> bool {
985    index % 2 == 1
986}
987
988/// Returns the index of the parent, given the index of a child.
989#[inline]
990const fn parent(index: usize) -> Option<usize> {
991    if index > 0 { Some((index - 1) >> 1) } else { None }
992}