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