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