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