miden_crypto/merkle/partial_mt/
mod.rs1use alloc::{
2 collections::{BTreeMap, BTreeSet},
3 string::String,
4 vec::Vec,
5};
6use core::fmt;
7
8use super::{
9 EMPTY_WORD, Eidos, InnerNodeInfo, MerkleError, MerklePath, MerkleProof, NodeIndex, Word,
10};
11use crate::utils::{
12 ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable, word_to_hex,
13};
14
15#[cfg(test)]
16mod tests;
17
18#[cfg(any(test, feature = "arbitrary"))]
22mod arbitrary {
23 extern crate alloc;
24
25 use alloc::vec::Vec;
26
27 use proptest::prelude::*;
28
29 use super::PartialMerkleTree;
30 use crate::{
31 Word,
32 merkle::{MerklePath, MerkleTree, NodeIndex},
33 };
34
35 impl Arbitrary for PartialMerkleTree {
36 type Parameters = ();
37 type Strategy = BoxedStrategy<Self>;
38
39 fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
40 prop_oneof![paths_from_real_tree().boxed(), single_deep_path().boxed()].boxed()
48 }
49 }
50
51 fn paths_from_real_tree() -> impl Strategy<Value = PartialMerkleTree> {
52 (1u8..=6)
53 .prop_flat_map(|depth| {
54 let count = 1usize << depth;
55 (
56 Just(depth),
57 proptest::collection::vec(any::<Word>(), count),
58 proptest::collection::vec(any::<bool>(), count),
59 )
60 })
61 .prop_map(|(depth, leaves, track_mask)| {
62 let tree = MerkleTree::new(&leaves).expect("leaf count is a power of two >= 2");
63 let paths: Vec<(u64, Word, MerklePath)> = track_mask
64 .iter()
65 .enumerate()
66 .filter(|(_, tracked)| **tracked)
67 .map(|(pos, _)| {
68 let node_index =
69 NodeIndex::new(depth, pos as u64).expect("position fits the depth");
70 let path = tree.get_path(node_index).expect("position within the tree");
71 (pos as u64, leaves[pos], path)
72 })
73 .collect();
74 PartialMerkleTree::with_paths(paths)
75 .expect("paths from one tree share a depth and no ancestor relation")
76 })
77 }
78
79 fn single_deep_path() -> impl Strategy<Value = PartialMerkleTree> {
80 (7u8..=64, any::<u64>(), any::<Word>())
81 .prop_flat_map(|(depth, index, value)| {
82 let mask = if depth == 64 { u64::MAX } else { (1u64 << depth) - 1 };
83 (
84 Just(depth),
85 Just(value),
86 Just(index & mask),
87 proptest::collection::vec(any::<Word>(), depth as usize),
88 )
89 })
90 .prop_map(|(_depth, value, index, path_nodes)| {
91 let path = MerklePath::new(path_nodes);
92 PartialMerkleTree::with_paths([(index, value, path)])
93 .expect("a single path is always a valid partial tree")
94 })
95 }
96}
97
98const ROOT_INDEX: NodeIndex = NodeIndex::root();
103
104const EMPTY_DIGEST: Word = EMPTY_WORD;
106
107#[derive(Debug, Clone, PartialEq, Eq)]
115#[cfg_attr(
116 all(feature = "arbitrary", test),
117 miden_test_serialization_macros::serialization_test
118)]
119pub struct PartialMerkleTree {
120 max_depth: u8,
121 nodes: BTreeMap<NodeIndex, Word>,
122 leaves: BTreeSet<NodeIndex>,
123}
124
125impl Default for PartialMerkleTree {
126 fn default() -> Self {
127 Self::new()
128 }
129}
130
131impl PartialMerkleTree {
132 pub const MIN_DEPTH: u8 = 1;
137
138 pub const MAX_DEPTH: u8 = 64;
140
141 pub fn new() -> Self {
146 PartialMerkleTree {
147 max_depth: 0,
148 nodes: BTreeMap::new(),
149 leaves: BTreeSet::new(),
150 }
151 }
152
153 pub fn with_paths<I>(paths: I) -> Result<Self, MerkleError>
157 where
158 I: IntoIterator<Item = (u64, Word, MerklePath)>,
159 {
160 let tree = PartialMerkleTree::new();
162
163 paths.into_iter().try_fold(tree, |mut tree, (index, value, path)| {
164 tree.add_path(index, value, path)?;
165 Ok(tree)
166 })
167 }
168
169 pub fn with_leaves<R, I>(entries: R) -> Result<Self, MerkleError>
181 where
182 R: IntoIterator<IntoIter = I>,
183 I: Iterator<Item = (NodeIndex, Word)> + ExactSizeIterator,
184 {
185 let entries = entries.into_iter();
186 if entries.len() == 0 {
187 return Ok(PartialMerkleTree::new());
188 }
189
190 let mut layers: BTreeMap<u8, Vec<u64>> = BTreeMap::new();
191 let mut leaves = BTreeSet::new();
192 let mut nodes = BTreeMap::new();
193
194 for (node_index, hash) in entries {
197 Self::check_depth(node_index.depth())?;
198 leaves.insert(node_index);
199 nodes.insert(node_index, hash);
200 layers
201 .entry(node_index.depth())
202 .and_modify(|layer_vec| layer_vec.push(node_index.position()))
203 .or_insert(vec![node_index.position()]);
204 }
205
206 let max_depth = *layers.keys().next_back().unwrap_or(&0);
208
209 for depth in 0..max_depth {
211 layers.entry(depth).or_default();
212 }
213
214 let mut layer_iter = layers.into_values().rev();
215 let mut parent_layer = layer_iter.next().unwrap();
216 let mut current_layer;
217
218 for depth in (1..max_depth + 1).rev() {
219 current_layer = layer_iter.next().unwrap();
221 core::mem::swap(&mut current_layer, &mut parent_layer);
222
223 current_layer.sort_unstable();
226 current_layer.dedup_by_key(|position| *position / 2);
227
228 for index_value in current_layer {
229 let parent_node = NodeIndex::new(depth - 1, index_value / 2)?;
231
232 if leaves.contains(&parent_node) {
234 return Err(MerkleError::EntryIsNotLeaf { node: parent_node });
235 }
236
237 let index = NodeIndex::new(depth, index_value)?;
239
240 let node = nodes.get(&index).ok_or(MerkleError::NodeIndexNotFoundInTree(index))?;
242 let sibling = nodes
244 .get(&index.sibling())
245 .ok_or(MerkleError::NodeIndexNotFoundInTree(index.sibling()))?;
246 let parent = Eidos::merge(&index.build_node(*node, *sibling));
248
249 parent_layer.push(parent_node.position());
251 nodes.insert(parent_node, parent);
253 }
254 }
255
256 Ok(PartialMerkleTree { max_depth, nodes, leaves })
257 }
258
259 pub fn root(&self) -> Word {
264 self.nodes.get(&ROOT_INDEX).cloned().unwrap_or(EMPTY_DIGEST)
265 }
266
267 pub fn max_depth(&self) -> u8 {
269 self.max_depth
270 }
271
272 pub fn get_node(&self, index: NodeIndex) -> Result<Word, MerkleError> {
277 self.nodes
278 .get(&index)
279 .ok_or(MerkleError::NodeIndexNotFoundInTree(index))
280 .copied()
281 }
282
283 pub fn is_leaf(&self, index: NodeIndex) -> bool {
285 self.leaves.contains(&index)
286 }
287
288 pub fn to_paths(&self) -> Vec<(NodeIndex, MerkleProof)> {
290 let mut paths = Vec::new();
291 self.leaves.iter().for_each(|&leaf| {
292 paths.push((
293 leaf,
294 MerkleProof {
295 value: self.get_node(leaf).expect("Failed to get leaf node"),
296 path: self.get_path(leaf).expect("Failed to get path"),
297 },
298 ));
299 });
300 paths
301 }
302
303 pub fn get_path(&self, mut index: NodeIndex) -> Result<MerklePath, MerkleError> {
313 if index.is_root() {
314 return Err(MerkleError::DepthTooSmall(index.depth()));
315 } else if index.depth() > self.max_depth() {
316 return Err(MerkleError::DepthTooBig(index.depth() as u64));
317 }
318
319 if !self.nodes.contains_key(&index) {
320 return Err(MerkleError::NodeIndexNotFoundInTree(index));
321 }
322
323 let mut path = Vec::new();
324 for _ in 0..index.depth() {
325 let sibling_index = index.sibling();
326 index.move_up();
327 let sibling =
328 self.nodes.get(&sibling_index).cloned().expect("Sibling node not in the map");
329 path.push(sibling);
330 }
331 Ok(MerklePath::new(path))
332 }
333
334 pub fn leaves(&self) -> impl Iterator<Item = (NodeIndex, Word)> + '_ {
339 self.leaves.iter().map(|&leaf| {
340 (
341 leaf,
342 self.get_node(leaf)
343 .unwrap_or_else(|_| panic!("Leaf with {leaf} is not in the nodes map")),
344 )
345 })
346 }
347
348 pub fn inner_nodes(&self) -> impl Iterator<Item = InnerNodeInfo> + '_ {
350 let inner_nodes = self.nodes.iter().filter(|(index, _)| !self.leaves.contains(index));
351 inner_nodes.map(|(index, digest)| {
352 let left_hash =
353 self.nodes.get(&index.left_child()).expect("Failed to get left child hash");
354 let right_hash =
355 self.nodes.get(&index.right_child()).expect("Failed to get right child hash");
356 InnerNodeInfo {
357 value: *digest,
358 left: *left_hash,
359 right: *right_hash,
360 }
361 })
362 }
363
364 pub fn add_path(
378 &mut self,
379 index_value: u64,
380 value: Word,
381 path: MerklePath,
382 ) -> Result<(), MerkleError> {
383 let index_value = NodeIndex::new(path.len() as u8, index_value)?;
384
385 Self::check_depth(index_value.depth())?;
386
387 let mut parent_hashes = [EMPTY_DIGEST; PartialMerkleTree::MAX_DEPTH as usize];
389 let (root, parent_count) =
390 Self::compute_path_nodes(index_value, value, &path, &mut parent_hashes);
391
392 let expected_root = self.root();
395 if expected_root != EMPTY_DIGEST && expected_root != root {
396 return Err(MerkleError::ConflictingRoots { expected_root, actual_root: root });
397 }
398
399 self.update_depth(index_value.depth());
400
401 self.leaves.insert(index_value);
403 let sibling_node_index = index_value.sibling();
404 self.leaves.insert(sibling_node_index);
405
406 self.nodes.insert(index_value, value);
408 self.nodes.insert(sibling_node_index, path[0]);
409
410 let mut index_value = index_value;
412 for (&parent_hash, &sibling_hash) in
413 parent_hashes[..parent_count].iter().zip(path.iter().skip(1))
414 {
415 index_value.move_up();
416 self.nodes.insert(index_value, parent_hash);
418
419 self.leaves.remove(&index_value);
421
422 let sibling_node = index_value.sibling();
423
424 if self.nodes.insert(sibling_node, sibling_hash).is_none() {
436 self.leaves.insert(sibling_node);
437 }
438 }
439
440 if expected_root == EMPTY_DIGEST {
441 self.nodes.insert(ROOT_INDEX, root);
442 }
443
444 Ok(())
445 }
446
447 pub fn update_leaf(&mut self, index: u64, value: Word) -> Result<Word, MerkleError> {
459 let mut node_index = NodeIndex::new(self.max_depth(), index)?;
460
461 for _ in 0..node_index.depth() {
463 if !self.leaves.contains(&node_index) {
464 node_index.move_up();
465 }
466 }
467
468 let old_value = self
470 .nodes
471 .insert(node_index, value)
472 .ok_or(MerkleError::NodeIndexNotFoundInTree(node_index))?;
473
474 if value == old_value {
476 return Ok(old_value);
477 }
478
479 let mut value = value;
480 for _ in 0..node_index.depth() {
481 let sibling = self.nodes.get(&node_index.sibling()).expect("sibling should exist");
482 value = Eidos::merge(&node_index.build_node(value, *sibling));
483 node_index.move_up();
484 self.nodes.insert(node_index, value);
485 }
486
487 Ok(old_value)
488 }
489
490 pub fn print(&self) -> Result<String, fmt::Error> {
495 let indent = " ";
496 let mut s = String::new();
497 s.push_str("root: ");
498 s.push_str(&word_to_hex(&self.root())?);
499 s.push('\n');
500 for d in 1..=self.max_depth() {
501 let entries = 2u64.pow(d.into());
502 for i in 0..entries {
503 let index = NodeIndex::new(d, i).expect("The index must always be valid");
504 let node = self.get_node(index);
505 let node = match node {
506 Err(_) => continue,
507 Ok(node) => node,
508 };
509
510 for _ in 0..d {
511 s.push_str(indent);
512 }
513 s.push_str(&format!("({}, {}): ", index.depth(), index.position()));
514 s.push_str(&word_to_hex(&node)?);
515 s.push('\n');
516 }
517 }
518
519 Ok(s)
520 }
521
522 fn update_depth(&mut self, new_depth: u8) {
527 self.max_depth = new_depth.max(self.max_depth);
528 }
529
530 fn check_depth(depth: u8) -> Result<(), MerkleError> {
532 if depth < Self::MIN_DEPTH {
534 return Err(MerkleError::DepthTooSmall(depth));
535 } else if Self::MAX_DEPTH < depth {
536 return Err(MerkleError::DepthTooBig(depth as u64));
537 }
538 Ok(())
539 }
540
541 fn compute_path_nodes(
546 index_value: NodeIndex,
547 value: Word,
548 path: &MerklePath,
549 parent_hashes: &mut [Word],
550 ) -> (Word, usize) {
551 let mut index_value = index_value;
552 let mut node = Eidos::merge(&index_value.build_node(value, path[0]));
553 let mut parent_count = 0;
554
555 for &sibling_hash in path.iter().skip(1) {
556 index_value.move_up();
557 parent_hashes[parent_count] = node;
558 parent_count += 1;
559 node = Eidos::merge(&index_value.build_node(node, sibling_hash));
560 }
561
562 (node, parent_count)
563 }
564}
565
566impl Serializable for PartialMerkleTree {
570 fn write_into<W: ByteWriter>(&self, target: &mut W) {
571 target.write_u64(self.leaves.len() as u64);
573 for leaf_index in self.leaves.iter() {
574 leaf_index.write_into(target);
575 self.get_node(*leaf_index).expect("Leaf hash not found").write_into(target);
576 }
577 }
578}
579
580impl Deserializable for PartialMerkleTree {
581 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
582 let leaves_len_u64 = source.read_u64()?;
583 let leaves_len = usize::try_from(leaves_len_u64).map_err(|_| {
584 DeserializationError::InvalidValue("PartialMerkleTree leaf count too large".into())
585 })?;
586
587 let leaf_nodes: Vec<(NodeIndex, Word)> =
589 source.read_many_iter(leaves_len)?.collect::<Result<_, _>>()?;
590
591 let pmt = PartialMerkleTree::with_leaves(leaf_nodes).map_err(|_| {
592 DeserializationError::InvalidValue("Invalid data for PartialMerkleTree creation".into())
593 })?;
594
595 Ok(pmt)
596 }
597
598 fn min_serialized_size() -> usize {
600 8
601 }
602}