arnaucube
arnaucube/miden-cryptoPublic Self-hosted repository
miden-crypto/src/merkle/store/mod.rs
src/merkle/store/mod.rsRaw
  1use super::{
  2    mmr::Mmr, BTreeMap, EmptySubtreeRoots, InnerNodeInfo, KvMap, MerkleError, MerklePath,
  3    MerkleStoreDelta, MerkleTree, NodeIndex, PartialMerkleTree, RecordingMap, RootPath, Rpo256,
  4    RpoDigest, SimpleSmt, TieredSmt, TryApplyDiff, ValuePath, Vec, EMPTY_WORD,
  5};
  6use crate::utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable};
  7use core::borrow::Borrow;
  8
  9#[cfg(test)]
 10mod tests;
 11
 12// MERKLE STORE
 13// ================================================================================================
 14
 15/// A default [MerkleStore] which uses a simple [BTreeMap] as the backing storage.
 16pub type DefaultMerkleStore = MerkleStore<BTreeMap<RpoDigest, StoreNode>>;
 17
 18/// A [MerkleStore] with recording capabilities which uses [RecordingMap] as the backing storage.
 19pub type RecordingMerkleStore = MerkleStore<RecordingMap<RpoDigest, StoreNode>>;
 20
 21#[derive(Debug, Default, Copy, Clone, Eq, PartialEq)]
 22#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
 23pub struct StoreNode {
 24    left: RpoDigest,
 25    right: RpoDigest,
 26}
 27
 28/// An in-memory data store for Merkelized data.
 29///
 30/// This is a in memory data store for Merkle trees, this store allows all the nodes of multiple
 31/// trees to live as long as necessary and without duplication, this allows the implementation of
 32/// space efficient persistent data structures.
 33///
 34/// Example usage:
 35///
 36/// ```rust
 37/// # use miden_crypto::{ZERO, Felt, Word};
 38/// # use miden_crypto::merkle::{NodeIndex, MerkleStore, MerkleTree};
 39/// # use miden_crypto::hash::rpo::Rpo256;
 40/// # const fn int_to_node(value: u64) -> Word {
 41/// #     [Felt::new(value), ZERO, ZERO, ZERO]
 42/// # }
 43/// # let A = int_to_node(1);
 44/// # let B = int_to_node(2);
 45/// # let C = int_to_node(3);
 46/// # let D = int_to_node(4);
 47/// # let E = int_to_node(5);
 48/// # let F = int_to_node(6);
 49/// # let G = int_to_node(7);
 50/// # let H0 = int_to_node(8);
 51/// # let H1 = int_to_node(9);
 52/// # let T0 = MerkleTree::new([A, B, C, D, E, F, G, H0].to_vec()).expect("even number of leaves provided");
 53/// # let T1 = MerkleTree::new([A, B, C, D, E, F, G, H1].to_vec()).expect("even number of leaves provided");
 54/// # let ROOT0 = T0.root();
 55/// # let ROOT1 = T1.root();
 56/// let mut store: MerkleStore = MerkleStore::new();
 57///
 58/// // the store is initialized with the SMT empty nodes
 59/// assert_eq!(store.num_internal_nodes(), 255);
 60///
 61/// let tree1 = MerkleTree::new(vec![A, B, C, D, E, F, G, H0]).unwrap();
 62/// let tree2 = MerkleTree::new(vec![A, B, C, D, E, F, G, H1]).unwrap();
 63///
 64/// // populates the store with two merkle trees, common nodes are shared
 65/// store.extend(tree1.inner_nodes());
 66/// store.extend(tree2.inner_nodes());
 67///
 68/// // every leaf except the last are the same
 69/// for i in 0..7 {
 70///     let idx0 = NodeIndex::new(3, i).unwrap();
 71///     let d0 = store.get_node(ROOT0, idx0).unwrap();
 72///     let idx1 = NodeIndex::new(3, i).unwrap();
 73///     let d1 = store.get_node(ROOT1, idx1).unwrap();
 74///     assert_eq!(d0, d1, "Both trees have the same leaf at pos {i}");
 75/// }
 76///
 77/// // The leafs A-B-C-D are the same for both trees, so are their 2 immediate parents
 78/// for i in 0..4 {
 79///     let idx0 = NodeIndex::new(3, i).unwrap();
 80///     let d0 = store.get_path(ROOT0, idx0).unwrap();
 81///     let idx1 = NodeIndex::new(3, i).unwrap();
 82///     let d1 = store.get_path(ROOT1, idx1).unwrap();
 83///     assert_eq!(d0.path[0..2], d1.path[0..2], "Both sub-trees are equal up to two levels");
 84/// }
 85///
 86/// // Common internal nodes are shared, the two added trees have a total of 30, but the store has
 87/// // only 10 new entries, corresponding to the 10 unique internal nodes of these trees.
 88/// assert_eq!(store.num_internal_nodes() - 255, 10);
 89/// ```
 90#[derive(Debug, Clone, Eq, PartialEq)]
 91#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
 92pub struct MerkleStore<T: KvMap<RpoDigest, StoreNode> = BTreeMap<RpoDigest, StoreNode>> {
 93    nodes: T,
 94}
 95
 96impl<T: KvMap<RpoDigest, StoreNode>> Default for MerkleStore<T> {
 97    fn default() -> Self {
 98        Self::new()
 99    }
100}
101
102impl<T: KvMap<RpoDigest, StoreNode>> MerkleStore<T> {
103    // CONSTRUCTORS
104    // --------------------------------------------------------------------------------------------
105
106    /// Creates an empty `MerkleStore` instance.
107    pub fn new() -> MerkleStore<T> {
108        // pre-populate the store with the empty hashes
109        let nodes = empty_hashes().into_iter().collect();
110        MerkleStore { nodes }
111    }
112
113    // PUBLIC ACCESSORS
114    // --------------------------------------------------------------------------------------------
115
116    /// Return a count of the non-leaf nodes in the store.
117    pub fn num_internal_nodes(&self) -> usize {
118        self.nodes.len()
119    }
120
121    /// Returns the node at `index` rooted on the tree `root`.
122    ///
123    /// # Errors
124    /// This method can return the following errors:
125    /// - `RootNotInStore` if the `root` is not present in the store.
126    /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in
127    ///   the store.
128    pub fn get_node(&self, root: RpoDigest, index: NodeIndex) -> Result<RpoDigest, MerkleError> {
129        let mut hash = root;
130
131        // corner case: check the root is in the store when called with index `NodeIndex::root()`
132        self.nodes.get(&hash).ok_or(MerkleError::RootNotInStore(hash))?;
133
134        for i in (0..index.depth()).rev() {
135            let node = self.nodes.get(&hash).ok_or(MerkleError::NodeNotInStore(hash, index))?;
136
137            let bit = (index.value() >> i) & 1;
138            hash = if bit == 0 { node.left } else { node.right }
139        }
140
141        Ok(hash)
142    }
143
144    /// Returns the node at the specified `index` and its opening to the `root`.
145    ///
146    /// The path starts at the sibling of the target leaf.
147    ///
148    /// # Errors
149    /// This method can return the following errors:
150    /// - `RootNotInStore` if the `root` is not present in the store.
151    /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in
152    ///   the store.
153    pub fn get_path(&self, root: RpoDigest, index: NodeIndex) -> Result<ValuePath, MerkleError> {
154        let mut hash = root;
155        let mut path = Vec::with_capacity(index.depth().into());
156
157        // corner case: check the root is in the store when called with index `NodeIndex::root()`
158        self.nodes.get(&hash).ok_or(MerkleError::RootNotInStore(hash))?;
159
160        for i in (0..index.depth()).rev() {
161            let node = self.nodes.get(&hash).ok_or(MerkleError::NodeNotInStore(hash, index))?;
162
163            let bit = (index.value() >> i) & 1;
164            hash = if bit == 0 {
165                path.push(node.right);
166                node.left
167            } else {
168                path.push(node.left);
169                node.right
170            }
171        }
172
173        // the path is computed from root to leaf, so it must be reversed
174        path.reverse();
175
176        Ok(ValuePath::new(hash, path))
177    }
178
179    // LEAF TRAVERSAL
180    // --------------------------------------------------------------------------------------------
181
182    /// Returns the depth of the first leaf or an empty node encountered while traversing the tree
183    /// from the specified root down according to the provided index.
184    ///
185    /// The `tree_depth` parameter specifies the depth of the tree rooted at `root`. The
186    /// maximum value the argument accepts is [u64::BITS].
187    ///
188    /// # Errors
189    /// Will return an error if:
190    /// - The provided root is not found.
191    /// - The provided `tree_depth` is greater than 64.
192    /// - The provided `index` is not valid for a depth equivalent to `tree_depth`.
193    /// - No leaf or an empty node was found while traversing the tree down to `tree_depth`.
194    pub fn get_leaf_depth(
195        &self,
196        root: RpoDigest,
197        tree_depth: u8,
198        index: u64,
199    ) -> Result<u8, MerkleError> {
200        // validate depth and index
201        if tree_depth > 64 {
202            return Err(MerkleError::DepthTooBig(tree_depth as u64));
203        }
204        NodeIndex::new(tree_depth, index)?;
205
206        // check if the root exists, providing the proper error report if it doesn't
207        let empty = EmptySubtreeRoots::empty_hashes(tree_depth);
208        let mut hash = root;
209        if !self.nodes.contains_key(&hash) {
210            return Err(MerkleError::RootNotInStore(hash));
211        }
212
213        // we traverse from root to leaf, so the path is reversed
214        let mut path = (index << (64 - tree_depth)).reverse_bits();
215
216        // iterate every depth and reconstruct the path from root to leaf
217        for depth in 0..=tree_depth {
218            // we short-circuit if an empty node has been found
219            if hash == empty[depth as usize] {
220                return Ok(depth);
221            }
222
223            // fetch the children pair, mapped by its parent hash
224            let children = match self.nodes.get(&hash) {
225                Some(node) => node,
226                None => return Ok(depth),
227            };
228
229            // traverse down
230            hash = if path & 1 == 0 { children.left } else { children.right };
231            path >>= 1;
232        }
233
234        // return an error because we exhausted the index but didn't find either a leaf or an
235        // empty node
236        Err(MerkleError::DepthTooBig(tree_depth as u64 + 1))
237    }
238
239    /// Returns index and value of a leaf node which is the only leaf node in a subtree defined by
240    /// the provided root. If the subtree contains zero or more than one leaf nodes None is
241    /// returned.
242    ///
243    /// The `tree_depth` parameter specifies the depth of the parent tree such that `root` is
244    /// located in this tree at `root_index`. The maximum value the argument accepts is
245    /// [u64::BITS].
246    ///
247    /// # Errors
248    /// Will return an error if:
249    /// - The provided root is not found.
250    /// - The provided `tree_depth` is greater than 64.
251    /// - The provided `root_index` has depth greater than `tree_depth`.
252    /// - A lone node at depth `tree_depth` is not a leaf node.
253    pub fn find_lone_leaf(
254        &self,
255        root: RpoDigest,
256        root_index: NodeIndex,
257        tree_depth: u8,
258    ) -> Result<Option<(NodeIndex, RpoDigest)>, MerkleError> {
259        // we set max depth at u64::BITS as this is the largest meaningful value for a 64-bit index
260        const MAX_DEPTH: u8 = u64::BITS as u8;
261        if tree_depth > MAX_DEPTH {
262            return Err(MerkleError::DepthTooBig(tree_depth as u64));
263        }
264        let empty = EmptySubtreeRoots::empty_hashes(MAX_DEPTH);
265
266        let mut node = root;
267        if !self.nodes.contains_key(&node) {
268            return Err(MerkleError::RootNotInStore(node));
269        }
270
271        let mut index = root_index;
272        if index.depth() > tree_depth {
273            return Err(MerkleError::DepthTooBig(index.depth() as u64));
274        }
275
276        // traverse down following the path of single non-empty nodes; this works because if a
277        // node has two empty children it cannot contain a lone leaf. similarly if a node has
278        // two non-empty children it must contain at least two leaves.
279        for depth in index.depth()..tree_depth {
280            // if the node is a leaf, return; otherwise, examine the node's children
281            let children = match self.nodes.get(&node) {
282                Some(node) => node,
283                None => return Ok(Some((index, node))),
284            };
285
286            let empty_node = empty[depth as usize + 1];
287            node = if children.left != empty_node && children.right == empty_node {
288                index = index.left_child();
289                children.left
290            } else if children.left == empty_node && children.right != empty_node {
291                index = index.right_child();
292                children.right
293            } else {
294                return Ok(None);
295            };
296        }
297
298        // if we are here, we got to `tree_depth`; thus, either the current node is a leaf node,
299        // and so we return it, or it is an internal node, and then we return an error
300        if self.nodes.contains_key(&node) {
301            Err(MerkleError::DepthTooBig(tree_depth as u64 + 1))
302        } else {
303            Ok(Some((index, node)))
304        }
305    }
306
307    // DATA EXTRACTORS
308    // --------------------------------------------------------------------------------------------
309
310    /// Returns a subset of this Merkle store such that the returned Merkle store contains all
311    /// nodes which are descendants of the specified roots.
312    ///
313    /// The roots for which no descendants exist in this Merkle store are ignored.
314    pub fn subset<I, R>(&self, roots: I) -> MerkleStore<T>
315    where
316        I: Iterator<Item = R>,
317        R: Borrow<RpoDigest>,
318    {
319        let mut store = MerkleStore::new();
320        for root in roots {
321            let root = *root.borrow();
322            store.clone_tree_from(root, self);
323        }
324        store
325    }
326
327    /// Iterator over the inner nodes of the [MerkleStore].
328    pub fn inner_nodes(&self) -> impl Iterator<Item = InnerNodeInfo> + '_ {
329        self.nodes.iter().map(|(r, n)| InnerNodeInfo {
330            value: *r,
331            left: n.left,
332            right: n.right,
333        })
334    }
335
336    /// Iterator over the non-empty leaves of the Merkle tree associated with the specified `root`
337    /// and `max_depth`.
338    pub fn non_empty_leaves(
339        &self,
340        root: RpoDigest,
341        max_depth: u8,
342    ) -> impl Iterator<Item = (NodeIndex, RpoDigest)> + '_ {
343        let empty_roots = EmptySubtreeRoots::empty_hashes(max_depth);
344        let mut stack = Vec::new();
345        stack.push((NodeIndex::new_unchecked(0, 0), root));
346
347        core::iter::from_fn(move || {
348            while let Some((index, node_hash)) = stack.pop() {
349                if index.depth() == max_depth {
350                    return Some((index, node_hash));
351                }
352
353                if let Some(node) = self.nodes.get(&node_hash) {
354                    if !empty_roots.contains(&node.left) {
355                        stack.push((index.left_child(), node.left));
356                    }
357                    if !empty_roots.contains(&node.right) {
358                        stack.push((index.right_child(), node.right));
359                    }
360                }
361            }
362
363            None
364        })
365    }
366
367    // STATE MUTATORS
368    // --------------------------------------------------------------------------------------------
369
370    /// Adds all the nodes of a Merkle path represented by `path`, opening to `node`. Returns the
371    /// new root.
372    ///
373    /// This will compute the sibling elements determined by the Merkle `path` and `node`, and
374    /// include all the nodes into the store.
375    pub fn add_merkle_path(
376        &mut self,
377        index: u64,
378        node: RpoDigest,
379        path: MerklePath,
380    ) -> Result<RpoDigest, MerkleError> {
381        let root = path.inner_nodes(index, node)?.fold(RpoDigest::default(), |_, node| {
382            let value: RpoDigest = node.value;
383            let left: RpoDigest = node.left;
384            let right: RpoDigest = node.right;
385
386            debug_assert_eq!(Rpo256::merge(&[left, right]), value);
387            self.nodes.insert(value, StoreNode { left, right });
388
389            node.value
390        });
391        Ok(root)
392    }
393
394    /// Adds all the nodes of multiple Merkle paths into the store.
395    ///
396    /// This will compute the sibling elements for each Merkle `path` and include all the nodes
397    /// into the store.
398    ///
399    /// For further reference, check [MerkleStore::add_merkle_path].
400    pub fn add_merkle_paths<I>(&mut self, paths: I) -> Result<(), MerkleError>
401    where
402        I: IntoIterator<Item = (u64, RpoDigest, MerklePath)>,
403    {
404        for (index_value, node, path) in paths.into_iter() {
405            self.add_merkle_path(index_value, node, path)?;
406        }
407        Ok(())
408    }
409
410    /// Sets a node to `value`.
411    ///
412    /// # Errors
413    /// This method can return the following errors:
414    /// - `RootNotInStore` if the `root` is not present in the store.
415    /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in
416    ///   the store.
417    pub fn set_node(
418        &mut self,
419        mut root: RpoDigest,
420        index: NodeIndex,
421        value: RpoDigest,
422    ) -> Result<RootPath, MerkleError> {
423        let node = value;
424        let ValuePath { value, path } = self.get_path(root, index)?;
425
426        // performs the update only if the node value differs from the opening
427        if node != value {
428            root = self.add_merkle_path(index.value(), node, path.clone())?;
429        }
430
431        Ok(RootPath { root, path })
432    }
433
434    /// Merges two elements and adds the resulting node into the store.
435    ///
436    /// Merges arbitrary values. They may be leafs, nodes, or a mixture of both.
437    pub fn merge_roots(
438        &mut self,
439        left_root: RpoDigest,
440        right_root: RpoDigest,
441    ) -> Result<RpoDigest, MerkleError> {
442        let parent = Rpo256::merge(&[left_root, right_root]);
443        self.nodes.insert(
444            parent,
445            StoreNode {
446                left: left_root,
447                right: right_root,
448            },
449        );
450
451        Ok(parent)
452    }
453
454    // DESTRUCTURING
455    // --------------------------------------------------------------------------------------------
456
457    /// Returns the inner storage of this MerkleStore while consuming `self`.
458    pub fn into_inner(self) -> T {
459        self.nodes
460    }
461
462    // HELPER METHODS
463    // --------------------------------------------------------------------------------------------
464
465    /// Recursively clones a tree with the specified root from the specified source into self.
466    ///
467    /// If the source store does not contain a tree with the specified root, this is a noop.
468    fn clone_tree_from(&mut self, root: RpoDigest, source: &Self) {
469        // process the node only if it is in the source
470        if let Some(node) = source.nodes.get(&root) {
471            // if the node has already been inserted, no need to process it further as all of its
472            // descendants should be already cloned from the source store
473            if self.nodes.insert(root, *node).is_none() {
474                self.clone_tree_from(node.left, source);
475                self.clone_tree_from(node.right, source);
476            }
477        }
478    }
479}
480
481// CONVERSIONS
482// ================================================================================================
483
484impl<T: KvMap<RpoDigest, StoreNode>> From<&MerkleTree> for MerkleStore<T> {
485    fn from(value: &MerkleTree) -> Self {
486        let nodes = combine_nodes_with_empty_hashes(value.inner_nodes()).collect();
487        Self { nodes }
488    }
489}
490
491impl<T: KvMap<RpoDigest, StoreNode>> From<&SimpleSmt> for MerkleStore<T> {
492    fn from(value: &SimpleSmt) -> Self {
493        let nodes = combine_nodes_with_empty_hashes(value.inner_nodes()).collect();
494        Self { nodes }
495    }
496}
497
498impl<T: KvMap<RpoDigest, StoreNode>> From<&Mmr> for MerkleStore<T> {
499    fn from(value: &Mmr) -> Self {
500        let nodes = combine_nodes_with_empty_hashes(value.inner_nodes()).collect();
501        Self { nodes }
502    }
503}
504
505impl<T: KvMap<RpoDigest, StoreNode>> From<&TieredSmt> for MerkleStore<T> {
506    fn from(value: &TieredSmt) -> Self {
507        let nodes = combine_nodes_with_empty_hashes(value.inner_nodes()).collect();
508        Self { nodes }
509    }
510}
511
512impl<T: KvMap<RpoDigest, StoreNode>> From<&PartialMerkleTree> for MerkleStore<T> {
513    fn from(value: &PartialMerkleTree) -> Self {
514        let nodes = combine_nodes_with_empty_hashes(value.inner_nodes()).collect();
515        Self { nodes }
516    }
517}
518
519impl<T: KvMap<RpoDigest, StoreNode>> From<T> for MerkleStore<T> {
520    fn from(values: T) -> Self {
521        let nodes = values.into_iter().chain(empty_hashes()).collect();
522        Self { nodes }
523    }
524}
525
526impl<T: KvMap<RpoDigest, StoreNode>> FromIterator<InnerNodeInfo> for MerkleStore<T> {
527    fn from_iter<I: IntoIterator<Item = InnerNodeInfo>>(iter: I) -> Self {
528        let nodes = combine_nodes_with_empty_hashes(iter).collect();
529        Self { nodes }
530    }
531}
532
533impl<T: KvMap<RpoDigest, StoreNode>> FromIterator<(RpoDigest, StoreNode)> for MerkleStore<T> {
534    fn from_iter<I: IntoIterator<Item = (RpoDigest, StoreNode)>>(iter: I) -> Self {
535        let nodes = iter.into_iter().chain(empty_hashes()).collect();
536        Self { nodes }
537    }
538}
539
540// ITERATORS
541// ================================================================================================
542impl<T: KvMap<RpoDigest, StoreNode>> Extend<InnerNodeInfo> for MerkleStore<T> {
543    fn extend<I: IntoIterator<Item = InnerNodeInfo>>(&mut self, iter: I) {
544        self.nodes.extend(iter.into_iter().map(|info| {
545            (
546                info.value,
547                StoreNode {
548                    left: info.left,
549                    right: info.right,
550                },
551            )
552        }));
553    }
554}
555
556// DiffT & ApplyDiffT TRAIT IMPLEMENTATION
557// ================================================================================================
558impl<T: KvMap<RpoDigest, StoreNode>> TryApplyDiff<RpoDigest, StoreNode> for MerkleStore<T> {
559    type Error = MerkleError;
560    type DiffType = MerkleStoreDelta;
561
562    fn try_apply(&mut self, diff: Self::DiffType) -> Result<(), MerkleError> {
563        for (root, delta) in diff.0 {
564            let mut root = root;
565            for cleared_slot in delta.cleared_slots() {
566                root = self
567                    .set_node(
568                        root,
569                        NodeIndex::new(delta.depth(), *cleared_slot)?,
570                        EMPTY_WORD.into(),
571                    )?
572                    .root;
573            }
574            for (updated_slot, updated_value) in delta.updated_slots() {
575                root = self
576                    .set_node(
577                        root,
578                        NodeIndex::new(delta.depth(), *updated_slot)?,
579                        (*updated_value).into(),
580                    )?
581                    .root;
582            }
583        }
584
585        Ok(())
586    }
587}
588
589// SERIALIZATION
590// ================================================================================================
591
592impl Serializable for StoreNode {
593    fn write_into<W: ByteWriter>(&self, target: &mut W) {
594        self.left.write_into(target);
595        self.right.write_into(target);
596    }
597}
598
599impl Deserializable for StoreNode {
600    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
601        let left = RpoDigest::read_from(source)?;
602        let right = RpoDigest::read_from(source)?;
603        Ok(StoreNode { left, right })
604    }
605}
606
607impl<T: KvMap<RpoDigest, StoreNode>> Serializable for MerkleStore<T> {
608    fn write_into<W: ByteWriter>(&self, target: &mut W) {
609        target.write_u64(self.nodes.len() as u64);
610
611        for (k, v) in self.nodes.iter() {
612            k.write_into(target);
613            v.write_into(target);
614        }
615    }
616}
617
618impl<T: KvMap<RpoDigest, StoreNode>> Deserializable for MerkleStore<T> {
619    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
620        let len = source.read_u64()?;
621        let mut nodes: Vec<(RpoDigest, StoreNode)> = Vec::with_capacity(len as usize);
622
623        for _ in 0..len {
624            let key = RpoDigest::read_from(source)?;
625            let value = StoreNode::read_from(source)?;
626            nodes.push((key, value));
627        }
628
629        Ok(nodes.into_iter().collect())
630    }
631}
632
633// HELPER FUNCTIONS
634// ================================================================================================
635
636/// Creates empty hashes for all the subtrees of a tree with a max depth of 255.
637fn empty_hashes() -> impl IntoIterator<Item = (RpoDigest, StoreNode)> {
638    let subtrees = EmptySubtreeRoots::empty_hashes(255);
639    subtrees.iter().rev().copied().zip(subtrees.iter().rev().skip(1).copied()).map(
640        |(child, parent)| {
641            (
642                parent,
643                StoreNode {
644                    left: child,
645                    right: child,
646                },
647            )
648        },
649    )
650}
651
652/// Consumes an iterator of [InnerNodeInfo] and returns an iterator of `(value, node)` tuples
653/// which includes the nodes associate with roots of empty subtrees up to a depth of 255.
654fn combine_nodes_with_empty_hashes(
655    nodes: impl IntoIterator<Item = InnerNodeInfo>,
656) -> impl Iterator<Item = (RpoDigest, StoreNode)> {
657    nodes
658        .into_iter()
659        .map(|info| {
660            (
661                info.value,
662                StoreNode {
663                    left: info.left,
664                    right: info.right,
665                },
666            )
667        })
668        .chain(empty_hashes())
669}