miden_crypto/merkle/smt/partial/mod.rs
1use alloc::{
2 collections::{BTreeMap, BTreeSet, VecDeque},
3 string::ToString,
4 vec::Vec,
5};
6
7use super::{EmptySubtreeRoots, LeafIndex, SMT_DEPTH};
8use crate::{
9 EMPTY_WORD, Map, Word,
10 merkle::{
11 InnerNodeInfo, MerkleError, NodeIndex, SparseMerklePath,
12 smt::{InnerNode, InnerNodes, Leaves, SmtLeaf, SmtLeafError, SmtProof},
13 },
14 utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable},
15};
16
17mod serialization;
18#[cfg(test)]
19mod tests;
20
21pub use serialization::UniqueNodes;
22
23/// Complete inner nodes on a path from a leaf to the root, ordered leaf-to-root.
24type PathNodes = [InnerNode; SMT_DEPTH as usize];
25
26/// A partial version of an [`super::Smt`].
27///
28/// This type can track a subset of the key-value pairs of a full [`super::Smt`] and allows for
29/// updating those pairs to compute the new root of the tree, as if the updates had been done on the
30/// full tree. This is useful so that not all leaves have to be present and loaded into memory to
31/// compute an update.
32///
33/// A key is considered "tracked" if either:
34/// 1. Its merkle path was explicitly added to the tree (via [`PartialSmt::add_path`] or
35/// [`PartialSmt::add_proof`]), or
36/// 2. The path from the leaf to the root goes through empty subtrees that are consistent with the
37/// stored inner nodes (provably empty with zero hash computations).
38///
39/// The second condition allows updating keys in empty subtrees without explicitly adding their
40/// merkle paths. This is verified by walking up from the leaf and checking that any stored
41/// inner node has an empty subtree root as the child on our path.
42///
43/// An important caveat is that only tracked keys can be updated. Attempting to update an
44/// untracked key will result in an error. See [`PartialSmt::insert`] for more details.
45///
46/// Once a partial SMT has been constructed, its root is set in stone. All subsequently added proofs
47/// or merkle paths must match that root, otherwise an error is returned.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct PartialSmt {
50 root: Word,
51 num_entries: usize,
52 leaves: Leaves<SmtLeaf>,
53 inner_nodes: InnerNodes,
54}
55
56impl PartialSmt {
57 // CONSTANTS
58 // --------------------------------------------------------------------------------------------
59
60 /// The default value used to compute the hash of empty leaves.
61 pub const EMPTY_VALUE: Word = EMPTY_WORD;
62
63 /// The root of an empty tree.
64 pub const EMPTY_ROOT: Word = *EmptySubtreeRoots::entry(SMT_DEPTH, 0);
65
66 // CONSTRUCTORS
67 // --------------------------------------------------------------------------------------------
68
69 /// Constructs a [`PartialSmt`] from a root.
70 ///
71 /// All subsequently added proofs or paths must have the same root.
72 pub fn new(root: Word) -> Self {
73 Self {
74 root,
75 num_entries: 0,
76 leaves: Leaves::<SmtLeaf>::default(),
77 inner_nodes: InnerNodes::default(),
78 }
79 }
80
81 /// Instantiates a new [`PartialSmt`] by calling [`PartialSmt::add_proof`] for all [`SmtProof`]s
82 /// in the provided iterator.
83 ///
84 /// If the provided iterator is empty, an empty [`PartialSmt`] is returned.
85 ///
86 /// # Errors
87 ///
88 /// Returns an error if:
89 /// - the roots of the provided proofs are not the same.
90 pub fn from_proofs<I>(proofs: I) -> Result<Self, MerkleError>
91 where
92 I: IntoIterator<Item = SmtProof>,
93 {
94 let mut proofs = proofs.into_iter();
95
96 let Some(first_proof) = proofs.next() else {
97 return Ok(Self::default());
98 };
99
100 // Add the first path to a fresh partial SMT. Its computed root becomes the expected root,
101 // and all subsequently added proofs must match it.
102 let (path, leaf) = first_proof.into_parts();
103 let (path_nodes, path_root) = Self::compute_path_nodes(&leaf, &path)?;
104 let mut partial_smt = Self::new(path_root);
105 partial_smt.commit_path(leaf, &path_nodes);
106
107 for proof in proofs {
108 partial_smt.add_proof(proof)?;
109 }
110
111 Ok(partial_smt)
112 }
113
114 // PUBLIC ACCESSORS
115 // --------------------------------------------------------------------------------------------
116
117 /// Returns the root of the tree.
118 pub fn root(&self) -> Word {
119 self.root
120 }
121
122 /// Returns an opening of the leaf associated with `key`. Conceptually, an opening is a Merkle
123 /// path to the leaf, as well as the leaf itself.
124 ///
125 /// # Errors
126 ///
127 /// Returns an error if:
128 /// - the key is not tracked by this partial SMT.
129 pub fn open(&self, key: &Word) -> Result<SmtProof, MerkleError> {
130 let leaf = self.get_leaf(key)?;
131 let merkle_path = self.get_path(key);
132 Ok(SmtProof::new_unchecked(merkle_path, leaf))
133 }
134
135 /// Returns the leaf to which `key` maps.
136 ///
137 /// # Errors
138 ///
139 /// Returns an error if:
140 /// - the key is not tracked by this partial SMT.
141 pub fn get_leaf(&self, key: &Word) -> Result<SmtLeaf, MerkleError> {
142 self.get_tracked_leaf(key).ok_or(MerkleError::UntrackedKey(*key))
143 }
144
145 /// Returns the value associated with `key`.
146 ///
147 /// # Errors
148 ///
149 /// Returns an error if:
150 /// - the key is not tracked by this partial SMT.
151 pub fn get_value(&self, key: &Word) -> Result<Word, MerkleError> {
152 self.get_tracked_leaf(key)
153 .map(|leaf| leaf.get_value(key).unwrap_or_default())
154 .ok_or(MerkleError::UntrackedKey(*key))
155 }
156
157 /// Returns an iterator over the inner nodes of the [`PartialSmt`].
158 pub fn inner_nodes(&self) -> impl Iterator<Item = InnerNodeInfo> + '_ {
159 self.inner_nodes.values().map(|e| InnerNodeInfo {
160 value: e.hash(),
161 left: e.left,
162 right: e.right,
163 })
164 }
165
166 /// Returns an iterator over the [`InnerNode`] and the respective [`NodeIndex`] of the
167 /// [`PartialSmt`].
168 pub fn inner_node_indices(&self) -> impl Iterator<Item = (NodeIndex, InnerNode)> + '_ {
169 self.inner_nodes.iter().map(|(idx, inner)| (*idx, inner.clone()))
170 }
171
172 /// Returns an iterator over the explicitly stored leaves of the [`PartialSmt`] in arbitrary
173 /// order.
174 ///
175 /// Note: This only returns leaves that were explicitly added via [`Self::add_path`] or
176 /// [`Self::add_proof`], or created through [`Self::insert`]. It does not include implicitly
177 /// trackable leaves in empty subtrees.
178 pub fn leaves(&self) -> impl Iterator<Item = (LeafIndex<SMT_DEPTH>, &SmtLeaf)> {
179 self.leaves
180 .iter()
181 .map(|(leaf_index, leaf)| (LeafIndex::new_max_depth(*leaf_index), leaf))
182 }
183
184 /// Returns an iterator over the tracked, non-empty key-value pairs of the [`PartialSmt`] in
185 /// arbitrary order.
186 pub fn entries(&self) -> impl Iterator<Item = &(Word, Word)> {
187 self.leaves().flat_map(|(_, leaf)| leaf.entries())
188 }
189
190 /// Returns the number of non-empty leaves in this tree.
191 ///
192 /// Note that this may return a different value from [Self::num_entries()] as a single leaf may
193 /// contain more than one key-value pair.
194 pub fn num_leaves(&self) -> usize {
195 self.leaves.len()
196 }
197
198 /// Returns the number of tracked, non-empty key-value pairs in this tree.
199 ///
200 /// Note that this may return a different value from [Self::num_leaves()] as a single leaf may
201 /// contain more than one key-value pair.
202 pub fn num_entries(&self) -> usize {
203 self.num_entries
204 }
205
206 /// Returns a boolean value indicating whether the [`PartialSmt`] tracks any leaves.
207 ///
208 /// Note that if a partial SMT does not track leaves, its root is not necessarily the empty SMT
209 /// root, since it could have been constructed from a different root but without tracking any
210 /// leaves.
211 pub fn tracks_leaves(&self) -> bool {
212 !self.leaves.is_empty()
213 }
214
215 // STATE MUTATORS
216 // --------------------------------------------------------------------------------------------
217
218 /// Inserts a value at the specified key, returning the previous value associated with that key.
219 /// Recall that by definition, any key that hasn't been updated is associated with
220 /// [`Self::EMPTY_VALUE`].
221 ///
222 /// This also recomputes all hashes between the leaf (associated with the key) and the root,
223 /// updating the root itself.
224 ///
225 /// # Errors
226 ///
227 /// Returns an error if:
228 /// - the key is not tracked (see the type documentation for the definition of "tracked"). If an
229 /// error is returned the tree is in the same state as before.
230 /// - inserting the key-value pair would exceed [`super::MAX_LEAF_ENTRIES`] (1024 entries) in
231 /// the leaf.
232 pub fn insert(&mut self, key: Word, value: Word) -> Result<Word, MerkleError> {
233 let current_leaf = self.get_tracked_leaf(&key).ok_or(MerkleError::UntrackedKey(key))?;
234 let leaf_index = current_leaf.index();
235 let previous_value = current_leaf.get_value(&key).unwrap_or(EMPTY_WORD);
236 let prev_entries = current_leaf.num_entries();
237
238 let leaf = self
239 .leaves
240 .entry(leaf_index.position())
241 .or_insert_with(|| SmtLeaf::new_empty(leaf_index));
242
243 if value != EMPTY_WORD {
244 leaf.insert(key, value).map_err(|e| match e {
245 SmtLeafError::TooManyLeafEntries { actual } => {
246 MerkleError::TooManyLeafEntries { actual }
247 },
248 other => panic!("unexpected SmtLeaf::insert error: {other:?}"),
249 })?;
250 } else {
251 leaf.remove(key);
252 }
253 let current_entries = leaf.num_entries();
254 let new_leaf_hash = leaf.hash();
255 self.num_entries = self.num_entries + current_entries - prev_entries;
256
257 // Remove empty leaf
258 if current_entries == 0 {
259 self.leaves.remove(&leaf_index.position());
260 }
261
262 // Recompute the path from leaf to root
263 self.recompute_nodes_from_leaf_to_root(leaf_index, new_leaf_hash);
264
265 Ok(previous_value)
266 }
267
268 /// Adds an [`SmtProof`] to this [`PartialSmt`].
269 ///
270 /// This is a convenience method which calls [`Self::add_path`] on the proof. See its
271 /// documentation for details on errors.
272 pub fn add_proof(&mut self, proof: SmtProof) -> Result<(), MerkleError> {
273 let (path, leaf) = proof.into_parts();
274 self.add_path(leaf, path)
275 }
276
277 /// Adds a leaf and its sparse merkle path to this [`PartialSmt`].
278 ///
279 /// If this function was called, any key that is part of the `leaf` can subsequently be updated
280 /// to a new value and produce a correct new tree root.
281 ///
282 /// # Errors
283 ///
284 /// Returns an error if:
285 /// - the path does not have [`SMT_DEPTH`] nodes.
286 /// - the new root after the insertion of the leaf and the path does not match the existing
287 /// root.
288 ///
289 /// If an error is returned, the tree is unchanged.
290 pub fn add_path(&mut self, leaf: SmtLeaf, path: SparseMerklePath) -> Result<(), MerkleError> {
291 let (path_nodes, path_root) = Self::compute_path_nodes(&leaf, &path)?;
292
293 // Check if the newly added merkle path is consistent with the existing tree. If not, the
294 // merkle path was invalid or computed against another tree. Nothing has been mutated yet.
295 if self.root != path_root {
296 return Err(MerkleError::ConflictingRoots {
297 expected_root: self.root,
298 actual_root: path_root,
299 });
300 }
301
302 self.commit_path(leaf, &path_nodes);
303 Ok(())
304 }
305
306 // UNIQUE NODES
307 // --------------------------------------------------------------------------------------------
308
309 /// Converts `self` into the [`UniqueNodes`] serialization representation for compact
310 /// serialization.
311 ///
312 /// This method assumes that the `PartialSmt` is in a valid state.
313 ///
314 /// # Reconstructable Sets
315 ///
316 /// We define the notion of a reconstructable set as one which stores the minimum amount of
317 /// information necessary in order to reconstruct the full state of the tree. We build this set
318 /// as follows:
319 ///
320 /// 1. Start at the leaves and traverse toward the root.
321 /// 2. Wherever a node's value is determined solely by children already implicitly contained
322 /// within the set, store no new information. If additional information is required (e.g. a
323 /// sibling node) store that.
324 /// 3. Repeat until the root is reached.
325 ///
326 /// To reconstruct the tree, we just start at the leaves and compute all intermediary nodes from
327 /// the data stored in the reconstructible set.
328 pub fn to_unique_nodes(&self) -> UniqueNodes {
329 // We start by getting all the known leaves, as these give us the starting point for the
330 // reconstruction.
331 let leaf_nodes = self
332 .leaves()
333 .map(|(k, v)| (k, v.clone()))
334 .collect::<Map<LeafIndex<SMT_DEPTH>, SmtLeaf>>();
335
336 // We also create storage for the nodes necessary for reconstruction of the tree...
337 let mut needed_nodes = BTreeMap::new();
338
339 // ... and grab the full set of inner nodes to work from as a queue for easy use. We sort
340 // them from the bottom of the tree to the top, but retain the standard left-to-right
341 // ordering.
342 let mut inner_nodes = self.inner_node_indices().collect::<Vec<(NodeIndex, InnerNode)>>();
343 inner_nodes.sort_by(|(il, _), (ir, _)| {
344 ir.depth().cmp(&il.depth()).then(il.position().cmp(&ir.position()))
345 });
346 let mut inner_nodes = inner_nodes.into_iter().collect::<VecDeque<(NodeIndex, InnerNode)>>();
347
348 // We also need to store the values for leaves where we ONLY have the hash value, rather
349 // than the proper leaf value.
350 let mut value_only_leaves = BTreeMap::new();
351
352 // We then need to iterate over all the nodes to work out which ones are reconstructible,
353 // and which need us to store additional data to be reconstructible.
354 while let Some((ix, v)) = inner_nodes.pop_front() {
355 // There must be data available for both of the node's children for it to be
356 // reconstructible.
357 for (child, val) in [(ix.left_child(), v.left), (ix.right_child(), v.right)] {
358 if child.depth() != SMT_DEPTH {
359 // A child of the node `v` can be in one of three states:
360 //
361 // 1. The child does not exist as a physical node in `self`, but its value as
362 // stored in `v` is real.
363 // 2. The child does not exist as a physical node in `self`, but its value is
364 // the default empty subtree root.
365 // 3. The child does exist as a physical node in `self`. By induction, as this
366 // algorithm runs bottom-up, the data to reconstruct the node already exists.
367 if self.get_inner_node(child).is_none() {
368 // In this case, the node does not exist physically, so we have to work out
369 // which of the other cases it is.
370 if val != *EmptySubtreeRoots::entry(SMT_DEPTH, child.depth())
371 && let Some(previous) = needed_nodes.insert(child, val)
372 {
373 assert_eq!(
374 previous, val,
375 "node was overwritten with a different value"
376 );
377 }
378 } else {
379 // Here, the node exists physically, so by induction, it is reconstructible.
380 }
381 } else {
382 // Here the child is a leaf node. Leaf nodes can be in one of three states:
383 //
384 // 1. A node that has the default empty value, in which case we encode it using
385 // absence in the compact representation.
386 // 2. A node that has a hash value, but that does not exist in the physical
387 // leaves in the PartialSmt. These are encoded using an auxiliary buffer to
388 // aid in reconstruction.
389 // 3. A node that exists in fully-materialized form. These are encoded with
390 // their full content.
391 //
392 // Cases 1 and 3 require no special handling here, as they are encoded with the
393 // leaves below. Case 2 needs us to take action here.
394 let empty_leaf_hash =
395 SmtLeaf::new_empty(LeafIndex::new_max_depth(child.position())).hash();
396
397 if val != empty_leaf_hash && !self.leaves.contains_key(&child.position()) {
398 // We are in case 2 here, as the value is not that of the empty leaf, nor is
399 // there a physical leaf stored in the tree for this. We store this leaf
400 // value in the auxiliary buffer so we can reconstruct correctly in this
401 // scenario.
402 value_only_leaves.insert(child.position(), val);
403 }
404 }
405 }
406 }
407
408 // With all the data gathered, we can convert our types as necessary to create our output.
409 let leaves = leaf_nodes.into_iter().map(|(i, l)| (i.position(), l)).collect();
410
411 UniqueNodes {
412 root: self.root(),
413 leaves,
414 nodes: needed_nodes,
415 value_only_leaves,
416 }
417 }
418
419 /// Constructs a new `PartialSmt` from the provided `unique_nodes`, reconstituting the full data
420 /// from the compact representation.
421 ///
422 /// This method assumes that the `unique_nodes` represent a valid `PartialSmt` instance.
423 ///
424 /// See the documentation of [`Self::to_unique_nodes`] for the reconstruction algorithm.
425 ///
426 /// # Errors
427 ///
428 /// - [`DeserializationError::InvalidValue`] if a leaf's map key does not match its embedded
429 /// index, or the reconstructed tree fails validation.
430 pub fn from_unique_nodes(unique_nodes: UniqueNodes) -> Result<Self, DeserializationError> {
431 unique_nodes.validate()?;
432
433 let mut smt = Self::new(unique_nodes.root);
434
435 // Reconstruction starts from every known leaf position. Stored internal nodes are also
436 // starting points because an exclusion proof may contain no leaf below them. Group these
437 // positions by depth so each layer can be rebuilt before its parent layer.
438 let mut active_by_depth = BTreeMap::<u8, BTreeSet<NodeIndex>>::new();
439
440 for &position in unique_nodes.leaves.keys().chain(unique_nodes.value_only_leaves.keys()) {
441 let index = NodeIndex::new(SMT_DEPTH, position)
442 .map_err(|e| DeserializationError::InvalidValue(e.to_string()))?;
443 active_by_depth.entry(SMT_DEPTH).or_default().insert(index);
444 }
445 for &index in unique_nodes.nodes.keys() {
446 active_by_depth.entry(index.depth()).or_default().insert(index);
447 }
448
449 // Rebuild the tree one layer at a time, from the deepest starting positions to the root.
450 for child_depth in (1..=SMT_DEPTH).rev() {
451 let Some(active_nodes) = active_by_depth.remove(&child_depth) else {
452 continue;
453 };
454
455 // Every active node requires its parent. The set removes shared parents before the
456 // next layer is built.
457 let parents = active_nodes.into_iter().map(NodeIndex::parent).collect::<BTreeSet<_>>();
458
459 for parent in &parents {
460 // A child is either a leaf, a node rebuilt on the prior pass, a stored sparse node,
461 // or an omitted empty subtree root. The lookup helpers handle the last two cases.
462 let [left, right] = [parent.left_child(), parent.right_child()].map(|child| {
463 if child.depth() == SMT_DEPTH {
464 unique_nodes.get_leaf_hash(child.position())
465 } else {
466 smt.get_inner_node(child)
467 .map(|node| node.hash())
468 .unwrap_or_else(|| unique_nodes.get_node_hash(child))
469 }
470 });
471 smt.insert_inner_node(*parent, InnerNode { left, right });
472 }
473
474 if child_depth > 1 {
475 // The parents become the active nodes for the next layer toward the root.
476 active_by_depth.entry(child_depth - 1).or_default().extend(parents);
477 }
478 }
479
480 for (position, leaf) in unique_nodes.leaves {
481 smt.num_entries += leaf.num_entries();
482 smt.leaves.insert(position, leaf);
483 }
484
485 smt.validate()?;
486
487 Ok(smt)
488 }
489
490 // PRIVATE HELPERS
491 // --------------------------------------------------------------------------------------------
492
493 /// Computes the complete inner nodes and the root that `leaf` and `path` imply, without
494 /// mutating `self`.
495 ///
496 /// Returns the inner nodes on the path, ordered leaf-to-root, and the resulting root. The path
497 /// must have exactly [`SMT_DEPTH`] nodes.
498 fn compute_path_nodes(
499 leaf: &SmtLeaf,
500 path: &SparseMerklePath,
501 ) -> Result<(PathNodes, Word), MerkleError> {
502 if path.depth() != SMT_DEPTH {
503 return Err(MerkleError::InvalidPathLength(SMT_DEPTH as usize));
504 }
505
506 let mut current_index = leaf.index().index;
507 let mut node_hash = leaf.hash();
508 let mut path_nodes: PathNodes = core::array::from_fn(|_| InnerNode::default());
509
510 for (path_node, sibling_hash) in path_nodes.iter_mut().zip(path.iter()) {
511 // Find the index of the sibling node and compute whether it is a left or right child.
512 let is_sibling_right = current_index.sibling().is_position_odd();
513
514 // Move the index up so it points to the parent of the current index and the sibling.
515 current_index.move_up();
516
517 // Construct the new parent node from the child that was updated and the sibling from
518 // the merkle path.
519 *path_node = if is_sibling_right {
520 InnerNode { left: node_hash, right: sibling_hash }
521 } else {
522 InnerNode { left: sibling_hash, right: node_hash }
523 };
524
525 node_hash = path_node.hash();
526 }
527
528 Ok((path_nodes, node_hash))
529 }
530
531 /// Writes a leaf and its precomputed inner nodes into the tree. Cannot fail.
532 fn commit_path(&mut self, leaf: SmtLeaf, path_nodes: &PathNodes) {
533 let mut current_index = leaf.index().index;
534
535 let prev_entries = self
536 .leaves
537 .get(¤t_index.position())
538 .map(SmtLeaf::num_entries)
539 .unwrap_or(0);
540 let current_entries = leaf.num_entries();
541 // Only store non-empty leaves
542 if current_entries > 0 {
543 self.leaves.insert(current_index.position(), leaf);
544 } else {
545 self.leaves.remove(¤t_index.position());
546 }
547
548 // Guaranteed not to over/underflow. All variables are <= MAX_LEAF_ENTRIES and result > 0.
549 self.num_entries = self.num_entries + current_entries - prev_entries;
550
551 for path_node in path_nodes.iter() {
552 // Move the index up so it points to the parent of the current index.
553 current_index.move_up();
554
555 // Insert the precomputed parent node without rebuilding it from the path.
556 self.insert_inner_node(current_index, path_node.clone());
557 }
558 }
559
560 /// Returns the leaf for a key if it can be tracked.
561 ///
562 /// A key is trackable if:
563 /// 1. It was explicitly added via `add_path`/`add_proof`, OR
564 /// 2. The path to the leaf goes through empty subtrees (provably empty)
565 ///
566 /// Returns `None` if the key cannot be tracked (path goes through non-empty
567 /// subtrees we don't have data for).
568 fn get_tracked_leaf(&self, key: &Word) -> Option<SmtLeaf> {
569 let leaf_index = Self::key_to_leaf_index(key);
570
571 // Explicitly stored leaves are always trackable
572 if let Some(leaf) = self.leaves.get(&leaf_index.position()) {
573 return Some(leaf.clone());
574 }
575
576 // Empty tree - all leaves implicitly trackable
577 if self.root == Self::EMPTY_ROOT {
578 return Some(SmtLeaf::new_empty(leaf_index));
579 }
580
581 // Walk from root down towards the leaf
582 let target: NodeIndex = leaf_index.into();
583 let mut index = NodeIndex::root();
584
585 for i in (0..SMT_DEPTH).rev() {
586 let inner_node = self.get_inner_node(index)?;
587
588 let is_right = target.is_nth_bit_odd(i);
589 let child_hash = if is_right { inner_node.right } else { inner_node.left };
590
591 // If child is empty subtree root, leaf is implicitly trackable
592 if child_hash == *EmptySubtreeRoots::entry(SMT_DEPTH, SMT_DEPTH - i) {
593 return Some(SmtLeaf::new_empty(leaf_index));
594 }
595
596 index = if is_right {
597 index.right_child()
598 } else {
599 index.left_child()
600 };
601 }
602
603 // Reached leaf level without finding empty subtree - can't track
604 None
605 }
606
607 /// Converts a key to a leaf index.
608 fn key_to_leaf_index(key: &Word) -> LeafIndex<SMT_DEPTH> {
609 let most_significant_felt = key[3];
610 LeafIndex::new_max_depth(most_significant_felt.as_canonical_u64())
611 }
612
613 /// Returns the inner node at the specified index, or `None` if not stored.
614 fn get_inner_node(&self, index: NodeIndex) -> Option<InnerNode> {
615 self.inner_nodes.get(&index).cloned()
616 }
617
618 /// Returns the inner node at the specified index, falling back to the empty subtree root
619 /// if not stored.
620 fn get_inner_node_or_empty(&self, index: NodeIndex) -> InnerNode {
621 self.get_inner_node(index)
622 .unwrap_or_else(|| EmptySubtreeRoots::get_inner_node(SMT_DEPTH, index.depth()))
623 }
624
625 /// Inserts an inner node at the specified index, or removes it if it equals the empty
626 /// subtree root.
627 fn insert_inner_node(&mut self, index: NodeIndex, inner_node: InnerNode) {
628 if inner_node == EmptySubtreeRoots::get_inner_node(SMT_DEPTH, index.depth()) {
629 self.inner_nodes.remove(&index);
630 } else {
631 self.inner_nodes.insert(index, inner_node);
632 }
633 }
634
635 /// Returns the merkle path for a key by walking up the tree from the leaf.
636 fn get_path(&self, key: &Word) -> SparseMerklePath {
637 let index = NodeIndex::from(Self::key_to_leaf_index(key));
638
639 // Use proof_indices to get sibling indices from leaf to root,
640 // and get each sibling's hash
641 SparseMerklePath::from_sized_iter(index.proof_indices().map(|idx| self.get_node_hash(idx)))
642 .expect("path should be valid since it's from a valid SMT")
643 }
644
645 /// Get the hash of a node at an arbitrary index, including the root or leaf hashes.
646 ///
647 /// The root index simply returns the root. Other hashes are retrieved by looking at
648 /// the parent inner node and returning the respective child hash.
649 fn get_node_hash(&self, index: NodeIndex) -> Word {
650 if index.is_root() {
651 return self.root;
652 }
653
654 let InnerNode { left, right } = self.get_inner_node_or_empty(index.parent());
655
656 if index.is_position_odd() { right } else { left }
657 }
658
659 /// Recomputes all inner nodes from a leaf up to the root after a leaf value change.
660 fn recompute_nodes_from_leaf_to_root(
661 &mut self,
662 leaf_index: LeafIndex<SMT_DEPTH>,
663 leaf_hash: Word,
664 ) {
665 use crate::hash::poseidon2::Poseidon2;
666
667 let mut index: NodeIndex = leaf_index.into();
668 let mut node_hash = leaf_hash;
669
670 for _ in (0..index.depth()).rev() {
671 let is_right = index.is_position_odd();
672 index.move_up();
673 let InnerNode { left, right } = self.get_inner_node_or_empty(index);
674 let (left, right) = if is_right {
675 (left, node_hash)
676 } else {
677 (node_hash, right)
678 };
679 node_hash = Poseidon2::merge(&[left, right]);
680
681 // insert_inner_node handles removing empty subtree roots
682 self.insert_inner_node(index, InnerNode { left, right });
683 }
684 self.root = node_hash;
685 }
686
687 /// Validates the internal structure during deserialization.
688 ///
689 /// Checks that:
690 /// - Each inner node's hash is consistent with its parent.
691 /// - Each leaf's hash is consistent with its parent inner node's left/right child.
692 fn validate(&self) -> Result<(), DeserializationError> {
693 // Validate each inner node is consistent with its parent
694 for (&idx, node) in &self.inner_nodes {
695 let node_hash = node.hash();
696 let expected_hash = self.get_node_hash(idx);
697
698 if node_hash != expected_hash {
699 return Err(DeserializationError::InvalidValue(
700 "inner node hash is inconsistent with parent".into(),
701 ));
702 }
703 }
704
705 // Validate each leaf's hash is consistent with its parent inner node
706 for (&leaf_pos, leaf) in &self.leaves {
707 let leaf_index = LeafIndex::<SMT_DEPTH>::new_max_depth(leaf_pos);
708 let node_index: NodeIndex = leaf_index.into();
709 let leaf_hash = leaf.hash();
710 let expected_hash = self.get_node_hash(node_index);
711
712 if leaf_hash != expected_hash {
713 return Err(DeserializationError::InvalidValue(
714 "leaf hash is inconsistent with parent inner node".into(),
715 ));
716 }
717 }
718
719 Ok(())
720 }
721}
722
723impl Default for PartialSmt {
724 /// Returns a new, empty [`PartialSmt`].
725 ///
726 /// All leaves in the returned tree are set to [`Self::EMPTY_VALUE`].
727 fn default() -> Self {
728 Self::new(Self::EMPTY_ROOT)
729 }
730}
731
732// CONVERSIONS
733// ================================================================================================
734
735impl From<super::Smt> for PartialSmt {
736 fn from(smt: super::Smt) -> Self {
737 Self {
738 root: smt.root(),
739 num_entries: smt.num_entries(),
740 leaves: smt.leaves().map(|(idx, leaf)| (idx.position(), leaf.clone())).collect(),
741 inner_nodes: smt.inner_node_indices().collect(),
742 }
743 }
744}
745
746// SERIALIZATION
747// ================================================================================================
748
749impl Serializable for PartialSmt {
750 fn write_into<W: ByteWriter>(&self, target: &mut W) {
751 let unique_rep = self.to_unique_nodes();
752 unique_rep.write_into(target);
753 }
754}
755
756impl Deserializable for PartialSmt {
757 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
758 let unique_rep = UniqueNodes::read_from(source)?;
759 PartialSmt::from_unique_nodes(unique_rep)
760 .map_err(|e| DeserializationError::InvalidValue(format!("{e}")))
761 }
762}