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, MerkleError, MerklePath, MerklePathSet,
  3    MerkleTree, NodeIndex, RootPath, Rpo256, RpoDigest, SimpleSmt, TieredSmt, ValuePath, Vec, Word,
  4};
  5use crate::utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable};
  6use core::borrow::Borrow;
  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    /// This method can return the following errors:
156    /// - `RootNotInStore` if the `root` is not present in the store.
157    /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in the store.
158    pub fn get_path(&self, root: Word, index: NodeIndex) -> Result<ValuePath, MerkleError> {
159        let mut hash: RpoDigest = root.into();
160        let mut path = Vec::with_capacity(index.depth().into());
161
162        // corner case: check the root is in the store when called with index `NodeIndex::root()`
163        self.nodes.get(&hash).ok_or(MerkleError::RootNotInStore(hash.into()))?;
164
165        for i in (0..index.depth()).rev() {
166            let node =
167                self.nodes.get(&hash).ok_or(MerkleError::NodeNotInStore(hash.into(), index))?;
168
169            let bit = (index.value() >> i) & 1;
170            hash = if bit == 0 {
171                path.push(node.right.into());
172                node.left
173            } else {
174                path.push(node.left.into());
175                node.right
176            }
177        }
178
179        // the path is computed from root to leaf, so it must be reversed
180        path.reverse();
181
182        Ok(ValuePath {
183            value: hash.into(),
184            path: MerklePath::new(path),
185        })
186    }
187
188    /// Reconstructs a path from the root until a leaf or empty node and returns its depth.
189    ///
190    /// The `tree_depth` parameter defines up to which depth the tree will be traversed, starting
191    /// from `root`. The maximum value the argument accepts is [u64::BITS].
192    ///
193    /// The traversed path from leaf to root will start at the least significant bit of `index`,
194    /// and will be executed for `tree_depth` bits.
195    ///
196    /// # Errors
197    /// Will return an error if:
198    /// - The provided root is not found.
199    /// - The path from the root continues to a depth greater than `tree_depth`.
200    /// - The provided `tree_depth` is greater than `64.
201    /// - The provided `index` is not valid for a depth equivalent to `tree_depth`. For more
202    /// information, check [NodeIndex::new].
203    pub fn get_leaf_depth(
204        &self,
205        root: Word,
206        tree_depth: u8,
207        index: u64,
208    ) -> Result<u8, MerkleError> {
209        // validate depth and index
210        if tree_depth > 64 {
211            return Err(MerkleError::DepthTooBig(tree_depth as u64));
212        }
213        NodeIndex::new(tree_depth, index)?;
214
215        // it's not illegal to have a maximum depth of `0`; we should just return the root in that
216        // case. this check will simplify the implementation as we could overflow bits for depth
217        // `0`.
218        if tree_depth == 0 {
219            return Ok(0);
220        }
221
222        // check if the root exists, providing the proper error report if it doesn't
223        let empty = EmptySubtreeRoots::empty_hashes(tree_depth);
224        let mut hash: RpoDigest = root.into();
225        if !self.nodes.contains_key(&hash) {
226            return Err(MerkleError::RootNotInStore(hash.into()));
227        }
228
229        // we traverse from root to leaf, so the path is reversed
230        let mut path = (index << (64 - tree_depth)).reverse_bits();
231
232        // iterate every depth and reconstruct the path from root to leaf
233        for depth in 0..tree_depth {
234            // we short-circuit if an empty node has been found
235            if hash == empty[depth as usize] {
236                return Ok(depth);
237            }
238
239            // fetch the children pair, mapped by its parent hash
240            let children = match self.nodes.get(&hash) {
241                Some(node) => node,
242                None => return Ok(depth),
243            };
244
245            // traverse down
246            hash = if path & 1 == 0 { children.left } else { children.right };
247            path >>= 1;
248        }
249
250        // at max depth assert it doesn't have sub-trees
251        if self.nodes.contains_key(&hash) {
252            return Err(MerkleError::DepthTooBig(tree_depth as u64 + 1));
253        }
254
255        // depleted bits; return max depth
256        Ok(tree_depth)
257    }
258
259    // DATA EXTRACTORS
260    // --------------------------------------------------------------------------------------------
261
262    /// Returns a subset of this Merkle store such that the returned Merkle store contains all
263    /// nodes which are descendants of the specified roots.
264    ///
265    /// The roots for which no descendants exist in this Merkle store are ignored.
266    pub fn subset<I, R>(&self, roots: I) -> MerkleStore
267    where
268        I: Iterator<Item = R>,
269        R: Borrow<Word>,
270    {
271        let mut store = MerkleStore::new();
272        for root in roots {
273            let root = RpoDigest::from(*root.borrow());
274            store.clone_tree_from(root, self);
275        }
276        store
277    }
278
279    /// Iterator over the inner nodes of the [MerkleStore].
280    pub fn inner_nodes(&self) -> impl Iterator<Item = InnerNodeInfo> + '_ {
281        self.nodes.iter().map(|(r, n)| InnerNodeInfo {
282            value: r.into(),
283            left: n.left.into(),
284            right: n.right.into(),
285        })
286    }
287
288    // STATE MUTATORS
289    // --------------------------------------------------------------------------------------------
290
291    /// Adds a sequence of nodes yielded by the provided iterator into the store.
292    pub fn extend<I>(&mut self, iter: I) -> &mut MerkleStore
293    where
294        I: Iterator<Item = InnerNodeInfo>,
295    {
296        for node in iter {
297            let value: RpoDigest = node.value.into();
298            let left: RpoDigest = node.left.into();
299            let right: RpoDigest = node.right.into();
300
301            debug_assert_eq!(Rpo256::merge(&[left, right]), value);
302            self.nodes.insert(value, Node { left, right });
303        }
304
305        self
306    }
307
308    /// Adds all the nodes of a Merkle path represented by `path`, opening to `node`. Returns the
309    /// new root.
310    ///
311    /// This will compute the sibling elements determined by the Merkle `path` and `node`, and
312    /// include all the nodes into the store.
313    pub fn add_merkle_path(
314        &mut self,
315        index: u64,
316        node: Word,
317        path: MerklePath,
318    ) -> Result<Word, MerkleError> {
319        let root = path.inner_nodes(index, node)?.fold(Word::default(), |_, node| {
320            let value: RpoDigest = node.value.into();
321            let left: RpoDigest = node.left.into();
322            let right: RpoDigest = node.right.into();
323
324            debug_assert_eq!(Rpo256::merge(&[left, right]), value);
325            self.nodes.insert(value, Node { left, right });
326
327            node.value
328        });
329        Ok(root)
330    }
331
332    /// Adds all the nodes of multiple Merkle paths into the store.
333    ///
334    /// This will compute the sibling elements for each Merkle `path` and include all the nodes
335    /// into the store.
336    ///
337    /// For further reference, check [MerkleStore::add_merkle_path].
338    pub fn add_merkle_paths<I>(&mut self, paths: I) -> Result<(), MerkleError>
339    where
340        I: IntoIterator<Item = (u64, Word, MerklePath)>,
341    {
342        for (index_value, node, path) in paths.into_iter() {
343            self.add_merkle_path(index_value, node, path)?;
344        }
345        Ok(())
346    }
347
348    /// Appends the provided [MerklePathSet] into the store.
349    ///
350    /// For further reference, check [MerkleStore::add_merkle_path].
351    pub fn add_merkle_path_set(&mut self, path_set: &MerklePathSet) -> Result<Word, MerkleError> {
352        let root = path_set.root();
353        for (index, path) in path_set.to_paths() {
354            self.add_merkle_path(index, path.value, path.path)?;
355        }
356        Ok(root)
357    }
358
359    /// Sets a node to `value`.
360    ///
361    /// # Errors
362    ///
363    /// This method can return the following errors:
364    /// - `RootNotInStore` if the `root` is not present in the store.
365    /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in the store.
366    pub fn set_node(
367        &mut self,
368        mut root: Word,
369        index: NodeIndex,
370        value: Word,
371    ) -> Result<RootPath, MerkleError> {
372        let node = value;
373        let ValuePath { value, path } = self.get_path(root, index)?;
374
375        // performs the update only if the node value differs from the opening
376        if node != value {
377            root = self.add_merkle_path(index.value(), node, path.clone())?;
378        }
379
380        Ok(RootPath { root, path })
381    }
382
383    /// Merges two elements and adds the resulting node into the store.
384    ///
385    /// Merges arbitrary values. They may be leafs, nodes, or a mixture of both.
386    pub fn merge_roots(&mut self, root1: Word, root2: Word) -> Result<Word, MerkleError> {
387        let left: RpoDigest = root1.into();
388        let right: RpoDigest = root2.into();
389
390        let parent = Rpo256::merge(&[left, right]);
391        self.nodes.insert(parent, Node { left, right });
392
393        Ok(parent.into())
394    }
395
396    // HELPER METHODS
397    // --------------------------------------------------------------------------------------------
398
399    /// Recursively clones a tree with the specified root from the specified source into self.
400    ///
401    /// If the source store does not contain a tree with the specified root, this is a noop.
402    fn clone_tree_from(&mut self, root: RpoDigest, source: &Self) {
403        // process the node only if it is in the source
404        if let Some(node) = source.nodes.get(&root) {
405            // if the node has already been inserted, no need to process it further as all of its
406            // descendants should be already cloned from the source store
407            if matches!(self.nodes.insert(root, *node), None) {
408                self.clone_tree_from(node.left, source);
409                self.clone_tree_from(node.right, source);
410            }
411        }
412    }
413}
414
415// CONVERSIONS
416// ================================================================================================
417
418impl From<&MerkleTree> for MerkleStore {
419    fn from(value: &MerkleTree) -> Self {
420        let mut store = MerkleStore::new();
421        store.extend(value.inner_nodes());
422        store
423    }
424}
425
426impl From<&SimpleSmt> for MerkleStore {
427    fn from(value: &SimpleSmt) -> Self {
428        let mut store = MerkleStore::new();
429        store.extend(value.inner_nodes());
430        store
431    }
432}
433
434impl From<&Mmr> for MerkleStore {
435    fn from(value: &Mmr) -> Self {
436        let mut store = MerkleStore::new();
437        store.extend(value.inner_nodes());
438        store
439    }
440}
441
442impl From<&TieredSmt> for MerkleStore {
443    fn from(value: &TieredSmt) -> Self {
444        let mut store = MerkleStore::new();
445        store.extend(value.inner_nodes());
446        store
447    }
448}
449
450impl FromIterator<InnerNodeInfo> for MerkleStore {
451    fn from_iter<T: IntoIterator<Item = InnerNodeInfo>>(iter: T) -> Self {
452        let mut store = MerkleStore::new();
453        store.extend(iter.into_iter());
454        store
455    }
456}
457
458// ITERATORS
459// ================================================================================================
460
461impl Extend<InnerNodeInfo> for MerkleStore {
462    fn extend<T: IntoIterator<Item = InnerNodeInfo>>(&mut self, iter: T) {
463        self.extend(iter.into_iter());
464    }
465}
466
467// SERIALIZATION
468// ================================================================================================
469
470impl Serializable for Node {
471    fn write_into<W: ByteWriter>(&self, target: &mut W) {
472        self.left.write_into(target);
473        self.right.write_into(target);
474    }
475}
476
477impl Deserializable for Node {
478    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
479        let left = RpoDigest::read_from(source)?;
480        let right = RpoDigest::read_from(source)?;
481        Ok(Node { left, right })
482    }
483}
484
485impl Serializable for MerkleStore {
486    fn write_into<W: ByteWriter>(&self, target: &mut W) {
487        target.write_u64(self.nodes.len() as u64);
488
489        for (k, v) in self.nodes.iter() {
490            k.write_into(target);
491            v.write_into(target);
492        }
493    }
494}
495
496impl Deserializable for MerkleStore {
497    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
498        let len = source.read_u64()?;
499        let mut nodes: BTreeMap<RpoDigest, Node> = BTreeMap::new();
500
501        for _ in 0..len {
502            let key = RpoDigest::read_from(source)?;
503            let value = Node::read_from(source)?;
504            nodes.insert(key, value);
505        }
506
507        Ok(MerkleStore { nodes })
508    }
509}