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, 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    ///
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<I, R>(&self, roots: I) -> MerkleStore
268    where
269        I: Iterator<Item = R>,
270        R: Borrow<Word>,
271    {
272        let mut store = MerkleStore::new();
273        for root in roots {
274            let root = RpoDigest::from(*root.borrow());
275            store.clone_tree_from(root, self);
276        }
277        store
278    }
279
280    /// Iterator over the inner nodes of the [MerkleStore].
281    pub fn inner_nodes(&self) -> impl Iterator<Item = InnerNodeInfo> + '_ {
282        self.nodes.iter().map(|(r, n)| InnerNodeInfo {
283            value: r.into(),
284            left: n.left.into(),
285            right: n.right.into(),
286        })
287    }
288
289    // STATE MUTATORS
290    // --------------------------------------------------------------------------------------------
291
292    /// Adds a sequence of nodes yielded by the provided iterator into the store.
293    pub fn extend<I>(&mut self, iter: I) -> &mut MerkleStore
294    where
295        I: Iterator<Item = InnerNodeInfo>,
296    {
297        for node in iter {
298            let value: RpoDigest = node.value.into();
299            let left: RpoDigest = node.left.into();
300            let right: RpoDigest = node.right.into();
301
302            debug_assert_eq!(Rpo256::merge(&[left, right]), value);
303            self.nodes.insert(value, Node { left, right });
304        }
305
306        self
307    }
308
309    /// Adds all the nodes of a Merkle path represented by `path`, opening to `node`. Returns the
310    /// new root.
311    ///
312    /// This will compute the sibling elements determined by the Merkle `path` and `node`, and
313    /// include all the nodes into the store.
314    pub fn add_merkle_path(
315        &mut self,
316        index: u64,
317        node: Word,
318        path: MerklePath,
319    ) -> Result<Word, MerkleError> {
320        let root = path.inner_nodes(index, node)?.fold(Word::default(), |_, node| {
321            let value: RpoDigest = node.value.into();
322            let left: RpoDigest = node.left.into();
323            let right: RpoDigest = node.right.into();
324
325            debug_assert_eq!(Rpo256::merge(&[left, right]), value);
326            self.nodes.insert(value, Node { left, right });
327
328            node.value
329        });
330        Ok(root)
331    }
332
333    /// Adds all the nodes of multiple Merkle paths into the store.
334    ///
335    /// This will compute the sibling elements for each Merkle `path` and include all the nodes
336    /// into the store.
337    ///
338    /// For further reference, check [MerkleStore::add_merkle_path].
339    pub fn add_merkle_paths<I>(&mut self, paths: I) -> Result<(), MerkleError>
340    where
341        I: IntoIterator<Item = (u64, Word, MerklePath)>,
342    {
343        for (index_value, node, path) in paths.into_iter() {
344            self.add_merkle_path(index_value, node, path)?;
345        }
346        Ok(())
347    }
348
349    /// Appends the provided [MerklePathSet] into the store.
350    ///
351    /// For further reference, check [MerkleStore::add_merkle_path].
352    pub fn add_merkle_path_set(&mut self, path_set: &MerklePathSet) -> Result<Word, MerkleError> {
353        let root = path_set.root();
354        for (index, path) in path_set.to_paths() {
355            self.add_merkle_path(index, path.value, path.path)?;
356        }
357        Ok(root)
358    }
359
360    /// Sets a node to `value`.
361    ///
362    /// # Errors
363    ///
364    /// This method can return the following errors:
365    /// - `RootNotInStore` if the `root` is not present in the store.
366    /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in the store.
367    pub fn set_node(
368        &mut self,
369        mut root: Word,
370        index: NodeIndex,
371        value: Word,
372    ) -> Result<RootPath, MerkleError> {
373        let node = value;
374        let ValuePath { value, path } = self.get_path(root, index)?;
375
376        // performs the update only if the node value differs from the opening
377        if node != value {
378            root = self.add_merkle_path(index.value(), node, path.clone())?;
379        }
380
381        Ok(RootPath { root, path })
382    }
383
384    /// Merges two elements and adds the resulting node into the store.
385    ///
386    /// Merges arbitrary values. They may be leafs, nodes, or a mixture of both.
387    pub fn merge_roots(&mut self, root1: Word, root2: Word) -> Result<Word, MerkleError> {
388        let left: RpoDigest = root1.into();
389        let right: RpoDigest = root2.into();
390
391        let parent = Rpo256::merge(&[left, right]);
392        self.nodes.insert(parent, Node { left, right });
393
394        Ok(parent.into())
395    }
396
397    // HELPER METHODS
398    // --------------------------------------------------------------------------------------------
399
400    /// Recursively clones a tree with the specified root from the specified source into self.
401    ///
402    /// If the source store does not contain a tree with the specified root, this is a noop.
403    fn clone_tree_from(&mut self, root: RpoDigest, source: &Self) {
404        // process the node only if it is in the source
405        if let Some(node) = source.nodes.get(&root) {
406            // if the node has already been inserted, no need to process it further as all of its
407            // descendants should be already cloned from the source store
408            if matches!(self.nodes.insert(root, *node), None) {
409                self.clone_tree_from(node.left, source);
410                self.clone_tree_from(node.right, source);
411            }
412        }
413    }
414}
415
416// CONVERSIONS
417// ================================================================================================
418
419impl From<&MerkleTree> for MerkleStore {
420    fn from(value: &MerkleTree) -> Self {
421        let mut store = MerkleStore::new();
422        store.extend(value.inner_nodes());
423        store
424    }
425}
426
427impl From<&SimpleSmt> for MerkleStore {
428    fn from(value: &SimpleSmt) -> Self {
429        let mut store = MerkleStore::new();
430        store.extend(value.inner_nodes());
431        store
432    }
433}
434
435impl From<&Mmr> for MerkleStore {
436    fn from(value: &Mmr) -> Self {
437        let mut store = MerkleStore::new();
438        store.extend(value.inner_nodes());
439        store
440    }
441}
442
443impl FromIterator<InnerNodeInfo> for MerkleStore {
444    fn from_iter<T: IntoIterator<Item = InnerNodeInfo>>(iter: T) -> Self {
445        let mut store = MerkleStore::new();
446        store.extend(iter.into_iter());
447        store
448    }
449}
450
451// ITERATORS
452// ================================================================================================
453
454impl Extend<InnerNodeInfo> for MerkleStore {
455    fn extend<T: IntoIterator<Item = InnerNodeInfo>>(&mut self, iter: T) {
456        self.extend(iter.into_iter());
457    }
458}
459
460// SERIALIZATION
461// ================================================================================================
462
463impl Serializable for Node {
464    fn write_into<W: ByteWriter>(&self, target: &mut W) {
465        self.left.write_into(target);
466        self.right.write_into(target);
467    }
468}
469
470impl Deserializable for Node {
471    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
472        let left = RpoDigest::read_from(source)?;
473        let right = RpoDigest::read_from(source)?;
474        Ok(Node { left, right })
475    }
476}
477
478impl Serializable for MerkleStore {
479    fn write_into<W: ByteWriter>(&self, target: &mut W) {
480        target.write_u64(self.nodes.len() as u64);
481
482        for (k, v) in self.nodes.iter() {
483            k.write_into(target);
484            v.write_into(target);
485        }
486    }
487}
488
489impl Deserializable for MerkleStore {
490    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
491        let len = source.read_u64()?;
492        let mut nodes: BTreeMap<RpoDigest, Node> = BTreeMap::new();
493
494        for _ in 0..len {
495            let key = RpoDigest::read_from(source)?;
496            let value = Node::read_from(source)?;
497            nodes.insert(key, value);
498        }
499
500        Ok(MerkleStore { nodes })
501    }
502}