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    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        let leaf_pos = LeafIndex::<SMT_DEPTH>::from(*key).value();
125
126        match self.leaves.get(&leaf_pos) {
127            Some(leaf) => leaf.get_value(key).unwrap_or_default(),
128            None => EMPTY_WORD,
129        }
130    }
131
132    /// Returns an opening of the leaf associated with `key`. Conceptually, an opening is a Merkle
133    /// path to the leaf, as well as the leaf itself.
134    pub fn open(&self, key: &RpoDigest) -> SmtProof {
135        <Self as SparseMerkleTree<SMT_DEPTH>>::open(self, key)
136    }
137
138    // ITERATORS
139    // --------------------------------------------------------------------------------------------
140
141    /// Returns an iterator over the leaves of this [Smt].
142    pub fn leaves(&self) -> impl Iterator<Item = (LeafIndex<SMT_DEPTH>, &SmtLeaf)> {
143        self.leaves
144            .iter()
145            .map(|(leaf_index, leaf)| (LeafIndex::new_max_depth(*leaf_index), leaf))
146    }
147
148    /// Returns an iterator over the key-value pairs of this [Smt].
149    pub fn entries(&self) -> impl Iterator<Item = &(RpoDigest, Word)> {
150        self.leaves().flat_map(|(_, leaf)| leaf.entries())
151    }
152
153    /// Returns an iterator over the inner nodes of this [Smt].
154    pub fn inner_nodes(&self) -> impl Iterator<Item = InnerNodeInfo> + '_ {
155        self.inner_nodes.values().map(|e| InnerNodeInfo {
156            value: e.hash(),
157            left: e.left,
158            right: e.right,
159        })
160    }
161
162    // STATE MUTATORS
163    // --------------------------------------------------------------------------------------------
164
165    /// Inserts a value at the specified key, returning the previous value associated with that key.
166    /// Recall that by definition, any key that hasn't been updated is associated with
167    /// [`Self::EMPTY_VALUE`].
168    ///
169    /// This also recomputes all hashes between the leaf (associated with the key) and the root,
170    /// updating the root itself.
171    pub fn insert(&mut self, key: RpoDigest, value: Word) -> Word {
172        <Self as SparseMerkleTree<SMT_DEPTH>>::insert(self, key, value)
173    }
174
175    // HELPERS
176    // --------------------------------------------------------------------------------------------
177
178    /// Inserts `value` at leaf index pointed to by `key`. `value` is guaranteed to not be the empty
179    /// value, such that this is indeed an insertion.
180    fn perform_insert(&mut self, key: RpoDigest, value: Word) -> Option<Word> {
181        debug_assert_ne!(value, Self::EMPTY_VALUE);
182
183        let leaf_index: LeafIndex<SMT_DEPTH> = Self::key_to_leaf_index(&key);
184
185        match self.leaves.get_mut(&leaf_index.value()) {
186            Some(leaf) => leaf.insert(key, value),
187            None => {
188                self.leaves.insert(leaf_index.value(), SmtLeaf::Single((key, value)));
189
190                None
191            },
192        }
193    }
194
195    /// Removes key-value pair at leaf index pointed to by `key` if it exists.
196    fn perform_remove(&mut self, key: RpoDigest) -> Option<Word> {
197        let leaf_index: LeafIndex<SMT_DEPTH> = Self::key_to_leaf_index(&key);
198
199        if let Some(leaf) = self.leaves.get_mut(&leaf_index.value()) {
200            let (old_value, is_empty) = leaf.remove(key);
201            if is_empty {
202                self.leaves.remove(&leaf_index.value());
203            }
204            old_value
205        } else {
206            // there's nothing stored at the leaf; nothing to update
207            None
208        }
209    }
210}
211
212impl SparseMerkleTree<SMT_DEPTH> for Smt {
213    type Key = RpoDigest;
214    type Value = Word;
215    type Leaf = SmtLeaf;
216    type Opening = SmtProof;
217
218    const EMPTY_VALUE: Self::Value = EMPTY_WORD;
219
220    fn root(&self) -> RpoDigest {
221        self.root
222    }
223
224    fn set_root(&mut self, root: RpoDigest) {
225        self.root = root;
226    }
227
228    fn get_inner_node(&self, index: NodeIndex) -> InnerNode {
229        self.inner_nodes.get(&index).cloned().unwrap_or_else(|| {
230            let node = EmptySubtreeRoots::entry(SMT_DEPTH, index.depth() + 1);
231
232            InnerNode { left: *node, right: *node }
233        })
234    }
235
236    fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode) {
237        self.inner_nodes.insert(index, inner_node);
238    }
239
240    fn remove_inner_node(&mut self, index: NodeIndex) {
241        let _ = self.inner_nodes.remove(&index);
242    }
243
244    fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option<Self::Value> {
245        // inserting an `EMPTY_VALUE` is equivalent to removing any value associated with `key`
246        if value != Self::EMPTY_VALUE {
247            self.perform_insert(key, value)
248        } else {
249            self.perform_remove(key)
250        }
251    }
252
253    fn get_leaf(&self, key: &RpoDigest) -> Self::Leaf {
254        let leaf_pos = LeafIndex::<SMT_DEPTH>::from(*key).value();
255
256        match self.leaves.get(&leaf_pos) {
257            Some(leaf) => leaf.clone(),
258            None => SmtLeaf::new_empty(key.into()),
259        }
260    }
261
262    fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest {
263        leaf.hash()
264    }
265
266    fn key_to_leaf_index(key: &RpoDigest) -> LeafIndex<SMT_DEPTH> {
267        let most_significant_felt = key[3];
268        LeafIndex::new_max_depth(most_significant_felt.as_int())
269    }
270
271    fn path_and_leaf_to_opening(path: MerklePath, leaf: SmtLeaf) -> SmtProof {
272        SmtProof::new_unchecked(path, leaf)
273    }
274}
275
276impl Default for Smt {
277    fn default() -> Self {
278        Self::new()
279    }
280}
281
282// CONVERSIONS
283// ================================================================================================
284
285impl From<Word> for LeafIndex<SMT_DEPTH> {
286    fn from(value: Word) -> Self {
287        // We use the most significant `Felt` of a `Word` as the leaf index.
288        Self::new_max_depth(value[3].as_int())
289    }
290}
291
292impl From<RpoDigest> for LeafIndex<SMT_DEPTH> {
293    fn from(value: RpoDigest) -> Self {
294        Word::from(value).into()
295    }
296}
297
298impl From<&RpoDigest> for LeafIndex<SMT_DEPTH> {
299    fn from(value: &RpoDigest) -> Self {
300        Word::from(value).into()
301    }
302}
303
304// SERIALIZATION
305// ================================================================================================
306
307impl Serializable for Smt {
308    fn write_into<W: ByteWriter>(&self, target: &mut W) {
309        // Write the number of filled leaves for this Smt
310        target.write_usize(self.entries().count());
311
312        // Write each (key, value) pair
313        for (key, value) in self.entries() {
314            target.write(key);
315            target.write(value);
316        }
317    }
318}
319
320impl Deserializable for Smt {
321    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
322        // Read the number of filled leaves for this Smt
323        let num_filled_leaves = source.read_usize()?;
324        let mut entries = Vec::with_capacity(num_filled_leaves);
325
326        for _ in 0..num_filled_leaves {
327            let key = source.read()?;
328            let value = source.read()?;
329            entries.push((key, value));
330        }
331
332        Self::with_entries(entries)
333            .map_err(|err| DeserializationError::InvalidValue(err.to_string()))
334    }
335}
336
337#[test]
338fn test_smt_serialization_deserialization() {
339    // Smt for default types (empty map)
340    let smt_default = Smt::default();
341    let bytes = smt_default.to_bytes();
342    assert_eq!(smt_default, Smt::read_from_bytes(&bytes).unwrap());
343
344    // Smt with values
345    let smt_leaves_2: [(RpoDigest, Word); 2] = [
346        (
347            RpoDigest::new([Felt::new(101), Felt::new(102), Felt::new(103), Felt::new(104)]),
348            [Felt::new(1_u64), Felt::new(2_u64), Felt::new(3_u64), Felt::new(4_u64)],
349        ),
350        (
351            RpoDigest::new([Felt::new(105), Felt::new(106), Felt::new(107), Felt::new(108)]),
352            [Felt::new(5_u64), Felt::new(6_u64), Felt::new(7_u64), Felt::new(8_u64)],
353        ),
354    ];
355    let smt = Smt::with_entries(smt_leaves_2).unwrap();
356
357    let bytes = smt.to_bytes();
358    assert_eq!(smt, Smt::read_from_bytes(&bytes).unwrap());
359}