-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathproof.rs
More file actions
2821 lines (2590 loc) · 102 KB
/
proof.rs
File metadata and controls
2821 lines (2590 loc) · 102 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Defines the generic inclusion [Proof] structure for Merkle-family data structures.
//!
//! The [Proof] struct is parameterized by a [`Family`] marker and a [`Digest`] type. Each Merkle
//! family (MMR, MMB, etc.) reuses the shared verification and reconstruction logic in this module,
//! while retaining any family-specific proof helpers in its submodule.
use crate::merkle::{hasher::Hasher, Bagging, Error, Family, Location, Position};
use alloc::{
collections::{BTreeMap, BTreeSet},
vec,
vec::Vec,
};
use bytes::{Buf, BufMut};
use commonware_codec::{varint::UInt, EncodeSize, ReadExt, ReadRangeExt, Write};
use commonware_cryptography::Digest;
use core::ops::Range;
/// Errors that can occur when reconstructing a digest from a proof due to invalid input.
#[derive(thiserror::Error, Debug)]
pub enum ReconstructionError {
#[error("invalid proof")]
InvalidProof,
#[error("missing digests in proof")]
MissingDigests,
#[error("extra digests in proof")]
ExtraDigests,
#[error("start location is out of bounds")]
InvalidStartLoc,
#[error("end location is out of bounds")]
InvalidEndLoc,
#[error("missing elements")]
MissingElements,
#[error("invalid size")]
InvalidSize,
}
/// Contains the information necessary for proving the inclusion of an element, or some range of
/// elements, in a Merkle-family data structure from its root digest.
///
/// For range proofs, the `digests` vector uses a fold-based layout:
///
/// 1. If there are folded peaks entirely before the proven range, the first digest is a single
/// accumulator produced by folding those peaks: `fold(fold(..., peak0), peak1)`. If there are
/// no such peaks, this entry is absent.
///
/// 2. The digests of any non-folded peaks entirely before the proven range, in peak iteration
/// order.
///
/// 3. For `ForwardFold`, the digests of peaks entirely after the proven range, in peak iteration
/// order. For `BackwardFold`, inactive after-peaks are still listed individually, while active
/// after-peaks are collapsed into one optional suffix accumulator.
///
/// 4. The sibling digests needed to reconstruct each range-peak digest from the proven elements,
/// in depth-first (forward consumption) order for each range peak.
///
/// Multi-proofs use a different, position-keyed layout: `digests` contains the sorted set of node
/// digests required by the requested `inactive_peaks` and bagging policy. For `BackwardFold`, this
/// may include active suffix peaks that a single range proof could collapse into a synthetic suffix
/// accumulator.
#[derive(Clone, Debug, Eq)]
pub struct Proof<F: Family, D: Digest> {
/// The total number of leaves in the data structure. For MMR proofs, this is the number of
/// leaves in the MMR, though other authenticated data structures may override the meaning of
/// this field. For example, the authenticated [crate::AuthenticatedBitMap] stores the number
/// of bits in the bitmap within this field.
pub leaves: Location<F>,
/// The number of inactive peaks in the structure when this proof was generated.
pub inactive_peaks: usize,
/// The digests necessary for proving inclusion.
pub digests: Vec<D>,
}
impl<F: Family, D: Digest> PartialEq for Proof<F, D> {
fn eq(&self, other: &Self) -> bool {
self.leaves == other.leaves
&& self.inactive_peaks == other.inactive_peaks
&& self.digests == other.digests
}
}
impl<F: Family, D: Digest> EncodeSize for Proof<F, D> {
fn encode_size(&self) -> usize {
self.leaves.encode_size()
+ UInt(self.inactive_peaks as u64).encode_size()
+ self.digests.encode_size()
}
}
impl<F: Family, D: Digest> Write for Proof<F, D> {
fn write(&self, buf: &mut impl BufMut) {
self.leaves.write(buf);
UInt(self.inactive_peaks as u64).write(buf);
self.digests.write(buf);
}
}
impl<F: Family, D: Digest> commonware_codec::Read for Proof<F, D> {
/// The maximum number of digests in the proof.
type Cfg = usize;
fn read_cfg(
buf: &mut impl Buf,
max_digests: &Self::Cfg,
) -> Result<Self, commonware_codec::Error> {
let leaves = Location::<F>::read(buf)?;
let inactive_peaks = usize::try_from(UInt::<u64>::read(buf)?.0).map_err(|_| {
commonware_codec::Error::Invalid("Proof", "inactive_peaks exceeds usize")
})?;
let digests = Vec::<D>::read_range(buf, ..=*max_digests)?;
Ok(Self {
leaves,
inactive_peaks,
digests,
})
}
}
impl<F: Family, D: Digest> Default for Proof<F, D> {
/// Create an empty proof. The empty proof will verify only against the root digest of an empty
/// (`leaves == 0`) data structure.
fn default() -> Self {
Self {
leaves: Location::new(0),
inactive_peaks: 0,
digests: vec![],
}
}
}
impl<F: Family, D: Digest> Proof<F, D> {
/// Return true if this proof proves that `element` appears at location `loc` within the
/// structure with root digest `root`, using the bagging carried by `hasher`.
pub fn verify_element_inclusion<H>(
&self,
hasher: &H,
element: &[u8],
loc: Location<F>,
root: &D,
) -> bool
where
H: Hasher<F, Digest = D>,
{
self.verify_range_inclusion(hasher, &[element], loc, root)
}
/// Return true if this proof verifies against the supplied root, using the bagging carried by
/// `hasher`.
pub fn verify_range_inclusion<H, E>(
&self,
hasher: &H,
elements: &[E],
start_loc: Location<F>,
root: &D,
) -> bool
where
H: Hasher<F, Digest = D>,
E: AsRef<[u8]>,
{
match self.reconstruct_root_inner(hasher, elements, start_loc, None) {
Ok(reconstructed_root) => *root == reconstructed_root,
Err(_error) => {
#[cfg(feature = "std")]
tracing::debug!(error = ?_error, "invalid proof input");
false
}
}
}
/// Returns true if this proof's `inactive_peaks` field matches the canonical value derived
/// from `size` and `inactivity_floor`.
pub fn matches_canonical_inactive_peaks(
&self,
size: Position<F>,
inactivity_floor: Location<F>,
) -> bool {
self.inactive_peaks == F::inactive_peaks(size, inactivity_floor)
}
/// Verify a position-keyed multi-proof using the bagging carried by `hasher`.
///
/// Multi-proofs keep every witness tied to a concrete node position, so this path may include
/// extra backward-bagged suffix peaks that range proofs can collapse into a suffix accumulator.
pub fn verify_multi_inclusion<H, E>(
&self,
hasher: &H,
elements: &[(E, Location<F>)],
root: &D,
) -> bool
where
H: Hasher<F, Digest = D>,
E: AsRef<[u8]>,
{
let bagging = hasher.root_bagging();
// Empty proof is valid only for an empty tree with no extra digest data.
if elements.is_empty() {
return self.digests.is_empty()
&& self.leaves == Location::new(0)
&& self.inactive_peaks == 0
&& *root
== hasher
.root(Location::new(0), 0, core::iter::empty())
.expect("zero inactive peaks is always valid");
}
// Collect all required positions with deduplication, and blueprints per element.
let mut node_positions = BTreeSet::new();
let mut blueprints = BTreeMap::new();
for (_, loc) in elements {
if !loc.is_valid_index() {
return false;
}
// `loc` is valid so it won't overflow from +1
let Ok(bp) = Blueprint::new(self.leaves, self.inactive_peaks, bagging, *loc..*loc + 1)
else {
return false;
};
node_positions.extend(bp.fold_prefix.iter().map(|s| s.pos));
node_positions.extend(&bp.fetch_nodes);
if let Some(suffix_peaks) = bp.suffix_peaks() {
node_positions.extend(suffix_peaks);
}
blueprints.insert(*loc, bp);
}
// Verify we have the exact number of digests needed
if node_positions.len() != self.digests.len() {
return false;
}
// Build position to digest mapping once
let node_digests: BTreeMap<Position<F>, D> = node_positions
.iter()
.zip(self.digests.iter())
.map(|(&pos, digest)| (pos, *digest))
.collect();
// Verify each element by constructing its sub-proof in fold-based format
for (element, loc) in elements {
let bp = &blueprints[loc];
let suffix_count = usize::from(bp.suffix_peaks().is_some());
let mut digests = Vec::with_capacity(
if bp.fold_prefix.is_empty() { 0 } else { 1 } + bp.fetch_nodes.len() + suffix_count,
);
if let Some((first_sub, rest)) = bp.fold_prefix.split_first() {
let first = *node_digests
.get(&first_sub.pos)
.expect("must exist by construction");
let acc = rest.iter().fold(first, |acc, sub| {
let d = node_digests
.get(&sub.pos)
.expect("must exist by construction");
hasher.fold(&acc, d)
});
digests.push(acc);
}
let prefix_active_count = bp.prefix_active_count();
let after_count = bp.after_peaks_count();
for &pos in &bp.fetch_nodes[..prefix_active_count + after_count] {
let d = node_digests.get(&pos).expect("must exist by construction");
digests.push(*d);
}
if let Some(suffix_peaks) = bp.suffix_peaks() {
let (last_pos, rest_pos) = suffix_peaks
.split_last()
.expect("suffix_peaks is non-empty when returned");
let mut acc = *node_digests
.get(last_pos)
.expect("must exist by construction");
for pos in rest_pos.iter().rev() {
let d = node_digests.get(pos).expect("must exist by construction");
acc = hasher.fold(d, &acc);
}
digests.push(acc);
}
for &pos in &bp.fetch_nodes[prefix_active_count + after_count..] {
let d = node_digests.get(&pos).expect("must exist by construction");
digests.push(*d);
}
let proof = Self {
leaves: self.leaves,
inactive_peaks: self.inactive_peaks,
digests,
};
match proof.reconstruct_root_inner(hasher, &[element.as_ref()], *loc, None) {
Ok(reconstructed_root) if &reconstructed_root == root => {}
Ok(_) | Err(_) => return false,
}
}
true
}
/// Reconstruct the root digest from this proof and the given consecutive elements using
/// the bagging carried by `hasher`, or return a `ReconstructionError` if the input data is
/// invalid.
pub fn reconstruct_root<H, E>(
&self,
hasher: &H,
elements: &[E],
start_loc: Location<F>,
) -> Result<D, ReconstructionError>
where
H: Hasher<F, Digest = D>,
E: AsRef<[u8]>,
{
self.reconstruct_root_inner(hasher, elements, start_loc, None)
}
/// Verify this proof against `root` and extract all authenticated digests.
///
/// Reconstructs the root from the proof and provided elements and returns every
/// `(position, digest)` pair required by that reconstruction, including the proof's own
/// digests. Returns [`Error::InvalidProof`] if the input data is malformed and
/// [`Error::RootMismatch`] if the reconstructed root does not match `root`.
pub fn verify_range_inclusion_and_extract_digests<H, E>(
&self,
hasher: &H,
elements: &[E],
start_loc: Location<F>,
root: &D,
) -> Result<Vec<(Position<F>, D)>, Error<F>>
where
H: Hasher<F, Digest = D>,
E: AsRef<[u8]>,
{
let mut collected_digests = Vec::new();
let Ok(reconstructed_root) =
self.reconstruct_root_inner(hasher, elements, start_loc, Some(&mut collected_digests))
else {
return Err(Error::InvalidProof);
};
if reconstructed_root != *root {
return Err(Error::RootMismatch);
}
Ok(collected_digests)
}
/// Verify this proof and the pinned nodes against `root`.
///
/// The proof's `inactive_peaks` field commits to the split boundary; peak bagging is selected
/// by `hasher`.
///
/// The `pinned_nodes` are the peak digests of the sub-structure at `start_loc`, in the order
/// returned by `Family::nodes_to_pin`. The proof authenticates the prefix `[0, start_loc)` via:
///
/// - fold-prefix peaks of the larger tree, and
/// - sibling subtrees inside the first range peak that lie wholly before `start_loc`.
///
/// When the larger tree has merged smaller subtrees into a bigger parent, the pins sit below
/// these authenticated subtrees. The verifier hashes pairs of pins up to each authenticated
/// subtree's root and compares against the proof.
///
/// For example, in MMB at `leaves=5, start_loc=4`, the proof describes `[0, 4)` as one
/// height-2 subtree `p7`, while the pins cover the same leaves as two height-1 subtrees
/// `p2`, `p5`:
///
/// ```text
/// proof authenticates: pins contain:
///
/// p7
/// / \
/// p2 p5 p2 p5
/// / \ / \ / \ / \
/// L0 L1 L2 L3 L0 L1 L2 L3
/// ```
///
/// The verifier walks down from `p7` via `F::children`, pulls the pins for `p2` and `p5`, and
/// hashes them back up (`node_digest(p7, pin[p2], pin[p5])`) to compare against the `p7`
/// digest the proof authenticates.
///
/// Returns `true` only if the proof reconstructs to `root` and every pinned node digest is
/// accounted for. When `start_loc` is 0, `pinned_nodes` must be empty.
pub fn verify_proof_and_pinned_nodes<H, E>(
&self,
hasher: &H,
elements: &[E],
start_loc: Location<F>,
pinned_nodes: &[D],
root: &D,
) -> bool
where
H: Hasher<F, Digest = D>,
E: AsRef<[u8]>,
{
self.try_verify_proof_and_pinned_nodes(hasher, elements, start_loc, pinned_nodes, root)
.is_some()
}
/// Fallible implementation of [`verify_proof_and_pinned_nodes`](Self::verify_proof_and_pinned_nodes).
///
/// Returns `Some(())` if the proof and pins are consistent with `root`, `None` otherwise. The
/// `Option` return lets the body use `?` on each fallible step; the public wrapper converts to
/// `bool` via `.is_some()`.
fn try_verify_proof_and_pinned_nodes<H, E>(
&self,
hasher: &H,
elements: &[E],
start_loc: Location<F>,
pinned_nodes: &[D],
root: &D,
) -> Option<()>
where
H: Hasher<F, Digest = D>,
E: AsRef<[u8]>,
{
let bagging = hasher.root_bagging();
let collected = self
.verify_range_inclusion_and_extract_digests(hasher, elements, start_loc, root)
.ok()?;
if elements.is_empty() {
return pinned_nodes.is_empty().then_some(());
}
if !start_loc.is_valid() || start_loc > self.leaves {
return None;
}
let pinned_positions: Vec<_> = F::nodes_to_pin(start_loc).collect();
if pinned_positions.len() != pinned_nodes.len() {
return None;
}
let end_loc = start_loc.checked_add(elements.len() as u64)?;
let bp = Blueprint::new(
self.leaves,
self.inactive_peaks,
bagging,
start_loc..end_loc,
)
.ok()?;
let mut pinned_map: BTreeMap<Position<F>, D> = pinned_positions
.into_iter()
.zip(pinned_nodes.iter().copied())
.collect();
// Fold-prefix peaks of the larger tree may have merged several pins together. Reconstruct
// each peak's digest by hashing the pins beneath it up to the peak, then compare the
// folded accumulator against the one the proof carries.
if let Some((first_sub, rest)) = bp.fold_prefix.split_first() {
let &expected = self.digests.first()?;
let mut acc = first_sub.reconstruct_from_pins(hasher, &mut pinned_map)?;
for sub in rest {
let d = sub.reconstruct_from_pins(hasher, &mut pinned_map)?;
acc = hasher.fold(&acc, &d);
}
if acc != expected {
return None;
}
}
let extracted: BTreeMap<Position<F>, D> = collected.into_iter().collect();
// Verify prefix active peaks that were not folded.
for sub in &bp.prefix_active_peaks {
let &expected = extracted.get(&sub.pos)?;
let d = sub.reconstruct_from_pins(hasher, &mut pinned_map)?;
if d != expected {
return None;
}
}
// Sibling subtrees inside the first range peak that lie wholly before `start_loc` are
// authenticated directly by the proof (their digests appear in `extracted`). Rebuild each
// from the pins and compare.
for sibling in bp.prefix_siblings() {
let &expected = extracted.get(&sibling.pos)?;
let d = sibling.reconstruct_from_pins(hasher, &mut pinned_map)?;
if d != expected {
return None;
}
}
// Every pin must have been consumed by one of the two reconstructions above.
pinned_map.is_empty().then_some(())
}
/// Reconstruct a root from range-proof digests and optionally collect authenticated nodes.
///
/// Reads the bagging policy from `hasher`. When `collected` is supplied, the verifier records
/// the intermediate node digests it authenticates while reconstructing the range.
pub(crate) fn reconstruct_root_inner<H, E>(
&self,
hasher: &H,
elements: &[E],
start_loc: Location<F>,
collected: Option<&mut Vec<(Position<F>, D)>>,
) -> Result<D, ReconstructionError>
where
H: Hasher<F, Digest = D>,
E: AsRef<[u8]>,
{
let bagging = hasher.root_bagging();
let mut collected = collected;
if elements.is_empty() {
if start_loc == 0 {
if self.inactive_peaks != 0 {
return Err(ReconstructionError::InvalidProof);
}
if self.leaves != Location::new(0) {
return Err(ReconstructionError::MissingElements);
}
return if self.digests.is_empty() {
Ok(hasher.digest(&self.leaves.to_be_bytes()))
} else {
Err(ReconstructionError::ExtraDigests)
};
}
return Err(ReconstructionError::MissingElements);
}
if !start_loc.is_valid_index() {
return Err(ReconstructionError::InvalidStartLoc);
}
let end_loc = start_loc
.checked_add(elements.len() as u64)
.ok_or(ReconstructionError::InvalidEndLoc)?;
if end_loc > self.leaves {
return Err(ReconstructionError::InvalidEndLoc);
}
let range = start_loc..end_loc;
let bp = Blueprint::new(self.leaves, self.inactive_peaks, bagging, range)
.map_err(|_| ReconstructionError::InvalidSize)?;
let proof_digests = bp.split_proof_digests(&self.digests)?;
// Collect all peak digests to provide to hasher.root().
let mut peak_digests = Vec::new();
if let Some(&digest) = proof_digests.fold_prefix {
peak_digests.push(digest);
}
for (sub, &digest) in bp
.prefix_active_peaks
.iter()
.zip(proof_digests.prefix_active_peaks)
{
peak_digests.push(digest);
if let Some(ref mut cd) = collected {
cd.push((sub.pos, digest));
}
}
let mut sibling_cursor = 0usize;
let mut elements_iter = elements.iter();
for peak in &bp.range_peaks {
let peak_digest = peak.reconstruct_digest(
hasher,
&bp.range,
&mut elements_iter,
proof_digests.siblings,
&mut sibling_cursor,
collected.as_deref_mut(),
)?;
if let Some(ref mut cd) = collected {
cd.push((peak.pos, peak_digest));
}
peak_digests.push(peak_digest);
}
for (&after_peak_pos, &digest) in bp.after_peaks.iter().zip(proof_digests.after_peaks) {
if let Some(ref mut cd) = collected {
cd.push((after_peak_pos, digest));
}
peak_digests.push(digest);
}
if let Some(&digest) = proof_digests.suffix_acc {
peak_digests.push(digest);
}
// Verify all elements were consumed.
if elements_iter.next().is_some() {
return Err(ReconstructionError::ExtraDigests);
}
// Verify all siblings were consumed.
if sibling_cursor != proof_digests.siblings.len() {
return Err(ReconstructionError::ExtraDigests);
}
hasher
.root_with_folded_peaks(
self.leaves,
bp.inactive_peaks_after_prefix_fold(self.inactive_peaks),
self.inactive_peaks,
peak_digests.iter(),
)
.ok_or(ReconstructionError::InvalidProof)
}
/// Authenticate the proven range without reconstructing the full generic Merkle root.
///
/// This consumes only the sibling digests needed to rebuild the proven range peaks, then returns
/// those peak digests in `collected`. It deliberately does not consume peak-bagging witnesses
/// such as prefix peaks, after peaks, or backward-fold suffix accumulators.
///
/// Current QMDB grafted proofs use this path because their final root is rebuilt by the wrapper
/// from the collected range peaks plus grafted prefix/suffix witnesses. Including generic
/// peak-bagging witnesses here would create proof bytes that the wrapper root ignores, making
/// those bytes malleable.
#[cfg(feature = "std")]
pub(crate) fn reconstruct_range_collecting<H, E>(
&self,
hasher: &H,
elements: &[E],
start_loc: Location<F>,
collected: &mut Vec<(Position<F>, D)>,
) -> Result<(), ReconstructionError>
where
H: Hasher<F, Digest = D>,
E: AsRef<[u8]>,
{
if elements.is_empty() {
return Err(ReconstructionError::MissingElements);
}
if !start_loc.is_valid_index() {
return Err(ReconstructionError::InvalidStartLoc);
}
let end_loc = start_loc
.checked_add(elements.len() as u64)
.ok_or(ReconstructionError::InvalidEndLoc)?;
if end_loc > self.leaves {
return Err(ReconstructionError::InvalidEndLoc);
}
let range = start_loc..end_loc;
let peaks = range_peaks(self.leaves, self.inactive_peaks, &range)
.map_err(|_| ReconstructionError::InvalidSize)?;
let mut sibling_cursor = 0usize;
let mut elements_iter = elements.iter();
for peak in &peaks {
let peak_digest = peak.reconstruct_digest(
hasher,
&range,
&mut elements_iter,
&self.digests,
&mut sibling_cursor,
None,
)?;
collected.push((peak.pos, peak_digest));
}
if elements_iter.next().is_some() || sibling_cursor != self.digests.len() {
return Err(ReconstructionError::ExtraDigests);
}
Ok(())
}
}
/// A perfect binary subtree within a peak, identified by its root position, height,
/// and the first leaf location it covers.
#[derive(Copy, Clone)]
pub(crate) struct Subtree<F: Family> {
/// Position of the subtree root node.
pub pos: Position<F>,
pub height: u32,
pub leaf_start: Location<F>,
}
impl<F: Family> Subtree<F> {
fn leaf_end(&self) -> Location<F> {
self.leaf_start + (1u64 << self.height)
}
/// True if this subtree's leaves lie wholly before `range.start`.
fn is_before(&self, range: &Range<Location<F>>) -> bool {
self.leaf_end() <= range.start
}
/// True if this subtree's leaves lie wholly outside `range` (either before it or after it).
fn is_outside(&self, range: &Range<Location<F>>) -> bool {
self.is_before(range) || self.leaf_start >= range.end
}
fn children(&self) -> (Self, Self) {
let (left_pos, right_pos) = F::children(self.pos, self.height);
let child_height = self.height - 1;
let mid = self.leaf_start + (1u64 << child_height);
(
Self {
pos: left_pos,
height: child_height,
leaf_start: self.leaf_start,
},
Self {
pos: right_pos,
height: child_height,
leaf_start: mid,
},
)
}
/// Collect sibling positions needed to reconstruct this subtree digest from a range of
/// elements, in left-first DFS order.
///
/// At each node: if the subtree is entirely outside the range, its root position is emitted. If
/// it's a leaf in the range, nothing is emitted. Otherwise, recurse into children.
fn collect_siblings(&self, range: &Range<Location<F>>, out: &mut Vec<Position<F>>) {
if self.is_outside(range) {
out.push(self.pos);
return;
}
if self.height > 0 {
let (left, right) = self.children();
left.collect_siblings(range, out);
right.collect_siblings(range, out);
}
}
/// Collect sibling subtrees that lie wholly before the proven range, in the same
/// left-first DFS order as [`collect_siblings`](Self::collect_siblings).
///
/// Only `range.start` is consulted: the `range.end` side doesn't matter for prefix
/// siblings. Pruning on `range.start` also keeps the traversal O(height) per peak:
/// pruning only by `range.end` would recurse into both children whenever a subtree
/// sits entirely inside the proven range, costing O(2^height) per such peak.
fn collect_prefix_siblings(&self, range: &Range<Location<F>>, out: &mut Vec<Self>) {
if self.is_before(range) {
out.push(*self);
return;
}
if self.leaf_start >= range.start {
return;
}
if self.height > 0 {
let (left, right) = self.children();
left.collect_prefix_siblings(range, out);
right.collect_prefix_siblings(range, out);
}
}
/// Reconstruct this subtree's digest from a set of finer-grained pinned positions, consuming
/// each pin as it is used.
///
/// Walks down via [`Self::children`] until each recursion hits a pin, then hashes back up with
/// [`Hasher::node_digest`] for position-keyed domain separation. Returns `None` if any required
/// pin is missing.
///
/// On failure, `pinned_map` may have been partially consumed. Callers are expected to return
/// immediately without inspecting it further.
fn reconstruct_from_pins<D, H>(
&self,
hasher: &H,
pinned_map: &mut BTreeMap<Position<F>, D>,
) -> Option<D>
where
D: Digest,
H: Hasher<F, Digest = D>,
{
if let Some(d) = pinned_map.remove(&self.pos) {
return Some(d);
}
if self.height == 0 {
return None;
}
let (left, right) = self.children();
let left_d = left.reconstruct_from_pins(hasher, pinned_map)?;
let right_d = right.reconstruct_from_pins(hasher, pinned_map)?;
Some(hasher.node_digest(self.pos, &left_d, &right_d))
}
/// Reconstruct the digest of this subtree from a range of elements and sibling digests,
/// consuming both in left-first DFS order.
///
/// At each node:
/// - If the subtree is entirely outside the range: consume a sibling digest.
/// - If it's a leaf in the range: hash the next element.
/// - Otherwise: recurse into children via [`Family::children`] and compute the node digest.
///
/// If `collected` is `Some`, every child `(position, digest)` pair encountered during
/// reconstruction is appended to the vector.
fn reconstruct_digest<D, H, E>(
&self,
hasher: &H,
range: &Range<Location<F>>,
elements: &mut E,
siblings: &[D],
cursor: &mut usize,
mut collected: Option<&mut Vec<(Position<F>, D)>>,
) -> Result<D, ReconstructionError>
where
D: Digest,
H: Hasher<F, Digest = D>,
E: Iterator<Item: AsRef<[u8]>>,
{
// Entirely outside the range: consume a sibling digest.
if self.is_outside(range) {
let Some(digest) = siblings.get(*cursor).copied() else {
return Err(ReconstructionError::MissingDigests);
};
*cursor += 1;
return Ok(digest);
}
// Leaf in range: hash the next element.
if self.height == 0 {
let elem = elements
.next()
.ok_or(ReconstructionError::MissingElements)?;
return Ok(hasher.leaf_digest(self.pos, elem.as_ref()));
}
// Recurse into children.
let (left, right) = self.children();
let left_d = left.reconstruct_digest(
hasher,
range,
elements,
siblings,
cursor,
collected.as_deref_mut(),
)?;
let right_d = right.reconstruct_digest(
hasher,
range,
elements,
siblings,
cursor,
collected.as_deref_mut(),
)?;
if let Some(ref mut cd) = collected {
cd.push((left.pos, left_d));
cd.push((right.pos, right_d));
}
Ok(hasher.node_digest(self.pos, &left_d, &right_d))
}
}
/// Return the peaks of a tree of `leaves` that overlap `range`, validating both the range and the
/// declared `inactive_peaks` boundary.
///
/// The returned subtrees are bagging-independent: `Blueprint::new`'s prefix/suffix accumulator
/// layout depends on bagging, but the per-peak partition of the proven range does not.
///
/// # Errors
///
/// See [`Blueprint::new`].
#[cfg(feature = "std")]
pub(crate) fn range_peaks<F: Family>(
leaves: Location<F>,
inactive_peaks: usize,
range: &Range<Location<F>>,
) -> Result<Vec<Subtree<F>>, super::Error<F>> {
// Bagging only affects `Blueprint`'s prefix/suffix bucketing; `range_peaks` is independent.
Blueprint::new(leaves, inactive_peaks, Bagging::ForwardFold, range.clone())
.map(|bp| bp.range_peaks)
}
/// Blueprint for a range proof, separating fold-prefix peaks from nodes that must be fetched.
pub(crate) struct Blueprint<F: Family> {
/// Total number of leaves in the structure this blueprint was built for.
leaves: Location<F>,
/// The location range this blueprint was built for.
range: Range<Location<F>>,
/// Peaks that precede the proven range (to be folded into a single accumulator).
pub(crate) fold_prefix: Vec<Subtree<F>>,
prefix_active_peaks: Vec<Subtree<F>>,
/// Peak positions entirely after the proven range.
after_peaks: Vec<Position<F>>,
/// Active peak positions after the proven range that are collapsed into one suffix accumulator.
suffix_peaks: Vec<Position<F>>,
/// The peaks that overlap the proven range.
range_peaks: Vec<Subtree<F>>,
/// Node positions to include in the proof: after-peaks followed by DFS siblings.
pub(crate) fetch_nodes: Vec<Position<F>>,
}
pub(crate) struct ProofDigestLayout<'a, D> {
pub(crate) fold_prefix: Option<&'a D>,
pub(crate) prefix_active_peaks: &'a [D],
pub(crate) after_peaks: &'a [D],
pub(crate) suffix_acc: Option<&'a D>,
pub(crate) siblings: &'a [D],
}
impl<F: Family> Blueprint<F> {
/// Build a range-proof blueprint for a caller-supplied bagging policy.
///
/// Forward bagging folds peaks before the range into one prefix accumulator. Backward bagging
/// also collapses active peaks after the range into one suffix accumulator while leaving inactive
/// after-peaks position-keyed.
pub(crate) fn new(
leaves: Location<F>,
inactive_peaks: usize,
bagging: Bagging,
range: Range<Location<F>>,
) -> Result<Self, super::Error<F>> {
if range.is_empty() {
return Err(super::Error::Empty);
}
let end_minus_one = range
.end
.checked_sub(1)
.expect("can't underflow because range is non-empty");
if end_minus_one >= leaves {
return Err(super::Error::RangeOutOfBounds(range.end));
}
let size = Position::try_from(leaves)?;
let mut fold_prefix = Vec::new();
let mut prefix_active_peaks = Vec::new();
let mut after_peaks = Vec::new();
let mut suffix_peaks = Vec::new();
let mut range_peaks = Vec::new();
let mut leaf_cursor = Location::new(0);
let mut peak_index = 0;
for (peak_pos, height) in F::peaks(size) {
let leaf_start = leaf_cursor;
let leaf_end = leaf_start + (1u64 << height);
if leaf_end <= range.start {
if peak_index < inactive_peaks || bagging == Bagging::ForwardFold {
fold_prefix.push(Subtree {
pos: peak_pos,
height,
leaf_start,
});
} else {
prefix_active_peaks.push(Subtree {
pos: peak_pos,
height,
leaf_start,
});
}
} else if leaf_start >= range.end {
if bagging == Bagging::BackwardFold && peak_index >= inactive_peaks {
suffix_peaks.push(peak_pos);
} else {
after_peaks.push(peak_pos);
}
} else {
range_peaks.push(Subtree {
pos: peak_pos,
height,
leaf_start,
});
}
leaf_cursor = leaf_end;
peak_index += 1;
}
// `inactive_peaks` is a global boundary over the tree's peaks, not just the peaks before
// this range. It may point into or beyond the proven range; reconstruction then folds the
// same global boundary and the final root comparison rejects non-canonical proofs.
if inactive_peaks > peak_index {
return Err(super::Error::InvalidProof);
}
assert!(
!range_peaks.is_empty(),
"at least one peak must contain range elements"
);
let mut fetch_nodes: Vec<_> = prefix_active_peaks.iter().map(|s| s.pos).collect();
fetch_nodes.extend_from_slice(&after_peaks);
for peak in &range_peaks {
peak.collect_siblings(&range, &mut fetch_nodes);
}
Ok(Self {
leaves,
range,
fold_prefix,
prefix_active_peaks,
after_peaks,
suffix_peaks,
range_peaks,
fetch_nodes,
})
}
/// Sibling subtrees of the first range peak that lie wholly before `self.range.start`.
///
/// Only the first range peak can contain such siblings; later range peaks are entirely at or
/// after `range.start` by this blueprint's classification.
pub(crate) fn prefix_siblings(&self) -> Vec<Subtree<F>> {
let mut out = Vec::new();
if let Some(peak) = self.range_peaks.first() {
peak.collect_prefix_siblings(&self.range, &mut out);
}
out
}
/// Return the number of active prefix peak digests stored before after-peak digests.
pub(crate) const fn prefix_active_count(&self) -> usize {
self.prefix_active_peaks.len()
}