Skip to main content

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    /// For each of `leaf_keys`, whether it is committed as a pointer
503    /// (ADR-0016) rather than a chunk.
504    pub leaf_is_pointer: Vec<bool>,
505    /// One sibling cut-hash per level on the path to the subtree root,
506    /// root-first.
507    pub sibling_cut_hashes: Vec<[u8; 32]>,
508}
509
510/// Compute the [`SubtreePlan`] for `(nonce, tree)` — selection geometry only,
511/// no chunk bytes touched.
512///
513/// # Errors
514///
515/// [`BuildProofError::BadKeyCount`] for an out-of-protocol tree;
516/// [`BuildProofError::MissingKey`] if a selected leaf index is not in the tree
517/// (internal inconsistency).
518pub fn subtree_plan(
519    tree: &super::commitment::MerkleTree,
520    nonce: &[u8; 32],
521) -> Result<SubtreePlan, BuildProofError> {
522    let key_count = tree.key_count();
523    let path = select_subtree_path(nonce, key_count).ok_or(BuildProofError::BadKeyCount)?;
524
525    // Defense-in-depth: the fixed-depth selection already bounds this to one
526    // block of `max_subtree_leaves` leaves, but reject BEFORE any leaf read if a
527    // future selection change ever produced an oversized subtree, so one request
528    // can never force unbounded round-1 read/hash work.
529    if path.real_leaf_count() > max_subtree_leaves(key_count) {
530        return Err(BuildProofError::BadKeyCount);
531    }
532
533    let mut leaf_keys = Vec::with_capacity(path.real_leaf_count() as usize);
534    let mut leaf_is_pointer = Vec::with_capacity(path.real_leaf_count() as usize);
535    for idx in path.leaf_start..path.leaf_end {
536        let key = tree
537            .key_at(idx as usize)
538            .ok_or(BuildProofError::MissingKey { leaf_index: idx })?;
539        leaf_keys.push(key);
540        leaf_is_pointer.push(tree.is_pointer_leaf(idx as usize));
541    }
542
543    // Sibling cut-hashes, root-first. The fixed-depth slot selection no longer
544    // follows a per-level nonce walk, so derive the on-path node at each level
545    // from `path.slot`'s prefix bits: the top `d + 1` bits give the node index at
546    // level `d + 1` below the root. The sibling is the other child at level
547    // `total_depth - (d + 1)` (counting up from leaves); on an odd level the
548    // missing sibling self-pairs (the chosen node is its own sibling).
549    let total_depth = u32::try_from(tree.levels_count().saturating_sub(1)).unwrap_or(0);
550    let mut sibling_cut_hashes = Vec::with_capacity(path.depth as usize);
551    for d in 0..path.depth {
552        let child = u64::from(path.slot) >> (path.depth - (d + 1));
553        let sibling = child ^ 1;
554        let level_from_leaves = (total_depth - (d + 1)) as usize;
555        let chosen_hash = tree.node_at(level_from_leaves, child);
556        let sib_hash = tree
557            .node_at(level_from_leaves, sibling)
558            .or(chosen_hash)
559            .ok_or(BuildProofError::BadKeyCount)?;
560        sibling_cut_hashes.push(sib_hash);
561    }
562
563    Ok(SubtreePlan {
564        leaf_keys,
565        leaf_is_pointer,
566        sibling_cut_hashes,
567    })
568}
569
570/// Build one subtree leaf from its key and the chunk bytes the responder holds.
571///
572/// The plain `bytes_hash` is the chunk's content address; the `nonced_root` is
573/// the fresh per-audit nonced block-tree root over the same bytes, committing
574/// possession at round-1 time (see [`crate::replication::slice`]).
575#[must_use]
576pub fn subtree_leaf(
577    nonce: &[u8; 32],
578    challenged_peer_id: &[u8; 32],
579    key: &XorName,
580    bytes: &[u8],
581) -> SubtreeLeaf {
582    SubtreeLeaf {
583        key: *key,
584        bytes_hash: *blake3::hash(bytes).as_bytes(),
585        content_len: u32::try_from(bytes.len()).unwrap_or(u32::MAX),
586        nonced_root: crate::replication::slice::nonced_block_root(
587            nonce,
588            challenged_peer_id,
589            key,
590            bytes,
591        ),
592    }
593}
594
595#[cfg(test)]
596#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
597mod tests {
598    use super::*;
599    use crate::replication::commitment::MerkleTree;
600
601    fn xn_u32(i: u32) -> XorName {
602        let mut k = [0u8; 32];
603        k[..4].copy_from_slice(&i.to_be_bytes()); // big-endian so numeric order == sort order
604        k
605    }
606    fn nonce_of(seed: u8) -> [u8; 32] {
607        [seed; 32]
608    }
609
610    // ---- sqrt_floor -------------------------------------------------------
611
612    #[test]
613    fn sqrt_floor_is_exact_ceil() {
614        assert_eq!(sqrt_floor(1), 1);
615        assert_eq!(sqrt_floor(4), 2);
616        assert_eq!(sqrt_floor(5), 3); // ceil(sqrt(5)) = 3
617        assert_eq!(sqrt_floor(9), 3);
618        assert_eq!(sqrt_floor(10), 4);
619        assert_eq!(sqrt_floor(100), 10);
620        assert_eq!(sqrt_floor(101), 11);
621        assert_eq!(sqrt_floor(1_000_000), 1000);
622    }
623
624    // ---- real_leaves_under ------------------------------------------------
625
626    #[test]
627    fn real_leaves_under_root_is_all() {
628        let d = tree_depth(100).unwrap();
629        assert_eq!(real_leaves_under(0, 0, 100, d), 100);
630    }
631
632    #[test]
633    fn real_leaves_under_padding_slot_is_zero() {
634        // key_count = 5, total_depth = 3 (next_pow2(5)=8). Leaf slots 5,6,7
635        // at the bottom are padding. The right half at depth 1 (slot 1) covers
636        // leaves [4,8) → only leaf 4 is real.
637        let d = tree_depth(5).unwrap();
638        assert_eq!(d, 3);
639        assert_eq!(real_leaves_under(1, 0, 5, d), 4); // [0,4)
640        assert_eq!(real_leaves_under(1, 1, 5, d), 1); // [4,8) ∩ [0,5) = {4}
641        assert_eq!(real_leaves_under(3, 7, 5, d), 0); // pure padding leaf
642        assert_eq!(real_leaves_under(2, 3, 5, d), 0); // [6,8) pure padding
643    }
644
645    // ---- select_subtree_path: dead-block regression -----------------------
646
647    #[test]
648    fn selection_never_empty_and_within_ceiling_across_sizes_and_nonces() {
649        for n in [
650            5u32, 6, 7, 9, 13, 17, 33, 65, 100, 129, 333, 1000, 1024, 1025,
651        ] {
652            let ceiling = max_subtree_leaves(n);
653            for seed in 0u8..=255 {
654                let path = select_subtree_path(&nonce_of(seed), n).unwrap();
655                // Never empty (ADR dead-block fix).
656                assert!(
657                    path.real_leaf_count() >= 1,
658                    "n={n} seed={seed}: empty selection"
659                );
660                // Bounded (DoS fix): one request reads at most one fixed-depth
661                // block, regardless of the (possibly adversarial) nonce.
662                assert!(
663                    path.real_leaf_count() <= ceiling,
664                    "n={n} seed={seed}: real={} > ceiling={ceiling}",
665                    path.real_leaf_count()
666                );
667                assert!(path.leaf_end <= n);
668                assert!(path.leaf_start < path.leaf_end);
669            }
670        }
671    }
672
673    /// The denial-of-service the fixed-depth selection closes: under the OLD
674    /// nonce-bit descent, `key_count = 2^19 + 1` with a nonce steering to the
675    /// sparse side selected the WHOLE tree (~2 TiB of reads). Now every nonce
676    /// selects at most one `max_subtree_leaves`-sized block, and the tail slot is
677    /// a single leaf — not
678    /// the root.
679    #[test]
680    fn adversarial_nonce_cannot_amplify_round1_work() {
681        for &n in &[513u32, 1025, 524_289, 1_000_000, MAX_COMMITMENT_KEY_COUNT] {
682            let ceiling = max_subtree_leaves(n);
683            // A generous cap: sqrt-scale, never the whole tree for a large N.
684            assert!(
685                u64::from(ceiling) <= 1024.max(u64::from(n)),
686                "n={n}: ceiling {ceiling} not sqrt-scale"
687            );
688            for nonce in [[0x00u8; 32], [0xFFu8; 32], [0xAAu8; 32], [0x55u8; 32]] {
689                let path = select_subtree_path(&nonce, n).unwrap();
690                assert!(
691                    path.real_leaf_count() <= ceiling && path.real_leaf_count() >= 1,
692                    "n={n}: real={} outside 1..={ceiling}",
693                    path.real_leaf_count()
694                );
695                if n >= 512 {
696                    assert!(
697                        u64::from(path.real_leaf_count()) < u64::from(n),
698                        "n={n}: a single request must not cover the whole tree"
699                    );
700                }
701            }
702        }
703    }
704
705    /// Every slot is selectable and the slots partition `0..key_count` with no
706    /// gaps, so the tail leaf is never permanently unauditable (coverage is
707    /// uniform over many audits).
708    #[test]
709    fn slots_partition_all_leaves_with_no_gaps() {
710        for &n in &[5u32, 17, 100, 1025, 524_289] {
711            let span = max_subtree_leaves(n);
712            let slot_count = n.div_ceil(span);
713            let mut covered = 0u32;
714            for slot in 0..slot_count {
715                let start = slot.saturating_mul(span);
716                let end = start.saturating_add(span).min(n);
717                assert_eq!(start, covered, "n={n} slot={slot}: gap before this slot");
718                assert!(end > start, "n={n} slot={slot}: empty slot");
719                covered = end;
720            }
721            assert_eq!(covered, n, "n={n}: slots do not cover all leaves");
722        }
723    }
724
725    #[test]
726    fn small_trees_select_whole_tree() {
727        for n in 1..=SMALL_TREE_FULL_AUDIT_FLOOR {
728            let path = select_subtree_path(&nonce_of(7), n).unwrap();
729            assert_eq!(path.depth, 0);
730            assert_eq!(path.leaf_start, 0);
731            assert_eq!(path.leaf_end, n);
732        }
733    }
734
735    #[test]
736    fn selection_is_deterministic() {
737        let n = 500;
738        let a = select_subtree_path(&nonce_of(42), n).unwrap();
739        let b = select_subtree_path(&nonce_of(42), n).unwrap();
740        assert_eq!(a, b);
741    }
742
743    #[test]
744    fn different_nonces_cover_different_branches_over_time() {
745        // Not every nonce differs, but the set of selected ranges must be > 1.
746        let n = 1024;
747        let mut starts = std::collections::HashSet::new();
748        for seed in 0u8..=255 {
749            let p = select_subtree_path(&nonce_of(seed), n).unwrap();
750            starts.insert(p.leaf_start);
751        }
752        assert!(
753            starts.len() > 4,
754            "nonce should spread selection: {}",
755            starts.len()
756        );
757    }
758
759    /// Deterministic per-trial nonce (no RNG): hash a counter.
760    fn nonce_for_trial(i: u32) -> [u8; 32] {
761        let mut h = blake3::Hasher::new();
762        h.update(b"detection-sim-trial");
763        h.update(&i.to_le_bytes());
764        *h.finalize().as_bytes()
765    }
766
767    /// Catch rate over `trials` audits: fraction whose nonce-selected subtree
768    /// overlaps at least one deleted leaf index.
769    fn catch_rate(n: u32, deleted: &std::collections::HashSet<u32>, trials: u32) -> f64 {
770        let mut caught = 0u32;
771        for t in 0..trials {
772            let path = select_subtree_path(&nonce_for_trial(t), n).unwrap();
773            if (path.leaf_start..path.leaf_end).any(|i| deleted.contains(&i)) {
774                caught += 1;
775            }
776        }
777        f64::from(caught) / f64::from(trials)
778    }
779
780    #[test]
781    fn detection_uniform_fast_clustered_floor() {
782        // ADR-0002 Validation: uniform deletions are caught fast; clustered
783        // (contiguous-block) deletions are caught at roughly the deleted
784        // fraction per audit (a floor), much slower. This encodes the core
785        // security claim that the audit RATE (not per-audit cleverness) is the
786        // lever against a clustered deleter.
787        let n = 1024u32; // sqrt = 32
788        let del_count = n / 10; // delete 10% ≈ 102
789
790        // Uniform: spread deletions evenly across the keyspace.
791        let uniform: std::collections::HashSet<u32> =
792            (0..del_count).map(|i| (i * n / del_count) % n).collect();
793        let uniform_rate = catch_rate(n, &uniform, 256);
794
795        // Clustered: one contiguous block of the same size.
796        let clustered: std::collections::HashSet<u32> = (0..del_count).collect();
797        let clustered_rate = catch_rate(n, &clustered, 256);
798
799        // Uniform should be caught on essentially every audit (spread across the
800        // whole tree; any selected subtree overlaps some deletion).
801        assert!(
802            uniform_rate > 0.95,
803            "uniform deletions should be caught almost every audit, got {uniform_rate}"
804        );
805        // Clustered (one contiguous f-block) is a floor NEAR the deleted
806        // fraction f=0.1 — the quantitative ADR claim. The exact rate depends on
807        // selection geometry (a block of ~102 leaves is hit when the selected
808        // ~sqrt(N) subtree overlaps it), but it must sit in a tight band around
809        // f, well below the uniform rate. We bound it to [0.04, 0.30].
810        assert!(
811            (0.04..=0.30).contains(&clustered_rate),
812            "clustered catch-rate should be near f=0.1, got {clustered_rate}"
813        );
814        assert!(
815            uniform_rate > clustered_rate * 2.0,
816            "uniform ({uniform_rate}) must be far easier to catch than clustered ({clustered_rate})"
817        );
818    }
819
820    #[test]
821    fn subtree_size_near_sqrt_for_balanced_tree() {
822        // For a power-of-two tree the selection should land near sqrt(N).
823        let n = 1024; // sqrt = 32, floor = 32
824        let path = select_subtree_path(&nonce_of(3), n).unwrap();
825        // It stops as soon as a child would drop below floor; the subtree size
826        // is between floor and 2*floor for a balanced tree.
827        assert!(path.real_leaf_count() >= 32);
828        assert!(
829            path.real_leaf_count() <= 64,
830            "got {}",
831            path.real_leaf_count()
832        );
833    }
834
835    // ---- end-to-end proof build + verify ----------------------------------
836
837    /// Deterministic chunk bytes for a key (test fixture). The tree is built
838    /// from `BLAKE3` of exactly these bytes, so the proof and the committed
839    /// root agree — mirroring how a real responder hashes the chunk it holds.
840    fn chunk_bytes(key: &XorName) -> Vec<u8> {
841        // Distinct, non-trivial bytes derived from the key.
842        let mut v = key.to_vec();
843        v.extend_from_slice(b"chunk-body");
844        v
845    }
846
847    /// Build tree entries `(key, BLAKE3(chunk_bytes(key)))` for `n` keys.
848    fn entries_for(n: u32) -> Vec<(XorName, [u8; 32])> {
849        (0..n)
850            .map(|i| {
851                let key = xn_u32(i);
852                let bytes_hash = *blake3::hash(&chunk_bytes(&key)).as_bytes();
853                (key, bytes_hash)
854            })
855            .collect()
856    }
857
858    /// Reference responder: build a real subtree proof via the production
859    /// [`build_subtree_proof`] from a `MerkleTree` over `entries`. Leaves are
860    /// hashed from `chunk_bytes(key)` — the same bytes whose hash built the
861    /// tree — so an honest proof verifies. This makes the tests exercise the
862    /// exact builder the responder runs.
863    fn build_proof(
864        entries: &[(XorName, [u8; 32])],
865        nonce: &[u8; 32],
866        peer_id: &[u8; 32],
867    ) -> (SubtreeProof, StorageCommitment) {
868        let tree = MerkleTree::build(entries.to_vec()).unwrap();
869        let key_count = tree.key_count();
870        let proof = build_subtree_proof(&tree, nonce, peer_id, |k| Some(chunk_bytes(k))).unwrap();
871        let commitment = fake_commitment(tree.root(), key_count, *peer_id);
872        (proof, commitment)
873    }
874
875    fn fake_commitment(root: [u8; 32], key_count: u32, peer: [u8; 32]) -> StorageCommitment {
876        StorageCommitment {
877            root,
878            key_count,
879            sender_peer_id: peer,
880            sender_public_key: vec![0u8; 1952],
881            signature: vec![0u8; 3293],
882        }
883    }
884
885    #[test]
886    fn honest_proof_verifies_at_many_sizes() {
887        let peer = [0xABu8; 32];
888        for n in [5u32, 8, 13, 17, 64, 100, 256, 1000] {
889            let entries = entries_for(n);
890            for seed in [1u8, 2, 7, 42, 200] {
891                let nonce = nonce_of(seed);
892                let (proof, commitment) = build_proof(&entries, &nonce, &peer);
893                assert_eq!(
894                    verify_subtree_proof(&proof, &nonce, &commitment),
895                    StructureVerdict::Valid,
896                    "n={n} seed={seed}"
897                );
898            }
899        }
900    }
901
902    #[test]
903    fn honest_proof_verifies_for_every_size_and_nonce() {
904        // Regression for the left-packed self-pairing geometry bug: the proof
905        // reconstruction must match the committed root for EVERY key count
906        // (not just powers of two / cherry-picked sizes) and every nonce. An
907        // earlier perfect-tree model false-failed honest nodes for ~70% of
908        // sizes; this guards against any reintroduction.
909        let peer = [7u8; 32];
910        for n in 5u32..=600 {
911            let entries = entries_for(n);
912            for seed in 0u8..32 {
913                let nonce = nonce_of(seed.wrapping_mul(17).wrapping_add(3));
914                let (proof, commitment) = build_proof(&entries, &nonce, &peer);
915                assert_eq!(
916                    verify_subtree_proof(&proof, &nonce, &commitment),
917                    StructureVerdict::Valid,
918                    "honest proof must verify at n={n} seed={seed}"
919                );
920            }
921        }
922    }
923
924    #[test]
925    fn tampered_leaf_breaks_root() {
926        let peer = [9u8; 32];
927        let entries = entries_for(100);
928        let nonce = nonce_of(5);
929        let (mut proof, commitment) = build_proof(&entries, &nonce, &peer);
930        proof.leaves[0].bytes_hash[0] ^= 0x01;
931        assert!(matches!(
932            verify_subtree_proof(&proof, &nonce, &commitment),
933            StructureVerdict::Invalid(_)
934        ));
935    }
936
937    #[test]
938    fn tampered_cut_hash_breaks_root() {
939        let peer = [9u8; 32];
940        let entries = entries_for(256);
941        let nonce = nonce_of(11);
942        let (mut proof, commitment) = build_proof(&entries, &nonce, &peer);
943        if let Some(c) = proof.sibling_cut_hashes.first_mut() {
944            c[0] ^= 0x01;
945        }
946        assert!(matches!(
947            verify_subtree_proof(&proof, &nonce, &commitment),
948            StructureVerdict::Invalid(_)
949        ));
950    }
951
952    #[test]
953    fn wrong_leaf_count_rejected() {
954        let peer = [9u8; 32];
955        let entries = entries_for(100);
956        let nonce = nonce_of(5);
957        let (mut proof, commitment) = build_proof(&entries, &nonce, &peer);
958        proof.leaves.pop();
959        assert_eq!(
960            verify_subtree_proof(&proof, &nonce, &commitment),
961            StructureVerdict::Invalid("wrong leaf count")
962        );
963    }
964
965    #[test]
966    fn non_ascending_leaves_rejected() {
967        let peer = [9u8; 32];
968        let entries = entries_for(100);
969        let nonce = nonce_of(5);
970        let (mut proof, commitment) = build_proof(&entries, &nonce, &peer);
971        if proof.leaves.len() >= 2 {
972            proof.leaves.swap(0, 1);
973        }
974        assert!(matches!(
975            verify_subtree_proof(&proof, &nonce, &commitment),
976            StructureVerdict::Invalid(_)
977        ));
978    }
979
980    // ---- spot-check selection ---------------------------------------------
981
982    #[test]
983    fn spotcheck_indices_in_range_and_distinct() {
984        let n = 1024;
985        let nonce = nonce_of(3);
986        let path = select_subtree_path(&nonce, n).unwrap();
987        let k = 8;
988        let idxs = select_spotcheck_indices(&nonce, &path, k);
989        assert_eq!(
990            u32::try_from(idxs.len()).unwrap(),
991            k.min(path.real_leaf_count())
992        );
993        let mut seen = std::collections::HashSet::new();
994        for i in &idxs {
995            assert!(*i < path.real_leaf_count());
996            assert!(seen.insert(*i), "duplicate spot-check index {i}");
997        }
998    }
999
1000    #[test]
1001    fn build_proof_reports_missing_bytes() {
1002        // A responder that no longer holds a selected, committed key's bytes
1003        // must surface MissingBytes (the caller turns this into a confirmed
1004        // failure, not a benign rejection).
1005        let entries = entries_for(100);
1006        let tree = MerkleTree::build(entries).unwrap();
1007        let nonce = nonce_of(5);
1008        let path = select_subtree_path(&nonce, tree.key_count()).unwrap();
1009        let victim = tree.key_at(path.leaf_start as usize).unwrap();
1010        let err = build_subtree_proof(&tree, &nonce, &[1u8; 32], |k| {
1011            if *k == victim {
1012                None
1013            } else {
1014                Some(chunk_bytes(k))
1015            }
1016        })
1017        .unwrap_err();
1018        assert_eq!(err, BuildProofError::MissingBytes { key: victim });
1019    }
1020
1021    #[test]
1022    fn spotcheck_returns_all_when_subtree_small() {
1023        // Construct a path with few real leaves.
1024        let path = SubtreePath {
1025            depth: 0,
1026            slot: 0,
1027            leaf_start: 0,
1028            leaf_end: 3,
1029        };
1030        let idxs = select_spotcheck_indices(&nonce_of(1), &path, 8);
1031        assert_eq!(idxs, vec![0, 1, 2]);
1032    }
1033
1034    #[test]
1035    fn spotcheck_always_yields_exactly_min_k_n_distinct_indices() {
1036        // The byte sample must NEVER be silently smaller than requested: a
1037        // short sample weakens round 2 without anyone noticing. Exercise many
1038        // nonces, subtree sizes, and k values, and require exactly min(k, n)
1039        // distinct in-range indices every time — plus determinism (auditor and
1040        // responder must derive the same set).
1041        for size in [1u32, 2, 3, 7, 8, 64, 1000] {
1042            let path = SubtreePath {
1043                depth: 0,
1044                slot: 0,
1045                leaf_start: 0,
1046                leaf_end: size,
1047            };
1048            for k in [1u32, 3, 5, 8] {
1049                for seed in 0..32u8 {
1050                    let nonce = nonce_of(seed);
1051                    let idxs = select_spotcheck_indices(&nonce, &path, k);
1052                    let expected = k.min(path.real_leaf_count()) as usize;
1053                    assert_eq!(
1054                        idxs.len(),
1055                        expected,
1056                        "size={size} k={k} seed={seed}: must yield exactly min(k, n)"
1057                    );
1058                    let mut seen = std::collections::HashSet::new();
1059                    for i in &idxs {
1060                        assert!(*i < path.real_leaf_count(), "index out of range");
1061                        assert!(seen.insert(*i), "duplicate index {i}");
1062                    }
1063                    assert_eq!(
1064                        idxs,
1065                        select_spotcheck_indices(&nonce, &path, k),
1066                        "selection must be deterministic"
1067                    );
1068                }
1069            }
1070        }
1071    }
1072
1073    #[test]
1074    fn fabricated_nonced_root_caught_by_spotcheck_probability() {
1075        // Simulate the realness check: a responder fabricates a fraction x of
1076        // nonced roots. The auditor opens k leaves; probability all k land on
1077        // honest leaves is (1-x)^k. Here we just assert the auditor *would* catch
1078        // a fabricated leaf: its committed root differs from the honest root
1079        // recomputed from the real chunk bytes under the audit nonce.
1080        let peer = [1u8; 32];
1081        let entries = entries_for(400);
1082        let nonce = nonce_of(9);
1083        let (mut proof, _commitment) = build_proof(&entries, &nonce, &peer);
1084        // Fabricate the nonced root on the first subtree leaf.
1085        if let Some(first) = proof.leaves.first_mut() {
1086            first.nonced_root[0] ^= 0xFF;
1087        }
1088        let leaf = proof.leaves.first().expect("proof has leaves");
1089        let real_bytes = chunk_bytes(&leaf.key);
1090        let expected =
1091            crate::replication::slice::nonced_block_root(&nonce, &peer, &leaf.key, &real_bytes);
1092        assert_ne!(
1093            leaf.nonced_root, expected,
1094            "fabricated nonced root must differ from real"
1095        );
1096    }
1097
1098    // ---- branch-substitution attack ---------------------------------------
1099
1100    #[test]
1101    fn responder_cannot_substitute_a_different_branch() {
1102        // ADR-0002 "Subtree selection": the random value alone fixes WHICH
1103        // branch is selected, so "the audited node cannot choose a convenient
1104        // branch to present." This is the load-bearing anti-substitution claim
1105        // and no existing test exercises it — the tamper tests only mangle a
1106        // hash within the *correct* branch.
1107        //
1108        // Attack: the responder builds a fully valid, internally-consistent
1109        // subtree proof for a DIFFERENT nonce (which the selection maps to a
1110        // different branch of the same committed tree), then presents it as the
1111        // answer to the auditor's nonce. Every leaf hash and every cut-hash is
1112        // genuine, the leaves are strictly ascending, and we deliberately pick
1113        // a decoy whose branch has the SAME leaf count and SAME depth as the
1114        // honest branch — so the cheap "wrong leaf count" / "wrong cut-hash
1115        // count" gates do NOT fire. The ONLY thing that can reject it is the
1116        // structural root re-derivation, which climbs using the auditor's
1117        // nonce-derived slot parity and position. It must reject.
1118        let peer = [0x5Au8; 32];
1119        let n = 1024u32; // balanced tree; sqrt floor = 32
1120        let entries = entries_for(n);
1121
1122        let audit_nonce = nonce_of(7);
1123        let audit_path = select_subtree_path(&audit_nonce, n).unwrap();
1124
1125        // Find a decoy nonce whose selected branch is a DIFFERENT slot but the
1126        // SAME depth (hence same real-leaf count for this balanced tree). This
1127        // forces rejection via the root check rather than a count mismatch.
1128        let mut decoy: Option<([u8; 32], SubtreePath)> = None;
1129        for seed in 0u8..=255 {
1130            let cand_nonce = nonce_of(seed);
1131            let cand = select_subtree_path(&cand_nonce, n).unwrap();
1132            if cand.depth == audit_path.depth
1133                && cand.slot != audit_path.slot
1134                && cand.real_leaf_count() == audit_path.real_leaf_count()
1135            {
1136                decoy = Some((cand_nonce, cand));
1137                break;
1138            }
1139        }
1140        let (decoy_nonce, decoy_path) =
1141            decoy.expect("a same-depth, different-slot decoy branch must exist for n=1024");
1142
1143        // Sanity: the decoy really is a different, equally-shaped branch.
1144        assert_ne!(decoy_path.slot, audit_path.slot);
1145        assert_eq!(decoy_path.depth, audit_path.depth);
1146        assert_eq!(decoy_path.real_leaf_count(), audit_path.real_leaf_count());
1147
1148        // The responder builds a genuine proof for the DECOY branch. Note the
1149        // nonced hashes are built with the decoy nonce too — but that does not
1150        // matter: the structural check below never inspects nonced hashes, and
1151        // the attack must already die on structure.
1152        let tree = MerkleTree::build(entries).unwrap();
1153        let decoy_proof =
1154            build_subtree_proof(&tree, &decoy_nonce, &peer, |k| Some(chunk_bytes(k))).unwrap();
1155
1156        // Pin the auditor's commitment to the genuine root of the same tree.
1157        let commitment = fake_commitment(tree.root(), n, peer);
1158
1159        // The honest answer to the SAME commitment + decoy nonce verifies, so
1160        // the proof itself is well-formed — it is only "wrong" relative to the
1161        // auditor's nonce.
1162        assert_eq!(
1163            verify_subtree_proof(&decoy_proof, &decoy_nonce, &commitment),
1164            StructureVerdict::Valid,
1165            "the decoy proof must be a genuinely valid proof for its own nonce"
1166        );
1167
1168        // The attack: present the decoy-branch proof against the AUDIT nonce.
1169        // The count gates cannot fire (same depth + leaf count by construction),
1170        // so this is the root re-derivation rejecting a substituted branch.
1171        let verdict = verify_subtree_proof(&decoy_proof, &audit_nonce, &commitment);
1172        assert_eq!(
1173            verdict,
1174            StructureVerdict::Invalid("root mismatch"),
1175            "substituting a different valid branch must be rejected by the root check, got {verdict:?}"
1176        );
1177    }
1178}