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 /// If the `concurrent` feature is enabled, this function uses a parallel implementation to
75 /// process the entries efficiently, otherwise it defaults to the sequential implementation.
76 ///
77 /// All leaves omitted from the entries list are set to [Self::EMPTY_VALUE].
78 ///
79 /// # Errors
80 /// Returns an error if the provided entries contain multiple values for the same key.
81 pub fn with_entries(
82 entries: impl IntoIterator<Item = (RpoDigest, Word)>,
83 ) -> Result<Self, MerkleError> {
84 #[cfg(feature = "concurrent")]
85 {
86 let mut seen_keys = BTreeSet::new();
87 let entries: Vec<_> = entries
88 .into_iter()
89 .map(|(key, value)| {
90 if seen_keys.insert(key) {
91 Ok((key, value))
92 } else {
93 Err(MerkleError::DuplicateValuesForIndex(
94 LeafIndex::<SMT_DEPTH>::from(key).value(),
95 ))
96 }
97 })
98 .collect::<Result<_, _>>()?;
99 if entries.is_empty() {
100 return Ok(Self::default());
101 }
102 <Self as SparseMerkleTree<SMT_DEPTH>>::with_entries_par(entries)
103 }
104 #[cfg(not(feature = "concurrent"))]
105 {
106 Self::with_entries_sequential(entries)
107 }
108 }
109
110 /// Returns a new [Smt] instantiated with leaves set as specified by the provided entries.
111 ///
112 /// This sequential implementation processes entries one at a time to build the tree.
113 /// All leaves omitted from the entries list are set to [Self::EMPTY_VALUE].
114 ///
115 /// # Errors
116 /// Returns an error if the provided entries contain multiple values for the same key.
117 pub fn with_entries_sequential(
118 entries: impl IntoIterator<Item = (RpoDigest, Word)>,
119 ) -> Result<Self, MerkleError> {
120 // create an empty tree
121 let mut tree = Self::new();
122
123 // This being a sparse data structure, the EMPTY_WORD is not assigned to the `BTreeMap`, so
124 // entries with the empty value need additional tracking.
125 let mut key_set_to_zero = BTreeSet::new();
126
127 for (key, value) in entries {
128 let old_value = tree.insert(key, value);
129
130 if old_value != EMPTY_WORD || key_set_to_zero.contains(&key) {
131 return Err(MerkleError::DuplicateValuesForIndex(
132 LeafIndex::<SMT_DEPTH>::from(key).value(),
133 ));
134 }
135
136 if value == EMPTY_WORD {
137 key_set_to_zero.insert(key);
138 };
139 }
140 Ok(tree)
141 }
142
143 /// Returns a new [`Smt`] instantiated from already computed leaves and nodes.
144 ///
145 /// This function performs minimal consistency checking. It is the caller's responsibility to
146 /// ensure the passed arguments are correct and consistent with each other.
147 ///
148 /// # Panics
149 /// With debug assertions on, this function panics if `root` does not match the root node in
150 /// `inner_nodes`.
151 pub fn from_raw_parts(
152 inner_nodes: BTreeMap<NodeIndex, InnerNode>,
153 leaves: BTreeMap<u64, SmtLeaf>,
154 root: RpoDigest,
155 ) -> Self {
156 // Our particular implementation of `from_raw_parts()` never returns `Err`.
157 <Self as SparseMerkleTree<SMT_DEPTH>>::from_raw_parts(inner_nodes, leaves, root).unwrap()
158 }
159
160 // PUBLIC ACCESSORS
161 // --------------------------------------------------------------------------------------------
162
163 /// Returns the depth of the tree
164 pub const fn depth(&self) -> u8 {
165 SMT_DEPTH
166 }
167
168 /// Returns the root of the tree
169 pub fn root(&self) -> RpoDigest {
170 <Self as SparseMerkleTree<SMT_DEPTH>>::root(self)
171 }
172
173 /// Returns the leaf to which `key` maps
174 pub fn get_leaf(&self, key: &RpoDigest) -> SmtLeaf {
175 <Self as SparseMerkleTree<SMT_DEPTH>>::get_leaf(self, key)
176 }
177
178 /// Returns the value associated with `key`
179 pub fn get_value(&self, key: &RpoDigest) -> Word {
180 <Self as SparseMerkleTree<SMT_DEPTH>>::get_value(self, key)
181 }
182
183 /// Returns an opening of the leaf associated with `key`. Conceptually, an opening is a Merkle
184 /// path to the leaf, as well as the leaf itself.
185 pub fn open(&self, key: &RpoDigest) -> SmtProof {
186 <Self as SparseMerkleTree<SMT_DEPTH>>::open(self, key)
187 }
188
189 /// Returns a boolean value indicating whether the SMT is empty.
190 pub fn is_empty(&self) -> bool {
191 debug_assert_eq!(self.leaves.is_empty(), self.root == Self::EMPTY_ROOT);
192 self.root == Self::EMPTY_ROOT
193 }
194
195 // ITERATORS
196 // --------------------------------------------------------------------------------------------
197
198 /// Returns an iterator over the leaves of this [Smt].
199 pub fn leaves(&self) -> impl Iterator<Item = (LeafIndex<SMT_DEPTH>, &SmtLeaf)> {
200 self.leaves
201 .iter()
202 .map(|(leaf_index, leaf)| (LeafIndex::new_max_depth(*leaf_index), leaf))
203 }
204
205 /// Returns an iterator over the key-value pairs of this [Smt].
206 pub fn entries(&self) -> impl Iterator<Item = &(RpoDigest, Word)> {
207 self.leaves().flat_map(|(_, leaf)| leaf.entries())
208 }
209
210 /// Returns an iterator over the inner nodes of this [Smt].
211 pub fn inner_nodes(&self) -> impl Iterator<Item = InnerNodeInfo> + '_ {
212 self.inner_nodes.values().map(|e| InnerNodeInfo {
213 value: e.hash(),
214 left: e.left,
215 right: e.right,
216 })
217 }
218
219 // STATE MUTATORS
220 // --------------------------------------------------------------------------------------------
221
222 /// Inserts a value at the specified key, returning the previous value associated with that key.
223 /// Recall that by definition, any key that hasn't been updated is associated with
224 /// [`Self::EMPTY_VALUE`].
225 ///
226 /// This also recomputes all hashes between the leaf (associated with the key) and the root,
227 /// updating the root itself.
228 pub fn insert(&mut self, key: RpoDigest, value: Word) -> Word {
229 <Self as SparseMerkleTree<SMT_DEPTH>>::insert(self, key, value)
230 }
231
232 /// Computes what changes are necessary to insert the specified key-value pairs into this Merkle
233 /// tree, allowing for validation before applying those changes.
234 ///
235 /// This method returns a [`MutationSet`], which contains all the information for inserting
236 /// `kv_pairs` into this Merkle tree already calculated, including the new root hash, which can
237 /// be queried with [`MutationSet::root()`]. Once a mutation set is returned,
238 /// [`Smt::apply_mutations()`] can be called in order to commit these changes to the Merkle
239 /// tree, or [`drop()`] to discard them.
240 ///
241 /// # Example
242 /// ```
243 /// # use miden_crypto::{hash::rpo::RpoDigest, Felt, Word};
244 /// # use miden_crypto::merkle::{Smt, EmptySubtreeRoots, SMT_DEPTH};
245 /// let mut smt = Smt::new();
246 /// let pair = (RpoDigest::default(), Word::default());
247 /// let mutations = smt.compute_mutations(vec![pair]);
248 /// assert_eq!(mutations.root(), *EmptySubtreeRoots::entry(SMT_DEPTH, 0));
249 /// smt.apply_mutations(mutations);
250 /// assert_eq!(smt.root(), *EmptySubtreeRoots::entry(SMT_DEPTH, 0));
251 /// ```
252 pub fn compute_mutations(
253 &self,
254 kv_pairs: impl IntoIterator<Item = (RpoDigest, Word)>,
255 ) -> MutationSet<SMT_DEPTH, RpoDigest, Word> {
256 <Self as SparseMerkleTree<SMT_DEPTH>>::compute_mutations(self, kv_pairs)
257 }
258
259 /// Apply the prospective mutations computed with [`Smt::compute_mutations()`] to this tree.
260 ///
261 /// # Errors
262 /// If `mutations` was computed on a tree with a different root than this one, returns
263 /// [`MerkleError::ConflictingRoots`] with a two-item [`Vec`]. The first item is the root hash
264 /// the `mutations` were computed against, and the second item is the actual current root of
265 /// this tree.
266 pub fn apply_mutations(
267 &mut self,
268 mutations: MutationSet<SMT_DEPTH, RpoDigest, Word>,
269 ) -> Result<(), MerkleError> {
270 <Self as SparseMerkleTree<SMT_DEPTH>>::apply_mutations(self, mutations)
271 }
272
273 // HELPERS
274 // --------------------------------------------------------------------------------------------
275
276 /// Inserts `value` at leaf index pointed to by `key`. `value` is guaranteed to not be the empty
277 /// value, such that this is indeed an insertion.
278 fn perform_insert(&mut self, key: RpoDigest, value: Word) -> Option<Word> {
279 debug_assert_ne!(value, Self::EMPTY_VALUE);
280
281 let leaf_index: LeafIndex<SMT_DEPTH> = Self::key_to_leaf_index(&key);
282
283 match self.leaves.get_mut(&leaf_index.value()) {
284 Some(leaf) => leaf.insert(key, value),
285 None => {
286 self.leaves.insert(leaf_index.value(), SmtLeaf::Single((key, value)));
287
288 None
289 },
290 }
291 }
292
293 /// Removes key-value pair at leaf index pointed to by `key` if it exists.
294 fn perform_remove(&mut self, key: RpoDigest) -> Option<Word> {
295 let leaf_index: LeafIndex<SMT_DEPTH> = Self::key_to_leaf_index(&key);
296
297 if let Some(leaf) = self.leaves.get_mut(&leaf_index.value()) {
298 let (old_value, is_empty) = leaf.remove(key);
299 if is_empty {
300 self.leaves.remove(&leaf_index.value());
301 }
302 old_value
303 } else {
304 // there's nothing stored at the leaf; nothing to update
305 None
306 }
307 }
308}
309
310impl SparseMerkleTree<SMT_DEPTH> for Smt {
311 type Key = RpoDigest;
312 type Value = Word;
313 type Leaf = SmtLeaf;
314 type Opening = SmtProof;
315
316 const EMPTY_VALUE: Self::Value = EMPTY_WORD;
317 const EMPTY_ROOT: RpoDigest = *EmptySubtreeRoots::entry(SMT_DEPTH, 0);
318
319 fn from_raw_parts(
320 inner_nodes: BTreeMap<NodeIndex, InnerNode>,
321 leaves: BTreeMap<u64, SmtLeaf>,
322 root: RpoDigest,
323 ) -> Result<Self, MerkleError> {
324 if cfg!(debug_assertions) {
325 let root_node = inner_nodes.get(&NodeIndex::root()).unwrap();
326 assert_eq!(root_node.hash(), root);
327 }
328
329 Ok(Self { root, inner_nodes, leaves })
330 }
331
332 fn root(&self) -> RpoDigest {
333 self.root
334 }
335
336 fn set_root(&mut self, root: RpoDigest) {
337 self.root = root;
338 }
339
340 fn get_inner_node(&self, index: NodeIndex) -> InnerNode {
341 self.inner_nodes
342 .get(&index)
343 .cloned()
344 .unwrap_or_else(|| EmptySubtreeRoots::get_inner_node(SMT_DEPTH, index.depth()))
345 }
346
347 fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode) {
348 self.inner_nodes.insert(index, inner_node);
349 }
350
351 fn remove_inner_node(&mut self, index: NodeIndex) {
352 let _ = self.inner_nodes.remove(&index);
353 }
354
355 fn insert_value(&mut self, key: Self::Key, value: Self::Value) -> Option<Self::Value> {
356 // inserting an `EMPTY_VALUE` is equivalent to removing any value associated with `key`
357 if value != Self::EMPTY_VALUE {
358 self.perform_insert(key, value)
359 } else {
360 self.perform_remove(key)
361 }
362 }
363
364 fn get_value(&self, key: &Self::Key) -> Self::Value {
365 let leaf_pos = LeafIndex::<SMT_DEPTH>::from(*key).value();
366
367 match self.leaves.get(&leaf_pos) {
368 Some(leaf) => leaf.get_value(key).unwrap_or_default(),
369 None => EMPTY_WORD,
370 }
371 }
372
373 fn get_leaf(&self, key: &RpoDigest) -> Self::Leaf {
374 let leaf_pos = LeafIndex::<SMT_DEPTH>::from(*key).value();
375
376 match self.leaves.get(&leaf_pos) {
377 Some(leaf) => leaf.clone(),
378 None => SmtLeaf::new_empty(key.into()),
379 }
380 }
381
382 fn hash_leaf(leaf: &Self::Leaf) -> RpoDigest {
383 leaf.hash()
384 }
385
386 fn construct_prospective_leaf(
387 &self,
388 mut existing_leaf: SmtLeaf,
389 key: &RpoDigest,
390 value: &Word,
391 ) -> SmtLeaf {
392 debug_assert_eq!(existing_leaf.index(), Self::key_to_leaf_index(key));
393
394 match existing_leaf {
395 SmtLeaf::Empty(_) => SmtLeaf::new_single(*key, *value),
396 _ => {
397 if *value != EMPTY_WORD {
398 existing_leaf.insert(*key, *value);
399 } else {
400 existing_leaf.remove(*key);
401 }
402
403 existing_leaf
404 },
405 }
406 }
407
408 fn key_to_leaf_index(key: &RpoDigest) -> LeafIndex<SMT_DEPTH> {
409 let most_significant_felt = key[3];
410 LeafIndex::new_max_depth(most_significant_felt.as_int())
411 }
412
413 fn path_and_leaf_to_opening(path: MerklePath, leaf: SmtLeaf) -> SmtProof {
414 SmtProof::new_unchecked(path, leaf)
415 }
416
417 fn pairs_to_leaf(mut pairs: Vec<(RpoDigest, Word)>) -> SmtLeaf {
418 assert!(!pairs.is_empty());
419
420 if pairs.len() > 1 {
421 SmtLeaf::new_multiple(pairs).unwrap()
422 } else {
423 let (key, value) = pairs.pop().unwrap();
424 // TODO: should we ever be constructing empty leaves from pairs?
425 if value == Self::EMPTY_VALUE {
426 let index = Self::key_to_leaf_index(&key);
427 SmtLeaf::new_empty(index)
428 } else {
429 SmtLeaf::new_single(key, value)
430 }
431 }
432 }
433}
434
435impl Default for Smt {
436 fn default() -> Self {
437 Self::new()
438 }
439}
440
441// CONVERSIONS
442// ================================================================================================
443
444impl From<Word> for LeafIndex<SMT_DEPTH> {
445 fn from(value: Word) -> Self {
446 // We use the most significant `Felt` of a `Word` as the leaf index.
447 Self::new_max_depth(value[3].as_int())
448 }
449}
450
451impl From<RpoDigest> for LeafIndex<SMT_DEPTH> {
452 fn from(value: RpoDigest) -> Self {
453 Word::from(value).into()
454 }
455}
456
457impl From<&RpoDigest> for LeafIndex<SMT_DEPTH> {
458 fn from(value: &RpoDigest) -> Self {
459 Word::from(value).into()
460 }
461}
462
463// SERIALIZATION
464// ================================================================================================
465
466impl Serializable for Smt {
467 fn write_into<W: ByteWriter>(&self, target: &mut W) {
468 // Write the number of filled leaves for this Smt
469 target.write_usize(self.entries().count());
470
471 // Write each (key, value) pair
472 for (key, value) in self.entries() {
473 target.write(key);
474 target.write(value);
475 }
476 }
477
478 fn get_size_hint(&self) -> usize {
479 let entries_count = self.entries().count();
480
481 // Each entry is the size of a digest plus a word.
482 entries_count.get_size_hint()
483 + entries_count * (RpoDigest::SERIALIZED_SIZE + EMPTY_WORD.get_size_hint())
484 }
485}
486
487impl Deserializable for Smt {
488 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
489 // Read the number of filled leaves for this Smt
490 let num_filled_leaves = source.read_usize()?;
491 let mut entries = Vec::with_capacity(num_filled_leaves);
492
493 for _ in 0..num_filled_leaves {
494 let key = source.read()?;
495 let value = source.read()?;
496 entries.push((key, value));
497 }
498
499 Self::with_entries(entries)
500 .map_err(|err| DeserializationError::InvalidValue(err.to_string()))
501 }
502}
503
504#[test]
505fn test_smt_serialization_deserialization() {
506 // Smt for default types (empty map)
507 let smt_default = Smt::default();
508 let bytes = smt_default.to_bytes();
509 assert_eq!(smt_default, Smt::read_from_bytes(&bytes).unwrap());
510 assert_eq!(bytes.len(), smt_default.get_size_hint());
511
512 // Smt with values
513 let smt_leaves_2: [(RpoDigest, Word); 2] = [
514 (
515 RpoDigest::new([Felt::new(101), Felt::new(102), Felt::new(103), Felt::new(104)]),
516 [Felt::new(1_u64), Felt::new(2_u64), Felt::new(3_u64), Felt::new(4_u64)],
517 ),
518 (
519 RpoDigest::new([Felt::new(105), Felt::new(106), Felt::new(107), Felt::new(108)]),
520 [Felt::new(5_u64), Felt::new(6_u64), Felt::new(7_u64), Felt::new(8_u64)],
521 ),
522 ];
523 let smt = Smt::with_entries(smt_leaves_2).unwrap();
524
525 let bytes = smt.to_bytes();
526 assert_eq!(smt, Smt::read_from_bytes(&bytes).unwrap());
527 assert_eq!(bytes.len(), smt.get_size_hint());
528}