miden_crypto/merkle/smt/mod.rs
1//! Sparse Merkle Tree (SMT) data structures.
2
3use alloc::vec::Vec;
4use core::{
5 fmt::{self, Display},
6 hash::Hash,
7};
8
9use super::{EmptySubtreeRoots, InnerNodeInfo, MerkleError, NodeIndex, SparseMerklePath};
10use crate::{
11 EMPTY_WORD, Map, Word,
12 hash::rpo::Rpo256,
13 utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable},
14};
15
16mod full;
17pub use full::{MAX_LEAF_ENTRIES, SMT_DEPTH, Smt, SmtLeaf, SmtLeafError, SmtProof, SmtProofError};
18
19#[cfg(feature = "concurrent")]
20mod large;
21#[cfg(feature = "internal")]
22pub use full::concurrent::{SubtreeLeaf, build_subtree_for_bench};
23#[cfg(feature = "concurrent")]
24pub use large::{
25 LargeSmt, LargeSmtError, MemoryStorage, SmtStorage, StorageUpdateParts, StorageUpdates,
26 Subtree, SubtreeError,
27};
28#[cfg(feature = "rocksdb")]
29pub use large::{RocksDbConfig, RocksDbStorage};
30
31mod large_forest;
32pub use large_forest::{
33 Backend, BackendError, ForestOperation, LargeSmtForest, LargeSmtForestError, RootInfo,
34 SmtForestUpdateBatch, SmtUpdateBatch,
35};
36
37mod simple;
38pub use simple::{SimpleSmt, SimpleSmtProof};
39
40mod partial;
41pub use partial::PartialSmt;
42
43mod forest;
44pub use forest::SmtForest;
45
46// CONSTANTS
47// ================================================================================================
48
49/// Minimum supported depth.
50pub const SMT_MIN_DEPTH: u8 = 1;
51
52/// Maximum supported depth.
53pub const SMT_MAX_DEPTH: u8 = 64;
54
55// SPARSE MERKLE TREE
56// ================================================================================================
57
58type InnerNodes = Map<NodeIndex, InnerNode>;
59type Leaves<T> = Map<u64, T>;
60type NodeMutations = Map<NodeIndex, NodeMutation>;
61
62/// An abstract description of a sparse Merkle tree.
63///
64/// A sparse Merkle tree is a key-value map which also supports proving that a given value is indeed
65/// stored at a given key in the tree. It is viewed as always being fully populated. If a leaf's
66/// value was not explicitly set, then its value is the default value. Typically, the vast majority
67/// of leaves will store the default value (hence it is "sparse"), and therefore the internal
68/// representation of the tree will only keep track of the leaves that have a different value from
69/// the default.
70///
71/// All leaves sit at the same depth. The deeper the tree, the more leaves it has; but also the
72/// longer its proofs are - of exactly `log(depth)` size. A tree cannot have depth 0, since such a
73/// tree is just a single value, and is probably a programming mistake.
74///
75/// Every key maps to one leaf. If there are as many keys as there are leaves, then
76/// [Self::Leaf] should be the same type as [Self::Value], as is the case with
77/// [crate::merkle::SimpleSmt]. However, if there are more keys than leaves, then [`Self::Leaf`]
78/// must accommodate all keys that map to the same leaf.
79///
80/// [SparseMerkleTree] currently doesn't support optimizations that compress Merkle proofs.
81pub(crate) trait SparseMerkleTree<const DEPTH: u8> {
82 /// The type for a key
83 type Key: Clone + Ord + Eq + Hash;
84 /// The type for a value
85 type Value: Clone + PartialEq;
86 /// The type for a leaf
87 type Leaf: Clone;
88 /// The type for an opening (i.e. a "proof") of a leaf
89 type Opening;
90
91 /// The default value used to compute the hash of empty leaves
92 const EMPTY_VALUE: Self::Value;
93
94 /// The root of the empty tree with provided DEPTH
95 const EMPTY_ROOT: Word;
96
97 // PROVIDED METHODS
98 // ---------------------------------------------------------------------------------------------
99
100 /// Returns a [SparseMerklePath] to the specified key.
101 ///
102 /// Mostly this is an implementation detail of [`Self::open()`].
103 fn get_path(&self, key: &Self::Key) -> SparseMerklePath {
104 let index = NodeIndex::from(Self::key_to_leaf_index(key));
105
106 // SAFETY: this is guaranteed to have depth <= SMT_MAX_DEPTH
107 SparseMerklePath::from_sized_iter(
108 index.proof_indices().map(|index| self.get_node_hash(index)),
109 )
110 .expect("failed to convert to SparseMerklePath")
111 }
112
113 /// Get the hash of a node at an arbitrary index, including the root or leaf hashes.
114 ///
115 /// The root index simply returns [`Self::root()`]. Other hashes are retrieved by calling
116 /// [`Self::get_inner_node()`] on the parent, and returning the respective child hash.
117 fn get_node_hash(&self, index: NodeIndex) -> Word {
118 if index.is_root() {
119 return self.root();
120 }
121
122 let InnerNode { left, right } = self.get_inner_node(index.parent());
123
124 let index_is_right = index.is_value_odd();
125 if index_is_right { right } else { left }
126 }
127
128 /// Returns an opening of the leaf associated with `key`. Conceptually, an opening is a sparse
129 /// Merkle path to the leaf, as well as the leaf itself.
130 fn open(&self, key: &Self::Key) -> Self::Opening {
131 let leaf = self.get_leaf(key);
132 let merkle_path = self.get_path(key);
133
134 Self::path_and_leaf_to_opening(merkle_path, leaf)
135 }
136
137 /// Inserts a value at the specified key, returning the previous value associated with that key.
138 /// Recall that by definition, any key that hasn't been updated is associated with
139 /// [`Self::EMPTY_VALUE`].
140 ///
141 /// This also recomputes all hashes between the leaf (associated with the key) and the root,
142 /// updating the root itself.
143 fn insert(&mut self, key: Self::Key, value: Self::Value) -> Result<Self::Value, MerkleError> {
144 let old_value = self.insert_value(key.clone(), value.clone())?.unwrap_or(Self::EMPTY_VALUE);
145
146 // if the old value and new value are the same, there is nothing to update
147 if value == old_value {
148 return Ok(value);
149 }
150
151 let leaf = self.get_leaf(&key);
152 let node_index = {
153 let leaf_index: LeafIndex<DEPTH> = Self::key_to_leaf_index(&key);
154 leaf_index.into()
155 };
156
157 self.recompute_nodes_from_index_to_root(node_index, Self::hash_leaf(&leaf));
158
159 Ok(old_value)
160 }
161
162 /// Recomputes the branch nodes (including the root) from `index` all the way to the root.
163 /// `node_hash_at_index` is the hash of the node stored at index.
164 fn recompute_nodes_from_index_to_root(
165 &mut self,
166 mut index: NodeIndex,
167 node_hash_at_index: Word,
168 ) {
169 let mut node_hash = node_hash_at_index;
170 for node_depth in (0..index.depth()).rev() {
171 let is_right = index.is_value_odd();
172 index.move_up();
173 let InnerNode { left, right } = self.get_inner_node(index);
174 let (left, right) = if is_right {
175 (left, node_hash)
176 } else {
177 (node_hash, right)
178 };
179 node_hash = Rpo256::merge(&[left, right]);
180
181 if node_hash == *EmptySubtreeRoots::entry(DEPTH, node_depth) {
182 // If a subtree is empty, then can remove the inner node, since it's equal to the
183 // default value
184 self.remove_inner_node(index);
185 } else {
186 self.insert_inner_node(index, InnerNode { left, right });
187 }
188 }
189 self.set_root(node_hash);
190 }
191
192 /// Computes what changes are necessary to insert the specified key-value pairs into this Merkle
193 /// tree, allowing for validation before applying those changes.
194 ///
195 /// This method returns a [`MutationSet`], which contains all the information for inserting
196 /// `kv_pairs` into this Merkle tree already calculated, including the new root hash, which can
197 /// be queried with [`MutationSet::root()`]. Once a mutation set is returned,
198 /// [`SparseMerkleTree::apply_mutations()`] can be called in order to commit these changes to
199 /// the Merkle tree, or [`drop()`] to discard them.
200 ///
201 /// # Errors
202 /// If mutations would exceed [`MAX_LEAF_ENTRIES`] (1024 entries) in a leaf, returns
203 /// [`MerkleError::TooManyLeafEntries`].
204 fn compute_mutations(
205 &self,
206 kv_pairs: impl IntoIterator<Item = (Self::Key, Self::Value)>,
207 ) -> Result<MutationSet<DEPTH, Self::Key, Self::Value>, MerkleError> {
208 self.compute_mutations_sequential(kv_pairs)
209 }
210
211 /// Sequential version of [`SparseMerkleTree::compute_mutations()`].
212 /// This is the default implementation.
213 fn compute_mutations_sequential(
214 &self,
215 kv_pairs: impl IntoIterator<Item = (Self::Key, Self::Value)>,
216 ) -> Result<MutationSet<DEPTH, Self::Key, Self::Value>, MerkleError> {
217 use NodeMutation::*;
218
219 let mut new_root = self.root();
220 let mut new_pairs: Map<Self::Key, Self::Value> = Default::default();
221 let mut node_mutations: NodeMutations = Default::default();
222
223 for (key, value) in kv_pairs {
224 // If the old value and the new value are the same, there is nothing to update.
225 // For the unusual case that kv_pairs has multiple values at the same key, we'll have
226 // to check the key-value pairs we've already seen to get the "effective" old value.
227 let old_value = new_pairs.get(&key).cloned().unwrap_or_else(|| self.get_value(&key));
228 if value == old_value {
229 continue;
230 }
231
232 let leaf_index = Self::key_to_leaf_index(&key);
233 let mut node_index = NodeIndex::from(leaf_index);
234
235 // We need the current leaf's hash to calculate the new leaf, but in the rare case that
236 // `kv_pairs` has multiple pairs that go into the same leaf, then those pairs are also
237 // part of the "current leaf".
238 let old_leaf = {
239 let pairs_at_index = new_pairs
240 .iter()
241 .filter(|&(new_key, _)| Self::key_to_leaf_index(new_key) == leaf_index);
242
243 pairs_at_index.fold(self.get_leaf(&key), |acc, (k, v)| {
244 // Most of the time `pairs_at_index` should only contain a single entry (or
245 // none at all), as multi-leaves should be really rare.
246 let existing_leaf = acc.clone();
247 self.construct_prospective_leaf(existing_leaf, k, v)
248 .expect("current leaf should be valid")
249 })
250 };
251
252 let new_leaf =
253 self.construct_prospective_leaf(old_leaf, &key, &value).map_err(|e| match e {
254 SmtLeafError::TooManyLeafEntries { actual } => {
255 MerkleError::TooManyLeafEntries { actual }
256 },
257 other => panic!("unexpected SmtLeaf::insert error: {:?}", other),
258 })?;
259
260 let mut new_child_hash = Self::hash_leaf(&new_leaf);
261
262 for node_depth in (0..node_index.depth()).rev() {
263 // Whether the node we're replacing is the right child or the left child.
264 let is_right = node_index.is_value_odd();
265 node_index.move_up();
266
267 let old_node = node_mutations
268 .get(&node_index)
269 .map(|mutation| match mutation {
270 Addition(node) => node.clone(),
271 Removal => EmptySubtreeRoots::get_inner_node(DEPTH, node_depth),
272 })
273 .unwrap_or_else(|| self.get_inner_node(node_index));
274
275 let new_node = if is_right {
276 InnerNode {
277 left: old_node.left,
278 right: new_child_hash,
279 }
280 } else {
281 InnerNode {
282 left: new_child_hash,
283 right: old_node.right,
284 }
285 };
286
287 // The next iteration will operate on this new node's hash.
288 new_child_hash = new_node.hash();
289
290 let &equivalent_empty_hash = EmptySubtreeRoots::entry(DEPTH, node_depth);
291 let is_removal = new_child_hash == equivalent_empty_hash;
292 let new_entry = if is_removal { Removal } else { Addition(new_node) };
293 node_mutations.insert(node_index, new_entry);
294 }
295
296 // Once we're at depth 0, the last node we made is the new root.
297 new_root = new_child_hash;
298 // And then we're done with this pair; on to the next one.
299 new_pairs.insert(key, value);
300 }
301
302 Ok(MutationSet {
303 old_root: self.root(),
304 new_root,
305 node_mutations,
306 new_pairs,
307 })
308 }
309
310 /// Applies the prospective mutations computed with [`SparseMerkleTree::compute_mutations()`] to
311 /// this tree.
312 ///
313 /// # Errors
314 /// If `mutations` was computed on a tree with a different root than this one, returns
315 /// [`MerkleError::ConflictingRoots`] with a two-item [`Vec`]. The first item is the root hash
316 /// the `mutations` were computed against, and the second item is the actual current root of
317 /// this tree.
318 /// If mutations would exceed [`MAX_LEAF_ENTRIES`] (1024 entries) in a leaf, returns
319 /// [`MerkleError::TooManyLeafEntries`].
320 fn apply_mutations(
321 &mut self,
322 mutations: MutationSet<DEPTH, Self::Key, Self::Value>,
323 ) -> Result<(), MerkleError>
324 where
325 Self: Sized,
326 {
327 use NodeMutation::*;
328 let MutationSet {
329 old_root,
330 node_mutations,
331 new_pairs,
332 new_root,
333 } = mutations;
334
335 // Guard against accidentally trying to apply mutations that were computed against a
336 // different tree, including a stale version of this tree.
337 if old_root != self.root() {
338 return Err(MerkleError::ConflictingRoots {
339 expected_root: self.root(),
340 actual_root: old_root,
341 });
342 }
343
344 for (index, mutation) in node_mutations {
345 match mutation {
346 Removal => {
347 self.remove_inner_node(index);
348 },
349 Addition(node) => {
350 self.insert_inner_node(index, node);
351 },
352 }
353 }
354
355 for (key, value) in new_pairs {
356 self.insert_value(key, value)?;
357 }
358
359 self.set_root(new_root);
360
361 Ok(())
362 }
363
364 /// Applies the prospective mutations computed with [`SparseMerkleTree::compute_mutations()`] to
365 /// this tree and returns the reverse mutation set. Applying the reverse mutation sets to the
366 /// updated tree will revert the changes.
367 ///
368 /// # Errors
369 /// If `mutations` was computed on a tree with a different root than this one, returns
370 /// [`MerkleError::ConflictingRoots`] with a two-item [`Vec`]. The first item is the root hash
371 /// the `mutations` were computed against, and the second item is the actual current root of
372 /// this tree.
373 fn apply_mutations_with_reversion(
374 &mut self,
375 mutations: MutationSet<DEPTH, Self::Key, Self::Value>,
376 ) -> Result<MutationSet<DEPTH, Self::Key, Self::Value>, MerkleError>
377 where
378 Self: Sized,
379 {
380 use NodeMutation::*;
381 let MutationSet {
382 old_root,
383 node_mutations,
384 new_pairs,
385 new_root,
386 } = mutations;
387
388 // Guard against accidentally trying to apply mutations that were computed against a
389 // different tree, including a stale version of this tree.
390 if old_root != self.root() {
391 return Err(MerkleError::ConflictingRoots {
392 expected_root: self.root(),
393 actual_root: old_root,
394 });
395 }
396
397 let mut reverse_mutations = NodeMutations::new();
398 for (index, mutation) in node_mutations {
399 match mutation {
400 Removal => {
401 if let Some(node) = self.remove_inner_node(index) {
402 reverse_mutations.insert(index, Addition(node));
403 }
404 },
405 Addition(node) => {
406 if let Some(old_node) = self.insert_inner_node(index, node) {
407 reverse_mutations.insert(index, Addition(old_node));
408 } else {
409 reverse_mutations.insert(index, Removal);
410 }
411 },
412 }
413 }
414
415 let mut reverse_pairs = Map::new();
416 for (key, value) in new_pairs {
417 match self.insert_value(key.clone(), value)? {
418 Some(old_value) => {
419 reverse_pairs.insert(key, old_value);
420 },
421 None => {
422 reverse_pairs.insert(key, Self::EMPTY_VALUE);
423 },
424 }
425 }
426
427 self.set_root(new_root);
428
429 Ok(MutationSet {
430 old_root: new_root,
431 node_mutations: reverse_mutations,
432 new_pairs: reverse_pairs,
433 new_root: old_root,
434 })
435 }
436
437 // REQUIRED METHODS
438 // ---------------------------------------------------------------------------------------------
439
440 /// Construct this type from already computed leaves and nodes. The caller ensures passed
441 /// arguments are correct and consistent with each other.
442 fn from_raw_parts(
443 inner_nodes: InnerNodes,
444 leaves: Leaves<Self::Leaf>,
445 root: Word,
446 ) -> Result<Self, MerkleError>
447 where
448 Self: Sized;
449
450 /// The root of the tree
451 fn root(&self) -> Word;
452
453 /// Sets the root of the tree
454 fn set_root(&mut self, root: Word);
455
456 /// Retrieves an inner node at the given index
457 fn get_inner_node(&self, index: NodeIndex) -> InnerNode;
458
459 /// Inserts an inner node at the given index
460 fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode) -> Option<InnerNode>;
461
462 /// Removes an inner node at the given index
463 fn remove_inner_node(&mut self, index: NodeIndex) -> Option<InnerNode>;
464
465 /// Inserts a leaf node, and returns the value at the key if already exists
466 fn insert_value(
467 &mut self,
468 key: Self::Key,
469 value: Self::Value,
470 ) -> Result<Option<Self::Value>, MerkleError>;
471
472 /// Returns the value at the specified key. Recall that by definition, any key that hasn't been
473 /// updated is associated with [`Self::EMPTY_VALUE`].
474 fn get_value(&self, key: &Self::Key) -> Self::Value;
475
476 /// Returns the leaf at the specified index.
477 fn get_leaf(&self, key: &Self::Key) -> Self::Leaf;
478
479 /// Returns the hash of a leaf
480 fn hash_leaf(leaf: &Self::Leaf) -> Word;
481
482 /// Returns what a leaf would look like if a key-value pair were inserted into the tree, without
483 /// mutating the tree itself. The existing leaf can be empty.
484 ///
485 /// To get a prospective leaf based on the current state of the tree, use `self.get_leaf(key)`
486 /// as the argument for `existing_leaf`. The return value from this function can be chained back
487 /// into this function as the first argument to continue making prospective changes.
488 ///
489 /// # Invariants
490 /// Because this method is for a prospective key-value insertion into a specific leaf,
491 /// `existing_leaf` must have the same leaf index as `key` (as determined by
492 /// [`SparseMerkleTree::key_to_leaf_index()`]), or the result will be meaningless.
493 ///
494 /// # Errors
495 /// If inserting the key-value pair would exceed [`MAX_LEAF_ENTRIES`] (1024 entries) in a leaf,
496 /// returns [`SmtLeafError::TooManyLeafEntries`].
497 fn construct_prospective_leaf(
498 &self,
499 existing_leaf: Self::Leaf,
500 key: &Self::Key,
501 value: &Self::Value,
502 ) -> Result<Self::Leaf, SmtLeafError>;
503
504 /// Maps a key to a leaf index
505 fn key_to_leaf_index(key: &Self::Key) -> LeafIndex<DEPTH>;
506
507 /// Maps a (SparseMerklePath, Self::Leaf) to an opening.
508 ///
509 /// The length `path` is guaranteed to be equal to `DEPTH`
510 fn path_and_leaf_to_opening(path: SparseMerklePath, leaf: Self::Leaf) -> Self::Opening;
511}
512
513// INNER NODE
514// ================================================================================================
515
516/// This struct is public so functions returning it can be used in `benches/`, but is otherwise not
517/// part of the public API.
518#[doc(hidden)]
519#[derive(Debug, Default, Clone, PartialEq, Eq)]
520#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
521pub struct InnerNode {
522 pub left: Word,
523 pub right: Word,
524}
525
526impl InnerNode {
527 pub fn hash(&self) -> Word {
528 Rpo256::merge(&[self.left, self.right])
529 }
530}
531
532// LEAF INDEX
533// ================================================================================================
534
535/// The index of a leaf, at a depth known at compile-time.
536#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
537#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
538pub struct LeafIndex<const DEPTH: u8> {
539 index: NodeIndex,
540}
541
542impl<const DEPTH: u8> LeafIndex<DEPTH> {
543 /// Creates a new `LeafIndex` with the specified value.
544 ///
545 /// # Errors
546 ///
547 /// Returns an error if the provided depth is less than the minimum supported depth.
548 pub fn new(value: u64) -> Result<Self, MerkleError> {
549 if DEPTH < SMT_MIN_DEPTH {
550 return Err(MerkleError::DepthTooSmall(DEPTH));
551 }
552
553 Ok(LeafIndex { index: NodeIndex::new(DEPTH, value)? })
554 }
555
556 /// Returns the numeric value of this leaf index.
557 pub fn value(&self) -> u64 {
558 self.index.value()
559 }
560}
561
562impl LeafIndex<SMT_MAX_DEPTH> {
563 /// Creates a new `LeafIndex` at the maximum supported depth without validation.
564 pub const fn new_max_depth(value: u64) -> Self {
565 LeafIndex {
566 index: NodeIndex::new_unchecked(SMT_MAX_DEPTH, value),
567 }
568 }
569}
570
571impl<const DEPTH: u8> From<LeafIndex<DEPTH>> for NodeIndex {
572 fn from(value: LeafIndex<DEPTH>) -> Self {
573 value.index
574 }
575}
576
577impl<const DEPTH: u8> TryFrom<NodeIndex> for LeafIndex<DEPTH> {
578 type Error = MerkleError;
579
580 fn try_from(node_index: NodeIndex) -> Result<Self, Self::Error> {
581 if node_index.depth() != DEPTH {
582 return Err(MerkleError::InvalidNodeIndexDepth {
583 expected: DEPTH,
584 provided: node_index.depth(),
585 });
586 }
587
588 Self::new(node_index.value())
589 }
590}
591
592impl<const DEPTH: u8> Serializable for LeafIndex<DEPTH> {
593 fn write_into<W: ByteWriter>(&self, target: &mut W) {
594 self.index.write_into(target);
595 }
596}
597
598impl<const DEPTH: u8> Deserializable for LeafIndex<DEPTH> {
599 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
600 Ok(Self { index: source.read()? })
601 }
602}
603
604impl<const DEPTH: u8> Display for LeafIndex<DEPTH> {
605 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
606 write!(f, "DEPTH={}, value={}", DEPTH, self.value())
607 }
608}
609
610// MUTATIONS
611// ================================================================================================
612
613/// A change to an inner node of a sparse Merkle tree that hasn't yet been applied.
614/// [`MutationSet`] stores this type in relation to a [`NodeIndex`] to keep track of what changes
615/// need to occur at which node indices.
616#[derive(Debug, Clone, PartialEq, Eq)]
617pub enum NodeMutation {
618 /// Node needs to be removed.
619 Removal,
620 /// Node needs to be inserted.
621 Addition(InnerNode),
622}
623
624/// Represents a group of prospective mutations to a `SparseMerkleTree`, created by
625/// `SparseMerkleTree::compute_mutations()`, and that can be applied with
626/// `SparseMerkleTree::apply_mutations()`.
627#[derive(Debug, Clone, Default, PartialEq, Eq)]
628pub struct MutationSet<const DEPTH: u8, K: Eq + Hash, V> {
629 /// The root of the Merkle tree this MutationSet is for, recorded at the time
630 /// [`SparseMerkleTree::compute_mutations()`] was called. Exists to guard against applying
631 /// mutations to the wrong tree or applying stale mutations to a tree that has since changed.
632 old_root: Word,
633 /// The set of nodes that need to be removed or added. The "effective" node at an index is the
634 /// Merkle tree's existing node at that index, with the [`NodeMutation`] in this map at that
635 /// index overlaid, if any. Each [`NodeMutation::Addition`] corresponds to a
636 /// [`SparseMerkleTree::insert_inner_node()`] call, and each [`NodeMutation::Removal`]
637 /// corresponds to a [`SparseMerkleTree::remove_inner_node()`] call.
638 node_mutations: NodeMutations,
639 /// The set of top-level key-value pairs we're prospectively adding to the tree, including
640 /// adding empty values. The "effective" value for a key is the value in this Map, falling
641 /// back to the existing value in the Merkle tree. Each entry corresponds to a
642 /// [`SparseMerkleTree::insert_value()`] call.
643 new_pairs: Map<K, V>,
644 /// The calculated root for the Merkle tree, given these mutations. Publicly retrievable with
645 /// [`MutationSet::root()`]. Corresponds to a [`SparseMerkleTree::set_root()`]. call.
646 new_root: Word,
647}
648
649impl<const DEPTH: u8, K: Eq + Hash, V> MutationSet<DEPTH, K, V> {
650 /// Returns the SMT root that was calculated during `SparseMerkleTree::compute_mutations()`. See
651 /// that method for more information.
652 pub fn root(&self) -> Word {
653 self.new_root
654 }
655
656 /// Returns the SMT root before the mutations were applied.
657 pub fn old_root(&self) -> Word {
658 self.old_root
659 }
660
661 /// Returns the set of inner nodes that need to be removed or added.
662 pub fn node_mutations(&self) -> &NodeMutations {
663 &self.node_mutations
664 }
665
666 /// Returns the set of top-level key-value pairs that need to be added, updated or deleted
667 /// (i.e. set to `EMPTY_WORD`).
668 pub fn new_pairs(&self) -> &Map<K, V> {
669 &self.new_pairs
670 }
671}
672
673// SERIALIZATION
674// ================================================================================================
675
676impl Serializable for InnerNode {
677 fn write_into<W: ByteWriter>(&self, target: &mut W) {
678 target.write(self.left);
679 target.write(self.right);
680 }
681}
682
683impl Deserializable for InnerNode {
684 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
685 let left = source.read()?;
686 let right = source.read()?;
687
688 Ok(Self { left, right })
689 }
690}
691
692impl Serializable for NodeMutation {
693 fn write_into<W: ByteWriter>(&self, target: &mut W) {
694 match self {
695 NodeMutation::Removal => target.write_bool(false),
696 NodeMutation::Addition(inner_node) => {
697 target.write_bool(true);
698 inner_node.write_into(target);
699 },
700 }
701 }
702}
703
704impl Deserializable for NodeMutation {
705 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
706 if source.read_bool()? {
707 let inner_node = source.read()?;
708 return Ok(NodeMutation::Addition(inner_node));
709 }
710
711 Ok(NodeMutation::Removal)
712 }
713}
714
715impl<const DEPTH: u8, K: Serializable + Eq + Hash, V: Serializable> Serializable
716 for MutationSet<DEPTH, K, V>
717{
718 fn write_into<W: ByteWriter>(&self, target: &mut W) {
719 target.write(self.old_root);
720 target.write(self.new_root);
721
722 let inner_removals: Vec<_> = self
723 .node_mutations
724 .iter()
725 .filter(|(_, value)| matches!(value, NodeMutation::Removal))
726 .map(|(key, _)| key)
727 .collect();
728 let inner_additions: Vec<_> = self
729 .node_mutations
730 .iter()
731 .filter_map(|(key, value)| match value {
732 NodeMutation::Addition(node) => Some((key, node)),
733 _ => None,
734 })
735 .collect();
736
737 target.write(inner_removals);
738 target.write(inner_additions);
739
740 target.write_usize(self.new_pairs.len());
741 target.write_many(&self.new_pairs);
742 }
743}
744
745impl<const DEPTH: u8, K: Deserializable + Ord + Eq + Hash, V: Deserializable> Deserializable
746 for MutationSet<DEPTH, K, V>
747{
748 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
749 let old_root = source.read()?;
750 let new_root = source.read()?;
751
752 let inner_removals: Vec<NodeIndex> = source.read()?;
753 let inner_additions: Vec<(NodeIndex, InnerNode)> = source.read()?;
754
755 let node_mutations = NodeMutations::from_iter(
756 inner_removals.into_iter().map(|index| (index, NodeMutation::Removal)).chain(
757 inner_additions
758 .into_iter()
759 .map(|(index, node)| (index, NodeMutation::Addition(node))),
760 ),
761 );
762
763 let num_new_pairs = source.read_usize()?;
764 let new_pairs: Map<_, _> =
765 source.read_many_iter(num_new_pairs)?.collect::<Result<_, _>>()?;
766
767 Ok(Self {
768 old_root,
769 node_mutations,
770 new_pairs,
771 new_root,
772 })
773 }
774}