arnaucube
arnaucube/miden-cryptoPublic Self-hosted repository
miden-crypto/src/merkle/smt/full/mod.rs
src/merkle/smt/full/mod.rsRaw
  1use alloc::{
  2    collections::{BTreeMap, BTreeSet},
  3    string::ToString,
  4    vec::Vec,
  5};
  6
  7use super::{
  8    EmptySubtreeRoots, Felt, InnerNode, InnerNodeInfo, LeafIndex, MerkleError, MerklePath,
  9    MutationSet, NodeIndex, Rpo256, RpoDigest, SparseMerkleTree, Word, EMPTY_WORD,
 10};
 11
 12mod error;
 13pub use error::{SmtLeafError, SmtProofError};
 14
 15mod leaf;
 16pub use leaf::SmtLeaf;
 17
 18mod proof;
 19pub use proof::SmtProof;
 20use winter_utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable};
 21
 22#[cfg(test)]
 23mod tests;
 24
 25// CONSTANTS
 26// ================================================================================================
 27
 28pub const SMT_DEPTH: u8 = 64;
 29
 30// SMT
 31// ================================================================================================
 32
 33/// Sparse Merkle tree mapping 256-bit keys to 256-bit values. Both keys and values are represented
 34/// by 4 field elements.
 35///
 36/// All leaves sit at depth 64. The most significant element of the key is used to identify the leaf
 37/// to which the key maps.
 38///
 39/// A leaf is either empty, or holds one or more key-value pairs. An empty leaf hashes to the empty
 40/// word. Otherwise, a leaf hashes to the hash of its key-value pairs, ordered by key first, value
 41/// second.
 42#[derive(Debug, Clone, PartialEq, Eq)]
 43#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
 44pub struct Smt {
 45    root: RpoDigest,
 46    leaves: BTreeMap<u64, SmtLeaf>,
 47    inner_nodes: BTreeMap<NodeIndex, InnerNode>,
 48}
 49
 50impl Smt {
 51    // CONSTANTS
 52    // --------------------------------------------------------------------------------------------
 53    /// The default value used to compute the hash of empty leaves
 54    pub const EMPTY_VALUE: Word = <Self as SparseMerkleTree<SMT_DEPTH>>::EMPTY_VALUE;
 55
 56    // CONSTRUCTORS
 57    // --------------------------------------------------------------------------------------------
 58
 59    /// Returns a new [Smt].
 60    ///
 61    /// All leaves in the returned tree are set to [Self::EMPTY_VALUE].
 62    pub fn new() -> Self {
 63        let root = *EmptySubtreeRoots::entry(SMT_DEPTH, 0);
 64
 65        Self {
 66            root,
 67            leaves: BTreeMap::new(),
 68            inner_nodes: BTreeMap::new(),
 69        }
 70    }
 71
 72    /// Returns a new [Smt] instantiated with leaves set as specified by the provided entries.
 73    ///
 74    /// All leaves omitted from the entries list are set to [Self::EMPTY_VALUE].
 75    ///
 76    /// # Errors
 77    /// Returns an error if the provided entries contain multiple values for the same key.
 78    pub fn with_entries(
 79        entries: impl IntoIterator<Item = (RpoDigest, Word)>,
 80    ) -> Result<Self, MerkleError> {
 81        // create an empty tree
 82        let mut tree = Self::new();
 83
 84        // This being a sparse data structure, the EMPTY_WORD is not assigned to the `BTreeMap`, so
 85        // entries with the empty value need additional tracking.
 86        let mut key_set_to_zero = BTreeSet::new();
 87
 88        for (key, value) in entries {
 89            let old_value = tree.insert(key, value);
 90
 91            if old_value != EMPTY_WORD || key_set_to_zero.contains(&key) {
 92                return Err(MerkleError::DuplicateValuesForIndex(
 93                    LeafIndex::<SMT_DEPTH>::from(key).value(),
 94                ));
 95            }
 96
 97            if value == EMPTY_WORD {
 98                key_set_to_zero.insert(key);
 99            };
100        }
101        Ok(tree)
102    }
103
104    // PUBLIC ACCESSORS
105    // --------------------------------------------------------------------------------------------
106
107    /// Returns the depth of the tree
108    pub const fn depth(&self) -> u8 {
109        SMT_DEPTH
110    }
111
112    /// Returns the root of the tree
113    pub fn root(&self) -> RpoDigest {
114        <Self as SparseMerkleTree<SMT_DEPTH>>::root(self)
115    }
116
117    /// Returns the leaf to which `key` maps
118    pub fn get_leaf(&self, key: &RpoDigest) -> SmtLeaf {
119        <Self as SparseMerkleTree<SMT_DEPTH>>::get_leaf(self, key)
120    }
121
122    /// Returns the value associated with `key`
123    pub fn get_value(&self, key: &RpoDigest) -> Word {
124        <Self as SparseMerkleTree<SMT_DEPTH>>::get_value(self, key)
125    }
126
127    /// Returns an opening of the leaf associated with `key`. Conceptually, an opening is a Merkle
128    /// path to the leaf, as well as the leaf itself.
129    pub fn open(&self, key: &RpoDigest) -> SmtProof {
130        <Self as SparseMerkleTree<SMT_DEPTH>>::open(self, key)
131    }
132
133    // ITERATORS
134    // --------------------------------------------------------------------------------------------
135
136    /// Returns an iterator over the leaves of this [Smt].
137    pub fn leaves(&self) -> impl Iterator<Item = (LeafIndex<SMT_DEPTH>, &SmtLeaf)> {
138        self.leaves
139            .iter()
140            .map(|(leaf_index, leaf)| (LeafIndex::new_max_depth(*leaf_index), leaf))
141    }
142
143    /// Returns an iterator over the key-value pairs of this [Smt].
144    pub fn entries(&self) -> impl Iterator<Item = &(RpoDigest, Word)> {
145        self.leaves().flat_map(|(_, leaf)| leaf.entries())
146    }
147
148    /// Returns an iterator over the inner nodes of this [Smt].
149    pub fn inner_nodes(&self) -> impl Iterator<Item = InnerNodeInfo> + '_ {
150        self.inner_nodes.values().map(|e| InnerNodeInfo {
151            value: e.hash(),
152            left: e.left,
153            right: e.right,
154        })
155    }
156
157    // STATE MUTATORS
158    // --------------------------------------------------------------------------------------------
159
160    /// Inserts a value at the specified key, returning the previous value associated with that key.
161    /// Recall that by definition, any key that hasn't been updated is associated with
162    /// [`Self::EMPTY_VALUE`].
163    ///
164    /// This also recomputes all hashes between the leaf (associated with the key) and the root,
165    /// updating the root itself.
166    pub fn insert(&mut self, key: RpoDigest, value: Word) -> Word {
167        <Self as SparseMerkleTree<SMT_DEPTH>>::insert(self, key, value)
168    }
169
170    /// Computes what changes are necessary to insert the specified key-value pairs into this Merkle
171    /// tree, allowing for validation before applying those changes.
172    ///
173    /// This method returns a [`MutationSet`], which contains all the information for inserting
174    /// `kv_pairs` into this Merkle tree already calculated, including the new root hash, which can
175    /// be queried with [`MutationSet::root()`]. Once a mutation set is returned,
176    /// [`Smt::apply_mutations()`] can be called in order to commit these changes to the Merkle
177    /// tree, or [`drop()`] to discard them.
178    ///
179    /// # Example
180    /// ```
181    /// # use miden_crypto::{hash::rpo::RpoDigest, Felt, Word};
182    /// # use miden_crypto::merkle::{Smt, EmptySubtreeRoots, SMT_DEPTH};
183    /// let mut smt = Smt::new();
184    /// let pair = (RpoDigest::default(), Word::default());
185    /// let mutations = smt.compute_mutations(vec![pair]);
186    /// assert_eq!(mutations.root(), *EmptySubtreeRoots::entry(SMT_DEPTH, 0));
187    /// smt.apply_mutations(mutations);
188    /// assert_eq!(smt.root(), *EmptySubtreeRoots::entry(SMT_DEPTH, 0));
189    /// ```
190    pub fn compute_mutations(
191        &self,
192        kv_pairs: impl IntoIterator<Item = (RpoDigest, Word)>,
193    ) -> MutationSet<SMT_DEPTH, RpoDigest, Word> {
194        <Self as SparseMerkleTree<SMT_DEPTH>>::compute_mutations(self, kv_pairs)
195    }
196
197    /// Apply the prospective mutations computed with [`Smt::compute_mutations()`] to this tree.
198    ///
199    /// # Errors
200    /// If `mutations` was computed on a tree with a different root than this one, returns
201    /// [`MerkleError::ConflictingRoots`] with a two-item [`Vec`]. The first item is the root hash
202    /// the `mutations` were computed against, and the second item is the actual current root of
203    /// this tree.
204    pub fn apply_mutations(
205        &mut self,
206        mutations: MutationSet<SMT_DEPTH, RpoDigest, Word>,
207    ) -> Result<(), MerkleError> {
208        <Self as SparseMerkleTree<SMT_DEPTH>>::apply_mutations(self, mutations)
209    }
210
211    // HELPERS
212    // --------------------------------------------------------------------------------------------
213
214    /// Inserts `value` at leaf index pointed to by `key`. `value` is guaranteed to not be the empty
215    /// value, such that this is indeed an insertion.
216    fn perform_insert(&mut self, key: RpoDigest, value: Word) -> Option<Word> {
217        debug_assert_ne!(value, Self::EMPTY_VALUE);
218
219        let leaf_index: LeafIndex<SMT_DEPTH> = Self::key_to_leaf_index(&key);
220
221        match self.leaves.get_mut(&leaf_index.value()) {
222            Some(leaf) => leaf.insert(key, value),
223            None => {
224                self.leaves.insert(leaf_index.value(), SmtLeaf::Single((key, value)));
225
226                None
227            },
228        }
229    }
230
231    /// Removes key-value pair at leaf index pointed to by `key` if it exists.
232    fn perform_remove(&mut self, key: RpoDigest) -> Option<Word> {
233        let leaf_index: LeafIndex<SMT_DEPTH> = Self::key_to_leaf_index(&key);
234
235        if let Some(leaf) = self.leaves.get_mut(&leaf_index.value()) {
236            let (old_value, is_empty) = leaf.remove(key);
237            if is_empty {
238                self.leaves.remove(&leaf_index.value());
239            }
240            old_value
241        } else {
242            // there's nothing stored at the leaf; nothing to update
243            None
244        }
245    }
246}
247
248impl SparseMerkleTree<SMT_DEPTH> for Smt {
249    type Key = RpoDigest;
250    type Value = Word;
251    type Leaf = SmtLeaf;
252    type Opening = SmtProof;
253
254    const EMPTY_VALUE: Self::Value = EMPTY_WORD;
255
256    fn root(&self) -> RpoDigest {
257        self.root
258    }
259
260    fn set_root(&mut self, root: RpoDigest) {
261        self.root = root;
262    }
263
264    fn get_inner_node(&self, index: NodeIndex) -> InnerNode {
265        self.inner_nodes
266            .get(&index)
267            .cloned()
268            .unwrap_or_else(|| EmptySubtreeRoots::get_inner_node(SMT_DEPTH, index.depth()))
269    }
270
271    fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode) {
272        self.inner_nodes.insert(index, inner_node);
273    }
274
275    fn remove_inner_node(&mut self, index: NodeIndex) {
276        let _ = self.inner_nodes.remove(&index);
277    }
278
279    fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option<Self::Value> {
280        // inserting an `EMPTY_VALUE` is equivalent to removing any value associated with `key`
281        if value != Self::EMPTY_VALUE {
282            self.perform_insert(key, value)
283        } else {
284            self.perform_remove(key)
285        }
286    }
287
288    fn get_value(&self, key: &Self::Key) -> Self::Value {
289        let leaf_pos = LeafIndex::<SMT_DEPTH>::from(*key).value();
290
291        match self.leaves.get(&leaf_pos) {
292            Some(leaf) => leaf.get_value(key).unwrap_or_default(),
293            None => EMPTY_WORD,
294        }
295    }
296
297    fn get_leaf(&self, key: &RpoDigest) -> Self::Leaf {
298        let leaf_pos = LeafIndex::<SMT_DEPTH>::from(*key).value();
299
300        match self.leaves.get(&leaf_pos) {
301            Some(leaf) => leaf.clone(),
302            None => SmtLeaf::new_empty(key.into()),
303        }
304    }
305
306    fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest {
307        leaf.hash()
308    }
309
310    fn construct_prospective_leaf(
311        &self,
312        mut existing_leaf: SmtLeaf,
313        key: &RpoDigest,
314        value: &Word,
315    ) -> SmtLeaf {
316        debug_assert_eq!(existing_leaf.index(), Self::key_to_leaf_index(key));
317
318        match existing_leaf {
319            SmtLeaf::Empty(_) => SmtLeaf::new_single(*key, *value),
320            _ => {
321                if *value != EMPTY_WORD {
322                    existing_leaf.insert(*key, *value);
323                } else {
324                    existing_leaf.remove(*key);
325                }
326
327                existing_leaf
328            },
329        }
330    }
331
332    fn key_to_leaf_index(key: &RpoDigest) -> LeafIndex<SMT_DEPTH> {
333        let most_significant_felt = key[3];
334        LeafIndex::new_max_depth(most_significant_felt.as_int())
335    }
336
337    fn path_and_leaf_to_opening(path: MerklePath, leaf: SmtLeaf) -> SmtProof {
338        SmtProof::new_unchecked(path, leaf)
339    }
340}
341
342impl Default for Smt {
343    fn default() -> Self {
344        Self::new()
345    }
346}
347
348// CONVERSIONS
349// ================================================================================================
350
351impl From<Word> for LeafIndex<SMT_DEPTH> {
352    fn from(value: Word) -> Self {
353        // We use the most significant `Felt` of a `Word` as the leaf index.
354        Self::new_max_depth(value[3].as_int())
355    }
356}
357
358impl From<RpoDigest> for LeafIndex<SMT_DEPTH> {
359    fn from(value: RpoDigest) -> Self {
360        Word::from(value).into()
361    }
362}
363
364impl From<&RpoDigest> for LeafIndex<SMT_DEPTH> {
365    fn from(value: &RpoDigest) -> Self {
366        Word::from(value).into()
367    }
368}
369
370// SERIALIZATION
371// ================================================================================================
372
373impl Serializable for Smt {
374    fn write_into<W: ByteWriter>(&self, target: &mut W) {
375        // Write the number of filled leaves for this Smt
376        target.write_usize(self.entries().count());
377
378        // Write each (key, value) pair
379        for (key, value) in self.entries() {
380            target.write(key);
381            target.write(value);
382        }
383    }
384}
385
386impl Deserializable for Smt {
387    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
388        // Read the number of filled leaves for this Smt
389        let num_filled_leaves = source.read_usize()?;
390        let mut entries = Vec::with_capacity(num_filled_leaves);
391
392        for _ in 0..num_filled_leaves {
393            let key = source.read()?;
394            let value = source.read()?;
395            entries.push((key, value));
396        }
397
398        Self::with_entries(entries)
399            .map_err(|err| DeserializationError::InvalidValue(err.to_string()))
400    }
401}
402
403#[test]
404fn test_smt_serialization_deserialization() {
405    // Smt for default types (empty map)
406    let smt_default = Smt::default();
407    let bytes = smt_default.to_bytes();
408    assert_eq!(smt_default, Smt::read_from_bytes(&bytes).unwrap());
409
410    // Smt with values
411    let smt_leaves_2: [(RpoDigest, Word); 2] = [
412        (
413            RpoDigest::new([Felt::new(101), Felt::new(102), Felt::new(103), Felt::new(104)]),
414            [Felt::new(1_u64), Felt::new(2_u64), Felt::new(3_u64), Felt::new(4_u64)],
415        ),
416        (
417            RpoDigest::new([Felt::new(105), Felt::new(106), Felt::new(107), Felt::new(108)]),
418            [Felt::new(5_u64), Felt::new(6_u64), Felt::new(7_u64), Felt::new(8_u64)],
419        ),
420    ];
421    let smt = Smt::with_entries(smt_leaves_2).unwrap();
422
423    let bytes = smt.to_bytes();
424    assert_eq!(smt, Smt::read_from_bytes(&bytes).unwrap());
425}