ant_node/replication/subtree.rs
1//! Gossip-triggered contiguous-subtree storage proof (ADR-0002).
2//!
3//! Pure, network-free core of the audit redesign. Given a peer's signed
4//! [`StorageCommitment`] and an auditor-chosen random nonce, both sides
5//! deterministically select **one contiguous subtree** of the committed
6//! Merkle tree; the responder expands that subtree to its leaves plus the
7//! sibling cut-hashes on the path to the root; the auditor rebuilds the root
8//! and spot-checks a few leaves against real chunk bytes.
9//!
10//! Three independent checks (ADR-0002 "Verification, three independent
11//! checks"); this module owns the first two — the third (response deadline)
12//! is enforced by the caller:
13//!
14//! 1. **Structure** — [`verify_subtree_proof`] re-derives the selected branch
15//! from `(nonce, key_count)`, rebuilds the root from the returned leaves and
16//! cut-hashes, and requires it to equal the pinned root.
17//! 2. **Verified slice** — [`select_spotcheck_indices`] picks a few leaves
18//! within the subtree; the caller opens one random block per leaf and checks
19//! a Bao slice against the chunk address plus a nonced-tree opening against
20//! the round-1 keyed `nonced_root`. Faking a fraction `x` of leaves survives
21//! only `(1 - x)^k`.
22//!
23//! ## Tree geometry (must match [`super::commitment::MerkleTree`])
24//!
25//! Leaves are sorted by key and fill positions `0..N`. The tree is
26//! left-packed: when a level has an odd number of nodes the last node is
27//! paired with itself (`node_hash(x, x)`). There are no explicit padding
28//! leaves; "padding" is the empty right side of a subtree slot that extends
29//! past `N`. Depth `D = ceil(log2(N))`. A node identified by `(depth, slot)`
30//! (depth measured from the root, slot in `0..2^depth`) covers the contiguous
31//! leaf range `[slot * span, (slot + 1) * span)` where `span = 2^(D - depth)`,
32//! intersected with `0..N`.
33
34use super::commitment::{leaf_hash, node_hash, StorageCommitment, MAX_COMMITMENT_KEY_COUNT};
35use crate::ant_protocol::XorName;
36use serde::{Deserialize, Serialize};
37
38/// Below this key count the whole tree is challenged; `sqrt` rounding is
39/// meaningless for tiny trees and a full proof is cheap.
40pub const SMALL_TREE_FULL_AUDIT_FLOOR: u32 = 4;
41
42/// One leaf of the selected subtree, as returned by the responder.
43#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
44pub struct SubtreeLeaf {
45 /// The committed key (chunk address) at this leaf position.
46 pub key: XorName,
47 /// `BLAKE3(record_bytes)` — the plain content hash. For a content-addressed
48 /// chunk this EQUALS `key` (the address IS the content hash), and the round-1
49 /// verifier enforces `bytes_hash == key` so credit for `key` cannot be earned
50 /// by proving possession of unrelated bytes. It is public; possessing it does
51 /// NOT prove possession of the bytes (that is what `nonced_root` is for). It is
52 /// also the BLAKE3/Bao root the round-2 slice verifies against.
53 pub bytes_hash: [u8; 32],
54 /// Length of the chunk's content, in bytes. Lets the auditor draw a random
55 /// 1 KiB block index in range and size the Bao slice for the final (short)
56 /// block. This field is NOT bound by the signed commitment (the Merkle leaf
57 /// hashes only `key ‖ bytes_hash`), so the round-2 verifier must not trust it
58 /// blind: `verify_block_slice` authenticates it against the Bao slice's own
59 /// length header (validated against the address), rejecting any claim that
60 /// disagrees with the true content length. Without that check a deflated
61 /// `content_len` would collapse the challenge to block 0 and forge possession
62 /// of a large chunk from a ~1 KiB prefix slice.
63 pub content_len: u32,
64 /// Root of the responder's fresh **nonced block tree** for this chunk (see
65 /// [`crate::replication::slice`]): a Merkle root over the chunk's 1 KiB
66 /// blocks whose leaves each bind the fresh nonce, peer, key and block bytes.
67 /// Building it requires every byte of the chunk under the fresh nonce, so it
68 /// commits real possession; round 2 opens one random block against it.
69 pub nonced_root: [u8; 32],
70}
71
72/// A responder's single-contiguous-subtree proof (ADR-0002 "The proof").
73#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
74pub struct SubtreeProof {
75 /// Every leaf of the selected subtree, in ascending leaf-index order.
76 pub leaves: Vec<SubtreeLeaf>,
77 /// One sibling cut-hash per level on the path from the root down to the
78 /// selected subtree root, ordered root-first. Each is the plain hash of
79 /// the unselected sibling node at that level.
80 pub sibling_cut_hashes: Vec<[u8; 32]>,
81}
82
83/// The deterministically-selected contiguous subtree, derived from
84/// `(nonce, key_count)` and agreed by both sides.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub struct SubtreePath {
87 /// Depth of the subtree root below the tree root (0 = whole tree).
88 pub depth: u32,
89 /// Slot index of the subtree root within its level, in `0..2^depth`.
90 pub slot: u32,
91 /// First real leaf index covered (inclusive).
92 pub leaf_start: u32,
93 /// One past the last real leaf index covered (exclusive). Always
94 /// `leaf_end > leaf_start`, so the selection never covers zero real
95 /// leaves — this is the ADR's dead-block fix.
96 pub leaf_end: u32,
97}
98
99impl SubtreePath {
100 /// Number of real (non-padding) leaves in the selected subtree.
101 #[must_use]
102 pub fn real_leaf_count(&self) -> u32 {
103 self.leaf_end - self.leaf_start
104 }
105}
106
107/// Tree depth `D = ceil(log2(key_count))`, matching `MerkleTree` / `verify_path`.
108///
109/// `key_count == 1` → depth 0 (the single leaf is the root). Returns `None`
110/// for an out-of-protocol `key_count` so callers reject it before any work.
111#[must_use]
112fn tree_depth(key_count: u32) -> Option<u32> {
113 if key_count == 0 || key_count > MAX_COMMITMENT_KEY_COUNT {
114 return None;
115 }
116 // checked_next_power_of_two cannot fail under the cap above, but the
117 // explicit check keeps behaviour identical across debug/release.
118 let rounded = key_count.checked_next_power_of_two()?;
119 Some(rounded.trailing_zeros())
120}
121
122/// Count real leaves under the node at `(depth, slot)` for a tree of `key_count`
123/// leaves. Pure function of geometry — identical on auditor and responder.
124///
125/// `span = 2^(total_depth - depth)`; the node covers `[slot*span, (slot+1)*span)`
126/// clamped to `0..key_count`. Test-only geometry helper.
127#[cfg(test)]
128#[must_use]
129fn real_leaves_under(depth: u32, slot: u64, key_count: u32, total_depth: u32) -> u32 {
130 let levels_below = total_depth - depth;
131 // span fits in u64: total_depth <= 20 for key_count <= 1e6.
132 let span = 1u64 << levels_below;
133 let start = slot.saturating_mul(span).min(u64::from(key_count));
134 let end = slot
135 .saturating_add(1)
136 .saturating_mul(span)
137 .min(u64::from(key_count));
138 // end >= start always; difference fits in u32 (<= key_count).
139 u32::try_from(end - start).unwrap_or(0)
140}
141
142/// `ceil(sqrt(key_count))` — the real-leaf floor a selected subtree must meet.
143#[must_use]
144fn sqrt_floor(key_count: u32) -> u32 {
145 // Exact integer ceil(sqrt(n)), float-free and MSRV-safe (no u64::isqrt).
146 // Newton's method converges to floor(sqrt(n)); then round up unless n is a
147 // perfect square. Always at least 1.
148 let n = u64::from(key_count);
149 if n <= 1 {
150 return 1;
151 }
152 let mut x = n;
153 let mut y = x.div_ceil(2);
154 while y < x {
155 x = y;
156 y = u64::midpoint(x, n / x);
157 }
158 // x == floor(sqrt(n)) here.
159 let ceil = if x.saturating_mul(x) == n { x } else { x + 1 };
160 u32::try_from(ceil.max(1)).unwrap_or(u32::MAX)
161}
162
163/// A stable `u64` drawn from the first 8 bytes of the nonce, used to pick the
164/// subtree slot uniformly. The nonce is fresh CSPRNG per audit, so modulo bias
165/// over the small slot count (≤ ~1000) is negligible.
166#[must_use]
167fn nonce_u64(nonce: &[u8; 32]) -> u64 {
168 let mut b = [0u8; 8];
169 b.copy_from_slice(&nonce[..8]);
170 u64::from_le_bytes(b)
171}
172
173/// The largest real-leaf count any selected subtree can have for `key_count`.
174///
175/// A full fixed-depth block of `next_power_of_two(ceil(sqrt(key_count)))` leaves.
176/// Bounds a single round-1 request's read/hash work (≤ 1024 leaves at the
177/// `MAX_COMMITMENT_KEY_COUNT` cap). Used both to size selection and as a
178/// pre-read defense-in-depth ceiling in [`subtree_plan`].
179#[must_use]
180pub fn max_subtree_leaves(key_count: u32) -> u32 {
181 if key_count <= SMALL_TREE_FULL_AUDIT_FLOOR {
182 return key_count;
183 }
184 sqrt_floor(key_count).next_power_of_two()
185}
186
187/// Deterministically select one contiguous subtree from `(nonce, key_count)`.
188///
189/// Picks one **fixed-depth block** of `span = next_power_of_two(ceil(sqrt(N)))`
190/// leaves, choosing the block uniformly by `nonce_u64 % slot_count`. Every block
191/// (including the short tail) is selectable with roughly equal probability, so
192/// the whole tree is covered over many audits, and a single request always reads
193/// at most `span` (≤ ~sqrt(N), ≤ 1024 at the cap) leaves — regardless of the
194/// nonce. This replaces the old nonce-bit descent, whose stop-at-parent rule let
195/// an adversarial nonce select a subtree far larger than `sqrt(N)` (up to the
196/// whole tree at `2^k + 1`), an unbounded round-1 work amplification.
197///
198/// Unpredictability is preserved: the responder cannot know the selected slot
199/// until it receives the fresh nonce. For `key_count <= SMALL_TREE_FULL_AUDIT_FLOOR`
200/// the whole tree is selected.
201///
202/// Returns `None` only for an out-of-protocol `key_count` (caller rejects).
203#[must_use]
204pub fn select_subtree_path(nonce: &[u8; 32], key_count: u32) -> Option<SubtreePath> {
205 let total_depth = tree_depth(key_count)?;
206
207 // Tiny trees: challenge everything.
208 if key_count <= SMALL_TREE_FULL_AUDIT_FLOOR {
209 return Some(SubtreePath {
210 depth: 0,
211 slot: 0,
212 leaf_start: 0,
213 leaf_end: key_count,
214 });
215 }
216
217 // Fixed block size >= sqrt(N), aligned to a tree level so the block IS a
218 // single subtree node at `depth = total_depth - log2(span)`.
219 let span = sqrt_floor(key_count).next_power_of_two();
220 let span_log2 = span.trailing_zeros();
221 // span <= next_power_of_two(key_count) == 2^total_depth, so span_log2 <=
222 // total_depth and depth is non-negative.
223 let depth = total_depth.saturating_sub(span_log2);
224 let slot_count = key_count.div_ceil(span);
225 let slot = u32::try_from(nonce_u64(nonce) % u64::from(slot_count)).unwrap_or(0);
226
227 let span64 = u64::from(span);
228 let leaf_start = u32::try_from(
229 u64::from(slot)
230 .saturating_mul(span64)
231 .min(u64::from(key_count)),
232 )
233 .unwrap_or(key_count);
234 let leaf_end = leaf_start.saturating_add(span).min(key_count);
235
236 Some(SubtreePath {
237 depth,
238 slot,
239 leaf_start,
240 leaf_end,
241 })
242}
243
244/// Pick `k` distinct nonce-derived leaf positions within the selected subtree.
245///
246/// Returned as indices into `path.real_leaf_count()` (0-based within the
247/// subtree). DETERMINISTIC from the nonce.
248///
249/// **NOT used for the live round-2 sample.** Deriving the slice-challenge sample
250/// from the round-1 nonce is unsound: the structural root check binds only
251/// `(key, bytes_hash)` (both public), not the per-leaf `nonced_root`, so a
252/// responder that knows the nonce at proof-build time could fabricate a
253/// `nonced_root` on every un-sampled leaf and hold only the predictable sample.
254/// The auditor therefore chooses the round-2 sample with fresh CSPRNG randomness
255/// *after* receiving the proof
256/// (`storage_commitment_audit::random_spotcheck_leaves`). This
257/// deterministic helper is retained only for tests/observers that need a
258/// reproducible selection.
259#[must_use]
260pub fn select_spotcheck_indices(nonce: &[u8; 32], path: &SubtreePath, k: u32) -> Vec<u32> {
261 let n = path.real_leaf_count();
262 if n == 0 {
263 return Vec::new();
264 }
265 if n <= k {
266 return (0..n).collect();
267 }
268 // Derive a stream of indices by hashing (nonce || counter) and reducing
269 // mod n; skip collisions. Bounded: k is small (clamped to the 3..=5 band)
270 // and n > k.
271 let mut out: Vec<u32> = Vec::with_capacity(k as usize);
272 let mut counter: u32 = 0;
273 while u32::try_from(out.len()).unwrap_or(u32::MAX) < k {
274 let mut h = blake3::Hasher::new();
275 h.update(b"autonomi.ant.replication.audit_spotcheck.v1");
276 h.update(nonce);
277 h.update(&counter.to_le_bytes());
278 let digest = *h.finalize().as_bytes();
279 let mut word = [0u8; 4];
280 word.copy_from_slice(&digest[..4]);
281 let idx = u32::from_le_bytes(word) % n;
282 if !out.contains(&idx) {
283 out.push(idx);
284 }
285 counter = counter.wrapping_add(1);
286 // Bound the hash stream (vanishingly unlikely to bite with n > k).
287 if counter > k.saturating_mul(64) {
288 break;
289 }
290 }
291 // Top up deterministically if the bounded hash stream collided too often:
292 // take the lowest indices not yet selected. Still nonce-independent only in
293 // this (astronomically rare) tail, and identical on every observer — the
294 // caller is guaranteed exactly min(k, n) distinct indices, so the byte
295 // sample is never silently smaller than requested.
296 let mut candidate: u32 = 0;
297 while u32::try_from(out.len()).unwrap_or(u32::MAX) < k && candidate < n {
298 if !out.contains(&candidate) {
299 out.push(candidate);
300 }
301 candidate += 1;
302 }
303 out
304}
305
306/// Verdict from [`verify_subtree_proof`]'s structural check.
307#[derive(Debug, Clone, PartialEq, Eq)]
308pub enum StructureVerdict {
309 /// Proof is well-formed and its root matches the pinned commitment.
310 Valid,
311 /// Proof is malformed or its root does not match. Carries a static reason
312 /// for logging; all variants are confirmed failures, not benign.
313 Invalid(&'static str),
314}
315
316/// Structural verification (ADR-0002 check 1): the returned subtree genuinely
317/// belongs to the committed tree.
318///
319/// Re-derives the selected branch from `(nonce, commitment.key_count)`,
320/// rebuilds the root from `proof.leaves` and `proof.sibling_cut_hashes`, and
321/// requires it to equal `commitment.root`. Also checks leaf count and
322/// ascending-key order (the committed tree sorts leaves by key).
323///
324/// This does NOT verify possession of bytes — that is the caller's spot-check
325/// using [`select_spotcheck_indices`]. It only proves the structure.
326#[must_use]
327pub fn verify_subtree_proof(
328 proof: &SubtreeProof,
329 nonce: &[u8; 32],
330 commitment: &StorageCommitment,
331) -> StructureVerdict {
332 let Some(path) = select_subtree_path(nonce, commitment.key_count) else {
333 return StructureVerdict::Invalid("out-of-protocol key_count");
334 };
335
336 // Leaf count must equal the agreed subtree's real-leaf count exactly.
337 let expected_leaves = path.real_leaf_count() as usize;
338 if proof.leaves.len() != expected_leaves {
339 return StructureVerdict::Invalid("wrong leaf count");
340 }
341 // Sibling cut-hashes: one per level on the path to the subtree root.
342 if proof.sibling_cut_hashes.len() != path.depth as usize {
343 return StructureVerdict::Invalid("wrong cut-hash count");
344 }
345
346 // Leaves must be strictly ascending by key (matches MerkleTree sort), which
347 // also rejects duplicates.
348 for w in proof.leaves.windows(2) {
349 if let [a, b] = w {
350 if a.key >= b.key {
351 return StructureVerdict::Invalid("leaves not strictly ascending");
352 }
353 }
354 }
355
356 // Out-of-protocol key_count cannot happen here (select_subtree_path already
357 // returned Some), but recompute total_depth defensively for the climb maths.
358 let Some(total_depth) = tree_depth(commitment.key_count) else {
359 return StructureVerdict::Invalid("out-of-protocol key_count");
360 };
361
362 // Phase A — reconstruct the selected subtree's root NODE exactly as the
363 // committed tree's level-by-level build produces it. The subtree root sits
364 // at `(level_from_leaves, slot)`, covering a left-packed block of leaves;
365 // folding that block up `level_from_leaves` levels with the same
366 // self-pair-the-last-node rule as `MerkleTree::build_next_level` yields the
367 // identical node (including the `node_hash(x, x)` self-pair when the block
368 // is the tree's odd tail at some level). `fold_to_root` stopped at a single
369 // hash and so skipped the self-pair when a truncated block reached length 1
370 // before climbing all the way to the subtree-root level — the geometry bug.
371 let leaf_hashes: Vec<[u8; 32]> = proof
372 .leaves
373 .iter()
374 .map(|l| leaf_hash(&l.key, &l.bytes_hash))
375 .collect();
376 let levels_to_subtree_root = total_depth - path.depth;
377 let mut cur = fold_levels(leaf_hashes, levels_to_subtree_root);
378
379 // Phase B — climb from the subtree root to the tree root using one sibling
380 // cut-hash per level, exactly like `verify_path`: the climb's left/right
381 // choice is the real node-index parity, NOT a nonce bit, and the self-pair
382 // of an odd level's last node falls out naturally when the builder supplied
383 // the chosen node itself as its own sibling. The cut-hashes are root-first,
384 // so we consume them in reverse (lowest climb step uses the last cut-hash).
385 //
386 // We recompute the node index of the subtree root the same way the builder
387 // walked the nonce bits, then halve it as we climb — mirroring `verify_path`.
388 let mut node_index = u64::from(path.slot);
389 for level_above in (0..path.depth).rev() {
390 let Some(sibling) = proof.sibling_cut_hashes.get(level_above as usize) else {
391 return StructureVerdict::Invalid("missing cut-hash");
392 };
393 cur = if node_index % 2 == 0 {
394 node_hash(&cur, sibling)
395 } else {
396 node_hash(sibling, &cur)
397 };
398 node_index /= 2;
399 }
400
401 if cur == commitment.root {
402 StructureVerdict::Valid
403 } else {
404 StructureVerdict::Invalid("root mismatch")
405 }
406}
407
408/// Fold a contiguous, left-aligned block of node hashes up exactly `levels`
409/// levels, applying the same left-packed self-pair rule as
410/// `MerkleTree::build_next_level` (`node_hash(x, x)` for an unpaired last node).
411///
412/// This is the generalisation of a single-leaf inclusion fold to a *range* of
413/// leaves: a subtree root at `(levels, slot)` covers a block whose left edge is
414/// pair-aligned at every sub-level, so the only odd run that can occur is the
415/// tree's genuine odd tail — exactly when `build_next_level` self-pairs. Folding
416/// the block `levels` times therefore reproduces the committed node bit-for-bit,
417/// including the self-pair that `fold_to_root` used to skip by stopping at a
418/// single hash too early.
419///
420/// `levels == 0` returns the block's single element unchanged (the subtree IS
421/// the tree, e.g. the small-tree full-audit case after its own folds, or a
422/// single-leaf tree). An empty input is impossible here (callers guarantee ≥ 1
423/// leaf via the dead-block fix); returns a zero hash defensively.
424#[must_use]
425fn fold_levels(mut level: Vec<[u8; 32]>, levels: u32) -> [u8; 32] {
426 if level.is_empty() {
427 return [0u8; 32];
428 }
429 // Fold up `levels` times using the SAME builder as `MerkleTree::build`
430 // (§10 — `build_next_level`), so the self-pair of an odd tail matches the
431 // committed tree exactly. Within a selected, left-aligned block the only
432 // odd run that can occur is the tree's genuine odd tail.
433 for _ in 0..levels {
434 level = crate::replication::commitment::build_next_level(&level);
435 }
436 // After `levels` folds of a `2^levels`-span left-aligned block, exactly one
437 // node remains; defensively fall back if the block was shorter.
438 level.first().copied().unwrap_or([0u8; 32])
439}
440
441/// Why a responder could not build a subtree proof for a challenge.
442#[derive(Debug, Clone, PartialEq, Eq)]
443pub enum BuildProofError {
444 /// The challenge's `key_count` (from the pinned commitment) is out of
445 /// protocol range. Should never happen for a commitment we built.
446 BadKeyCount,
447 /// A selected leaf's key could not be resolved from the tree (internal
448 /// inconsistency; should never happen).
449 MissingKey {
450 /// The leaf index that could not be resolved.
451 leaf_index: u32,
452 },
453 /// The responder no longer holds the bytes for a selected, committed key.
454 /// This is real storage loss / deliberate non-response — the caller turns
455 /// it into a confirmed audit failure, NOT a benign rejection.
456 MissingBytes {
457 /// The committed key whose bytes are gone.
458 key: XorName,
459 },
460}
461
462/// Build the single-contiguous-subtree proof for `(nonce, tree)` (responder).
463///
464/// `bytes_for(&key)` returns the chunk bytes the responder holds for a key, or
465/// `None` if it cannot read them. Walks the same nonce-selected path the
466/// auditor will re-derive, reads the unselected sibling cut-hashes directly
467/// from the committed tree (so they are provably consistent with the gossiped
468/// root), and builds each selected leaf's plain and nonced hashes from the real
469/// bytes.
470///
471/// # Errors
472///
473/// See [`BuildProofError`]. `MissingBytes` is the one the caller penalises;
474/// the others indicate an internal inconsistency.
475pub fn build_subtree_proof(
476 tree: &super::commitment::MerkleTree,
477 nonce: &[u8; 32],
478 challenged_peer_id: &[u8; 32],
479 bytes_for: impl Fn(&XorName) -> Option<Vec<u8>>,
480) -> Result<SubtreeProof, BuildProofError> {
481 let plan = subtree_plan(tree, nonce)?;
482 let mut leaves = Vec::with_capacity(plan.leaf_keys.len());
483 for key in &plan.leaf_keys {
484 let bytes = bytes_for(key).ok_or(BuildProofError::MissingBytes { key: *key })?;
485 leaves.push(subtree_leaf(nonce, challenged_peer_id, key, &bytes));
486 }
487 Ok(SubtreeProof {
488 leaves,
489 sibling_cut_hashes: plan.sibling_cut_hashes,
490 })
491}
492
493/// The pure (no-bytes) geometry of a subtree proof.
494///
495/// Holds the ordered keys whose bytes the responder must hash and the sibling
496/// cut-hashes read from the tree. Splitting this out lets an async responder
497/// read chunk bytes per leaf without forcing the tree-walking maths to be async.
498#[derive(Debug, Clone)]
499pub struct SubtreePlan {
500 /// The selected leaves' keys, in ascending leaf-index order.
501 pub leaf_keys: Vec<XorName>,
502 /// One sibling cut-hash per level on the path to the subtree root,
503 /// root-first.
504 pub sibling_cut_hashes: Vec<[u8; 32]>,
505}
506
507/// Compute the [`SubtreePlan`] for `(nonce, tree)` — selection geometry only,
508/// no chunk bytes touched.
509///
510/// # Errors
511///
512/// [`BuildProofError::BadKeyCount`] for an out-of-protocol tree;
513/// [`BuildProofError::MissingKey`] if a selected leaf index is not in the tree
514/// (internal inconsistency).
515pub fn subtree_plan(
516 tree: &super::commitment::MerkleTree,
517 nonce: &[u8; 32],
518) -> Result<SubtreePlan, BuildProofError> {
519 let key_count = tree.key_count();
520 let path = select_subtree_path(nonce, key_count).ok_or(BuildProofError::BadKeyCount)?;
521
522 // Defense-in-depth: the fixed-depth selection already bounds this to one
523 // block of `max_subtree_leaves` leaves, but reject BEFORE any leaf read if a
524 // future selection change ever produced an oversized subtree, so one request
525 // can never force unbounded round-1 read/hash work.
526 if path.real_leaf_count() > max_subtree_leaves(key_count) {
527 return Err(BuildProofError::BadKeyCount);
528 }
529
530 let mut leaf_keys = Vec::with_capacity(path.real_leaf_count() as usize);
531 for idx in path.leaf_start..path.leaf_end {
532 let key = tree
533 .key_at(idx as usize)
534 .ok_or(BuildProofError::MissingKey { leaf_index: idx })?;
535 leaf_keys.push(key);
536 }
537
538 // Sibling cut-hashes, root-first. The fixed-depth slot selection no longer
539 // follows a per-level nonce walk, so derive the on-path node at each level
540 // from `path.slot`'s prefix bits: the top `d + 1` bits give the node index at
541 // level `d + 1` below the root. The sibling is the other child at level
542 // `total_depth - (d + 1)` (counting up from leaves); on an odd level the
543 // missing sibling self-pairs (the chosen node is its own sibling).
544 let total_depth = u32::try_from(tree.levels_count().saturating_sub(1)).unwrap_or(0);
545 let mut sibling_cut_hashes = Vec::with_capacity(path.depth as usize);
546 for d in 0..path.depth {
547 let child = u64::from(path.slot) >> (path.depth - (d + 1));
548 let sibling = child ^ 1;
549 let level_from_leaves = (total_depth - (d + 1)) as usize;
550 let chosen_hash = tree.node_at(level_from_leaves, child);
551 let sib_hash = tree
552 .node_at(level_from_leaves, sibling)
553 .or(chosen_hash)
554 .ok_or(BuildProofError::BadKeyCount)?;
555 sibling_cut_hashes.push(sib_hash);
556 }
557
558 Ok(SubtreePlan {
559 leaf_keys,
560 sibling_cut_hashes,
561 })
562}
563
564/// Build one subtree leaf from its key and the chunk bytes the responder holds.
565///
566/// The plain `bytes_hash` is the chunk's content address; the `nonced_root` is
567/// the fresh per-audit nonced block-tree root over the same bytes, committing
568/// possession at round-1 time (see [`crate::replication::slice`]).
569#[must_use]
570pub fn subtree_leaf(
571 nonce: &[u8; 32],
572 challenged_peer_id: &[u8; 32],
573 key: &XorName,
574 bytes: &[u8],
575) -> SubtreeLeaf {
576 SubtreeLeaf {
577 key: *key,
578 bytes_hash: *blake3::hash(bytes).as_bytes(),
579 content_len: u32::try_from(bytes.len()).unwrap_or(u32::MAX),
580 nonced_root: crate::replication::slice::nonced_block_root(
581 nonce,
582 challenged_peer_id,
583 key,
584 bytes,
585 ),
586 }
587}
588
589#[cfg(test)]
590#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
591mod tests {
592 use super::*;
593 use crate::replication::commitment::MerkleTree;
594
595 fn xn_u32(i: u32) -> XorName {
596 let mut k = [0u8; 32];
597 k[..4].copy_from_slice(&i.to_be_bytes()); // big-endian so numeric order == sort order
598 k
599 }
600 fn nonce_of(seed: u8) -> [u8; 32] {
601 [seed; 32]
602 }
603
604 // ---- sqrt_floor -------------------------------------------------------
605
606 #[test]
607 fn sqrt_floor_is_exact_ceil() {
608 assert_eq!(sqrt_floor(1), 1);
609 assert_eq!(sqrt_floor(4), 2);
610 assert_eq!(sqrt_floor(5), 3); // ceil(sqrt(5)) = 3
611 assert_eq!(sqrt_floor(9), 3);
612 assert_eq!(sqrt_floor(10), 4);
613 assert_eq!(sqrt_floor(100), 10);
614 assert_eq!(sqrt_floor(101), 11);
615 assert_eq!(sqrt_floor(1_000_000), 1000);
616 }
617
618 // ---- real_leaves_under ------------------------------------------------
619
620 #[test]
621 fn real_leaves_under_root_is_all() {
622 let d = tree_depth(100).unwrap();
623 assert_eq!(real_leaves_under(0, 0, 100, d), 100);
624 }
625
626 #[test]
627 fn real_leaves_under_padding_slot_is_zero() {
628 // key_count = 5, total_depth = 3 (next_pow2(5)=8). Leaf slots 5,6,7
629 // at the bottom are padding. The right half at depth 1 (slot 1) covers
630 // leaves [4,8) → only leaf 4 is real.
631 let d = tree_depth(5).unwrap();
632 assert_eq!(d, 3);
633 assert_eq!(real_leaves_under(1, 0, 5, d), 4); // [0,4)
634 assert_eq!(real_leaves_under(1, 1, 5, d), 1); // [4,8) ∩ [0,5) = {4}
635 assert_eq!(real_leaves_under(3, 7, 5, d), 0); // pure padding leaf
636 assert_eq!(real_leaves_under(2, 3, 5, d), 0); // [6,8) pure padding
637 }
638
639 // ---- select_subtree_path: dead-block regression -----------------------
640
641 #[test]
642 fn selection_never_empty_and_within_ceiling_across_sizes_and_nonces() {
643 for n in [
644 5u32, 6, 7, 9, 13, 17, 33, 65, 100, 129, 333, 1000, 1024, 1025,
645 ] {
646 let ceiling = max_subtree_leaves(n);
647 for seed in 0u8..=255 {
648 let path = select_subtree_path(&nonce_of(seed), n).unwrap();
649 // Never empty (ADR dead-block fix).
650 assert!(
651 path.real_leaf_count() >= 1,
652 "n={n} seed={seed}: empty selection"
653 );
654 // Bounded (DoS fix): one request reads at most one fixed-depth
655 // block, regardless of the (possibly adversarial) nonce.
656 assert!(
657 path.real_leaf_count() <= ceiling,
658 "n={n} seed={seed}: real={} > ceiling={ceiling}",
659 path.real_leaf_count()
660 );
661 assert!(path.leaf_end <= n);
662 assert!(path.leaf_start < path.leaf_end);
663 }
664 }
665 }
666
667 /// The denial-of-service the fixed-depth selection closes: under the OLD
668 /// nonce-bit descent, `key_count = 2^19 + 1` with a nonce steering to the
669 /// sparse side selected the WHOLE tree (~2 TiB of reads). Now every nonce
670 /// selects at most one `max_subtree_leaves`-sized block, and the tail slot is
671 /// a single leaf — not
672 /// the root.
673 #[test]
674 fn adversarial_nonce_cannot_amplify_round1_work() {
675 for &n in &[513u32, 1025, 524_289, 1_000_000, MAX_COMMITMENT_KEY_COUNT] {
676 let ceiling = max_subtree_leaves(n);
677 // A generous cap: sqrt-scale, never the whole tree for a large N.
678 assert!(
679 u64::from(ceiling) <= 1024.max(u64::from(n)),
680 "n={n}: ceiling {ceiling} not sqrt-scale"
681 );
682 for nonce in [[0x00u8; 32], [0xFFu8; 32], [0xAAu8; 32], [0x55u8; 32]] {
683 let path = select_subtree_path(&nonce, n).unwrap();
684 assert!(
685 path.real_leaf_count() <= ceiling && path.real_leaf_count() >= 1,
686 "n={n}: real={} outside 1..={ceiling}",
687 path.real_leaf_count()
688 );
689 if n >= 512 {
690 assert!(
691 u64::from(path.real_leaf_count()) < u64::from(n),
692 "n={n}: a single request must not cover the whole tree"
693 );
694 }
695 }
696 }
697 }
698
699 /// Every slot is selectable and the slots partition `0..key_count` with no
700 /// gaps, so the tail leaf is never permanently unauditable (coverage is
701 /// uniform over many audits).
702 #[test]
703 fn slots_partition_all_leaves_with_no_gaps() {
704 for &n in &[5u32, 17, 100, 1025, 524_289] {
705 let span = max_subtree_leaves(n);
706 let slot_count = n.div_ceil(span);
707 let mut covered = 0u32;
708 for slot in 0..slot_count {
709 let start = slot.saturating_mul(span);
710 let end = start.saturating_add(span).min(n);
711 assert_eq!(start, covered, "n={n} slot={slot}: gap before this slot");
712 assert!(end > start, "n={n} slot={slot}: empty slot");
713 covered = end;
714 }
715 assert_eq!(covered, n, "n={n}: slots do not cover all leaves");
716 }
717 }
718
719 #[test]
720 fn small_trees_select_whole_tree() {
721 for n in 1..=SMALL_TREE_FULL_AUDIT_FLOOR {
722 let path = select_subtree_path(&nonce_of(7), n).unwrap();
723 assert_eq!(path.depth, 0);
724 assert_eq!(path.leaf_start, 0);
725 assert_eq!(path.leaf_end, n);
726 }
727 }
728
729 #[test]
730 fn selection_is_deterministic() {
731 let n = 500;
732 let a = select_subtree_path(&nonce_of(42), n).unwrap();
733 let b = select_subtree_path(&nonce_of(42), n).unwrap();
734 assert_eq!(a, b);
735 }
736
737 #[test]
738 fn different_nonces_cover_different_branches_over_time() {
739 // Not every nonce differs, but the set of selected ranges must be > 1.
740 let n = 1024;
741 let mut starts = std::collections::HashSet::new();
742 for seed in 0u8..=255 {
743 let p = select_subtree_path(&nonce_of(seed), n).unwrap();
744 starts.insert(p.leaf_start);
745 }
746 assert!(
747 starts.len() > 4,
748 "nonce should spread selection: {}",
749 starts.len()
750 );
751 }
752
753 /// Deterministic per-trial nonce (no RNG): hash a counter.
754 fn nonce_for_trial(i: u32) -> [u8; 32] {
755 let mut h = blake3::Hasher::new();
756 h.update(b"detection-sim-trial");
757 h.update(&i.to_le_bytes());
758 *h.finalize().as_bytes()
759 }
760
761 /// Catch rate over `trials` audits: fraction whose nonce-selected subtree
762 /// overlaps at least one deleted leaf index.
763 fn catch_rate(n: u32, deleted: &std::collections::HashSet<u32>, trials: u32) -> f64 {
764 let mut caught = 0u32;
765 for t in 0..trials {
766 let path = select_subtree_path(&nonce_for_trial(t), n).unwrap();
767 if (path.leaf_start..path.leaf_end).any(|i| deleted.contains(&i)) {
768 caught += 1;
769 }
770 }
771 f64::from(caught) / f64::from(trials)
772 }
773
774 #[test]
775 fn detection_uniform_fast_clustered_floor() {
776 // ADR-0002 Validation: uniform deletions are caught fast; clustered
777 // (contiguous-block) deletions are caught at roughly the deleted
778 // fraction per audit (a floor), much slower. This encodes the core
779 // security claim that the audit RATE (not per-audit cleverness) is the
780 // lever against a clustered deleter.
781 let n = 1024u32; // sqrt = 32
782 let del_count = n / 10; // delete 10% ≈ 102
783
784 // Uniform: spread deletions evenly across the keyspace.
785 let uniform: std::collections::HashSet<u32> =
786 (0..del_count).map(|i| (i * n / del_count) % n).collect();
787 let uniform_rate = catch_rate(n, &uniform, 256);
788
789 // Clustered: one contiguous block of the same size.
790 let clustered: std::collections::HashSet<u32> = (0..del_count).collect();
791 let clustered_rate = catch_rate(n, &clustered, 256);
792
793 // Uniform should be caught on essentially every audit (spread across the
794 // whole tree; any selected subtree overlaps some deletion).
795 assert!(
796 uniform_rate > 0.95,
797 "uniform deletions should be caught almost every audit, got {uniform_rate}"
798 );
799 // Clustered (one contiguous f-block) is a floor NEAR the deleted
800 // fraction f=0.1 — the quantitative ADR claim. The exact rate depends on
801 // selection geometry (a block of ~102 leaves is hit when the selected
802 // ~sqrt(N) subtree overlaps it), but it must sit in a tight band around
803 // f, well below the uniform rate. We bound it to [0.04, 0.30].
804 assert!(
805 (0.04..=0.30).contains(&clustered_rate),
806 "clustered catch-rate should be near f=0.1, got {clustered_rate}"
807 );
808 assert!(
809 uniform_rate > clustered_rate * 2.0,
810 "uniform ({uniform_rate}) must be far easier to catch than clustered ({clustered_rate})"
811 );
812 }
813
814 #[test]
815 fn subtree_size_near_sqrt_for_balanced_tree() {
816 // For a power-of-two tree the selection should land near sqrt(N).
817 let n = 1024; // sqrt = 32, floor = 32
818 let path = select_subtree_path(&nonce_of(3), n).unwrap();
819 // It stops as soon as a child would drop below floor; the subtree size
820 // is between floor and 2*floor for a balanced tree.
821 assert!(path.real_leaf_count() >= 32);
822 assert!(
823 path.real_leaf_count() <= 64,
824 "got {}",
825 path.real_leaf_count()
826 );
827 }
828
829 // ---- end-to-end proof build + verify ----------------------------------
830
831 /// Deterministic chunk bytes for a key (test fixture). The tree is built
832 /// from `BLAKE3` of exactly these bytes, so the proof and the committed
833 /// root agree — mirroring how a real responder hashes the chunk it holds.
834 fn chunk_bytes(key: &XorName) -> Vec<u8> {
835 // Distinct, non-trivial bytes derived from the key.
836 let mut v = key.to_vec();
837 v.extend_from_slice(b"chunk-body");
838 v
839 }
840
841 /// Build tree entries `(key, BLAKE3(chunk_bytes(key)))` for `n` keys.
842 fn entries_for(n: u32) -> Vec<(XorName, [u8; 32])> {
843 (0..n)
844 .map(|i| {
845 let key = xn_u32(i);
846 let bytes_hash = *blake3::hash(&chunk_bytes(&key)).as_bytes();
847 (key, bytes_hash)
848 })
849 .collect()
850 }
851
852 /// Reference responder: build a real subtree proof via the production
853 /// [`build_subtree_proof`] from a `MerkleTree` over `entries`. Leaves are
854 /// hashed from `chunk_bytes(key)` — the same bytes whose hash built the
855 /// tree — so an honest proof verifies. This makes the tests exercise the
856 /// exact builder the responder runs.
857 fn build_proof(
858 entries: &[(XorName, [u8; 32])],
859 nonce: &[u8; 32],
860 peer_id: &[u8; 32],
861 ) -> (SubtreeProof, StorageCommitment) {
862 let tree = MerkleTree::build(entries.to_vec()).unwrap();
863 let key_count = tree.key_count();
864 let proof = build_subtree_proof(&tree, nonce, peer_id, |k| Some(chunk_bytes(k))).unwrap();
865 let commitment = fake_commitment(tree.root(), key_count, *peer_id);
866 (proof, commitment)
867 }
868
869 fn fake_commitment(root: [u8; 32], key_count: u32, peer: [u8; 32]) -> StorageCommitment {
870 StorageCommitment {
871 root,
872 key_count,
873 sender_peer_id: peer,
874 sender_public_key: vec![0u8; 1952],
875 signature: vec![0u8; 3293],
876 }
877 }
878
879 #[test]
880 fn honest_proof_verifies_at_many_sizes() {
881 let peer = [0xABu8; 32];
882 for n in [5u32, 8, 13, 17, 64, 100, 256, 1000] {
883 let entries = entries_for(n);
884 for seed in [1u8, 2, 7, 42, 200] {
885 let nonce = nonce_of(seed);
886 let (proof, commitment) = build_proof(&entries, &nonce, &peer);
887 assert_eq!(
888 verify_subtree_proof(&proof, &nonce, &commitment),
889 StructureVerdict::Valid,
890 "n={n} seed={seed}"
891 );
892 }
893 }
894 }
895
896 #[test]
897 fn honest_proof_verifies_for_every_size_and_nonce() {
898 // Regression for the left-packed self-pairing geometry bug: the proof
899 // reconstruction must match the committed root for EVERY key count
900 // (not just powers of two / cherry-picked sizes) and every nonce. An
901 // earlier perfect-tree model false-failed honest nodes for ~70% of
902 // sizes; this guards against any reintroduction.
903 let peer = [7u8; 32];
904 for n in 5u32..=600 {
905 let entries = entries_for(n);
906 for seed in 0u8..32 {
907 let nonce = nonce_of(seed.wrapping_mul(17).wrapping_add(3));
908 let (proof, commitment) = build_proof(&entries, &nonce, &peer);
909 assert_eq!(
910 verify_subtree_proof(&proof, &nonce, &commitment),
911 StructureVerdict::Valid,
912 "honest proof must verify at n={n} seed={seed}"
913 );
914 }
915 }
916 }
917
918 #[test]
919 fn tampered_leaf_breaks_root() {
920 let peer = [9u8; 32];
921 let entries = entries_for(100);
922 let nonce = nonce_of(5);
923 let (mut proof, commitment) = build_proof(&entries, &nonce, &peer);
924 proof.leaves[0].bytes_hash[0] ^= 0x01;
925 assert!(matches!(
926 verify_subtree_proof(&proof, &nonce, &commitment),
927 StructureVerdict::Invalid(_)
928 ));
929 }
930
931 #[test]
932 fn tampered_cut_hash_breaks_root() {
933 let peer = [9u8; 32];
934 let entries = entries_for(256);
935 let nonce = nonce_of(11);
936 let (mut proof, commitment) = build_proof(&entries, &nonce, &peer);
937 if let Some(c) = proof.sibling_cut_hashes.first_mut() {
938 c[0] ^= 0x01;
939 }
940 assert!(matches!(
941 verify_subtree_proof(&proof, &nonce, &commitment),
942 StructureVerdict::Invalid(_)
943 ));
944 }
945
946 #[test]
947 fn wrong_leaf_count_rejected() {
948 let peer = [9u8; 32];
949 let entries = entries_for(100);
950 let nonce = nonce_of(5);
951 let (mut proof, commitment) = build_proof(&entries, &nonce, &peer);
952 proof.leaves.pop();
953 assert_eq!(
954 verify_subtree_proof(&proof, &nonce, &commitment),
955 StructureVerdict::Invalid("wrong leaf count")
956 );
957 }
958
959 #[test]
960 fn non_ascending_leaves_rejected() {
961 let peer = [9u8; 32];
962 let entries = entries_for(100);
963 let nonce = nonce_of(5);
964 let (mut proof, commitment) = build_proof(&entries, &nonce, &peer);
965 if proof.leaves.len() >= 2 {
966 proof.leaves.swap(0, 1);
967 }
968 assert!(matches!(
969 verify_subtree_proof(&proof, &nonce, &commitment),
970 StructureVerdict::Invalid(_)
971 ));
972 }
973
974 // ---- spot-check selection ---------------------------------------------
975
976 #[test]
977 fn spotcheck_indices_in_range_and_distinct() {
978 let n = 1024;
979 let nonce = nonce_of(3);
980 let path = select_subtree_path(&nonce, n).unwrap();
981 let k = 8;
982 let idxs = select_spotcheck_indices(&nonce, &path, k);
983 assert_eq!(
984 u32::try_from(idxs.len()).unwrap(),
985 k.min(path.real_leaf_count())
986 );
987 let mut seen = std::collections::HashSet::new();
988 for i in &idxs {
989 assert!(*i < path.real_leaf_count());
990 assert!(seen.insert(*i), "duplicate spot-check index {i}");
991 }
992 }
993
994 #[test]
995 fn build_proof_reports_missing_bytes() {
996 // A responder that no longer holds a selected, committed key's bytes
997 // must surface MissingBytes (the caller turns this into a confirmed
998 // failure, not a benign rejection).
999 let entries = entries_for(100);
1000 let tree = MerkleTree::build(entries).unwrap();
1001 let nonce = nonce_of(5);
1002 let path = select_subtree_path(&nonce, tree.key_count()).unwrap();
1003 let victim = tree.key_at(path.leaf_start as usize).unwrap();
1004 let err = build_subtree_proof(&tree, &nonce, &[1u8; 32], |k| {
1005 if *k == victim {
1006 None
1007 } else {
1008 Some(chunk_bytes(k))
1009 }
1010 })
1011 .unwrap_err();
1012 assert_eq!(err, BuildProofError::MissingBytes { key: victim });
1013 }
1014
1015 #[test]
1016 fn spotcheck_returns_all_when_subtree_small() {
1017 // Construct a path with few real leaves.
1018 let path = SubtreePath {
1019 depth: 0,
1020 slot: 0,
1021 leaf_start: 0,
1022 leaf_end: 3,
1023 };
1024 let idxs = select_spotcheck_indices(&nonce_of(1), &path, 8);
1025 assert_eq!(idxs, vec![0, 1, 2]);
1026 }
1027
1028 #[test]
1029 fn spotcheck_always_yields_exactly_min_k_n_distinct_indices() {
1030 // The byte sample must NEVER be silently smaller than requested: a
1031 // short sample weakens round 2 without anyone noticing. Exercise many
1032 // nonces, subtree sizes, and k values, and require exactly min(k, n)
1033 // distinct in-range indices every time — plus determinism (auditor and
1034 // responder must derive the same set).
1035 for size in [1u32, 2, 3, 7, 8, 64, 1000] {
1036 let path = SubtreePath {
1037 depth: 0,
1038 slot: 0,
1039 leaf_start: 0,
1040 leaf_end: size,
1041 };
1042 for k in [1u32, 3, 5, 8] {
1043 for seed in 0..32u8 {
1044 let nonce = nonce_of(seed);
1045 let idxs = select_spotcheck_indices(&nonce, &path, k);
1046 let expected = k.min(path.real_leaf_count()) as usize;
1047 assert_eq!(
1048 idxs.len(),
1049 expected,
1050 "size={size} k={k} seed={seed}: must yield exactly min(k, n)"
1051 );
1052 let mut seen = std::collections::HashSet::new();
1053 for i in &idxs {
1054 assert!(*i < path.real_leaf_count(), "index out of range");
1055 assert!(seen.insert(*i), "duplicate index {i}");
1056 }
1057 assert_eq!(
1058 idxs,
1059 select_spotcheck_indices(&nonce, &path, k),
1060 "selection must be deterministic"
1061 );
1062 }
1063 }
1064 }
1065 }
1066
1067 #[test]
1068 fn fabricated_nonced_root_caught_by_spotcheck_probability() {
1069 // Simulate the realness check: a responder fabricates a fraction x of
1070 // nonced roots. The auditor opens k leaves; probability all k land on
1071 // honest leaves is (1-x)^k. Here we just assert the auditor *would* catch
1072 // a fabricated leaf: its committed root differs from the honest root
1073 // recomputed from the real chunk bytes under the audit nonce.
1074 let peer = [1u8; 32];
1075 let entries = entries_for(400);
1076 let nonce = nonce_of(9);
1077 let (mut proof, _commitment) = build_proof(&entries, &nonce, &peer);
1078 // Fabricate the nonced root on the first subtree leaf.
1079 if let Some(first) = proof.leaves.first_mut() {
1080 first.nonced_root[0] ^= 0xFF;
1081 }
1082 let leaf = proof.leaves.first().expect("proof has leaves");
1083 let real_bytes = chunk_bytes(&leaf.key);
1084 let expected =
1085 crate::replication::slice::nonced_block_root(&nonce, &peer, &leaf.key, &real_bytes);
1086 assert_ne!(
1087 leaf.nonced_root, expected,
1088 "fabricated nonced root must differ from real"
1089 );
1090 }
1091
1092 // ---- branch-substitution attack ---------------------------------------
1093
1094 #[test]
1095 fn responder_cannot_substitute_a_different_branch() {
1096 // ADR-0002 "Subtree selection": the random value alone fixes WHICH
1097 // branch is selected, so "the audited node cannot choose a convenient
1098 // branch to present." This is the load-bearing anti-substitution claim
1099 // and no existing test exercises it — the tamper tests only mangle a
1100 // hash within the *correct* branch.
1101 //
1102 // Attack: the responder builds a fully valid, internally-consistent
1103 // subtree proof for a DIFFERENT nonce (which the selection maps to a
1104 // different branch of the same committed tree), then presents it as the
1105 // answer to the auditor's nonce. Every leaf hash and every cut-hash is
1106 // genuine, the leaves are strictly ascending, and we deliberately pick
1107 // a decoy whose branch has the SAME leaf count and SAME depth as the
1108 // honest branch — so the cheap "wrong leaf count" / "wrong cut-hash
1109 // count" gates do NOT fire. The ONLY thing that can reject it is the
1110 // structural root re-derivation, which climbs using the auditor's
1111 // nonce-derived slot parity and position. It must reject.
1112 let peer = [0x5Au8; 32];
1113 let n = 1024u32; // balanced tree; sqrt floor = 32
1114 let entries = entries_for(n);
1115
1116 let audit_nonce = nonce_of(7);
1117 let audit_path = select_subtree_path(&audit_nonce, n).unwrap();
1118
1119 // Find a decoy nonce whose selected branch is a DIFFERENT slot but the
1120 // SAME depth (hence same real-leaf count for this balanced tree). This
1121 // forces rejection via the root check rather than a count mismatch.
1122 let mut decoy: Option<([u8; 32], SubtreePath)> = None;
1123 for seed in 0u8..=255 {
1124 let cand_nonce = nonce_of(seed);
1125 let cand = select_subtree_path(&cand_nonce, n).unwrap();
1126 if cand.depth == audit_path.depth
1127 && cand.slot != audit_path.slot
1128 && cand.real_leaf_count() == audit_path.real_leaf_count()
1129 {
1130 decoy = Some((cand_nonce, cand));
1131 break;
1132 }
1133 }
1134 let (decoy_nonce, decoy_path) =
1135 decoy.expect("a same-depth, different-slot decoy branch must exist for n=1024");
1136
1137 // Sanity: the decoy really is a different, equally-shaped branch.
1138 assert_ne!(decoy_path.slot, audit_path.slot);
1139 assert_eq!(decoy_path.depth, audit_path.depth);
1140 assert_eq!(decoy_path.real_leaf_count(), audit_path.real_leaf_count());
1141
1142 // The responder builds a genuine proof for the DECOY branch. Note the
1143 // nonced hashes are built with the decoy nonce too — but that does not
1144 // matter: the structural check below never inspects nonced hashes, and
1145 // the attack must already die on structure.
1146 let tree = MerkleTree::build(entries).unwrap();
1147 let decoy_proof =
1148 build_subtree_proof(&tree, &decoy_nonce, &peer, |k| Some(chunk_bytes(k))).unwrap();
1149
1150 // Pin the auditor's commitment to the genuine root of the same tree.
1151 let commitment = fake_commitment(tree.root(), n, peer);
1152
1153 // The honest answer to the SAME commitment + decoy nonce verifies, so
1154 // the proof itself is well-formed — it is only "wrong" relative to the
1155 // auditor's nonce.
1156 assert_eq!(
1157 verify_subtree_proof(&decoy_proof, &decoy_nonce, &commitment),
1158 StructureVerdict::Valid,
1159 "the decoy proof must be a genuinely valid proof for its own nonce"
1160 );
1161
1162 // The attack: present the decoy-branch proof against the AUDIT nonce.
1163 // The count gates cannot fire (same depth + leaf count by construction),
1164 // so this is the root re-derivation rejecting a substituted branch.
1165 let verdict = verify_subtree_proof(&decoy_proof, &audit_nonce, &commitment);
1166 assert_eq!(
1167 verdict,
1168 StructureVerdict::Invalid("root mismatch"),
1169 "substituting a different valid branch must be rejected by the root check, got {verdict:?}"
1170 );
1171 }
1172}