miden_crypto/merkle/smt/
mod.rs

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