arnaucube
arnaucube/miden-cryptoPublic Self-hosted repository
miden-crypto/src/merkle/smt/mod.rs
src/merkle/smt/mod.rsRaw
  1use alloc::{collections::BTreeMap, vec::Vec};
  2
  3use super::{EmptySubtreeRoots, InnerNodeInfo, MerkleError, MerklePath, NodeIndex};
  4use crate::{
  5    hash::rpo::{Rpo256, RpoDigest},
  6    Felt, Word, EMPTY_WORD,
  7};
  8
  9mod full;
 10pub use full::{Smt, SmtLeaf, SmtLeafError, SmtProof, SmtProofError, SMT_DEPTH};
 11
 12mod simple;
 13pub use simple::SimpleSmt;
 14
 15// CONSTANTS
 16// ================================================================================================
 17
 18/// Minimum supported depth.
 19pub const SMT_MIN_DEPTH: u8 = 1;
 20
 21/// Maximum supported depth.
 22pub const SMT_MAX_DEPTH: u8 = 64;
 23
 24// SPARSE MERKLE TREE
 25// ================================================================================================
 26
 27/// An abstract description of a sparse Merkle tree.
 28///
 29/// A sparse Merkle tree is a key-value map which also supports proving that a given value is indeed
 30/// stored at a given key in the tree. It is viewed as always being fully populated. If a leaf's
 31/// value was not explicitly set, then its value is the default value. Typically, the vast majority
 32/// of leaves will store the default value (hence it is "sparse"), and therefore the internal
 33/// representation of the tree will only keep track of the leaves that have a different value from
 34/// the default.
 35///
 36/// All leaves sit at the same depth. The deeper the tree, the more leaves it has; but also the
 37/// longer its proofs are - of exactly `log(depth)` size. A tree cannot have depth 0, since such a
 38/// tree is just a single value, and is probably a programming mistake.
 39///
 40/// Every key maps to one leaf. If there are as many keys as there are leaves, then
 41/// [Self::Leaf] should be the same type as [Self::Value], as is the case with
 42/// [crate::merkle::SimpleSmt]. However, if there are more keys than leaves, then [`Self::Leaf`]
 43/// must accomodate all keys that map to the same leaf.
 44///
 45/// [SparseMerkleTree] currently doesn't support optimizations that compress Merkle proofs.
 46pub(crate) trait SparseMerkleTree<const DEPTH: u8> {
 47    /// The type for a key
 48    type Key: Clone + Ord;
 49    /// The type for a value
 50    type Value: Clone + PartialEq;
 51    /// The type for a leaf
 52    type Leaf: Clone;
 53    /// The type for an opening (i.e. a "proof") of a leaf
 54    type Opening;
 55
 56    /// The default value used to compute the hash of empty leaves
 57    const EMPTY_VALUE: Self::Value;
 58
 59    // PROVIDED METHODS
 60    // ---------------------------------------------------------------------------------------------
 61
 62    /// Returns an opening of the leaf associated with `key`. Conceptually, an opening is a Merkle
 63    /// path to the leaf, as well as the leaf itself.
 64    fn open(&self, key: &Self::Key) -> Self::Opening {
 65        let leaf = self.get_leaf(key);
 66
 67        let mut index: NodeIndex = {
 68            let leaf_index: LeafIndex<DEPTH> = Self::key_to_leaf_index(key);
 69            leaf_index.into()
 70        };
 71
 72        let merkle_path = {
 73            let mut path = Vec::with_capacity(index.depth() as usize);
 74            for _ in 0..index.depth() {
 75                let is_right = index.is_value_odd();
 76                index.move_up();
 77                let InnerNode { left, right } = self.get_inner_node(index);
 78                let value = if is_right { left } else { right };
 79                path.push(value);
 80            }
 81
 82            MerklePath::new(path)
 83        };
 84
 85        Self::path_and_leaf_to_opening(merkle_path, leaf)
 86    }
 87
 88    /// Inserts a value at the specified key, returning the previous value associated with that key.
 89    /// Recall that by definition, any key that hasn't been updated is associated with
 90    /// [`Self::EMPTY_VALUE`].
 91    ///
 92    /// This also recomputes all hashes between the leaf (associated with the key) and the root,
 93    /// updating the root itself.
 94    fn insert(&mut self, key: Self::Key, value: Self::Value) -> Self::Value {
 95        let old_value = self.insert_value(key.clone(), value.clone()).unwrap_or(Self::EMPTY_VALUE);
 96
 97        // if the old value and new value are the same, there is nothing to update
 98        if value == old_value {
 99            return value;
100        }
101
102        let leaf = self.get_leaf(&key);
103        let node_index = {
104            let leaf_index: LeafIndex<DEPTH> = Self::key_to_leaf_index(&key);
105            leaf_index.into()
106        };
107
108        self.recompute_nodes_from_index_to_root(node_index, Self::hash_leaf(&leaf));
109
110        old_value
111    }
112
113    /// Recomputes the branch nodes (including the root) from `index` all the way to the root.
114    /// `node_hash_at_index` is the hash of the node stored at index.
115    fn recompute_nodes_from_index_to_root(
116        &mut self,
117        mut index: NodeIndex,
118        node_hash_at_index: RpoDigest,
119    ) {
120        let mut node_hash = node_hash_at_index;
121        for node_depth in (0..index.depth()).rev() {
122            let is_right = index.is_value_odd();
123            index.move_up();
124            let InnerNode { left, right } = self.get_inner_node(index);
125            let (left, right) = if is_right {
126                (left, node_hash)
127            } else {
128                (node_hash, right)
129            };
130            node_hash = Rpo256::merge(&[left, right]);
131
132            if node_hash == *EmptySubtreeRoots::entry(DEPTH, node_depth) {
133                // If a subtree is empty, when can remove the inner node, since it's equal to the
134                // default value
135                self.remove_inner_node(index)
136            } else {
137                self.insert_inner_node(index, InnerNode { left, right });
138            }
139        }
140        self.set_root(node_hash);
141    }
142
143    /// Computes what changes are necessary to insert the specified key-value pairs into this Merkle
144    /// tree, allowing for validation before applying those changes.
145    ///
146    /// This method returns a [`MutationSet`], which contains all the information for inserting
147    /// `kv_pairs` into this Merkle tree already calculated, including the new root hash, which can
148    /// be queried with [`MutationSet::root()`]. Once a mutation set is returned,
149    /// [`SparseMerkleTree::apply_mutations()`] can be called in order to commit these changes to
150    /// the Merkle tree, or [`drop()`] to discard them.
151    fn compute_mutations(
152        &self,
153        kv_pairs: impl IntoIterator<Item = (Self::Key, Self::Value)>,
154    ) -> MutationSet<DEPTH, Self::Key, Self::Value> {
155        use NodeMutation::*;
156
157        let mut new_root = self.root();
158        let mut new_pairs: BTreeMap<Self::Key, Self::Value> = Default::default();
159        let mut node_mutations: BTreeMap<NodeIndex, NodeMutation> = Default::default();
160
161        for (key, value) in kv_pairs {
162            // If the old value and the new value are the same, there is nothing to update.
163            // For the unusual case that kv_pairs has multiple values at the same key, we'll have
164            // to check the key-value pairs we've already seen to get the "effective" old value.
165            let old_value = new_pairs.get(&key).cloned().unwrap_or_else(|| self.get_value(&key));
166            if value == old_value {
167                continue;
168            }
169
170            let leaf_index = Self::key_to_leaf_index(&key);
171            let mut node_index = NodeIndex::from(leaf_index);
172
173            // We need the current leaf's hash to calculate the new leaf, but in the rare case that
174            // `kv_pairs` has multiple pairs that go into the same leaf, then those pairs are also
175            // part of the "current leaf".
176            let old_leaf = {
177                let pairs_at_index = new_pairs
178                    .iter()
179                    .filter(|&(new_key, _)| Self::key_to_leaf_index(new_key) == leaf_index);
180
181                pairs_at_index.fold(self.get_leaf(&key), |acc, (k, v)| {
182                    // Most of the time `pairs_at_index` should only contain a single entry (or
183                    // none at all), as multi-leaves should be really rare.
184                    let existing_leaf = acc.clone();
185                    self.construct_prospective_leaf(existing_leaf, k, v)
186                })
187            };
188
189            let new_leaf = self.construct_prospective_leaf(old_leaf, &key, &value);
190
191            let mut new_child_hash = Self::hash_leaf(&new_leaf);
192
193            for node_depth in (0..node_index.depth()).rev() {
194                // Whether the node we're replacing is the right child or the left child.
195                let is_right = node_index.is_value_odd();
196                node_index.move_up();
197
198                let old_node = node_mutations
199                    .get(&node_index)
200                    .map(|mutation| match mutation {
201                        Addition(node) => node.clone(),
202                        Removal => EmptySubtreeRoots::get_inner_node(DEPTH, node_depth),
203                    })
204                    .unwrap_or_else(|| self.get_inner_node(node_index));
205
206                let new_node = if is_right {
207                    InnerNode {
208                        left: old_node.left,
209                        right: new_child_hash,
210                    }
211                } else {
212                    InnerNode {
213                        left: new_child_hash,
214                        right: old_node.right,
215                    }
216                };
217
218                // The next iteration will operate on this new node's hash.
219                new_child_hash = new_node.hash();
220
221                let &equivalent_empty_hash = EmptySubtreeRoots::entry(DEPTH, node_depth);
222                let is_removal = new_child_hash == equivalent_empty_hash;
223                let new_entry = if is_removal { Removal } else { Addition(new_node) };
224                node_mutations.insert(node_index, new_entry);
225            }
226
227            // Once we're at depth 0, the last node we made is the new root.
228            new_root = new_child_hash;
229            // And then we're done with this pair; on to the next one.
230            new_pairs.insert(key, value);
231        }
232
233        MutationSet {
234            old_root: self.root(),
235            new_root,
236            node_mutations,
237            new_pairs,
238        }
239    }
240
241    /// Apply the prospective mutations computed with [`SparseMerkleTree::compute_mutations()`] to
242    /// this tree.
243    ///
244    /// # Errors
245    /// If `mutations` was computed on a tree with a different root than this one, returns
246    /// [`MerkleError::ConflictingRoots`] with a two-item [`Vec`]. The first item is the root hash
247    /// the `mutations` were computed against, and the second item is the actual current root of
248    /// this tree.
249    fn apply_mutations(
250        &mut self,
251        mutations: MutationSet<DEPTH, Self::Key, Self::Value>,
252    ) -> Result<(), MerkleError>
253    where
254        Self: Sized,
255    {
256        use NodeMutation::*;
257        let MutationSet {
258            old_root,
259            node_mutations,
260            new_pairs,
261            new_root,
262        } = mutations;
263
264        // Guard against accidentally trying to apply mutations that were computed against a
265        // different tree, including a stale version of this tree.
266        if old_root != self.root() {
267            return Err(MerkleError::ConflictingRoots(vec![old_root, self.root()]));
268        }
269
270        for (index, mutation) in node_mutations {
271            match mutation {
272                Removal => self.remove_inner_node(index),
273                Addition(node) => self.insert_inner_node(index, node),
274            }
275        }
276
277        for (key, value) in new_pairs {
278            self.insert_value(key, value);
279        }
280
281        self.set_root(new_root);
282
283        Ok(())
284    }
285
286    // REQUIRED METHODS
287    // ---------------------------------------------------------------------------------------------
288
289    /// The root of the tree
290    fn root(&self) -> RpoDigest;
291
292    /// Sets the root of the tree
293    fn set_root(&mut self, root: RpoDigest);
294
295    /// Retrieves an inner node at the given index
296    fn get_inner_node(&self, index: NodeIndex) -> InnerNode;
297
298    /// Inserts an inner node at the given index
299    fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode);
300
301    /// Removes an inner node at the given index
302    fn remove_inner_node(&mut self, index: NodeIndex);
303
304    /// Inserts a leaf node, and returns the value at the key if already exists
305    fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option<Self::Value>;
306
307    /// Returns the value at the specified key. Recall that by definition, any key that hasn't been
308    /// updated is associated with [`Self::EMPTY_VALUE`].
309    fn get_value(&self, key: &Self::Key) -> Self::Value;
310
311    /// Returns the leaf at the specified index.
312    fn get_leaf(&self, key: &Self::Key) -> Self::Leaf;
313
314    /// Returns the hash of a leaf
315    fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest;
316
317    /// Returns what a leaf would look like if a key-value pair were inserted into the tree, without
318    /// mutating the tree itself. The existing leaf can be empty.
319    ///
320    /// To get a prospective leaf based on the current state of the tree, use `self.get_leaf(key)`
321    /// as the argument for `existing_leaf`. The return value from this function can be chained back
322    /// into this function as the first argument to continue making prospective changes.
323    ///
324    /// # Invariants
325    /// Because this method is for a prospective key-value insertion into a specific leaf,
326    /// `existing_leaf` must have the same leaf index as `key` (as determined by
327    /// [`SparseMerkleTree::key_to_leaf_index()`]), or the result will be meaningless.
328    fn construct_prospective_leaf(
329        &self,
330        existing_leaf: Self::Leaf,
331        key: &Self::Key,
332        value: &Self::Value,
333    ) -> Self::Leaf;
334
335    /// Maps a key to a leaf index
336    fn key_to_leaf_index(key: &Self::Key) -> LeafIndex<DEPTH>;
337
338    /// Maps a (MerklePath, Self::Leaf) to an opening.
339    ///
340    /// The length `path` is guaranteed to be equal to `DEPTH`
341    fn path_and_leaf_to_opening(path: MerklePath, leaf: Self::Leaf) -> Self::Opening;
342}
343
344// INNER NODE
345// ================================================================================================
346
347#[derive(Debug, Default, Clone, PartialEq, Eq)]
348#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
349pub(crate) struct InnerNode {
350    pub left: RpoDigest,
351    pub right: RpoDigest,
352}
353
354impl InnerNode {
355    pub fn hash(&self) -> RpoDigest {
356        Rpo256::merge(&[self.left, self.right])
357    }
358}
359
360// LEAF INDEX
361// ================================================================================================
362
363/// The index of a leaf, at a depth known at compile-time.
364#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
365#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
366pub struct LeafIndex<const DEPTH: u8> {
367    index: NodeIndex,
368}
369
370impl<const DEPTH: u8> LeafIndex<DEPTH> {
371    pub fn new(value: u64) -> Result<Self, MerkleError> {
372        if DEPTH < SMT_MIN_DEPTH {
373            return Err(MerkleError::DepthTooSmall(DEPTH));
374        }
375
376        Ok(LeafIndex { index: NodeIndex::new(DEPTH, value)? })
377    }
378
379    pub fn value(&self) -> u64 {
380        self.index.value()
381    }
382}
383
384impl LeafIndex<SMT_MAX_DEPTH> {
385    pub const fn new_max_depth(value: u64) -> Self {
386        LeafIndex {
387            index: NodeIndex::new_unchecked(SMT_MAX_DEPTH, value),
388        }
389    }
390}
391
392impl<const DEPTH: u8> From<LeafIndex<DEPTH>> for NodeIndex {
393    fn from(value: LeafIndex<DEPTH>) -> Self {
394        value.index
395    }
396}
397
398impl<const DEPTH: u8> TryFrom<NodeIndex> for LeafIndex<DEPTH> {
399    type Error = MerkleError;
400
401    fn try_from(node_index: NodeIndex) -> Result<Self, Self::Error> {
402        if node_index.depth() != DEPTH {
403            return Err(MerkleError::InvalidDepth {
404                expected: DEPTH,
405                provided: node_index.depth(),
406            });
407        }
408
409        Self::new(node_index.value())
410    }
411}
412
413// MUTATIONS
414// ================================================================================================
415
416/// A change to an inner node of a [`SparseMerkleTree`] that hasn't yet been applied.
417/// [`MutationSet`] stores this type in relation to a [`NodeIndex`] to keep track of what changes
418/// need to occur at which node indices.
419#[derive(Debug, Clone, PartialEq, Eq)]
420pub(crate) enum NodeMutation {
421    /// Corresponds to [`SparseMerkleTree::remove_inner_node()`].
422    Removal,
423    /// Corresponds to [`SparseMerkleTree::insert_inner_node()`].
424    Addition(InnerNode),
425}
426
427/// Represents a group of prospective mutations to a `SparseMerkleTree`, created by
428/// `SparseMerkleTree::compute_mutations()`, and that can be applied with
429/// `SparseMerkleTree::apply_mutations()`.
430#[derive(Debug, Clone, PartialEq, Eq, Default)]
431pub struct MutationSet<const DEPTH: u8, K, V> {
432    /// The root of the Merkle tree this MutationSet is for, recorded at the time
433    /// [`SparseMerkleTree::compute_mutations()`] was called. Exists to guard against applying
434    /// mutations to the wrong tree or applying stale mutations to a tree that has since changed.
435    old_root: RpoDigest,
436    /// The set of nodes that need to be removed or added. The "effective" node at an index is the
437    /// Merkle tree's existing node at that index, with the [`NodeMutation`] in this map at that
438    /// index overlayed, if any. Each [`NodeMutation::Addition`] corresponds to a
439    /// [`SparseMerkleTree::insert_inner_node()`] call, and each [`NodeMutation::Removal`]
440    /// corresponds to a [`SparseMerkleTree::remove_inner_node()`] call.
441    node_mutations: BTreeMap<NodeIndex, NodeMutation>,
442    /// The set of top-level key-value pairs we're prospectively adding to the tree, including
443    /// adding empty values. The "effective" value for a key is the value in this BTreeMap, falling
444    /// back to the existing value in the Merkle tree. Each entry corresponds to a
445    /// [`SparseMerkleTree::insert_value()`] call.
446    new_pairs: BTreeMap<K, V>,
447    /// The calculated root for the Merkle tree, given these mutations. Publicly retrievable with
448    /// [`MutationSet::root()`]. Corresponds to a [`SparseMerkleTree::set_root()`]. call.
449    new_root: RpoDigest,
450}
451
452impl<const DEPTH: u8, K, V> MutationSet<DEPTH, K, V> {
453    /// Queries the root that was calculated during `SparseMerkleTree::compute_mutations()`. See
454    /// that method for more information.
455    pub fn root(&self) -> RpoDigest {
456        self.new_root
457    }
458}