arnaucube
arnaucube/miden-cryptoPublic Self-hosted repository
miden-crypto/src/merkle/store/mod.rs
src/merkle/store/mod.rsRaw
  1use super::mmr::{Mmr, MmrPeaks};
  2use super::{
  3    BTreeMap, EmptySubtreeRoots, MerkleError, MerklePath, MerklePathSet, MerkleTree, NodeIndex,
  4    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 Merkle-lized 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/// // populates the store with two merkle trees, common nodes are shared
 51/// store.add_merkle_tree([A, B, C, D, E, F, G, H0]);
 52/// store.add_merkle_tree([A, B, C, D, E, F, G, H1]);
 53///
 54/// // every leaf except the last are the same
 55/// for i in 0..7 {
 56///     let idx0 = NodeIndex::new(3, i).unwrap();
 57///     let d0 = store.get_node(ROOT0, idx0).unwrap();
 58///     let idx1 = NodeIndex::new(3, i).unwrap();
 59///     let d1 = store.get_node(ROOT1, idx1).unwrap();
 60///     assert_eq!(d0, d1, "Both trees have the same leaf at pos {i}");
 61/// }
 62///
 63/// // The leafs A-B-C-D are the same for both trees, so are their 2 immediate parents
 64/// for i in 0..4 {
 65///     let idx0 = NodeIndex::new(3, i).unwrap();
 66///     let d0 = store.get_path(ROOT0, idx0).unwrap();
 67///     let idx1 = NodeIndex::new(3, i).unwrap();
 68///     let d1 = store.get_path(ROOT1, idx1).unwrap();
 69///     assert_eq!(d0.path[0..2], d1.path[0..2], "Both sub-trees are equal up to two levels");
 70/// }
 71///
 72/// // Common internal nodes are shared, the two added trees have a total of 30, but the store has
 73/// // only 10 new entries, corresponding to the 10 unique internal nodes of these trees.
 74/// assert_eq!(store.num_internal_nodes() - 255, 10);
 75/// ```
 76#[derive(Debug, Clone, Eq, PartialEq)]
 77pub struct MerkleStore {
 78    nodes: BTreeMap<RpoDigest, Node>,
 79}
 80
 81impl Default for MerkleStore {
 82    fn default() -> Self {
 83        Self::new()
 84    }
 85}
 86
 87impl MerkleStore {
 88    // CONSTRUCTORS
 89    // --------------------------------------------------------------------------------------------
 90
 91    /// Creates an empty `MerkleStore` instance.
 92    pub fn new() -> MerkleStore {
 93        // pre-populate the store with the empty hashes
 94        let subtrees = EmptySubtreeRoots::empty_hashes(255);
 95        let nodes = subtrees
 96            .iter()
 97            .rev()
 98            .copied()
 99            .zip(subtrees.iter().rev().skip(1).copied())
100            .map(|(child, parent)| {
101                (
102                    parent,
103                    Node {
104                        left: child,
105                        right: child,
106                    },
107                )
108            })
109            .collect();
110
111        MerkleStore { nodes }
112    }
113
114    /// Appends the provided merkle tree represented by its `leaves` to the set.
115    pub fn with_merkle_tree<I>(mut self, leaves: I) -> Result<Self, MerkleError>
116    where
117        I: IntoIterator<Item = Word>,
118    {
119        self.add_merkle_tree(leaves)?;
120        Ok(self)
121    }
122
123    /// Appends the provided Sparse Merkle tree represented by its `entries` to the set.
124    ///
125    /// For more information, check [MerkleStore::add_sparse_merkle_tree].
126    pub fn with_sparse_merkle_tree<R, I>(
127        mut self,
128        depth: u8,
129        entries: R,
130    ) -> Result<Self, MerkleError>
131    where
132        R: IntoIterator<IntoIter = I>,
133        I: Iterator<Item = (u64, Word)> + ExactSizeIterator,
134    {
135        self.add_sparse_merkle_tree(depth, entries)?;
136        Ok(self)
137    }
138
139    /// Appends the provided merkle path set.
140    pub fn with_merkle_path(
141        mut self,
142        index_value: u64,
143        node: Word,
144        path: MerklePath,
145    ) -> Result<Self, MerkleError> {
146        self.add_merkle_path(index_value, node, path)?;
147        Ok(self)
148    }
149
150    /// Appends the provided merkle path set.
151    pub fn with_merkle_paths<I>(mut self, paths: I) -> Result<Self, MerkleError>
152    where
153        I: IntoIterator<Item = (u64, Word, MerklePath)>,
154    {
155        self.add_merkle_paths(paths)?;
156        Ok(self)
157    }
158
159    /// Appends the provided [Mmr] represented by its `leaves` to the set.
160    pub fn with_mmr<I>(mut self, leaves: I) -> Result<Self, MerkleError>
161    where
162        I: IntoIterator<Item = Word>,
163    {
164        self.add_mmr(leaves)?;
165        Ok(self)
166    }
167
168    // PUBLIC ACCESSORS
169    // --------------------------------------------------------------------------------------------
170
171    /// Return a count of the non-leaf nodes in the store.
172    pub fn num_internal_nodes(&self) -> usize {
173        self.nodes.len()
174    }
175
176    /// Returns the node at `index` rooted on the tree `root`.
177    ///
178    /// # Errors
179    ///
180    /// This method can return the following errors:
181    /// - `RootNotInStore` if the `root` is not present in the store.
182    /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in the store.
183    pub fn get_node(&self, root: Word, index: NodeIndex) -> Result<Word, MerkleError> {
184        let mut hash: RpoDigest = root.into();
185
186        // corner case: check the root is in the store when called with index `NodeIndex::root()`
187        self.nodes.get(&hash).ok_or(MerkleError::RootNotInStore(hash.into()))?;
188
189        for i in (0..index.depth()).rev() {
190            let node =
191                self.nodes.get(&hash).ok_or(MerkleError::NodeNotInStore(hash.into(), index))?;
192
193            let bit = (index.value() >> i) & 1;
194            hash = if bit == 0 { node.left } else { node.right }
195        }
196
197        Ok(hash.into())
198    }
199
200    /// Returns the node at the specified `index` and its opening to the `root`.
201    ///
202    /// The path starts at the sibling of the target leaf.
203    ///
204    /// # Errors
205    ///
206    /// This method can return the following errors:
207    /// - `RootNotInStore` if the `root` is not present in the store.
208    /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in the store.
209    pub fn get_path(&self, root: Word, index: NodeIndex) -> Result<ValuePath, MerkleError> {
210        let mut hash: RpoDigest = root.into();
211        let mut path = Vec::with_capacity(index.depth().into());
212
213        // corner case: check the root is in the store when called with index `NodeIndex::root()`
214        self.nodes.get(&hash).ok_or(MerkleError::RootNotInStore(hash.into()))?;
215
216        for i in (0..index.depth()).rev() {
217            let node =
218                self.nodes.get(&hash).ok_or(MerkleError::NodeNotInStore(hash.into(), index))?;
219
220            let bit = (index.value() >> i) & 1;
221            hash = if bit == 0 {
222                path.push(node.right.into());
223                node.left
224            } else {
225                path.push(node.left.into());
226                node.right
227            }
228        }
229
230        // the path is computed from root to leaf, so it must be reversed
231        path.reverse();
232
233        Ok(ValuePath {
234            value: hash.into(),
235            path: MerklePath::new(path),
236        })
237    }
238
239    /// Reconstructs a path from the root until a leaf or empty node and returns its depth.
240    ///
241    /// The `tree_depth` parameter defines up to which depth the tree will be traversed, starting
242    /// from `root`. The maximum value the argument accepts is [u64::BITS].
243    ///
244    /// The traversed path from leaf to root will start at the least significant bit of `index`,
245    /// and will be executed for `tree_depth` bits.
246    ///
247    /// # Errors
248    /// Will return an error if:
249    /// - The provided root is not found.
250    /// - The path from the root continues to a depth greater than `tree_depth`.
251    /// - The provided `tree_depth` is greater than `64.
252    /// - The provided `index` is not valid for a depth equivalent to `tree_depth`. For more
253    /// information, check [NodeIndex::new].
254    pub fn get_leaf_depth(
255        &self,
256        root: Word,
257        tree_depth: u8,
258        index: u64,
259    ) -> Result<u8, MerkleError> {
260        // validate depth and index
261        if tree_depth > 64 {
262            return Err(MerkleError::DepthTooBig(tree_depth as u64));
263        }
264        NodeIndex::new(tree_depth, index)?;
265
266        // it's not illegal to have a maximum depth of `0`; we should just return the root in that
267        // case. this check will simplify the implementation as we could overflow bits for depth
268        // `0`.
269        if tree_depth == 0 {
270            return Ok(0);
271        }
272
273        // check if the root exists, providing the proper error report if it doesn't
274        let empty = EmptySubtreeRoots::empty_hashes(tree_depth);
275        let mut hash: RpoDigest = root.into();
276        if !self.nodes.contains_key(&hash) {
277            return Err(MerkleError::RootNotInStore(hash.into()));
278        }
279
280        // we traverse from root to leaf, so the path is reversed
281        let mut path = (index << (64 - tree_depth)).reverse_bits();
282
283        // iterate every depth and reconstruct the path from root to leaf
284        for depth in 0..tree_depth {
285            // we short-circuit if an empty node has been found
286            if hash == empty[depth as usize] {
287                return Ok(depth);
288            }
289
290            // fetch the children pair, mapped by its parent hash
291            let children = match self.nodes.get(&hash) {
292                Some(node) => node,
293                None => return Ok(depth),
294            };
295
296            // traverse down
297            hash = if path & 1 == 0 { children.left } else { children.right };
298            path >>= 1;
299        }
300
301        // at max depth assert it doesn't have sub-trees
302        if self.nodes.contains_key(&hash) {
303            return Err(MerkleError::DepthTooBig(tree_depth as u64 + 1));
304        }
305
306        // depleted bits; return max depth
307        Ok(tree_depth)
308    }
309
310    // STATE MUTATORS
311    // --------------------------------------------------------------------------------------------
312
313    /// Adds all the nodes of a Merkle tree represented by `leaves`.
314    ///
315    /// This will instantiate a Merkle tree using `leaves` and include all the nodes into the
316    /// store.
317    ///
318    /// # Errors
319    ///
320    /// This method may return the following errors:
321    /// - `DepthTooSmall` if leaves is empty or contains only 1 element
322    /// - `NumLeavesNotPowerOfTwo` if the number of leaves is not a power-of-two
323    pub fn add_merkle_tree<I>(&mut self, leaves: I) -> Result<Word, MerkleError>
324    where
325        I: IntoIterator<Item = Word>,
326    {
327        let leaves: Vec<_> = leaves.into_iter().collect();
328        if leaves.len() < 2 {
329            return Err(MerkleError::DepthTooSmall(leaves.len() as u8));
330        }
331
332        let tree = MerkleTree::new(leaves)?;
333        for node in tree.inner_nodes() {
334            self.nodes.insert(
335                node.value.into(),
336                Node {
337                    left: node.left.into(),
338                    right: node.right.into(),
339                },
340            );
341        }
342
343        Ok(tree.root())
344    }
345
346    /// Adds a Sparse Merkle tree defined by the specified `entries` to the store, and returns the
347    /// root of the added tree.
348    ///
349    /// The entries are expected to contain tuples of `(index, node)` describing nodes in the tree
350    /// at `depth`.
351    ///
352    /// # Errors
353    /// Returns an error if the provided `depth` is greater than [SimpleSmt::MAX_DEPTH].
354    pub fn add_sparse_merkle_tree<R, I>(
355        &mut self,
356        depth: u8,
357        entries: R,
358    ) -> Result<Word, MerkleError>
359    where
360        R: IntoIterator<IntoIter = I>,
361        I: Iterator<Item = (u64, Word)> + ExactSizeIterator,
362    {
363        let smt = SimpleSmt::new(depth)?.with_leaves(entries)?;
364        for node in smt.inner_nodes() {
365            self.nodes.insert(
366                node.value.into(),
367                Node {
368                    left: node.left.into(),
369                    right: node.right.into(),
370                },
371            );
372        }
373
374        Ok(smt.root())
375    }
376
377    /// Adds all the nodes of a Merkle path represented by `path`, opening to `node`. Returns the
378    /// new root.
379    ///
380    /// This will compute the sibling elements determined by the Merkle `path` and `node`, and
381    /// include all the nodes into the store.
382    pub fn add_merkle_path(
383        &mut self,
384        index_value: u64,
385        mut node: Word,
386        path: MerklePath,
387    ) -> Result<Word, MerkleError> {
388        let mut index = NodeIndex::new(path.len() as u8, index_value)?;
389
390        for sibling in path {
391            let (left, right) = match index.is_value_odd() {
392                true => (sibling, node),
393                false => (node, sibling),
394            };
395            let parent = Rpo256::merge(&[left.into(), right.into()]);
396            self.nodes.insert(
397                parent,
398                Node {
399                    left: left.into(),
400                    right: right.into(),
401                },
402            );
403
404            index.move_up();
405            node = parent.into();
406        }
407
408        Ok(node)
409    }
410
411    /// Adds all the nodes of multiple Merkle paths into the store.
412    ///
413    /// This will compute the sibling elements for each Merkle `path` and include all the nodes
414    /// into the store.
415    ///
416    /// For further reference, check [MerkleStore::add_merkle_path].
417    pub fn add_merkle_paths<I>(&mut self, paths: I) -> Result<(), MerkleError>
418    where
419        I: IntoIterator<Item = (u64, Word, MerklePath)>,
420    {
421        for (index_value, node, path) in paths.into_iter() {
422            self.add_merkle_path(index_value, node, path)?;
423        }
424        Ok(())
425    }
426
427    /// Appends the provided [MerklePathSet] into the store.
428    ///
429    /// For further reference, check [MerkleStore::add_merkle_path].
430    pub fn add_merkle_path_set(&mut self, path_set: &MerklePathSet) -> Result<Word, MerkleError> {
431        let root = path_set.root();
432        for (index, path) in path_set.to_paths() {
433            self.add_merkle_path(index, path.value, path.path)?;
434        }
435        Ok(root)
436    }
437
438    /// Appends the provided [Mmr] into the store.
439    pub fn add_mmr<I>(&mut self, leaves: I) -> Result<MmrPeaks, MerkleError>
440    where
441        I: IntoIterator<Item = Word>,
442    {
443        let mmr = Mmr::from(leaves);
444        for node in mmr.inner_nodes() {
445            self.nodes.insert(
446                node.value.into(),
447                Node {
448                    left: node.left.into(),
449                    right: node.right.into(),
450                },
451            );
452        }
453
454        Ok(mmr.accumulator())
455    }
456
457    /// Sets a node to `value`.
458    ///
459    /// # Errors
460    ///
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 store.
464    pub fn set_node(
465        &mut self,
466        mut root: Word,
467        index: NodeIndex,
468        value: Word,
469    ) -> Result<RootPath, MerkleError> {
470        let node = value;
471        let ValuePath { value, path } = self.get_path(root, index)?;
472
473        // performs the update only if the node value differs from the opening
474        if node != value {
475            root = self.add_merkle_path(index.value(), node, path.clone())?;
476        }
477
478        Ok(RootPath { root, path })
479    }
480
481    /// Merges two elements and adds the resulting node into the store.
482    ///
483    /// Merges arbitrary values. They may be leafs, nodes, or a mixture of both.
484    pub fn merge_roots(&mut self, root1: Word, root2: Word) -> Result<Word, MerkleError> {
485        let root1: RpoDigest = root1.into();
486        let root2: RpoDigest = root2.into();
487
488        let parent: Word = Rpo256::merge(&[root1, root2]).into();
489        self.nodes.insert(
490            parent.into(),
491            Node {
492                left: root1,
493                right: root2,
494            },
495        );
496
497        Ok(parent)
498    }
499}
500
501// SERIALIZATION
502// ================================================================================================
503
504impl Serializable for Node {
505    fn write_into<W: ByteWriter>(&self, target: &mut W) {
506        self.left.write_into(target);
507        self.right.write_into(target);
508    }
509}
510
511impl Deserializable for Node {
512    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
513        let left = RpoDigest::read_from(source)?;
514        let right = RpoDigest::read_from(source)?;
515        Ok(Node { left, right })
516    }
517}
518
519impl Serializable for MerkleStore {
520    fn write_into<W: ByteWriter>(&self, target: &mut W) {
521        target.write_u64(self.nodes.len() as u64);
522
523        for (k, v) in self.nodes.iter() {
524            k.write_into(target);
525            v.write_into(target);
526        }
527    }
528}
529
530impl Deserializable for MerkleStore {
531    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
532        let len = source.read_u64()?;
533        let mut nodes: BTreeMap<RpoDigest, Node> = BTreeMap::new();
534
535        for _ in 0..len {
536            let key = RpoDigest::read_from(source)?;
537            let value = Node::read_from(source)?;
538            nodes.insert(key, value);
539        }
540
541        Ok(MerkleStore { nodes })
542    }
543}