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
188            .get(&hash)
189            .ok_or(MerkleError::RootNotInStore(hash.into()))?;
190
191        for i in (0..index.depth()).rev() {
192            let node = self
193                .nodes
194                .get(&hash)
195                .ok_or(MerkleError::NodeNotInStore(hash.into(), index))?;
196
197            let bit = (index.value() >> i) & 1;
198            hash = if bit == 0 { node.left } else { node.right }
199        }
200
201        Ok(hash.into())
202    }
203
204    /// Returns the node at the specified `index` and its opening to the `root`.
205    ///
206    /// The path starts at the sibling of the target leaf.
207    ///
208    /// # Errors
209    ///
210    /// This method can return the following errors:
211    /// - `RootNotInStore` if the `root` is not present in the store.
212    /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in the store.
213    pub fn get_path(&self, root: Word, index: NodeIndex) -> Result<ValuePath, MerkleError> {
214        let mut hash: RpoDigest = root.into();
215        let mut path = Vec::with_capacity(index.depth().into());
216
217        // corner case: check the root is in the store when called with index `NodeIndex::root()`
218        self.nodes
219            .get(&hash)
220            .ok_or(MerkleError::RootNotInStore(hash.into()))?;
221
222        for i in (0..index.depth()).rev() {
223            let node = self
224                .nodes
225                .get(&hash)
226                .ok_or(MerkleError::NodeNotInStore(hash.into(), index))?;
227
228            let bit = (index.value() >> i) & 1;
229            hash = if bit == 0 {
230                path.push(node.right.into());
231                node.left
232            } else {
233                path.push(node.left.into());
234                node.right
235            }
236        }
237
238        // the path is computed from root to leaf, so it must be reversed
239        path.reverse();
240
241        Ok(ValuePath {
242            value: hash.into(),
243            path: MerklePath::new(path),
244        })
245    }
246
247    // STATE MUTATORS
248    // --------------------------------------------------------------------------------------------
249
250    /// Adds all the nodes of a Merkle tree represented by `leaves`.
251    ///
252    /// This will instantiate a Merkle tree using `leaves` and include all the nodes into the
253    /// store.
254    ///
255    /// # Errors
256    ///
257    /// This method may return the following errors:
258    /// - `DepthTooSmall` if leaves is empty or contains only 1 element
259    /// - `NumLeavesNotPowerOfTwo` if the number of leaves is not a power-of-two
260    pub fn add_merkle_tree<I>(&mut self, leaves: I) -> Result<Word, MerkleError>
261    where
262        I: IntoIterator<Item = Word>,
263    {
264        let leaves: Vec<_> = leaves.into_iter().collect();
265        if leaves.len() < 2 {
266            return Err(MerkleError::DepthTooSmall(leaves.len() as u8));
267        }
268
269        let tree = MerkleTree::new(leaves)?;
270        for node in tree.inner_nodes() {
271            self.nodes.insert(
272                node.value.into(),
273                Node {
274                    left: node.left.into(),
275                    right: node.right.into(),
276                },
277            );
278        }
279
280        Ok(tree.root())
281    }
282
283    /// Adds a Sparse Merkle tree defined by the specified `entries` to the store, and returns the
284    /// root of the added tree.
285    ///
286    /// The entries are expected to contain tuples of `(index, node)` describing nodes in the tree
287    /// at `depth`.
288    ///
289    /// # Errors
290    /// Returns an error if the provided `depth` is greater than [SimpleSmt::MAX_DEPTH].
291    pub fn add_sparse_merkle_tree<R, I>(
292        &mut self,
293        depth: u8,
294        entries: R,
295    ) -> Result<Word, MerkleError>
296    where
297        R: IntoIterator<IntoIter = I>,
298        I: Iterator<Item = (u64, Word)> + ExactSizeIterator,
299    {
300        let smt = SimpleSmt::new(depth)?.with_leaves(entries)?;
301        for node in smt.inner_nodes() {
302            self.nodes.insert(
303                node.value.into(),
304                Node {
305                    left: node.left.into(),
306                    right: node.right.into(),
307                },
308            );
309        }
310
311        Ok(smt.root())
312    }
313
314    /// Adds all the nodes of a Merkle path represented by `path`, opening to `node`. Returns the
315    /// new root.
316    ///
317    /// This will compute the sibling elements determined by the Merkle `path` and `node`, and
318    /// include all the nodes into the store.
319    pub fn add_merkle_path(
320        &mut self,
321        index_value: u64,
322        mut node: Word,
323        path: MerklePath,
324    ) -> Result<Word, MerkleError> {
325        let mut index = NodeIndex::new(path.len() as u8, index_value)?;
326
327        for sibling in path {
328            let (left, right) = match index.is_value_odd() {
329                true => (sibling, node),
330                false => (node, sibling),
331            };
332            let parent = Rpo256::merge(&[left.into(), right.into()]);
333            self.nodes.insert(
334                parent,
335                Node {
336                    left: left.into(),
337                    right: right.into(),
338                },
339            );
340
341            index.move_up();
342            node = parent.into();
343        }
344
345        Ok(node)
346    }
347
348    /// Adds all the nodes of multiple Merkle paths into the store.
349    ///
350    /// This will compute the sibling elements for each Merkle `path` and include all the nodes
351    /// into the store.
352    ///
353    /// For further reference, check [MerkleStore::add_merkle_path].
354    pub fn add_merkle_paths<I>(&mut self, paths: I) -> Result<(), MerkleError>
355    where
356        I: IntoIterator<Item = (u64, Word, MerklePath)>,
357    {
358        for (index_value, node, path) in paths.into_iter() {
359            self.add_merkle_path(index_value, node, path)?;
360        }
361        Ok(())
362    }
363
364    /// Appends the provided [MerklePathSet] into the store.
365    ///
366    /// For further reference, check [MerkleStore::add_merkle_path].
367    pub fn add_merkle_path_set(&mut self, path_set: &MerklePathSet) -> Result<Word, MerkleError> {
368        let root = path_set.root();
369        for (index, path) in path_set.to_paths() {
370            self.add_merkle_path(index, path.value, path.path)?;
371        }
372        Ok(root)
373    }
374
375    /// Appends the provided [Mmr] into the store.
376    pub fn add_mmr<I>(&mut self, leaves: I) -> Result<MmrPeaks, MerkleError>
377    where
378        I: IntoIterator<Item = Word>,
379    {
380        let mmr = Mmr::from(leaves);
381        for node in mmr.inner_nodes() {
382            self.nodes.insert(
383                node.value.into(),
384                Node {
385                    left: node.left.into(),
386                    right: node.right.into(),
387                },
388            );
389        }
390
391        Ok(mmr.accumulator())
392    }
393
394    /// Sets a node to `value`.
395    ///
396    /// # Errors
397    ///
398    /// This method can return the following errors:
399    /// - `RootNotInStore` if the `root` is not present in the store.
400    /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in the store.
401    pub fn set_node(
402        &mut self,
403        mut root: Word,
404        index: NodeIndex,
405        value: Word,
406    ) -> Result<RootPath, MerkleError> {
407        let node = value;
408        let ValuePath { value, path } = self.get_path(root, index)?;
409
410        // performs the update only if the node value differs from the opening
411        if node != value {
412            root = self.add_merkle_path(index.value(), node, path.clone())?;
413        }
414
415        Ok(RootPath { root, path })
416    }
417
418    pub fn merge_roots(&mut self, root1: Word, root2: Word) -> Result<Word, MerkleError> {
419        let root1: RpoDigest = root1.into();
420        let root2: RpoDigest = root2.into();
421
422        if !self.nodes.contains_key(&root1) {
423            Err(MerkleError::NodeNotInStore(root1.into(), NodeIndex::root()))
424        } else if !self.nodes.contains_key(&root1) {
425            Err(MerkleError::NodeNotInStore(root2.into(), NodeIndex::root()))
426        } else {
427            let parent: Word = Rpo256::merge(&[root1, root2]).into();
428            self.nodes.insert(
429                parent.into(),
430                Node {
431                    left: root1,
432                    right: root2,
433                },
434            );
435
436            Ok(parent)
437        }
438    }
439}
440
441// SERIALIZATION
442// ================================================================================================
443
444impl Serializable for Node {
445    fn write_into<W: ByteWriter>(&self, target: &mut W) {
446        self.left.write_into(target);
447        self.right.write_into(target);
448    }
449}
450
451impl Deserializable for Node {
452    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
453        let left = RpoDigest::read_from(source)?;
454        let right = RpoDigest::read_from(source)?;
455        Ok(Node { left, right })
456    }
457}
458
459impl Serializable for MerkleStore {
460    fn write_into<W: ByteWriter>(&self, target: &mut W) {
461        target.write_u64(self.nodes.len() as u64);
462
463        for (k, v) in self.nodes.iter() {
464            k.write_into(target);
465            v.write_into(target);
466        }
467    }
468}
469
470impl Deserializable for MerkleStore {
471    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
472        let len = source.read_u64()?;
473        let mut nodes: BTreeMap<RpoDigest, Node> = BTreeMap::new();
474
475        for _ in 0..len {
476            let key = RpoDigest::read_from(source)?;
477            let value = Node::read_from(source)?;
478            nodes.insert(key, value);
479        }
480
481        Ok(MerkleStore { nodes })
482    }
483}