Skip to main content

miden_crypto/merkle/store/
mod.rs

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