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 /// Returns a boolean value indicating whether the SMT is empty.
134 pub fn is_empty(&self) -> bool {
135 debug_assert_eq!(self.leaves.is_empty(), self.root == Self::EMPTY_ROOT);
136 self.root == Self::EMPTY_ROOT
137 }
138
139 // ITERATORS
140 // --------------------------------------------------------------------------------------------
141
142 /// Returns an iterator over the leaves of this [Smt].
143 pub fn leaves(&self) -> impl Iterator<Item = (LeafIndex<SMT_DEPTH>, &SmtLeaf)> {
144 self.leaves
145 .iter()
146 .map(|(leaf_index, leaf)| (LeafIndex::new_max_depth(*leaf_index), leaf))
147 }
148
149 /// Returns an iterator over the key-value pairs of this [Smt].
150 pub fn entries(&self) -> impl Iterator<Item = &(RpoDigest, Word)> {
151 self.leaves().flat_map(|(_, leaf)| leaf.entries())
152 }
153
154 /// Returns an iterator over the inner nodes of this [Smt].
155 pub fn inner_nodes(&self) -> impl Iterator<Item = InnerNodeInfo> + '_ {
156 self.inner_nodes.values().map(|e| InnerNodeInfo {
157 value: e.hash(),
158 left: e.left,
159 right: e.right,
160 })
161 }
162
163 // STATE MUTATORS
164 // --------------------------------------------------------------------------------------------
165
166 /// Inserts a value at the specified key, returning the previous value associated with that key.
167 /// Recall that by definition, any key that hasn't been updated is associated with
168 /// [`Self::EMPTY_VALUE`].
169 ///
170 /// This also recomputes all hashes between the leaf (associated with the key) and the root,
171 /// updating the root itself.
172 pub fn insert(&mut self, key: RpoDigest, value: Word) -> Word {
173 <Self as SparseMerkleTree<SMT_DEPTH>>::insert(self, key, value)
174 }
175
176 /// Computes what changes are necessary to insert the specified key-value pairs into this Merkle
177 /// tree, allowing for validation before applying those changes.
178 ///
179 /// This method returns a [`MutationSet`], which contains all the information for inserting
180 /// `kv_pairs` into this Merkle tree already calculated, including the new root hash, which can
181 /// be queried with [`MutationSet::root()`]. Once a mutation set is returned,
182 /// [`Smt::apply_mutations()`] can be called in order to commit these changes to the Merkle
183 /// tree, or [`drop()`] to discard them.
184 ///
185 /// # Example
186 /// ```
187 /// # use miden_crypto::{hash::rpo::RpoDigest, Felt, Word};
188 /// # use miden_crypto::merkle::{Smt, EmptySubtreeRoots, SMT_DEPTH};
189 /// let mut smt = Smt::new();
190 /// let pair = (RpoDigest::default(), Word::default());
191 /// let mutations = smt.compute_mutations(vec![pair]);
192 /// assert_eq!(mutations.root(), *EmptySubtreeRoots::entry(SMT_DEPTH, 0));
193 /// smt.apply_mutations(mutations);
194 /// assert_eq!(smt.root(), *EmptySubtreeRoots::entry(SMT_DEPTH, 0));
195 /// ```
196 pub fn compute_mutations(
197 &self,
198 kv_pairs: impl IntoIterator<Item = (RpoDigest, Word)>,
199 ) -> MutationSet<SMT_DEPTH, RpoDigest, Word> {
200 <Self as SparseMerkleTree<SMT_DEPTH>>::compute_mutations(self, kv_pairs)
201 }
202
203 /// Apply the prospective mutations computed with [`Smt::compute_mutations()`] to this tree.
204 ///
205 /// # Errors
206 /// If `mutations` was computed on a tree with a different root than this one, returns
207 /// [`MerkleError::ConflictingRoots`] with a two-item [`Vec`]. The first item is the root hash
208 /// the `mutations` were computed against, and the second item is the actual current root of
209 /// this tree.
210 pub fn apply_mutations(
211 &mut self,
212 mutations: MutationSet<SMT_DEPTH, RpoDigest, Word>,
213 ) -> Result<(), MerkleError> {
214 <Self as SparseMerkleTree<SMT_DEPTH>>::apply_mutations(self, mutations)
215 }
216
217 // HELPERS
218 // --------------------------------------------------------------------------------------------
219
220 /// Inserts `value` at leaf index pointed to by `key`. `value` is guaranteed to not be the empty
221 /// value, such that this is indeed an insertion.
222 fn perform_insert(&mut self, key: RpoDigest, value: Word) -> Option<Word> {
223 debug_assert_ne!(value, Self::EMPTY_VALUE);
224
225 let leaf_index: LeafIndex<SMT_DEPTH> = Self::key_to_leaf_index(&key);
226
227 match self.leaves.get_mut(&leaf_index.value()) {
228 Some(leaf) => leaf.insert(key, value),
229 None => {
230 self.leaves.insert(leaf_index.value(), SmtLeaf::Single((key, value)));
231
232 None
233 },
234 }
235 }
236
237 /// Removes key-value pair at leaf index pointed to by `key` if it exists.
238 fn perform_remove(&mut self, key: RpoDigest) -> Option<Word> {
239 let leaf_index: LeafIndex<SMT_DEPTH> = Self::key_to_leaf_index(&key);
240
241 if let Some(leaf) = self.leaves.get_mut(&leaf_index.value()) {
242 let (old_value, is_empty) = leaf.remove(key);
243 if is_empty {
244 self.leaves.remove(&leaf_index.value());
245 }
246 old_value
247 } else {
248 // there's nothing stored at the leaf; nothing to update
249 None
250 }
251 }
252}
253
254impl SparseMerkleTree<SMT_DEPTH> for Smt {
255 type Key = RpoDigest;
256 type Value = Word;
257 type Leaf = SmtLeaf;
258 type Opening = SmtProof;
259
260 const EMPTY_VALUE: Self::Value = EMPTY_WORD;
261 const EMPTY_ROOT: RpoDigest = *EmptySubtreeRoots::entry(SMT_DEPTH, 0);
262
263 fn root(&self) -> RpoDigest {
264 self.root
265 }
266
267 fn set_root(&mut self, root: RpoDigest) {
268 self.root = root;
269 }
270
271 fn get_inner_node(&self, index: NodeIndex) -> InnerNode {
272 self.inner_nodes
273 .get(&index)
274 .cloned()
275 .unwrap_or_else(|| EmptySubtreeRoots::get_inner_node(SMT_DEPTH, index.depth()))
276 }
277
278 fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode) {
279 self.inner_nodes.insert(index, inner_node);
280 }
281
282 fn remove_inner_node(&mut self, index: NodeIndex) {
283 let _ = self.inner_nodes.remove(&index);
284 }
285
286 fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option<Self::Value> {
287 // inserting an `EMPTY_VALUE` is equivalent to removing any value associated with `key`
288 if value != Self::EMPTY_VALUE {
289 self.perform_insert(key, value)
290 } else {
291 self.perform_remove(key)
292 }
293 }
294
295 fn get_value(&self, key: &Self::Key) -> Self::Value {
296 let leaf_pos = LeafIndex::<SMT_DEPTH>::from(*key).value();
297
298 match self.leaves.get(&leaf_pos) {
299 Some(leaf) => leaf.get_value(key).unwrap_or_default(),
300 None => EMPTY_WORD,
301 }
302 }
303
304 fn get_leaf(&self, key: &RpoDigest) -> Self::Leaf {
305 let leaf_pos = LeafIndex::<SMT_DEPTH>::from(*key).value();
306
307 match self.leaves.get(&leaf_pos) {
308 Some(leaf) => leaf.clone(),
309 None => SmtLeaf::new_empty(key.into()),
310 }
311 }
312
313 fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest {
314 leaf.hash()
315 }
316
317 fn construct_prospective_leaf(
318 &self,
319 mut existing_leaf: SmtLeaf,
320 key: &RpoDigest,
321 value: &Word,
322 ) -> SmtLeaf {
323 debug_assert_eq!(existing_leaf.index(), Self::key_to_leaf_index(key));
324
325 match existing_leaf {
326 SmtLeaf::Empty(_) => SmtLeaf::new_single(*key, *value),
327 _ => {
328 if *value != EMPTY_WORD {
329 existing_leaf.insert(*key, *value);
330 } else {
331 existing_leaf.remove(*key);
332 }
333
334 existing_leaf
335 },
336 }
337 }
338
339 fn key_to_leaf_index(key: &RpoDigest) -> LeafIndex<SMT_DEPTH> {
340 let most_significant_felt = key[3];
341 LeafIndex::new_max_depth(most_significant_felt.as_int())
342 }
343
344 fn path_and_leaf_to_opening(path: MerklePath, leaf: SmtLeaf) -> SmtProof {
345 SmtProof::new_unchecked(path, leaf)
346 }
347}
348
349impl Default for Smt {
350 fn default() -> Self {
351 Self::new()
352 }
353}
354
355// CONVERSIONS
356// ================================================================================================
357
358impl From<Word> for LeafIndex<SMT_DEPTH> {
359 fn from(value: Word) -> Self {
360 // We use the most significant `Felt` of a `Word` as the leaf index.
361 Self::new_max_depth(value[3].as_int())
362 }
363}
364
365impl From<RpoDigest> for LeafIndex<SMT_DEPTH> {
366 fn from(value: RpoDigest) -> Self {
367 Word::from(value).into()
368 }
369}
370
371impl From<&RpoDigest> for LeafIndex<SMT_DEPTH> {
372 fn from(value: &RpoDigest) -> Self {
373 Word::from(value).into()
374 }
375}
376
377// SERIALIZATION
378// ================================================================================================
379
380impl Serializable for Smt {
381 fn write_into<W: ByteWriter>(&self, target: &mut W) {
382 // Write the number of filled leaves for this Smt
383 target.write_usize(self.entries().count());
384
385 // Write each (key, value) pair
386 for (key, value) in self.entries() {
387 target.write(key);
388 target.write(value);
389 }
390 }
391
392 fn get_size_hint(&self) -> usize {
393 let entries_count = self.entries().count();
394
395 // Each entry is the size of a digest plus a word.
396 entries_count.get_size_hint()
397 + entries_count * (RpoDigest::SERIALIZED_SIZE + EMPTY_WORD.get_size_hint())
398 }
399}
400
401impl Deserializable for Smt {
402 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
403 // Read the number of filled leaves for this Smt
404 let num_filled_leaves = source.read_usize()?;
405 let mut entries = Vec::with_capacity(num_filled_leaves);
406
407 for _ in 0..num_filled_leaves {
408 let key = source.read()?;
409 let value = source.read()?;
410 entries.push((key, value));
411 }
412
413 Self::with_entries(entries)
414 .map_err(|err| DeserializationError::InvalidValue(err.to_string()))
415 }
416}
417
418#[test]
419fn test_smt_serialization_deserialization() {
420 // Smt for default types (empty map)
421 let smt_default = Smt::default();
422 let bytes = smt_default.to_bytes();
423 assert_eq!(smt_default, Smt::read_from_bytes(&bytes).unwrap());
424 assert_eq!(bytes.len(), smt_default.get_size_hint());
425
426 // Smt with values
427 let smt_leaves_2: [(RpoDigest, Word); 2] = [
428 (
429 RpoDigest::new([Felt::new(101), Felt::new(102), Felt::new(103), Felt::new(104)]),
430 [Felt::new(1_u64), Felt::new(2_u64), Felt::new(3_u64), Felt::new(4_u64)],
431 ),
432 (
433 RpoDigest::new([Felt::new(105), Felt::new(106), Felt::new(107), Felt::new(108)]),
434 [Felt::new(5_u64), Felt::new(6_u64), Felt::new(7_u64), Felt::new(8_u64)],
435 ),
436 ];
437 let smt = Smt::with_entries(smt_leaves_2).unwrap();
438
439 let bytes = smt.to_bytes();
440 assert_eq!(smt, Smt::read_from_bytes(&bytes).unwrap());
441 assert_eq!(bytes.len(), smt.get_size_hint());
442}