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