1use crate::curve::Fr;
17use crate::hash::{degrade_to_transient, transient_hash};
18use crate::repr::FieldRepr;
19use base_crypto::hash::{HashOutput, persistent_hash};
20use base_crypto::repr::{BinaryHashRepr, MemWrite};
21use derive_where::derive_where;
22use fake::Dummy;
23#[cfg(feature = "proptest")]
24use proptest::arbitrary::Arbitrary;
25#[cfg(feature = "proptest")]
26use proptest_derive::Arbitrary;
27use rand::Rng;
28use rand::distributions::{Distribution, Standard};
29use serde::{Deserialize, Deserializer, Serialize, Serializer, ser::SerializeTuple};
30#[cfg(feature = "proptest")]
31use serialize::NoStrategy;
32use serialize::{Deserializable, Serializable, Tagged, tag_enforcement_test};
33use std::error::Error;
34use std::fmt::{self, Debug, Display, Formatter};
35use std::hash::Hash;
36#[cfg(feature = "proptest")]
37use std::marker::PhantomData;
38use std::ops::{Bound, Deref, RangeBounds, RangeInclusive};
39use storage_core as storage;
40use storage_core::DefaultDB;
41use storage_core::Storable;
42use storage_core::arena::{ArenaKey, Sp};
43use storage_core::db::DB;
44#[cfg(test)]
45use storage_core::db::InMemoryDB;
46use storage_core::storable::Loader;
47
48#[derive(PartialEq, Eq, PartialOrd, Hash, Clone, Debug, Ord, Serializable)]
50pub struct MerkleTreeHash(HashOutput);
51
52#[derive(Debug, Clone, FieldRepr, Serializable)]
54pub struct MerklePath<T> {
55 pub leaf: T,
57 pub path: Vec<MerklePathEntry>,
59}
60
61pub const LEAF_HASH_DOMAIN_SEP: &[u8] = b"mdn:lh";
63
64fn range_sub(range: (Bound<u64>, Bound<u64>), sub: u64) -> Option<(Bound<u64>, Bound<u64>)> {
65 let start = match range.0 {
67 Bound::Unbounded => Bound::Unbounded,
68 Bound::Included(n) => match n.checked_sub(sub) {
69 Some(m) => Bound::Included(m),
70 None => Bound::Unbounded,
71 },
72 Bound::Excluded(n) => match n.checked_sub(sub) {
73 Some(m) => Bound::Excluded(m),
74 None => Bound::Unbounded,
75 },
76 };
77 let end = match range.1 {
81 Bound::Unbounded => Bound::Unbounded,
82 Bound::Included(n) => Bound::Included(n.checked_sub(sub)?),
83 Bound::Excluded(n) => Bound::Excluded(n.checked_sub(sub)?),
84 };
85 if range_empty((start, end)) {
86 None
87 } else {
88 Some((start, end))
89 }
90}
91
92fn range_empty(range: (Bound<u64>, Bound<u64>)) -> bool {
93 if let Some((start, end)) = range_force_inclusive(range) {
94 start > end
95 } else {
96 true
97 }
98}
99
100fn range_force_inclusive(range: (Bound<u64>, Bound<u64>)) -> Option<(u64, u64)> {
101 let inclusive_start = match range.0 {
102 Bound::Unbounded => 0,
103 Bound::Included(n) => n,
104 Bound::Excluded(u64::MAX) => return None,
105 Bound::Excluded(n) => n + 1,
106 };
107 let inclusive_end = match range.1 {
108 Bound::Unbounded => u64::MAX,
109 Bound::Included(n) => n,
110 Bound::Excluded(0) => return None,
111 Bound::Excluded(n) => n - 1,
112 };
113 Some((inclusive_start, inclusive_end))
114}
115
116fn overlap(a: (Bound<u64>, Bound<u64>), b: impl RangeBounds<u64>) -> Option<RangeInclusive<u64>> {
117 let b = (b.start_bound().cloned(), b.end_bound().cloned());
118 let a_inclusive = range_force_inclusive(a)?;
119 let b_inclusive = range_force_inclusive(b)?;
120 let start = u64::max(a_inclusive.0, b_inclusive.0);
121 let end = u64::min(a_inclusive.1, b_inclusive.1);
122 if start <= end {
123 Some(start..=end)
124 } else {
125 None
126 }
127}
128
129#[derive(Debug, Clone)]
132pub struct InvalidIndex(pub u64);
133
134impl Display for InvalidIndex {
135 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
136 write!(f, "invalid index into sparse merkle tree: {}", self.0)
137 }
138}
139
140impl Error for InvalidIndex {}
141
142#[derive(Debug, Copy, Clone, PartialEq, Eq)]
145#[non_exhaustive]
146pub enum InvalidUpdate {
147 CollapsedIndex(u128, u8),
150 StubUpdate(u128, u8),
153 EndBeforeStart(u64, u64),
155 EndOutOfTree(u64),
157 IndexOutOfTree(u64),
159 WrongNumberOfSegments(usize, usize),
161 NotFullyRehashed,
163 BadUpdatePath,
165}
166
167impl Display for InvalidUpdate {
168 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
169 use InvalidUpdate::*;
170 match self {
171 CollapsedIndex(idx, height) => write!(
172 f,
173 "attempted update on collapsed sub-tree at {idx}/{height}"
174 ),
175 StubUpdate(idx, height) => {
176 write!(f, "attempted update on updated sub-tree at {idx}/{height}")
177 }
178 EndBeforeStart(start, end) => write!(
179 f,
180 "attempted update with end ({end}) after before ({start})"
181 ),
182 EndOutOfTree(end) => write!(f, "attempted update with end ({end}) outside of the tree"),
183 IndexOutOfTree(index) => {
184 write!(f, "attempted update at index ({index}) outside of the tree")
185 }
186 WrongNumberOfSegments(..) => write!(f, "attempted update with mismatch segment count"),
187 NotFullyRehashed => write!(f, "attempted update without the tree being fully rehashed"),
188 BadUpdatePath => write!(
189 f,
190 "attempted to apply an update path that wasn't compatible with the tree"
191 ),
192 }
193 }
194}
195
196impl Error for InvalidUpdate {}
197
198pub fn leaf_hash<T: BinaryHashRepr + ?Sized>(value: &T) -> HashOutput {
200 let mut data = Vec::with_capacity(value.binary_len() + LEAF_HASH_DOMAIN_SEP.len());
201 data.extend(LEAF_HASH_DOMAIN_SEP);
202 value.binary_repr(&mut data);
203 persistent_hash(&data)
204}
205
206impl<T: BinaryHashRepr> MerklePath<T> {
207 pub fn root(&self) -> MerkleTreeDigest {
209 MerkleTreeDigest(self.path.iter().fold(
210 degrade_to_transient(leaf_hash(&self.leaf)),
211 |acc, entry| {
212 if entry.goes_left {
213 transient_hash(&[acc, entry.sibling.0])
214 } else {
215 transient_hash(&[entry.sibling.0, acc])
216 }
217 },
218 ))
219 }
220}
221
222#[derive(Debug, Clone, FieldRepr, Serializable)]
224pub struct MerklePathEntry {
225 pub sibling: MerkleTreeDigest,
227 pub goes_left: bool,
229}
230
231#[derive(Debug, Clone, PartialEq, Eq, Serializable, Storable)]
237#[tag = "tree-insertion-path[v1]"]
238#[storable(base)]
239pub struct TreeInsertionPath<A>
240where
241 A: Serializable + Deserializable + Clone + Sync + Send + 'static,
242{
243 pub leaf: (HashOutput, A),
245 pub path: Vec<TreeInsertionPathEntry>,
247}
248tag_enforcement_test!(TreeInsertionPath<()>);
249
250#[derive(Debug, Clone, PartialEq, Eq, Serializable)]
252#[tag = "tree-insertion-path-entry[v1]"]
253pub struct TreeInsertionPathEntry {
254 pub hash: Option<MerkleTreeDigest>,
256 pub goes_left: bool,
258}
259tag_enforcement_test!(TreeInsertionPathEntry);
260
261#[derive(
263 Copy,
264 Clone,
265 Hash,
266 Default,
267 PartialEq,
268 Eq,
269 PartialOrd,
270 Ord,
271 FieldRepr,
272 Serializable,
273 Serialize,
274 Dummy,
275 Storable,
276)]
277#[storable(base)]
278#[cfg_attr(feature = "proptest", derive(Arbitrary))]
279#[tag = "merkle-tree-digest[v1]"]
280pub struct MerkleTreeDigest(pub Fr);
281tag_enforcement_test!(MerkleTreeDigest);
282
283impl rand::distributions::Distribution<MerkleTreeDigest> for rand::distributions::Standard {
284 fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> MerkleTreeDigest {
285 MerkleTreeDigest(rng.r#gen())
286 }
287}
288
289impl From<Fr> for MerkleTreeDigest {
290 fn from(field: Fr) -> MerkleTreeDigest {
291 MerkleTreeDigest(field)
292 }
293}
294
295impl From<MerkleTreeDigest> for Fr {
296 fn from(digest: MerkleTreeDigest) -> Fr {
297 digest.0
298 }
299}
300impl Debug for MerkleTreeDigest {
301 fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
302 write!(formatter, "{}", self.0)
303 }
304}
305
306#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serializable)]
308#[tag = "merkle-tree-collapsed-update[v1]"]
309pub struct MerkleTreeCollapsedUpdate {
310 pub start: u64,
312 pub end: u64,
314 hashes: Vec<MerkleTreeDigest>,
315}
316tag_enforcement_test!(MerkleTreeCollapsedUpdate);
317
318impl Debug for MerkleTreeCollapsedUpdate {
319 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
320 f.debug_struct("MerkleTreeCollapsedUpdate")
321 .field("start", &self.start)
322 .field("end", &self.end)
323 .finish()
324 }
325}
326
327impl MerkleTreeCollapsedUpdate {
328 fn step_sizes(mut a: u64, b: u64) -> Vec<u8> {
329 let msb_diff = (b ^ a).ilog2() as u8;
341 let mut res = Vec::with_capacity(u8::max(1, msb_diff) as usize * 2 - 1);
342 for bit in 0..msb_diff {
344 let shifted = 1 << bit as u64;
345 if (a & shifted) != 0 {
346 a += shifted;
347 res.push(bit);
348 }
349 }
350 if a & (1 << msb_diff) == 0 {
352 res.push(msb_diff);
353 }
354 for bit in (0..msb_diff).rev() {
356 if (b & (1 << bit as u64)) != 0 {
357 res.push(bit);
358 }
359 }
360 res
361 }
362
363 fn partial_index<A: Storable<D>, D: DB>(
364 tree: &MerkleTree<A, D>,
365 idx: u128,
366 height: u8,
367 ) -> Result<MerkleTreeDigest, InvalidUpdate> {
368 let hdiff = tree.height() - height;
369 let mut curr = tree.0.deref();
370 for i in 0..hdiff {
371 let go_left = (idx & (1u128 << (tree.height() - i - 1))) == 0;
372 match curr {
373 Leaf { .. } => unreachable!(),
374 Node { left, right, .. } => curr = if go_left { left } else { right },
375 Collapsed { .. } => return Err(InvalidUpdate::CollapsedIndex(idx, height)),
376 Stub { .. } => return Err(InvalidUpdate::StubUpdate(idx, height)),
377 }
378 }
379 Ok(MerkleTreeDigest(
380 curr.root().ok_or(InvalidUpdate::NotFullyRehashed)?,
381 ))
382 }
383
384 pub fn new<A: Storable<D>, D: DB>(
391 tree: &MerkleTree<A, D>,
392 start: u64,
393 end: u64,
394 ) -> Result<Self, InvalidUpdate> {
395 if end < start {
396 return Err(InvalidUpdate::EndBeforeStart(start, end));
397 }
398 if (end as u128) >= (1u128 << tree.height()) {
399 return Err(InvalidUpdate::EndOutOfTree(end));
400 }
401 let step_sizes = Self::step_sizes(start, end + 1);
402 let mut hashes = Vec::with_capacity(step_sizes.len());
403 let mut curr = start as u128;
404 for step in step_sizes.into_iter() {
405 hashes.push(Self::partial_index(tree, curr, step)?);
406 curr += 1u128 << step as u128;
407 }
408 Ok(MerkleTreeCollapsedUpdate { start, end, hashes })
409 }
410}
411
412#[derive_where(Clone, PartialOrd, PartialEq, Ord, Eq; A)]
421#[derive(Storable)]
422#[storable(db = D)]
423#[tag = "merkle-tree[v1]"]
424pub struct MerkleTree<A: Storable<D>, D: DB = DefaultDB>(
425 #[cfg(feature = "public-internal-structure")] pub Sp<MerkleTreeNode<A, D>, D>,
426 #[cfg(not(feature = "public-internal-structure"))] Sp<MerkleTreeNode<A, D>, D>,
427);
428tag_enforcement_test!(MerkleTree<(), InMemoryDB>);
429
430impl<A: Storable<D>, D: DB> Hash for MerkleTree<A, D> {
431 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
432 Hash::hash(&self.0.hash(), state)
433 }
434}
435
436impl<A: Debug + Storable<D>, D: DB> Debug for MerkleTree<A, D> {
437 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
438 f.write_fmt(format_args!("MerkleTree(root = {:?}) ", self.root()))?;
439 self.0.fmt(f)
440 }
441}
442
443struct SerdeMerkleTreeMap<'a, A: Storable<D>, D: DB>(&'a MerkleTree<A, D>);
444
445impl<A: Serialize + Storable<D>, D: DB> Serialize for MerkleTree<A, D> {
446 fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
447 let mut pair = ser.serialize_tuple(2)?;
448 pair.serialize_element(&self.height())?;
449 pair.serialize_element(&SerdeMerkleTreeMap(self))?;
450 pair.end()
451 }
452}
453
454impl<A: Serialize + Storable<D>, D: DB> Serialize for SerdeMerkleTreeMap<'_, A, D> {
455 fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
456 ser.collect_map(self.0.iter_aux())
457 }
458}
459
460impl<'de, A: Deserialize<'de> + Storable<D>, D: DB> Deserialize<'de> for MerkleTree<A, D> {
461 fn deserialize<D2: Deserializer<'de>>(de: D2) -> Result<Self, D2::Error> {
462 let (height, data): (u8, std::collections::HashMap<u64, (HashOutput, A)>) =
463 Deserialize::deserialize(de)?;
464 data.into_iter()
465 .try_fold(MerkleTree::blank(height), |mt, (k, (v, a))| {
466 MerkleTree::try_update_hash(&mt, k, v, a)
467 .map_err(<D2::Error as serde::de::Error>::custom)
468 })
469 .map(|mt| mt.rehash())
470 }
471}
472
473#[derive_where(Clone, Hash, Ord, PartialOrd, Eq, PartialEq; A)]
475#[derive(Storable)]
476#[storable(db = D, invariant = MerkleTreeNode::invariant)]
477#[tag = "merkle-tree-node[v1]"]
478pub enum MerkleTreeNode<A: Storable<D>, D: DB> {
479 Leaf {
481 hash: HashOutput,
483 aux: A,
485 },
486 Collapsed {
488 hash: Fr,
490 height: u8,
492 },
493 Stub {
495 height: u8,
497 },
498 Node {
500 hash: Option<Sp<Fr, D>>,
502 #[storable(child)]
504 left: Sp<MerkleTreeNode<A, D>, D>,
505 #[storable(child)]
507 right: Sp<MerkleTreeNode<A, D>, D>,
508 height: u8,
510 },
511}
512tag_enforcement_test!(MerkleTreeNode<(), InMemoryDB>);
513
514impl<Faker, D: DB> fake::Dummy<Faker> for MerkleTree<(), D> {
515 fn dummy(_config: &Faker) -> Self {
516 let mut mt = MerkleTree::<(), D>::blank(32);
518 if let Ok(updated) = mt
519 .try_update(0, &Fr::from(42u64), ())
520 .and_then(|mt| mt.try_update(0, &Fr::from(41u64), ()))
521 .and_then(|mt| mt.try_update(3, &Fr::from(43u64), ()))
522 .and_then(|mt| mt.try_update(62, &Fr::from(12u64), ()))
523 {
524 mt = updated;
525 }
526 mt
527 }
528
529 fn dummy_with_rng<R: rand::Rng + ?Sized>(config: &Faker, _rng: &mut R) -> Self {
530 Self::dummy(config)
531 }
532}
533
534struct DebugCollapsed;
535
536impl Debug for DebugCollapsed {
537 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
538 write!(f, "<collapsed>")
539 }
540}
541
542struct DebugEntry<'a, A>(HashOutput, &'a A);
543
544impl<A: Debug> Debug for DebugEntry<'_, A> {
545 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
546 write!(f, "({:?}, {:?})", self.0, self.1)
547 }
548}
549
550impl<A: Debug + Storable<D>, D: DB> Debug for MerkleTreeNode<A, D> {
551 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
552 use LeafOrCollapsed::*;
553 let mut map = f.debug_map();
554 let mut current_collapsed_range = None;
555 for leaf in self.leaves().into_iter() {
556 match (leaf, current_collapsed_range) {
557 (Leaf { index, hash, aux }, None) => {
558 map.entry(&index, &DebugEntry(hash, aux));
559 }
560 (Leaf { index, hash, aux }, Some((start, end))) => {
561 map.entry(&(start..=end), &DebugCollapsed);
562 current_collapsed_range = None;
563 map.entry(&index, &DebugEntry(hash, aux));
564 }
565 (Collapsed { start, end }, Some((start2, end2))) if end2 + 1 == start => {
566 current_collapsed_range = Some((start2, end));
567 }
568 (Collapsed { start, end }, Some((start2, end2))) => {
569 map.entry(&(start2..=end2), &DebugCollapsed);
570 current_collapsed_range = Some((start, end));
571 }
572 (Collapsed { start, end }, None) => {
573 current_collapsed_range = Some((start, end));
574 }
575 }
576 }
577 if let Some((start, end)) = current_collapsed_range {
578 map.entry(&(start..=end), &DebugCollapsed);
579 }
580 map.finish()
581 }
582}
583
584enum LeafOrCollapsed<'a, A> {
585 Leaf {
586 index: u64,
587 hash: HashOutput,
588 aux: &'a A,
589 },
590 Collapsed {
591 start: u64,
592 end: u64,
593 },
594}
595
596impl<A> LeafOrCollapsed<'_, A> {
597 fn upgrade(self, shift: u64) -> Self {
598 use LeafOrCollapsed::*;
599 match self {
600 Leaf { index, hash, aux } => Leaf {
601 index: index + shift,
602 hash,
603 aux,
604 },
605 Collapsed { start, end } => Collapsed {
606 start: start + shift,
607 end: end + shift,
608 },
609 }
610 }
611}
612
613impl<A: Storable<D>, D: DB> MerkleTreeNode<A, D> {
614 fn invariant(&self) -> std::io::Result<()> {
615 if let Node {
616 left,
617 right,
618 height,
619 hash,
620 } = self
621 {
622 if *height == 0 || *height - 1 != left.height() || *height - 1 != right.height() {
623 return Err(std::io::Error::new(
624 std::io::ErrorKind::InvalidData,
625 "MerkleTree inconsistent height on deserialization",
626 ));
627 }
628 if hash.is_some() && (left.root().is_none() || right.root().is_none()) {
647 return Err(std::io::Error::new(
648 std::io::ErrorKind::InvalidData,
649 "MerkleTree children not rehashed, but parent claiming to be",
650 ));
651 }
652 }
653 Ok(())
654 }
655
656 fn leaves_in_range(&self, range: (Bound<u64>, Bound<u64>)) -> Vec<LeafOrCollapsed<'_, A>> {
657 match self {
658 Leaf { hash, aux } if range.contains(&0) => vec![LeafOrCollapsed::Leaf {
659 index: 0,
660 hash: *hash,
661 aux,
662 }],
663 Stub { .. } | Leaf { .. } => Vec::new(),
664 Collapsed { .. } => {
665 if let Some(range) = overlap(range, 0..(1 << self.height())) {
666 vec![LeafOrCollapsed::Collapsed {
667 start: *range.start(),
668 end: *range.end(),
669 }]
670 } else {
671 Vec::new()
672 }
673 }
674 Node { left, right, .. } => left
675 .leaves_in_range(range)
676 .into_iter()
677 .chain(
678 range_sub(range, 1 << left.height())
679 .into_iter()
680 .flat_map(|sub_range| right.leaves_in_range(sub_range).into_iter())
681 .map(|leaf| leaf.upgrade(1 << left.height())),
682 )
683 .collect(),
684 }
685 }
686
687 fn leaves(&self) -> Vec<LeafOrCollapsed<'_, A>> {
688 self.leaves_in_range((Bound::Unbounded, Bound::Unbounded))
689 }
690
691 fn new(height: u8) -> Self {
692 Stub { height }
693 }
694
695 fn height(&self) -> u8 {
696 match self {
697 Leaf { .. } => 0,
698 Stub { height, .. } => *height,
699 Collapsed { height, .. } => *height,
700 Node { height, .. } => *height,
701 }
702 }
703
704 fn root(&self) -> Option<Fr> {
705 match self {
706 Leaf { hash, .. } => Some(degrade_to_transient(*hash)),
707 Stub { .. } => Some(Fr::default()),
708 Collapsed { hash, .. } => Some(*hash),
709 Node { hash, .. } => hash.as_ref().map(|h| **h),
710 }
711 }
712
713 #[allow(clippy::wrong_self_convention)]
714 fn is_collapsed(&self) -> bool {
715 matches!(self, Collapsed { .. })
716 }
717
718 fn update_from_evidence_internal(
719 &self,
720 leaf: (HashOutput, A),
721 path: &[TreeInsertionPathEntry],
722 ) -> Result<Self, InvalidUpdate> {
723 if let Collapsed { height, .. } = self {
724 let hash = if path.is_empty() {
725 degrade_to_transient(leaf.0)
726 } else {
727 path.last()
728 .expect("non-empty")
729 .hash
730 .ok_or(InvalidUpdate::BadUpdatePath)?
731 .0
732 };
733 return Ok(Collapsed {
734 hash,
735 height: *height,
736 });
737 }
738 if path.is_empty() {
739 return Ok(Leaf {
740 hash: leaf.0,
741 aux: leaf.1,
742 });
743 }
744 let entry = path.last().expect("non-empty");
745 Ok(match self {
746 Node {
747 left,
748 right,
749 height,
750 ..
751 } => {
752 if entry.goes_left {
753 Node {
754 hash: None,
755 left: Sp::new(
756 left.update_from_evidence_internal(leaf, &path[..path.len() - 1])?,
757 ),
758 right: right.clone(),
759 height: *height,
760 }
761 } else {
762 Node {
763 hash: None,
764 left: left.clone(),
765 right: Sp::new(
766 right.update_from_evidence_internal(leaf, &path[..path.len() - 1])?,
767 ),
768 height: *height,
769 }
770 }
771 }
772 Stub { .. } | Leaf { .. } | Collapsed { .. } => {
773 return Err(InvalidUpdate::BadUpdatePath);
774 }
775 })
776 }
777
778 pub fn index(&self, index: u64) -> Option<(HashOutput, &A)> {
782 match self {
783 Leaf { hash, aux, .. } => Some((*hash, aux)),
784 Stub { .. } => None,
785 Collapsed { .. } => None,
786 Node {
787 left,
788 right,
789 height,
790 ..
791 } => {
792 let cmp = 1 << (height - 1);
793 if index < cmp {
794 left.index(index)
795 } else {
796 right.index(index - cmp)
797 }
798 }
799 }
800 }
801}
802
803impl<A: Storable<D>, D: DB> MerkleTreeNode<A, D> {
804 fn partial_insert(
805 &self,
806 idx: u128,
807 height: u8,
808 digest: MerkleTreeDigest,
809 ) -> Result<Sp<Self, D>, InvalidUpdate> {
810 let hdiff = self.height() - height;
811 #[allow(clippy::type_complexity)]
812 let mut stack: Vec<(Sp<MerkleTreeNode<A, D>, D>, bool)> =
813 Vec::with_capacity(hdiff as usize);
814 let theight = self.height();
815 let mut curr: Sp<MerkleTreeNode<A, D>, D> = Sp::new(self.clone());
816 for i in 0..hdiff {
817 let go_left = idx & (1u128 << (theight - i - 1)) == 0;
818 match curr.clone().deref() {
819 Leaf { .. } => unreachable!(),
820 Node { left, right, .. } => {
821 curr = if go_left { left.clone() } else { right.clone() };
822 stack.push((if go_left { right.clone() } else { left.clone() }, go_left));
823 }
824 Stub { height } => {
825 curr = Sp::new(Stub { height: height - 1 });
826 stack.push((Sp::new(Stub { height: height - 1 }), go_left));
827 }
828 Collapsed { .. } => return Err(InvalidUpdate::CollapsedIndex(idx, height)),
829 }
830 }
831 Ok(stack.into_iter().rev().enumerate().fold(
832 Sp::new(Collapsed {
833 hash: digest.0,
834 height,
835 }),
836 |acc, (i, (sibling, goes_left))| {
837 let (left, right) = if goes_left {
838 (acc, sibling)
839 } else {
840 (sibling, acc)
841 };
842 Sp::new(Node {
843 left,
844 right,
845 height: height + 1 + i as u8,
846 hash: None,
847 })
848 },
849 ))
850 }
851
852 pub fn rehash(&self) -> Self {
854 match self {
855 Leaf { .. } | Collapsed { .. } | Stub { .. } | Node { hash: Some(_), .. } => {
856 self.clone()
857 }
858 Node {
859 hash: None,
860 left,
861 right,
862 height,
863 } => {
864 let left = Sp::new(left.rehash());
865 let right = Sp::new(right.rehash());
866 let hash = Some(Sp::new(transient_hash(&[
867 left.root().expect("rehashed tree must have root"),
868 right.root().expect("rehashed tree must have root"),
869 ])));
870 Node {
871 hash,
872 left,
873 right,
874 height: *height,
875 }
876 }
877 }
878 }
879
880 fn collapse(&self, start: u64, end: u64) -> Sp<Self, D> {
881 match self {
882 Leaf { hash, .. } => {
883 return Sp::new(Collapsed {
884 hash: degrade_to_transient(*hash),
885 height: 0,
886 });
887 }
888 Collapsed { .. } => return Sp::new(self.clone()),
889 _ => {}
890 }
891 let h = self.height();
892 if start == 0 && end == (1 << h) - 1 {
893 return Sp::new(Collapsed {
894 hash: self.rehash().root().expect("rehashed tree must have root"),
895 height: h,
896 });
897 }
898 let self2 = if let Stub { height } = self {
899 let new = Sp::new(MerkleTreeNode::<A, D>::new(*height - 1));
900 Some(Node {
901 hash: Some(Sp::new(Fr::default())),
902 left: new.clone(),
903 right: new,
904 height: *height,
905 })
906 } else {
907 None
908 };
909 if let Node {
910 left,
911 right,
912 height,
913 hash,
914 ..
915 } = self2.as_ref().unwrap_or(self)
916 {
917 let cmp = 1 << (h - 1);
918 let left = if start < cmp {
919 left.collapse(start, u64::min(end, cmp - 1))
920 } else {
921 left.clone()
922 };
923 let right = if end >= cmp {
924 right.collapse(start.saturating_sub(cmp), end - cmp)
925 } else {
926 right.clone()
927 };
928 if left.is_collapsed() && right.is_collapsed() {
929 return Sp::new(Collapsed {
930 hash: self.rehash().root().expect("rehashed node must have root"),
931 height: *height,
932 });
933 }
934 Sp::new(Node {
935 left,
936 right,
937 hash: hash.clone(),
939 height: *height,
940 })
941 } else {
942 unreachable!()
943 }
944 }
945
946 #[deprecated = "This version panics rather than throwing errors. Prefer `try_update_hash`."]
949 pub fn update_hash(&self, index: u64, new_leaf: HashOutput, new_aux: A) -> Sp<Self, D> {
950 self.try_update_hash(index, new_leaf, new_aux)
951 .expect("attempted update into collapsed tree")
952 }
953
954 pub fn try_update_hash(
957 &self,
958 index: u64,
959 new_leaf: HashOutput,
960 new_aux: A,
961 ) -> Result<Sp<Self, D>, InvalidUpdate> {
962 if (index as u128) >= (1u128 << self.height()) {
963 return Err(InvalidUpdate::IndexOutOfTree(index));
964 }
965 let h = self.height();
966 if self.is_collapsed() {
967 return Err(InvalidUpdate::CollapsedIndex(index as u128, h));
968 }
969 if self.height() == 0 {
970 return Ok(Sp::new(Leaf {
971 hash: new_leaf,
972 aux: new_aux,
973 }));
974 }
975 let self2 = if let Stub { height } = self {
976 let new = Sp::new(MerkleTreeNode::new(*height - 1));
977 Some(Node {
978 hash: None,
979 left: new.clone(),
980 right: new,
981 height: *height,
982 })
983 } else {
984 None
985 };
986 if let Node {
987 left,
988 right,
989 height,
990 ..
991 } = self2.as_ref().unwrap_or(self)
992 {
993 let cmp = 1 << (h - 1);
994 let (left, right) = if index < cmp {
997 (
998 left.try_update_hash(index, new_leaf, new_aux)?,
999 right.clone(),
1000 )
1001 } else {
1002 (
1003 left.clone(),
1004 right.try_update_hash(index - cmp, new_leaf, new_aux)?,
1005 )
1006 };
1007 Ok(Sp::new(Node {
1008 left,
1009 right,
1010 hash: None,
1011 height: *height,
1012 }))
1013 } else {
1014 unreachable!()
1015 }
1016 }
1017}
1018
1019use MerkleTreeNode::*;
1020
1021pub struct MerkleTreeIter(std::vec::IntoIter<(u64, HashOutput)>);
1023
1024impl Iterator for MerkleTreeIter {
1025 type Item = (u64, HashOutput);
1026
1027 fn next(&mut self) -> Option<Self::Item> {
1028 self.0.next()
1029 }
1030}
1031
1032pub struct MerkleTreeIterAux<A>(std::vec::IntoIter<(u64, (HashOutput, A))>);
1034
1035impl<A> Iterator for MerkleTreeIterAux<A> {
1036 type Item = (u64, (HashOutput, A));
1037
1038 fn next(&mut self) -> Option<Self::Item> {
1039 self.0.next()
1040 }
1041}
1042
1043impl<A: Storable<D>, D: DB> MerkleTree<A, D> {
1044 pub fn blank(height: u8) -> Self {
1046 MerkleTree(Sp::new(Stub { height }))
1047 }
1048
1049 #[deprecated = "This version panics rather than throwing errors. Prefer `try_update_hash`."]
1052 pub fn update_hash(&self, index: u64, new_leaf: HashOutput, aux: A) -> Self {
1053 #[allow(deprecated)]
1054 MerkleTree(self.0.update_hash(index, new_leaf, aux))
1055 }
1056
1057 pub fn try_update_hash(
1060 &self,
1061 index: u64,
1062 new_leaf: HashOutput,
1063 aux: A,
1064 ) -> Result<Self, InvalidUpdate> {
1065 Ok(MerkleTree(self.0.try_update_hash(index, new_leaf, aux)?))
1066 }
1067
1068 #[deprecated = "This version panics rather than throwing errors. Prefer `try_update_hash`."]
1075 pub fn update<T: BinaryHashRepr + ?Sized>(&self, index: u64, value: &T, aux: A) -> Self {
1076 #[allow(deprecated)]
1077 self.update_hash(index, crate::merkle_tree::leaf_hash(value), aux)
1078 }
1079
1080 pub fn try_update<T: BinaryHashRepr + ?Sized>(
1082 &self,
1083 index: u64,
1084 value: &T,
1085 aux: A,
1086 ) -> Result<Self, InvalidUpdate> {
1087 self.try_update_hash(index, crate::merkle_tree::leaf_hash(value), aux)
1088 }
1089
1090 pub fn collapse(&self, start: u64, end: u64) -> Self {
1093 MerkleTree(self.0.collapse(start, end))
1094 }
1095
1096 fn partial_insert(
1097 self,
1098 idx: u128,
1099 height: u8,
1100 digest: MerkleTreeDigest,
1101 ) -> Result<Self, InvalidUpdate> {
1102 Ok(MerkleTree(self.0.partial_insert(idx, height, digest)?))
1103 }
1104
1105 pub fn apply_collapsed_update(
1108 &self,
1109 update: &MerkleTreeCollapsedUpdate,
1110 ) -> Result<Self, InvalidUpdate> {
1111 let segments = MerkleTreeCollapsedUpdate::step_sizes(update.start, update.end + 1);
1112 if segments.len() != update.hashes.len() {
1113 return Err(InvalidUpdate::WrongNumberOfSegments(
1114 segments.len(),
1115 update.hashes.len(),
1116 ));
1117 }
1118 let mut curr_idx = update.start as u128;
1119 let mut curr = self.clone();
1120 for (segment, hash) in segments.into_iter().zip(update.hashes.iter()) {
1121 curr = curr.partial_insert(curr_idx, segment, *hash)?.clone();
1122 curr_idx += 1u128 << segment as u128;
1123 }
1124 Ok(curr)
1125 }
1126}
1127
1128impl<A: Storable<D>, D: DB> MerkleTree<A, D> {
1129 pub fn height(&self) -> u8 {
1131 self.0.height()
1132 }
1133
1134 pub fn root(&self) -> Option<MerkleTreeDigest> {
1138 self.0.root().map(MerkleTreeDigest)
1139 }
1140
1141 pub fn rehash(&self) -> Self {
1145 MerkleTree(Sp::new(self.0.rehash()))
1146 }
1147
1148 pub fn index(&self, index: u64) -> Option<(HashOutput, &A)> {
1151 self.0.index(index)
1152 }
1153
1154 pub fn iter(&self) -> MerkleTreeIter {
1156 MerkleTreeIter(
1157 self.0
1158 .leaves()
1159 .into_iter()
1160 .filter_map(|leaf| match leaf {
1161 LeafOrCollapsed::Leaf { index, hash, .. } => Some((index, hash)),
1162 _ => None,
1163 })
1164 .collect::<Vec<_>>()
1165 .into_iter(),
1166 )
1167 }
1168
1169 pub fn iter_aux(&self) -> MerkleTreeIterAux<A> {
1171 MerkleTreeIterAux(
1172 self.0
1173 .leaves()
1174 .into_iter()
1175 .filter_map(|leaf| match leaf {
1176 LeafOrCollapsed::Leaf { index, hash, aux } => {
1177 Some((index, (hash, aux.clone())))
1178 }
1179 _ => None,
1180 })
1181 .collect::<Vec<_>>()
1182 .into_iter(),
1183 )
1184 }
1185
1186 pub fn find_path_for_leaf<T: BinaryHashRepr>(&self, leaf: T) -> Option<MerklePath<T>> {
1193 self.find_path_for_leaf_inner(leaf_hash(&leaf), leaf, ..)
1194 }
1195
1196 pub fn find_path_for_leaf_within_range<T: BinaryHashRepr>(
1198 &self,
1199 leaf: T,
1200 range: impl RangeBounds<u64>,
1201 ) -> Option<MerklePath<T>> {
1202 self.find_path_for_leaf_inner(leaf_hash(&leaf), leaf, range)
1203 }
1204
1205 pub fn find_path_for_hashed_leaf_within_range(
1207 &self,
1208 leaf_hash: HashOutput,
1209 range: impl RangeBounds<u64>,
1210 ) -> Option<MerklePath<HashOutput>> {
1211 self.find_path_for_leaf_inner(leaf_hash, leaf_hash, range)
1212 }
1213
1214 fn find_path_for_leaf_inner<T>(
1215 &self,
1216 leaf_hash: HashOutput,
1217 leaf: T,
1218 range: impl RangeBounds<u64>,
1219 ) -> Option<MerklePath<T>> {
1220 for (index, hash) in self
1221 .0
1222 .leaves_in_range((range.start_bound().cloned(), range.end_bound().cloned()))
1223 .into_iter()
1224 .filter_map(|leaf| match leaf {
1225 LeafOrCollapsed::Leaf { index, hash, .. } => Some((index, hash)),
1226 _ => None,
1227 })
1228 {
1229 if leaf_hash == hash {
1230 return self.path_for_leaf(index, leaf).ok();
1231 }
1232 }
1233 None
1234 }
1235
1236 pub fn update_from_evidence(
1240 &self,
1241 insertion: TreeInsertionPath<A>,
1242 ) -> Result<Self, InvalidUpdate>
1243 where
1244 A: Serializable + Deserializable + Clone + Sync + Send + 'static,
1245 {
1246 Ok(MerkleTree(Sp::new(self.0.update_from_evidence_internal(
1247 insertion.leaf,
1248 &insertion.path,
1249 )?)))
1250 }
1251
1252 pub fn insertion_evidence(&self, index: u64) -> Result<TreeInsertionPath<A>, InvalidIndex>
1255 where
1256 A: Serializable + Deserializable + Clone + Sync + Send + 'static,
1257 {
1258 if self.height() == 0 {
1259 return Err(InvalidIndex(index));
1260 }
1261 let (path, lefts) = self.path_for_index_internal(index, false)?;
1262 let leaf = self.index(index).ok_or(InvalidIndex(index))?;
1263 Ok(TreeInsertionPath {
1264 leaf: (leaf.0, leaf.1.clone()),
1265 path: path
1266 .into_iter()
1267 .zip(lefts)
1268 .map(|(hash, goes_left)| {
1269 Ok(TreeInsertionPathEntry {
1270 hash: hash.map(MerkleTreeDigest),
1271 goes_left,
1272 })
1273 })
1274 .rev()
1275 .collect::<Result<_, _>>()?,
1276 })
1277 }
1278
1279 pub fn path_for_leaf<T>(&self, index: u64, leaf: T) -> Result<MerklePath<T>, InvalidIndex> {
1283 if self.height() == 0 {
1284 return if index == 0 {
1285 Ok(MerklePath {
1286 leaf,
1287 path: Vec::new(),
1288 })
1289 } else {
1290 Err(InvalidIndex(index))
1291 };
1292 }
1293 let (path, lefts) = self.path_for_index_internal(index, true)?;
1294 Ok(MerklePath {
1295 leaf,
1296 path: path
1297 .into_iter()
1298 .zip(lefts)
1299 .map(|(sibling, goes_left)| {
1300 Ok(MerklePathEntry {
1301 sibling: MerkleTreeDigest(sibling.ok_or(InvalidIndex(index))?),
1302 goes_left,
1303 })
1304 })
1305 .rev()
1306 .collect::<Result<_, _>>()?,
1307 })
1308 }
1309
1310 fn path_for_index_internal(
1311 &self,
1312 index: u64,
1313 siblings: bool,
1314 ) -> Result<(Vec<Option<Fr>>, Vec<bool>), InvalidIndex> {
1315 let mut at = self.0.deref();
1316 let mut i = index;
1317 assert!(
1318 at.height() >= 1,
1319 "height-0 trees should have been caught earlier"
1320 );
1321 let mut path = Vec::with_capacity(at.height() as usize);
1322 let mut goes_left = Vec::with_capacity(at.height() as usize);
1323 while at.height() > 1 {
1324 let cmp = 1 << (at.height() - 1);
1325 let nxt = match at {
1326 Leaf { .. } => unreachable!(),
1327 Stub { .. } => return Err(InvalidIndex(index)),
1328 Collapsed { .. } => return Err(InvalidIndex(index)),
1329 Node { left, right, .. } => {
1330 if i < cmp {
1331 path.push(if siblings { right.root() } else { at.root() });
1332 goes_left.push(true);
1333 left
1334 } else {
1335 path.push(if siblings { left.root() } else { at.root() });
1336 goes_left.push(false);
1337 i -= cmp;
1338 right
1339 }
1340 }
1341 };
1342 at = nxt;
1343 }
1344 goes_left.push(i == 0);
1345 let path_elem = match (siblings, i, at) {
1346 (_, _, Stub { .. }) => return Err(InvalidIndex(index)),
1347 (false, _, at) => at.root(),
1348 (true, 0, Node { right, .. }) => right.root(),
1349 (true, 1, Node { left, .. }) => left.root(),
1350 _ => unreachable!(),
1351 };
1352 path.push(path_elem);
1353 Ok((path, goes_left))
1354 }
1355}
1356
1357#[cfg(feature = "proptest")]
1358impl<A: Debug + Storable<D>, D: DB> Arbitrary for MerkleTree<A, D>
1359where
1360 Standard: Distribution<A>,
1361{
1362 type Parameters = ();
1363 type Strategy = NoStrategy<MerkleTree<A, D>>;
1364
1365 fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
1366 NoStrategy(PhantomData)
1367 }
1368}
1369
1370impl<A: Storable<D>, D: DB> Distribution<MerkleTree<A, D>> for Standard
1371where
1372 Standard: Distribution<u8> + Distribution<Fr> + Distribution<A>,
1373{
1374 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> MerkleTree<A, D> {
1375 let height: u8 = rng.gen_range(1..17);
1376 let mut mt = MerkleTree::blank(height);
1377
1378 for i in 0..height {
1379 if let Ok(updated) = mt.try_update(i.into(), &rng.r#gen::<Fr>(), rng.r#gen()) {
1380 mt = updated;
1381 }
1382 }
1383
1384 mt.rehash()
1385 }
1386}
1387
1388#[cfg(test)]
1389mod tests {
1390 use sha2::Sha256;
1391
1392 use storage_core::db::InMemoryDB;
1393
1394 use super::*;
1395
1396 fn new_mt<A: Storable<InMemoryDB>>(height: u8) -> MerkleTree<A, InMemoryDB<Sha256>> {
1397 MerkleTree::<A, InMemoryDB<Sha256>>::blank(height)
1398 }
1399
1400 #[test]
1401 fn test_membership() {
1402 let tree = new_mt::<()>(32)
1403 .try_update(0, &Fr::from(42u64), ())
1404 .and_then(|mt| mt.try_update(0, &Fr::from(41u64), ()))
1405 .and_then(|mt| mt.try_update(3, &Fr::from(43u64), ()))
1406 .and_then(|mt| mt.try_update(62, &Fr::from(12u64), ()))
1407 .unwrap()
1408 .rehash();
1409 assert_eq!(
1410 tree.path_for_leaf(0, Fr::from(41u64)).unwrap().root(),
1411 tree.root().unwrap()
1412 );
1413 assert_eq!(
1414 tree.path_for_leaf(3, Fr::from(43u64)).unwrap().root(),
1415 tree.root().unwrap()
1416 );
1417 assert_eq!(
1418 tree.path_for_leaf(62, Fr::from(12u64)).unwrap().root(),
1419 tree.root().unwrap()
1420 );
1421 }
1422
1423 #[test]
1424 fn test_collapse_good() {
1425 let tree = new_mt::<()>(32)
1426 .try_update(0, &Fr::from(42u64), ())
1427 .and_then(|mt| mt.try_update(0, &Fr::from(41u64), ()))
1428 .and_then(|mt| mt.try_update(3, &Fr::from(43u64), ()))
1429 .and_then(|mt| mt.try_update(62, &Fr::from(12u64), ()))
1430 .unwrap()
1431 .collapse(0, 61)
1432 .rehash();
1433 assert_eq!(
1434 tree.path_for_leaf(62, Fr::from(12u64)).unwrap().root(),
1435 tree.root().unwrap()
1436 );
1437 }
1438
1439 #[test]
1440 fn test_collapse_bad_proof() {
1441 let tree = new_mt::<()>(32)
1442 .try_update(0, &Fr::from(42u64), ())
1443 .and_then(|mt| mt.try_update(0, &Fr::from(41u64), ()))
1444 .and_then(|mt| mt.try_update(3, &Fr::from(43u64), ()))
1445 .and_then(|mt| mt.try_update(62, &Fr::from(12u64), ()))
1446 .unwrap()
1447 .collapse(0, 61)
1448 .rehash();
1449 assert!(tree.path_for_leaf(3, Fr::from(43u64)).is_err());
1450 }
1451
1452 #[test]
1453 fn test_collapse_bad_update() {
1454 let tree = new_mt::<()>(32)
1455 .try_update(0, &Fr::from(42u64), ())
1456 .and_then(|mt| mt.try_update(0, &Fr::from(41u64), ()))
1457 .and_then(|mt| mt.try_update(3, &Fr::from(43u64), ()))
1458 .and_then(|mt| mt.try_update(62, &Fr::from(12u64), ()))
1459 .unwrap()
1460 .collapse(0, 61)
1461 .try_update(61, &Fr::from(0xdeadbeefu64), ());
1462 assert_eq!(tree, Err(InvalidUpdate::CollapsedIndex(1, 1)));
1463 }
1464
1465 #[test]
1466 fn test_incremental_collapse() {
1467 let tree = new_mt::<()>(3)
1468 .try_update(0, &Fr::from(42u64), ())
1469 .unwrap()
1470 .collapse(0, 0)
1471 .try_update(1, &Fr::from(42u64), ())
1472 .unwrap()
1473 .collapse(1, 1)
1474 .try_update(2, &Fr::from(42u64), ())
1475 .unwrap()
1476 .collapse(2, 2)
1477 .try_update(3, &Fr::from(42u64), ())
1478 .unwrap()
1479 .try_update(4, &Fr::from(42u64), ())
1480 .unwrap()
1481 .collapse(4, 4);
1482 let tree2 = new_mt::<()>(3)
1483 .try_update(0, &Fr::from(42u64), ())
1484 .and_then(|mt| mt.try_update(1, &Fr::from(42u64), ()))
1485 .and_then(|mt| mt.try_update(2, &Fr::from(42u64), ()))
1486 .and_then(|mt| mt.try_update(3, &Fr::from(42u64), ()))
1487 .and_then(|mt| mt.try_update(4, &Fr::from(42u64), ()))
1488 .unwrap()
1489 .collapse(0, 2)
1490 .collapse(4, 4);
1491 assert_eq!(tree, tree2);
1492 }
1493
1494 #[test]
1495 fn test_collapsed_update() {
1496 let t = new_mt::<()>(6)
1497 .try_update(0, &Fr::from(42u64), ())
1498 .unwrap()
1499 .try_update(1, &Fr::from(42u64), ())
1500 .unwrap();
1501 let t2 = (2..=32)
1502 .fold(t.clone(), |t, i| {
1503 t.try_update(i, &Fr::from(42u64), ()).unwrap()
1504 })
1505 .rehash();
1506 let upd1 = MerkleTreeCollapsedUpdate::new(&t2, 2, 2).unwrap();
1507 let upd2 = MerkleTreeCollapsedUpdate::new(&t2, 3, 31).unwrap();
1508 let t3 = t.try_update(32, &Fr::from(42u64), ()).unwrap();
1509 let t4 = t3
1510 .apply_collapsed_update(&upd1)
1511 .unwrap()
1512 .apply_collapsed_update(&upd2)
1513 .unwrap()
1514 .rehash();
1515 assert_eq!(t4.root(), t2.root());
1516 }
1517
1518 #[test]
1519 fn test_insertion_evidence() {
1520 let t = (0..=32)
1521 .fold(new_mt::<()>(6), |t, i| {
1522 t.try_update(i, &Fr::from(42u64), ()).unwrap()
1523 })
1524 .rehash();
1525 let t2 = t.try_update(12, &Fr::from(43u64), ()).unwrap().rehash();
1526 let evidence = t2.insertion_evidence(12).unwrap();
1527 assert_eq!(
1528 t.update_from_evidence(evidence.clone()).unwrap().rehash(),
1529 t2
1530 );
1531 assert_eq!(
1532 t.collapse(0, 32)
1533 .update_from_evidence(evidence)
1534 .unwrap()
1535 .rehash()
1536 .root(),
1537 t2.root()
1538 );
1539 let t3 = (33..64).fold(
1541 t.try_update(12, &Fr::from(43u64), ()).unwrap().rehash(),
1542 |t, i| t.try_update(i, &Fr::from(42u64), ()).unwrap(),
1543 );
1544 let evidence = t3.insertion_evidence(12).unwrap();
1545 dbg!(&evidence);
1546 assert_eq!(
1548 t.collapse(0, 32)
1549 .update_from_evidence(evidence)
1550 .unwrap()
1551 .rehash()
1552 .root(),
1553 t2.root()
1554 );
1555 }
1556
1557 #[test]
1558 fn test_singleton_collapsed_update() {
1559 let t = new_mt::<()>(6)
1560 .try_update(0, &Fr::from(42u64), ())
1561 .unwrap()
1562 .rehash();
1563 let upd = MerkleTreeCollapsedUpdate::new(&t, 0, 0).unwrap();
1564 let t2 = new_mt::<()>(6)
1565 .apply_collapsed_update(&upd)
1566 .unwrap()
1567 .rehash();
1568 assert_eq!(t.root(), t2.root());
1569 }
1570
1571 #[test]
1572 fn test_tiny_trees() {
1573 let t = new_mt::<()>(1)
1574 .try_update(0, &Fr::from(42u64), ())
1575 .unwrap()
1576 .try_update(1, &Fr::from(42u64), ())
1577 .unwrap();
1578 t.path_for_leaf(0, Fr::from(42u64)).unwrap();
1579 let t = new_mt::<()>(0).try_update(0, &Fr::from(42u64), ()).unwrap();
1580 t.path_for_leaf(0, Fr::from(42u64)).unwrap();
1581 }
1582
1583 #[test]
1584 fn test_aux_data() {
1585 let t = new_mt::<u8>(32)
1586 .try_update(0, &Fr::from(42u64), 10)
1587 .unwrap();
1588 for (_index, (_hash, aux)) in t.iter_aux() {
1589 assert_eq!(aux, 10);
1590 }
1591 }
1592
1593 #[test]
1594 fn test_find_path_for_leaf_within_range() {
1595 let tree = new_mt::<()>(32)
1596 .try_update(0, &Fr::from(10u64), ())
1597 .and_then(|mt| mt.try_update(5, &Fr::from(20u64), ()))
1598 .and_then(|mt| mt.try_update(10, &Fr::from(30u64), ()))
1599 .unwrap()
1600 .rehash();
1601
1602 assert!(
1604 tree.find_path_for_leaf_within_range(Fr::from(20u64), ..)
1605 .is_some()
1606 );
1607
1608 assert!(
1610 tree.find_path_for_leaf_within_range(Fr::from(20u64), 3..=7)
1611 .is_some()
1612 );
1613
1614 assert!(
1616 tree.find_path_for_leaf_within_range(Fr::from(20u64), 0..=4)
1617 .is_none()
1618 );
1619 assert!(
1620 tree.find_path_for_leaf_within_range(Fr::from(20u64), 6..=100)
1621 .is_none()
1622 );
1623
1624 let path = tree
1626 .find_path_for_leaf_within_range(Fr::from(30u64), 8..=12)
1627 .expect("leaf at index 10 should be in range 8..=12");
1628 assert_eq!(path.root(), tree.root().unwrap());
1629 }
1630
1631 #[test]
1632 fn test_find_path_for_hashed_leaf_within_range() {
1633 let tree = new_mt::<()>(32)
1634 .try_update(0, &Fr::from(10u64), ())
1635 .and_then(|mt| mt.try_update(5, &Fr::from(20u64), ()))
1636 .unwrap()
1637 .rehash();
1638
1639 let hash = leaf_hash(&Fr::from(20u64));
1640
1641 assert!(
1643 tree.find_path_for_hashed_leaf_within_range(hash, ..)
1644 .is_some()
1645 );
1646
1647 assert!(
1649 tree.find_path_for_hashed_leaf_within_range(hash, 5..=5)
1650 .is_some()
1651 );
1652 assert!(
1653 tree.find_path_for_hashed_leaf_within_range(hash, 0..=4)
1654 .is_none()
1655 );
1656 }
1657
1658 #[test]
1659 fn test_find_within_range_with_collapsed() {
1660 let tree = new_mt::<()>(6)
1661 .try_update(0, &Fr::from(10u64), ())
1662 .and_then(|mt| mt.try_update(5, &Fr::from(20u64), ()))
1663 .and_then(|mt| mt.try_update(10, &Fr::from(30u64), ()))
1664 .unwrap()
1665 .collapse(0, 4)
1666 .rehash();
1667
1668 assert!(
1670 tree.find_path_for_leaf_within_range(Fr::from(10u64), ..)
1671 .is_none()
1672 );
1673
1674 assert!(
1676 tree.find_path_for_leaf_within_range(Fr::from(20u64), ..)
1677 .is_some()
1678 );
1679
1680 assert!(
1682 tree.find_path_for_leaf_within_range(Fr::from(20u64), 0..=4)
1683 .is_none()
1684 );
1685 }
1686
1687 #[test]
1688 fn test_find_within_range_duplicate_leaves() {
1689 let val = Fr::from(42u64);
1690 let tree = new_mt::<()>(6)
1691 .try_update(2, &val, ())
1692 .and_then(|mt| mt.try_update(5, &val, ()))
1693 .and_then(|mt| mt.try_update(8, &val, ()))
1694 .unwrap()
1695 .rehash();
1696
1697 let path = tree
1699 .find_path_for_leaf_within_range(val, 4..=6)
1700 .expect("should find leaf at index 5");
1701 assert_eq!(path.root(), tree.root().unwrap());
1702
1703 let path = tree
1704 .find_path_for_leaf_within_range(val, 7..=10)
1705 .expect("should find leaf at index 8");
1706 assert_eq!(path.root(), tree.root().unwrap());
1707
1708 assert!(tree.find_path_for_leaf_within_range(val, 3..=4).is_none());
1710 }
1711
1712 #[test]
1713 fn test_update_rejects_out_of_bounds_index() {
1714 let val = Fr::from(42u64);
1715 let tree = new_mt::<()>(1).try_update(1, &val, ()).unwrap().rehash();
1716
1717 let root_before = tree.root().unwrap();
1718
1719 let other_value = Fr::from(43u64);
1720 let result = tree.try_update(10, &other_value, ()).unwrap_err();
1721
1722 assert_eq!(result, InvalidUpdate::IndexOutOfTree(10));
1723 assert_eq!(tree.root().unwrap(), root_before);
1724 }
1725
1726 #[test]
1727 fn test_update_hash_rejects_out_of_bounds_index() {
1728 let val = Fr::from(42u64);
1729 let tree = new_mt::<()>(1);
1730 let hash = leaf_hash(&val);
1731
1732 let result = tree.try_update_hash(10, hash, ()).unwrap_err();
1733
1734 assert_eq!(result, InvalidUpdate::IndexOutOfTree(10));
1735 }
1736
1737 #[cfg(feature = "proptest")]
1738 proptest::proptest! {
1739 #[test]
1740 fn test_update_rejects_indices_at_or_above_tree_size(
1741 height in 0u8..=20,
1742 extra in 0u64..=1024,
1743 leaf in proptest::arbitrary::any::<u64>(),
1744 ) {
1745 let tree = new_mt::<()>(height);
1746 let tree_size = 1u64 << height;
1747 let index = tree_size + extra;
1748
1749 proptest::prop_assert_eq!(
1750 tree.try_update(index, &Fr::from(leaf), ()).unwrap_err(),
1751 InvalidUpdate::IndexOutOfTree(index),
1752 );
1753 }
1754 }
1755}