arnaucube
arnaucube/miden-cryptoPublic Self-hosted repository
miden-crypto/src/merkle/store/mod.rs
src/merkle/store/mod.rsRaw
  1use super::mmr::Mmr;
  2use super::{
  3    BTreeMap, EmptySubtreeRoots, InnerNodeInfo, MerkleError, MerklePath, MerklePathSet, MerkleTree,
  4    NodeIndex, RootPath, Rpo256, RpoDigest, SimpleSmt, ValuePath, Vec, Word,
  5};
  6use crate::utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable};
  7
  8#[cfg(test)]
  9mod tests;
 10
 11#[derive(Debug, Default, Copy, Clone, Eq, PartialEq)]
 12pub struct Node {
 13    left: RpoDigest,
 14    right: RpoDigest,
 15}
 16
 17/// An in-memory data store for Merkelized data.
 18///
 19/// This is a in memory data store for Merkle trees, this store allows all the nodes of multiple
 20/// trees to live as long as necessary and without duplication, this allows the implementation of
 21/// space efficient persistent data structures.
 22///
 23/// Example usage:
 24///
 25/// ```rust
 26/// # use miden_crypto::{ZERO, Felt, Word};
 27/// # use miden_crypto::merkle::{NodeIndex, MerkleStore, MerkleTree};
 28/// # use miden_crypto::hash::rpo::Rpo256;
 29/// # const fn int_to_node(value: u64) -> Word {
 30/// #     [Felt::new(value), ZERO, ZERO, ZERO]
 31/// # }
 32/// # let A = int_to_node(1);
 33/// # let B = int_to_node(2);
 34/// # let C = int_to_node(3);
 35/// # let D = int_to_node(4);
 36/// # let E = int_to_node(5);
 37/// # let F = int_to_node(6);
 38/// # let G = int_to_node(7);
 39/// # let H0 = int_to_node(8);
 40/// # let H1 = int_to_node(9);
 41/// # let T0 = MerkleTree::new([A, B, C, D, E, F, G, H0].to_vec()).expect("even number of leaves provided");
 42/// # let T1 = MerkleTree::new([A, B, C, D, E, F, G, H1].to_vec()).expect("even number of leaves provided");
 43/// # let ROOT0 = T0.root();
 44/// # let ROOT1 = T1.root();
 45/// let mut store = MerkleStore::new();
 46///
 47/// // the store is initialized with the SMT empty nodes
 48/// assert_eq!(store.num_internal_nodes(), 255);
 49///
 50/// let tree1 = MerkleTree::new(vec![A, B, C, D, E, F, G, H0]).unwrap();
 51/// let tree2 = MerkleTree::new(vec![A, B, C, D, E, F, G, H1]).unwrap();
 52///
 53/// // populates the store with two merkle trees, common nodes are shared
 54/// store
 55///     .extend(tree1.inner_nodes())
 56///     .extend(tree2.inner_nodes());
 57///
 58/// // every leaf except the last are the same
 59/// for i in 0..7 {
 60///     let idx0 = NodeIndex::new(3, i).unwrap();
 61///     let d0 = store.get_node(ROOT0, idx0).unwrap();
 62///     let idx1 = NodeIndex::new(3, i).unwrap();
 63///     let d1 = store.get_node(ROOT1, idx1).unwrap();
 64///     assert_eq!(d0, d1, "Both trees have the same leaf at pos {i}");
 65/// }
 66///
 67/// // The leafs A-B-C-D are the same for both trees, so are their 2 immediate parents
 68/// for i in 0..4 {
 69///     let idx0 = NodeIndex::new(3, i).unwrap();
 70///     let d0 = store.get_path(ROOT0, idx0).unwrap();
 71///     let idx1 = NodeIndex::new(3, i).unwrap();
 72///     let d1 = store.get_path(ROOT1, idx1).unwrap();
 73///     assert_eq!(d0.path[0..2], d1.path[0..2], "Both sub-trees are equal up to two levels");
 74/// }
 75///
 76/// // Common internal nodes are shared, the two added trees have a total of 30, but the store has
 77/// // only 10 new entries, corresponding to the 10 unique internal nodes of these trees.
 78/// assert_eq!(store.num_internal_nodes() - 255, 10);
 79/// ```
 80#[derive(Debug, Clone, Eq, PartialEq)]
 81pub struct MerkleStore {
 82    nodes: BTreeMap<RpoDigest, Node>,
 83}
 84
 85impl Default for MerkleStore {
 86    fn default() -> Self {
 87        Self::new()
 88    }
 89}
 90
 91impl MerkleStore {
 92    // CONSTRUCTORS
 93    // --------------------------------------------------------------------------------------------
 94
 95    /// Creates an empty `MerkleStore` instance.
 96    pub fn new() -> MerkleStore {
 97        // pre-populate the store with the empty hashes
 98        let subtrees = EmptySubtreeRoots::empty_hashes(255);
 99        let nodes = subtrees
100            .iter()
101            .rev()
102            .copied()
103            .zip(subtrees.iter().rev().skip(1).copied())
104            .map(|(child, parent)| {
105                (
106                    parent,
107                    Node {
108                        left: child,
109                        right: child,
110                    },
111                )
112            })
113            .collect();
114
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    ///
130    /// This method can return the following errors:
131    /// - `RootNotInStore` if the `root` is not present in the store.
132    /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in the store.
133    pub fn get_node(&self, root: Word, index: NodeIndex) -> Result<Word, MerkleError> {
134        let mut hash: RpoDigest = root.into();
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.into()))?;
138
139        for i in (0..index.depth()).rev() {
140            let node =
141                self.nodes.get(&hash).ok_or(MerkleError::NodeNotInStore(hash.into(), index))?;
142
143            let bit = (index.value() >> i) & 1;
144            hash = if bit == 0 { node.left } else { node.right }
145        }
146
147        Ok(hash.into())
148    }
149
150    /// Returns the node at the specified `index` and its opening to the `root`.
151    ///
152    /// The path starts at the sibling of the target leaf.
153    ///
154    /// # Errors
155    ///
156    /// This method can return the following errors:
157    /// - `RootNotInStore` if the `root` is not present in the store.
158    /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in the store.
159    pub fn get_path(&self, root: Word, index: NodeIndex) -> Result<ValuePath, MerkleError> {
160        let mut hash: RpoDigest = root.into();
161        let mut path = Vec::with_capacity(index.depth().into());
162
163        // corner case: check the root is in the store when called with index `NodeIndex::root()`
164        self.nodes.get(&hash).ok_or(MerkleError::RootNotInStore(hash.into()))?;
165
166        for i in (0..index.depth()).rev() {
167            let node =
168                self.nodes.get(&hash).ok_or(MerkleError::NodeNotInStore(hash.into(), index))?;
169
170            let bit = (index.value() >> i) & 1;
171            hash = if bit == 0 {
172                path.push(node.right.into());
173                node.left
174            } else {
175                path.push(node.left.into());
176                node.right
177            }
178        }
179
180        // the path is computed from root to leaf, so it must be reversed
181        path.reverse();
182
183        Ok(ValuePath {
184            value: hash.into(),
185            path: MerklePath::new(path),
186        })
187    }
188
189    /// Reconstructs a path from the root until a leaf or empty node and returns its depth.
190    ///
191    /// The `tree_depth` parameter defines up to which depth the tree will be traversed, starting
192    /// from `root`. The maximum value the argument accepts is [u64::BITS].
193    ///
194    /// The traversed path from leaf to root will start at the least significant bit of `index`,
195    /// and will be executed for `tree_depth` bits.
196    ///
197    /// # Errors
198    /// Will return an error if:
199    /// - The provided root is not found.
200    /// - The path from the root continues to a depth greater than `tree_depth`.
201    /// - The provided `tree_depth` is greater than `64.
202    /// - The provided `index` is not valid for a depth equivalent to `tree_depth`. For more
203    /// information, check [NodeIndex::new].
204    pub fn get_leaf_depth(
205        &self,
206        root: Word,
207        tree_depth: u8,
208        index: u64,
209    ) -> Result<u8, MerkleError> {
210        // validate depth and index
211        if tree_depth > 64 {
212            return Err(MerkleError::DepthTooBig(tree_depth as u64));
213        }
214        NodeIndex::new(tree_depth, index)?;
215
216        // it's not illegal to have a maximum depth of `0`; we should just return the root in that
217        // case. this check will simplify the implementation as we could overflow bits for depth
218        // `0`.
219        if tree_depth == 0 {
220            return Ok(0);
221        }
222
223        // check if the root exists, providing the proper error report if it doesn't
224        let empty = EmptySubtreeRoots::empty_hashes(tree_depth);
225        let mut hash: RpoDigest = root.into();
226        if !self.nodes.contains_key(&hash) {
227            return Err(MerkleError::RootNotInStore(hash.into()));
228        }
229
230        // we traverse from root to leaf, so the path is reversed
231        let mut path = (index << (64 - tree_depth)).reverse_bits();
232
233        // iterate every depth and reconstruct the path from root to leaf
234        for depth in 0..tree_depth {
235            // we short-circuit if an empty node has been found
236            if hash == empty[depth as usize] {
237                return Ok(depth);
238            }
239
240            // fetch the children pair, mapped by its parent hash
241            let children = match self.nodes.get(&hash) {
242                Some(node) => node,
243                None => return Ok(depth),
244            };
245
246            // traverse down
247            hash = if path & 1 == 0 { children.left } else { children.right };
248            path >>= 1;
249        }
250
251        // at max depth assert it doesn't have sub-trees
252        if self.nodes.contains_key(&hash) {
253            return Err(MerkleError::DepthTooBig(tree_depth as u64 + 1));
254        }
255
256        // depleted bits; return max depth
257        Ok(tree_depth)
258    }
259
260    // DATA EXTRACTORS
261    // --------------------------------------------------------------------------------------------
262
263    /// Returns a subset of this Merkle store such that the returned Merkle store contains all
264    /// nodes which are descendants of the specified roots.
265    ///
266    /// The roots for which no descendants exist in this Merkle store are ignored.
267    pub fn subset(&self, roots: &[Word]) -> MerkleStore {
268        let mut store = MerkleStore::new();
269        for root in roots {
270            let root = RpoDigest::from(*root);
271            self.clone_tree_into(root, &mut store);
272        }
273        store
274    }
275
276    /// Iterator over the inner nodes of the [MerkleStore].
277    pub fn inner_nodes(&self) -> impl Iterator<Item = InnerNodeInfo> + '_ {
278        self.nodes.iter().map(|(r, n)| InnerNodeInfo {
279            value: r.into(),
280            left: n.left.into(),
281            right: n.right.into(),
282        })
283    }
284
285    // STATE MUTATORS
286    // --------------------------------------------------------------------------------------------
287
288    /// Adds a sequence of nodes yielded by the provided iterator into the store.
289    pub fn extend<I>(&mut self, iter: I) -> &mut MerkleStore
290    where
291        I: Iterator<Item = InnerNodeInfo>,
292    {
293        for node in iter {
294            let value: RpoDigest = node.value.into();
295            let left: RpoDigest = node.left.into();
296            let right: RpoDigest = node.right.into();
297
298            debug_assert_eq!(Rpo256::merge(&[left, right]), value);
299            self.nodes.insert(value, Node { left, right });
300        }
301
302        self
303    }
304
305    /// Adds all the nodes of a Merkle path represented by `path`, opening to `node`. Returns the
306    /// new root.
307    ///
308    /// This will compute the sibling elements determined by the Merkle `path` and `node`, and
309    /// include all the nodes into the store.
310    pub fn add_merkle_path(
311        &mut self,
312        index: u64,
313        node: Word,
314        path: MerklePath,
315    ) -> Result<Word, MerkleError> {
316        let root = path.inner_nodes(index, node)?.fold(Word::default(), |_, node| {
317            let value: RpoDigest = node.value.into();
318            let left: RpoDigest = node.left.into();
319            let right: RpoDigest = node.right.into();
320
321            debug_assert_eq!(Rpo256::merge(&[left, right]), value);
322            self.nodes.insert(value, Node { left, right });
323
324            node.value
325        });
326        Ok(root)
327    }
328
329    /// Adds all the nodes of multiple Merkle paths into the store.
330    ///
331    /// This will compute the sibling elements for each Merkle `path` and include all the nodes
332    /// into the store.
333    ///
334    /// For further reference, check [MerkleStore::add_merkle_path].
335    pub fn add_merkle_paths<I>(&mut self, paths: I) -> Result<(), MerkleError>
336    where
337        I: IntoIterator<Item = (u64, Word, MerklePath)>,
338    {
339        for (index_value, node, path) in paths.into_iter() {
340            self.add_merkle_path(index_value, node, path)?;
341        }
342        Ok(())
343    }
344
345    /// Appends the provided [MerklePathSet] into the store.
346    ///
347    /// For further reference, check [MerkleStore::add_merkle_path].
348    pub fn add_merkle_path_set(&mut self, path_set: &MerklePathSet) -> Result<Word, MerkleError> {
349        let root = path_set.root();
350        for (index, path) in path_set.to_paths() {
351            self.add_merkle_path(index, path.value, path.path)?;
352        }
353        Ok(root)
354    }
355
356    /// Sets a node to `value`.
357    ///
358    /// # Errors
359    ///
360    /// This method can return the following errors:
361    /// - `RootNotInStore` if the `root` is not present in the store.
362    /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in the store.
363    pub fn set_node(
364        &mut self,
365        mut root: Word,
366        index: NodeIndex,
367        value: Word,
368    ) -> Result<RootPath, MerkleError> {
369        let node = value;
370        let ValuePath { value, path } = self.get_path(root, index)?;
371
372        // performs the update only if the node value differs from the opening
373        if node != value {
374            root = self.add_merkle_path(index.value(), node, path.clone())?;
375        }
376
377        Ok(RootPath { root, path })
378    }
379
380    /// Merges two elements and adds the resulting node into the store.
381    ///
382    /// Merges arbitrary values. They may be leafs, nodes, or a mixture of both.
383    pub fn merge_roots(&mut self, root1: Word, root2: Word) -> Result<Word, MerkleError> {
384        let left: RpoDigest = root1.into();
385        let right: RpoDigest = root2.into();
386
387        let parent = Rpo256::merge(&[left, right]);
388        self.nodes.insert(parent, Node { left, right });
389
390        Ok(parent.into())
391    }
392
393    // HELPER METHODS
394    // --------------------------------------------------------------------------------------------
395
396    /// Recursively clones a tree starting at the specified root into the specified target.
397    ///
398    /// If this Merkle store does not contain a tree with the specified root, this is a noop.
399    fn clone_tree_into(&self, root: RpoDigest, target: &mut Self) {
400        // process the node only if it is in this store
401        if let Some(node) = self.nodes.get(&root) {
402            // if the node has already been inserted, no need to process it further as all of its
403            // descendants should be already in the target store
404            if matches!(target.nodes.insert(root, *node), None) {
405                self.clone_tree_into(node.left, target);
406                self.clone_tree_into(node.right, target);
407            }
408        }
409    }
410}
411
412// CONVERSIONS
413// ================================================================================================
414
415impl From<&MerkleTree> for MerkleStore {
416    fn from(value: &MerkleTree) -> Self {
417        let mut store = MerkleStore::new();
418        store.extend(value.inner_nodes());
419        store
420    }
421}
422
423impl From<&SimpleSmt> for MerkleStore {
424    fn from(value: &SimpleSmt) -> Self {
425        let mut store = MerkleStore::new();
426        store.extend(value.inner_nodes());
427        store
428    }
429}
430
431impl From<&Mmr> for MerkleStore {
432    fn from(value: &Mmr) -> Self {
433        let mut store = MerkleStore::new();
434        store.extend(value.inner_nodes());
435        store
436    }
437}
438
439impl FromIterator<InnerNodeInfo> for MerkleStore {
440    fn from_iter<T: IntoIterator<Item = InnerNodeInfo>>(iter: T) -> Self {
441        let mut store = MerkleStore::new();
442        store.extend(iter.into_iter());
443        store
444    }
445}
446
447// ITERATORS
448// ================================================================================================
449
450impl Extend<InnerNodeInfo> for MerkleStore {
451    fn extend<T: IntoIterator<Item = InnerNodeInfo>>(&mut self, iter: T) {
452        self.extend(iter.into_iter());
453    }
454}
455
456// SERIALIZATION
457// ================================================================================================
458
459impl Serializable for Node {
460    fn write_into<W: ByteWriter>(&self, target: &mut W) {
461        self.left.write_into(target);
462        self.right.write_into(target);
463    }
464}
465
466impl Deserializable for Node {
467    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
468        let left = RpoDigest::read_from(source)?;
469        let right = RpoDigest::read_from(source)?;
470        Ok(Node { left, right })
471    }
472}
473
474impl Serializable for MerkleStore {
475    fn write_into<W: ByteWriter>(&self, target: &mut W) {
476        target.write_u64(self.nodes.len() as u64);
477
478        for (k, v) in self.nodes.iter() {
479            k.write_into(target);
480            v.write_into(target);
481        }
482    }
483}
484
485impl Deserializable for MerkleStore {
486    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
487        let len = source.read_u64()?;
488        let mut nodes: BTreeMap<RpoDigest, Node> = BTreeMap::new();
489
490        for _ in 0..len {
491            let key = RpoDigest::read_from(source)?;
492            let value = Node::read_from(source)?;
493            nodes.insert(key, value);
494        }
495
496        Ok(MerkleStore { nodes })
497    }
498}