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