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