Skip to main content

ant_node/replication/
storage_commitment_audit.rs

1//! Gossip-triggered contiguous-subtree storage audit (ADR-0002).
2//!
3//! A node commits to what it stores (a signed Merkle [`StorageCommitment`]
4//! gossiped to neighbours). On receiving a peer's changed commitment, a
5//! neighbour may audit it: pin the just-gossiped root, send a fresh nonce that
6//! deterministically selects one contiguous subtree, and require the peer to
7//! prove that subtree (structure + real bytes) within a deadline. This module
8//! owns the auditor entry point [`run_subtree_audit`] and the responder handler
9//! [`handle_subtree_challenge`]; the pure proof maths live in
10//! [`crate::replication::subtree`].
11
12use std::collections::{HashMap, HashSet};
13use std::sync::Arc;
14use std::time::{Duration, Instant};
15
16use crate::logging::{debug, info, warn};
17use bytes::Bytes;
18use rand::Rng;
19
20use crate::ant_protocol::XorName;
21use crate::pointer::store::{PointerStore, SUPERSEDED_RETENTION};
22use crate::replication::commitment::{commitment_hash, pointer_leaf_hash, StorageCommitment};
23use crate::replication::commitment_state::ResponderCommitmentState;
24use crate::replication::config::{
25    ReplicationConfig, MAX_SLICE_OPENINGS, SUBTREE_AUDIT_PROTOCOL_ID,
26    SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES, SUBTREE_SESSION_TTL,
27};
28use crate::replication::protocol::{
29    RejectKind, ReplicationMessage, ReplicationMessageBody, SubtreeAuditChallenge,
30    SubtreeAuditResponse, SubtreeSliceChallenge, SubtreeSliceItem, SubtreeSliceOpening,
31    SubtreeSliceResponse, MAX_POINTER_RECORDS_PER_ITEM,
32};
33use crate::replication::recent_provers::RecentProvers;
34use crate::replication::slice::nonced_block_root;
35use crate::replication::subtree::{
36    select_subtree_path, subtree_plan, verify_subtree_proof, StructureVerdict, SubtreeLeaf,
37    SubtreeProof,
38};
39use crate::replication::types::{AuditFailureReason, AuditFailureSummary, FailureEvidence};
40use crate::storage::ChunkStore;
41use ant_protocol::pointer::{Pointer, POINTER_WIRE_LEN};
42use saorsa_core::identity::PeerId;
43use saorsa_core::P2PNode;
44use tokio::sync::RwLock;
45
46// The gossip-triggered auditor shares the engine's [`AuditTickResult`] outcome
47// type with the responsible-chunk audit (defined in [`super::audit`]), so the
48// engine can dispatch both audits' results through one match.
49use crate::replication::audit::AuditTickResult;
50
51// ---------------------------------------------------------------------------
52// Auditor side
53// ---------------------------------------------------------------------------
54
55/// ADR-0002 round-2 slice challenge samples a SMALL surprise set of the proven
56/// leaves (3..=5). Small enough that the responder's honest local-disk read of
57/// the original chunks stays well inside the response deadline, which is a
58/// liveness bound and nothing more here: the reply is a few KB, so no deadline
59/// prices a relay out of fetching it (ADR-0009). Large enough that faking a
60/// fraction `x` of leaves survives only `(1 - x)^k`.
61const BYTE_SPOTCHECK_MIN: u32 = 3;
62const BYTE_SPOTCHECK_MAX: u32 = 5;
63
64// Each sampled leaf produces up to two openings (a fresh-random block plus the
65// claimed final block, deduplicated when they coincide), so the opening cap must
66// cover twice the leaf sample.
67const _: () = assert!(
68    2 * BYTE_SPOTCHECK_MAX as usize <= MAX_SLICE_OPENINGS,
69    "MAX_SLICE_OPENINGS must cover two openings per sampled leaf"
70);
71
72/// ADR-0004 A1: with grace removed, the responder retries a TRANSIENT chunk-read
73/// error a few times before rejecting `Transient` (which routes to the timeout
74/// lane). A momentary disk blip usually clears within these attempts; only a
75/// persistent read failure — the node genuinely cannot serve committed bytes —
76/// falls through. Total added latency ((attempts − 1) × backoff) stays well inside the
77/// audit response deadline.
78const AUDIT_READ_RETRY_ATTEMPTS: u32 = 3;
79const AUDIT_READ_RETRY_BACKOFF: Duration = Duration::from_millis(200);
80
81/// Read a committed chunk's bytes, retrying a transient read error up to
82/// [`AUDIT_READ_RETRY_ATTEMPTS`] times with [`AUDIT_READ_RETRY_BACKOFF`] between
83/// tries. `Ok(None)` (bytes definitively absent — real loss) is NOT retried; only
84/// an `Err` (transient IO) is. A persistent `Err` is returned so the caller emits
85/// `RejectKind::Transient` (timeout lane).
86async fn get_raw_retrying(
87    storage: &ChunkStore,
88    key: &XorName,
89) -> crate::error::Result<Option<Vec<u8>>> {
90    let mut attempt = 1u32;
91    loop {
92        match storage.get_raw(key).await {
93            Ok(v) => return Ok(v),
94            Err(e) if attempt < AUDIT_READ_RETRY_ATTEMPTS => {
95                debug!(
96                    "Audit: transient read error for {} (attempt {attempt}/{AUDIT_READ_RETRY_ATTEMPTS}): {e}; retrying",
97                    hex::encode(key)
98                );
99                attempt += 1;
100                tokio::time::sleep(AUDIT_READ_RETRY_BACKOFF).await;
101            }
102            Err(e) => return Err(e),
103        }
104    }
105}
106
107/// How the auditor grades a *responsive* audit rejection (ADR-0004 A1: grace
108/// removed). The decision is a pure function of the [`RejectKind`] so it can be
109/// unit-tested independently of the P2P/side-effect machinery.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111enum RejectGrade {
112    /// Provable misbehaviour → confirmed failure (trust penalty + credit
113    /// revocation downstream).
114    Confirmed,
115    /// Non-response/timeout lane: no trust penalty, but the pinned commitment's
116    /// holder credit is revoked (the peer answered but could not prove possession).
117    TimeoutLane,
118}
119
120/// Grade a responsive rejection. Repudiating a pinned root (`UnknownCommitment`)
121/// or an explicit protocol fault is a confirmed failure; a `Transient` read error
122/// (already retried by the responder) routes to the timeout lane.
123const fn grade_reject(kind: RejectKind) -> RejectGrade {
124    match kind {
125        RejectKind::UnknownCommitment | RejectKind::Protocol => RejectGrade::Confirmed,
126        RejectKind::Transient => RejectGrade::TimeoutLane,
127    }
128}
129
130/// Holder-eligibility cache the auditor credits on a passing audit.
131///
132/// Owned by [`crate::replication::ReplicationEngine`]; borrowed here so a
133/// passing audit can record `(peer, commitment_hash)` as a proven holder for
134/// downstream quorum / paid-list credit.
135pub struct AuditCredit<'a> {
136    /// Holder-eligibility cache.
137    pub recent_provers: &'a Arc<RwLock<RecentProvers>>,
138}
139
140/// Local subsystem that launched a storage-commitment audit.
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub enum SubtreeAuditOrigin {
143    /// Lottery-gated audit after commitment gossip.
144    Gossip,
145    /// Deterministic audit after a commitment-backed payment.
146    FirstMonetized,
147    /// Explicit test or diagnostic request.
148    Manual,
149}
150
151#[cfg(feature = "logging")]
152impl SubtreeAuditOrigin {
153    const fn as_str(self) -> &'static str {
154        match self {
155            Self::Gossip => "gossip",
156            Self::FirstMonetized => "first_monetized",
157            Self::Manual => "manual",
158        }
159    }
160}
161
162/// The cross-cutting context for verifying one audit response, bundled so the
163/// response-dispatch and verification functions stay readable.
164struct AuditCtx<'a> {
165    p2p_node: &'a Arc<P2PNode>,
166    challenged_peer: &'a PeerId,
167    challenge_id: u64,
168    nonce: [u8; 32],
169    expected_commitment_hash: [u8; 32],
170    config: &'a ReplicationConfig,
171    credit: Option<&'a AuditCredit<'a>>,
172    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
173    origin: SubtreeAuditOrigin,
174}
175
176/// Run one gossip-triggered subtree audit against `challenged_peer`, pinned to
177/// the commitment hash the peer just gossiped (`expected_commitment_hash`).
178///
179/// ADR-0002 two-round audit. The auditor sends a fresh random nonce and runs:
180///
181/// 1. **Structure** (round 1) — the returned subtree rebuilds to the pinned
182///    root, within a size-scaled deadline.
183/// 2. **Verified slice** (round 2) — for a 3..=5 FRESHLY-RANDOM sample of the
184///    proven leaves (chosen after the proof arrives, not nonce-derived — see
185///    `random_spotcheck_leaves`), the auditor opens one random 1 KiB block per
186///    leaf (plus its final block) and verifies a Bao slice against the chunk
187///    address and a nonced-tree opening against the round-1 `nonced_root`, over
188///    the bytes the responder serves. The auditor holds none of the peer's
189///    chunks, and possession is the round-1 commitment, not a full-chunk transfer.
190/// 3. **Timing** — a response deadline still bounds liveness, but (unlike the old
191///    full-byte round 2) it is no longer the possession proof; that is the
192///    round-1 `nonced_root` commitment.
193///
194/// A timeout (either round) is reported as [`AuditFailureReason::Timeout`] (the
195/// caller applies the strike/grace policy). Any structural failure, served
196/// content that fails a hash, an explicit `Absent` for a committed sampled key,
197/// or a rejection of a recently gossiped commitment, is a confirmed failure
198/// acted on immediately. On a full pass, records the peer as a proven holder.
199pub async fn run_subtree_audit(
200    p2p_node: &Arc<P2PNode>,
201    config: &ReplicationConfig,
202    challenged_peer: &PeerId,
203    expected_commitment_hash: [u8; 32],
204    key_count: u32,
205    credit: Option<&AuditCredit<'_>>,
206) -> AuditTickResult {
207    run_subtree_audit_with_origin(
208        p2p_node,
209        config,
210        challenged_peer,
211        expected_commitment_hash,
212        key_count,
213        credit,
214        SubtreeAuditOrigin::Manual,
215    )
216    .await
217}
218
219/// Run a subtree audit while retaining the local scheduler origin in logs.
220pub(crate) async fn run_subtree_audit_with_origin(
221    p2p_node: &Arc<P2PNode>,
222    config: &ReplicationConfig,
223    challenged_peer: &PeerId,
224    expected_commitment_hash: [u8; 32],
225    key_count: u32,
226    credit: Option<&AuditCredit<'_>>,
227    origin: SubtreeAuditOrigin,
228) -> AuditTickResult {
229    let (nonce, challenge_id) = {
230        let mut rng = rand::thread_rng();
231        (rng.gen::<[u8; 32]>(), rng.gen::<u64>())
232    };
233
234    let challenge = SubtreeAuditChallenge {
235        challenge_id,
236        nonce,
237        challenged_peer_id: *challenged_peer.as_bytes(),
238        expected_commitment_hash,
239    };
240    let msg = ReplicationMessage {
241        request_id: challenge_id,
242        body: ReplicationMessageBody::SubtreeAuditChallenge(challenge),
243    };
244    let encoded = match msg.encode() {
245        Ok(data) => data,
246        Err(e) => {
247            warn!("Audit: failed to encode subtree challenge for {challenged_peer}: {e}");
248            return AuditTickResult::Idle;
249        }
250    };
251
252    // Size the proof deadline from the ACTUAL selected subtree (its real-leaf
253    // count for this nonce + key_count), not a fixed worst-case hint. This keeps
254    // the deadline proportional to the work an honest responder actually owes —
255    // hashing ~sqrt(N) chunks at local-disk speed — so a slow honest node is not
256    // failed for being large. It is not an anti-relay bound: see ADR-0009, the
257    // proof is delegable at any deadline. The auditor and responder derive the
258    // same selection, so we know the leaf count before the response arrives.
259    let subtree_leaves = select_subtree_path(&nonce, key_count).map_or_else(
260        || config.subtree_audit_timeout_leaf_hint(),
261        |p| p.real_leaf_count() as usize,
262    );
263    let timeout = config.audit_response_timeout(subtree_leaves);
264
265    info!(
266        target: "ant_node::replication::audit_requester",
267        event = "started",
268        audit_origin = origin.as_str(),
269        audit_round = "subtree",
270        challenged_peer = %challenged_peer,
271        challenge_id,
272        work_items = subtree_leaves,
273        timeout_ms = timeout.as_millis(),
274        "Outbound audit request started"
275    );
276    let request_started = Instant::now();
277    let response = match p2p_node
278        .send_request(challenged_peer, SUBTREE_AUDIT_PROTOCOL_ID, encoded, timeout)
279        .await
280    {
281        Ok(resp) => {
282            info!(
283                target: "ant_node::replication::audit_requester",
284                event = "completed",
285                audit_origin = origin.as_str(),
286                audit_round = "subtree",
287                challenged_peer = %challenged_peer,
288                challenge_id,
289                work_items = subtree_leaves,
290                elapsed_ms = request_started.elapsed().as_millis(),
291                outcome = "response",
292                "Outbound audit request completed"
293            );
294            resp
295        }
296        Err(e) => {
297            warn!(
298                target: "ant_node::replication::audit_requester",
299                event = "completed",
300                audit_origin = origin.as_str(),
301                audit_round = "subtree",
302                challenged_peer = %challenged_peer,
303                challenge_id,
304                work_items = subtree_leaves,
305                elapsed_ms = request_started.elapsed().as_millis(),
306                outcome = "no_response",
307                error = %e,
308                "Outbound audit request completed without a response"
309            );
310            return failed(challenged_peer, challenge_id, AuditFailureReason::Timeout);
311        }
312    };
313
314    let resp_msg = match ReplicationMessage::decode_subtree_audit_response(&response.data) {
315        Ok(m) => m,
316        Err(e) => {
317            warn!("Audit: failed to decode subtree response from {challenged_peer}: {e}");
318            return failed(
319                challenged_peer,
320                challenge_id,
321                AuditFailureReason::MalformedResponse,
322            );
323        }
324    };
325
326    let ctx = AuditCtx {
327        p2p_node,
328        challenged_peer,
329        challenge_id,
330        nonce,
331        expected_commitment_hash,
332        config,
333        credit,
334        origin,
335    };
336    dispatch_subtree_response(resp_msg.body, &ctx).await
337}
338
339/// Outcome of the round-2 slice challenge round-trip (auditor side).
340enum SliceRound {
341    /// The responder returned per-opening items (verified by the caller).
342    Served(Vec<SubtreeSliceItem>),
343    /// The responder rejected the slice challenge (confirmed failure for a
344    /// recently pinned commitment).
345    Rejected,
346    /// The responder rejected with `Transient` (a local read error): routed to
347    /// the non-response/timeout lane — no trust penalty, but the pinned
348    /// commitment's holder credit is revoked, because the peer answered and
349    /// could not prove possession, so it must not keep stale credit.
350    ///
351    /// This lands in the same place as [`SliceRound::Timeout`] below, which also
352    /// revokes commitment-scoped credit without a trust penalty. The two are
353    /// kept separate because they say different things about the peer — one
354    /// could not read its disk, the other did not reply at all — and only the
355    /// reason is logged differently.
356    TransientReject,
357    /// No response within the slice deadline, or a transport error. Routed to
358    /// the non-response/timeout lane: no trust penalty, but the pinned
359    /// commitment's holder credit is revoked.
360    ///
361    /// Silence here is not the same as a silent peer in general. The responder
362    /// answered round 1 in this same exchange, so it was live and reachable, and
363    /// it saw which blocks were drawn before deciding whether to reply. Leaving
364    /// credit in place would make "answer only when the draw is favourable" a
365    /// free strategy: an unfavourable sample would cost nothing and the credit
366    /// earned from an earlier favourable one would survive. Revoking scopes the
367    /// cost to the pinned commitment, so the peer must actually answer a round 2
368    /// to hold credit, while an honest node that drops one reply keeps its trust
369    /// intact and re-earns credit on its next audit.
370    Timeout,
371    /// The responder claimed `Bootstrapping` in round 2 after answering a valid
372    /// round-1 proof. A node that just produced a signed subtree proof is
373    /// provably not bootstrapping, so this responsive contradiction is a
374    /// confirmed failure (not a graced timeout): it revokes the peer's holder
375    /// credit and takes the trust penalty.
376    ///
377    /// This classification relies on `is_bootstrapping` being ONE-WAY (true →
378    /// false; see `mod.rs`): a round-1 proof implies the snapshot was already
379    /// `false`, and a restart drops the single-use round-1 session so round 2 is
380    /// answered `Transient` before this branch is ever reached. An honest running
381    /// node therefore cannot produce this response; only a malicious, incompatible,
382    /// or future broken-state peer can. If a "re-bootstrap" (false → true)
383    /// transition is ever added, it MUST clear live sessions or this policy must
384    /// be revisited.
385    ResponsiveBootstrap,
386    /// Malformed / unexpected round-2 response body.
387    Malformed,
388}
389
390/// Round 2: ask the responder to open `openings` blocks (one 1 KiB block per
391/// sampled leaf, at most [`MAX_SLICE_OPENINGS`]) with a Bao verified slice plus a
392/// nonced block-tree opening each. The reply is a few KB total, so there is no
393/// batching. The responder cannot have predicted which leaves — or which block
394/// within each — are opened (fresh post-proof randomness).
395#[allow(clippy::too_many_lines)]
396async fn request_slice_proof(ctx: &AuditCtx<'_>, openings: &[SubtreeSliceOpening]) -> SliceRound {
397    let challenge = SubtreeSliceChallenge {
398        challenge_id: ctx.challenge_id,
399        nonce: ctx.nonce,
400        challenged_peer_id: *ctx.challenged_peer.as_bytes(),
401        expected_commitment_hash: ctx.expected_commitment_hash,
402        openings: openings.to_vec(),
403    };
404    let msg = ReplicationMessage {
405        request_id: ctx.challenge_id,
406        body: ReplicationMessageBody::SubtreeSliceChallenge(challenge),
407    };
408    let encoded = match msg.encode() {
409        Ok(data) => data,
410        Err(e) => {
411            warn!("Audit: failed to encode slice challenge: {e}");
412            return SliceRound::Malformed;
413        }
414    };
415
416    // Deadline sized to "honest responder reads `openings.len()` full local
417    // chunks to build their proofs": generous, because what binds the bytes is
418    // the round-1 nonced commitment, not the clock. It is a liveness bound only
419    // — the reply is a few KB, so no deadline prices a relay out of it, and the
420    // proof is delegable at any deadline (ADR-0009).
421    let timeout = ctx.config.slice_audit_response_timeout(openings.len());
422    info!(
423        target: "ant_node::replication::audit_requester",
424        event = "started",
425        audit_origin = ctx.origin.as_str(),
426        audit_round = "byte",
427        challenged_peer = %ctx.challenged_peer,
428        challenge_id = ctx.challenge_id,
429        work_items = openings.len(),
430        timeout_ms = timeout.as_millis(),
431        "Outbound audit request started"
432    );
433    let request_started = Instant::now();
434    let response = match ctx
435        .p2p_node
436        .send_request(
437            ctx.challenged_peer,
438            SUBTREE_AUDIT_PROTOCOL_ID,
439            encoded,
440            timeout,
441        )
442        .await
443    {
444        Ok(resp) => {
445            info!(
446                target: "ant_node::replication::audit_requester",
447                event = "completed",
448                audit_origin = ctx.origin.as_str(),
449                audit_round = "byte",
450                challenged_peer = %ctx.challenged_peer,
451                challenge_id = ctx.challenge_id,
452                work_items = openings.len(),
453                elapsed_ms = request_started.elapsed().as_millis(),
454                outcome = "response",
455                "Outbound audit request completed"
456            );
457            resp
458        }
459        Err(e) => {
460            warn!(
461                target: "ant_node::replication::audit_requester",
462                event = "completed",
463                audit_origin = ctx.origin.as_str(),
464                audit_round = "byte",
465                challenged_peer = %ctx.challenged_peer,
466                challenge_id = ctx.challenge_id,
467                work_items = openings.len(),
468                elapsed_ms = request_started.elapsed().as_millis(),
469                outcome = "no_response",
470                error = %e,
471                "Outbound audit request completed without a response"
472            );
473            return SliceRound::Timeout;
474        }
475    };
476
477    let resp_msg = match ReplicationMessage::decode_subtree_audit_response(&response.data) {
478        Ok(m) => m,
479        Err(e) => {
480            warn!("Audit: failed to decode slice response: {e}");
481            return SliceRound::Malformed;
482        }
483    };
484
485    classify_slice_response(resp_msg.body, ctx.challenge_id, ctx.challenged_peer)
486}
487
488/// Classify a decoded round-2 body into a [`SliceRound`].
489///
490/// Pure over the wire body so the round-2 accounting boundary is testable
491/// without a live `P2PNode`; [`request_slice_proof`] calls exactly this on the
492/// bytes it decoded.
493///
494/// Every arm is guarded on `challenge_id`: a body carrying any other id is
495/// `Malformed`, so a responder cannot answer a hard challenge with a softer
496/// verdict minted for a different one.
497fn classify_slice_response(
498    body: ReplicationMessageBody,
499    challenge_id: u64,
500    challenged_peer: &PeerId,
501) -> SliceRound {
502    match body {
503        ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Items {
504            challenge_id: id,
505            items,
506        }) if id == challenge_id => SliceRound::Served(items),
507        ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Rejected {
508            challenge_id: id,
509            kind,
510            reason,
511        }) if id == challenge_id => {
512            // ADR-0004 A1: grace removed. UnknownCommitment/Protocol repudiation
513            // of a pinned root is a confirmed failure; a Transient read error
514            // routes to the timeout lane (credit revoked, no trust penalty) — the
515            // responder retries reads first, so a Transient reaching round 2 means
516            // it still could not serve committed bytes.
517            match grade_reject(kind) {
518                RejectGrade::Confirmed => {
519                    warn!(
520                        "Audit: {challenged_peer} rejected slice challenge \
521                         ({kind:?}; confirmed): {reason}"
522                    );
523                    SliceRound::Rejected
524                }
525                RejectGrade::TimeoutLane => {
526                    debug!(
527                        "Audit: {challenged_peer} returned Transient for slice challenge \
528                         (timeout lane): {reason}"
529                    );
530                    SliceRound::TransientReject
531                }
532            }
533        }
534        // A node claiming bootstrap MID-AUDIT (it just answered round 1 with a
535        // valid signed proof) is contradicting itself: a bootstrapping node has
536        // no committed data to prove. A graced timeout here would let it keep the
537        // holder credit it earned earlier while dodging every round-2 possession
538        // check, so this is a confirmed failure with credit revocation.
539        ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Bootstrapping {
540            challenge_id: id,
541        }) if id == challenge_id => SliceRound::ResponsiveBootstrap,
542        _ => SliceRound::Malformed,
543    }
544}
545
546/// Whether a round-2 outcome must revoke the holder credit carried by the
547/// commitment the auditor pinned.
548///
549/// True for every outcome that ends round 2 without a completed possession
550/// proof but stays in the graced timeout lane — an explicit `Transient` reject
551/// and silence alike. Both mean the peer did not prove it still holds the bytes
552/// it committed to, so it must not keep standing earned by an earlier audit.
553///
554/// Silence matters most here. By round 2 the responder has already answered
555/// round 1, so it is demonstrably live, and it learns which blocks were drawn
556/// before it decides whether to reply. If silence kept credit, replying only to
557/// favourable draws would cost nothing: unfavourable samples would be free and
558/// credit from an earlier favourable one would persist, so the sampling
559/// probability would describe answered passes rather than detection. Revoking
560/// makes every unanswered round 2 cost the peer its standing for that
561/// commitment, while an honest peer that drops one reply takes no trust penalty
562/// and re-earns credit on its next audit.
563///
564/// The confirmed lanes (`Rejected`, `ResponsiveBootstrap`, `Malformed`) are
565/// excluded because they revoke more broadly downstream, via
566/// `apply_audit_failure_credit_revocation` → `forget_peer`.
567const fn round2_revokes_pinned_credit(round: &SliceRound) -> bool {
568    matches!(round, SliceRound::TransientReject | SliceRound::Timeout)
569}
570
571/// Map a decoded response body to an audit outcome (auditor side). A response
572/// whose `challenge_id` doesn't match, or any non-subtree body, is malformed.
573async fn dispatch_subtree_response(
574    body: ReplicationMessageBody,
575    ctx: &AuditCtx<'_>,
576) -> AuditTickResult {
577    let challenged_peer = ctx.challenged_peer;
578    let challenge_id = ctx.challenge_id;
579    let malformed = || {
580        failed(
581            challenged_peer,
582            challenge_id,
583            AuditFailureReason::MalformedResponse,
584        )
585    };
586    match body {
587        ReplicationMessageBody::SubtreeAuditResponse(SubtreeAuditResponse::Bootstrapping {
588            challenge_id: resp_id,
589        }) => {
590            if resp_id != challenge_id {
591                return malformed();
592            }
593            AuditTickResult::BootstrapClaim {
594                peer: *challenged_peer,
595            }
596        }
597        ReplicationMessageBody::SubtreeAuditResponse(SubtreeAuditResponse::Rejected {
598            challenge_id: resp_id,
599            kind,
600            reason,
601        }) => {
602            if resp_id != challenge_id {
603                return malformed();
604            }
605            // ADR-0004 A1: audit grace is REMOVED. Answerability is now
606            // restart-durable (persisted retention) and the auditor only pins
607            // in-window roots, so an honest node can always answer a pin it could
608            // be challenged on. A responsive rejection is therefore graded on the
609            // kind, with no grace:
610            match grade_reject(kind) {
611                // Repudiating a pinned root the node published (`UnknownCommitment`)
612                // or an explicit protocol fault is provable misbehaviour →
613                // confirmed failure (trust penalty + credit revocation happen
614                // downstream in handle_subtree_failed_audit).
615                RejectGrade::Confirmed => {
616                    warn!(
617                        "Audit: peer {challenged_peer} rejected subtree challenge \
618                         ({kind:?}; confirmed — grace removed): {reason}"
619                    );
620                    failed(challenged_peer, challenge_id, AuditFailureReason::Rejected)
621                }
622                // A transient local read error (already retried by the responder)
623                // is not a provable cheat, but not graced-with-standing either:
624                // route it to the non-response/timeout lane — no trust penalty, but
625                // revoke the holder credit for THIS pinned commitment so it gains
626                // no positive standing (a Transient-spammer profits nothing).
627                // Scoped to the commitment hash, not the whole peer, so a stale
628                // audit of an old commitment cannot erase credit re-earned for a
629                // newer one.
630                RejectGrade::TimeoutLane => {
631                    if let Some(credit) = ctx.credit {
632                        credit
633                            .recent_provers
634                            .write()
635                            .await
636                            .forget_commitment(&ctx.expected_commitment_hash);
637                    }
638                    debug!(
639                        "Audit: peer {challenged_peer} returned Transient for subtree challenge \
640                         (timeout lane; credit for the pinned commitment revoked): {reason}"
641                    );
642                    failed(challenged_peer, challenge_id, AuditFailureReason::Timeout)
643                }
644            }
645        }
646        ReplicationMessageBody::SubtreeAuditResponse(SubtreeAuditResponse::Proof {
647            challenge_id: resp_id,
648            commitment,
649            proof,
650        }) => {
651            if resp_id != challenge_id {
652                return malformed();
653            }
654            verify_subtree_response(ctx, &commitment, &proof).await
655        }
656        _ => {
657            warn!("Audit: unexpected response type from {challenged_peer}");
658            malformed()
659        }
660    }
661}
662
663/// The pure verdict of evaluating a subtree-audit response, independent of
664/// storage/network. Tests call this directly so the SHIPPED gate logic is what
665/// gets exercised (no reimplementation that could drift).
666#[derive(Debug, Clone, PartialEq, Eq)]
667pub(crate) enum AuditVerdict {
668    /// All gates passed and at least one leaf was byte-verified.
669    Pass {
670        /// Number of leaves whose real bytes were verified in round 2.
671        checked: usize,
672    },
673    /// A confirmed failure with this reason (penalizable / acted upon).
674    Fail(AuditFailureReason),
675}
676
677/// Round-1 structural evaluation of a subtree-audit proof (ADR-0002).
678///
679/// Runs the cheap gates in fail-fast order: pin / identity / signature →
680/// structure (the returned subtree rebuilds to the pinned root). It does **not**
681/// prove byte possession — the leaves carry only the public `bytes_hash` (the
682/// chunk address), a `content_len`, and a `nonced_root` the responder computed
683/// itself. Possession is proven in round 2 ([`verify_slice_response`]), where the
684/// auditor opens a freshly-random (post-proof) block per sampled leaf and
685/// verifies a Bao slice against the address plus a nonced-tree opening against
686/// the round-1 `nonced_root` — over the SERVED bytes, so the auditor never holds
687/// the peer's chunks.
688///
689/// Returns [`StructureVerdict::Valid`] (proceed to round 2) or a confirmed
690/// [`AuditFailureReason`] mapped from the failing gate.
691pub(crate) fn evaluate_subtree_structure(
692    commitment: &StorageCommitment,
693    proof: &SubtreeProof,
694    nonce: &[u8; 32],
695    expected_commitment_hash: &[u8; 32],
696    challenged_peer_bytes: &[u8; 32],
697) -> Result<(), AuditFailureReason> {
698    // -- Pin + identity + signature --
699    if &commitment.sender_peer_id != challenged_peer_bytes {
700        return Err(AuditFailureReason::Rejected);
701    }
702    let derived_peer_id = *blake3::hash(&commitment.sender_public_key).as_bytes();
703    if derived_peer_id != commitment.sender_peer_id {
704        return Err(AuditFailureReason::Rejected);
705    }
706    match commitment_hash(commitment) {
707        Some(h) if &h == expected_commitment_hash => {}
708        _ => return Err(AuditFailureReason::Rejected),
709    }
710    if !crate::replication::commitment::verify_commitment_signature(commitment) {
711        return Err(AuditFailureReason::Rejected);
712    }
713
714    // -- Structure --
715    if let StructureVerdict::Invalid(_) = verify_subtree_proof(proof, nonce, commitment) {
716        return Err(AuditFailureReason::DigestMismatch);
717    }
718
719    // -- Content-address binding (possession-forgery guard) --
720    // The commitment is only sound for CONTENT-ADDRESSED chunks, where the key IS
721    // the content hash (`key == BLAKE3(content)`), so an honest leaf is always
722    // `(key, key)` (see the commitment builder's `(k, k)` shortcut). The signed
723    // Merkle leaf hashes `key ‖ bytes_hash` WITHOUT forcing them equal, yet round 2
724    // authenticates the served slice against `bytes_hash` while holder credit is
725    // recorded for `key`. A leaf with `bytes_hash != key` would therefore let a peer
726    // earn credit for an expensive address `key` by proving possession of an
727    // unrelated (e.g. one-byte) chunk hashing to `bytes_hash`. Reject any such leaf:
728    // for honest content-addressed data the two are identical, so this never fails
729    // an honest holder, and it re-binds Chain 1's `bytes_hash` check to the credited
730    // `key`.
731    //
732    // A pointer (ADR-0016) is the one other honest leaf shape: its address is not
733    // a content hash, so it is committed as `(key, pointer_leaf_hash(key))` at the
734    // fixed record length, and round 2 proves possession with the whole signed
735    // record instead of a slice. Anything else is still rejected.
736    if proof
737        .leaves
738        .iter()
739        .any(|l| l.bytes_hash != l.key && !is_pointer_leaf(l))
740    {
741        return Err(AuditFailureReason::DigestMismatch);
742    }
743    Ok(())
744}
745
746// Round 2 may be owed the record an update replaced after round 1 bound it.
747const _: () = assert!(
748    SUPERSEDED_RETENTION.as_secs() > SUBTREE_SESSION_TTL.as_secs(),
749    "a replaced pointer record must outlive the audit session that may be owed it"
750);
751
752/// What round 1 bound for each committed pointer it proved, by address.
753///
754/// Each is the nonced root round 1 reported over the record it read
755/// (ADR-0019). Round 2 is owed that record, whatever the pointer holds by the
756/// time it asks.
757pub type PointerBindings = HashMap<XorName, [u8; 32]>;
758
759/// The pointer bindings a round-1 response reports. Only a proof reports any.
760#[must_use]
761pub fn pointer_bindings(response: &SubtreeAuditResponse) -> PointerBindings {
762    match response {
763        SubtreeAuditResponse::Proof { proof, .. } => proof
764            .leaves
765            .iter()
766            .filter(|leaf| is_pointer_leaf(leaf))
767            .map(|leaf| (leaf.key, leaf.nonced_root))
768            .collect(),
769        _ => PointerBindings::new(),
770    }
771}
772
773/// Whether a round-1 leaf commits a pointer (ADR-0016): committed under
774/// [`pointer_leaf_hash`] of its key, at the fixed record length.
775fn is_pointer_leaf(leaf: &SubtreeLeaf) -> bool {
776    leaf.bytes_hash == pointer_leaf_hash(&leaf.key)
777        && usize::try_from(leaf.content_len).ok() == Some(POINTER_WIRE_LEN)
778}
779
780/// Check the round-2 item for a pointer leaf: one of the records served must
781/// prove it. An admitted absence is `KeyAbsent`; anything else that does not
782/// prove it, including no item at all, is `DigestMismatch`.
783fn verify_pointer_item(
784    nonce: &[u8; 32],
785    challenged_peer_bytes: &[u8; 32],
786    leaf: &SubtreeLeaf,
787    items: &[SubtreeSliceItem],
788) -> Result<(), AuditFailureReason> {
789    let served = items.iter().find_map(|it| match it {
790        SubtreeSliceItem::PointerRecord { key, records } if key == &leaf.key => {
791            Some(Some(records.as_slice()))
792        }
793        SubtreeSliceItem::Absent { key } if key == &leaf.key => Some(None),
794        _ => None,
795    });
796    match served {
797        Some(Some(records))
798            if records
799                .iter()
800                .any(|record| proves_pointer(nonce, challenged_peer_bytes, leaf, record)) =>
801        {
802            Ok(())
803        }
804        Some(None) => Err(AuditFailureReason::KeyAbsent),
805        _ => Err(AuditFailureReason::DigestMismatch),
806    }
807}
808
809/// Whether `record` proves the pointer `leaf` commits: its signature verifies,
810/// it belongs at the leaf's address, and it is the record round 1 bound the
811/// leaf's nonced root over.
812fn proves_pointer(
813    nonce: &[u8; 32],
814    challenged_peer_bytes: &[u8; 32],
815    leaf: &SubtreeLeaf,
816    record: &[u8],
817) -> bool {
818    nonced_block_root(nonce, challenged_peer_bytes, &leaf.key, record) == leaf.nonced_root
819        && Pointer::from_bytes(record).is_ok_and(|pointer| pointer.address() == leaf.key)
820}
821
822/// The auditor's **freshly-randomised** spot-check sample of the round-1 proof:
823/// `count` distinct leaves (deduplicated, in increasing-index order) whose
824/// original bytes the auditor will demand in round 2.
825///
826/// CRITICAL (ADR-0002 soundness): the sample MUST NOT be derivable from
827/// anything the responder knew when it built the round-1 proof. The structural
828/// root check binds only `(key, bytes_hash)` (both public — `bytes_hash` is the
829/// chunk's network address), NOT `nonced_root`. So a relay holding only public
830/// addresses can fabricate a structurally-valid proof with a bogus `nonced_root`
831/// on every leaf and, if it could predict which leaves round 2 opens, fetch
832/// only those and pass — earning holder credit for leaves it never held.
833///
834/// Picking the sample with fresh CSPRNG randomness AFTER the proof is received
835/// turns round 1 into a commitment and round 2 into an unpredictable challenge
836/// (cut-and-choose): to pass with probability above `(1 - faked_fraction)^count`
837/// the responder must have produced a correct `nonced_root` — which requires the
838/// real bytes under the fresh nonce — for essentially every leaf at round-1
839/// commit time. The auditor still holds none of the peer's chunks. The block
840/// index opened within each sampled leaf is likewise drawn fresh
841/// ([`random_block_index`]), so no single block can be prepared in advance.
842fn random_spotcheck_leaves(
843    proof: &SubtreeProof,
844    count: u32,
845) -> Vec<&crate::replication::subtree::SubtreeLeaf> {
846    let n = proof.leaves.len();
847    if n == 0 {
848        return Vec::new();
849    }
850    let want = (count as usize).min(n);
851    let mut rng = rand::thread_rng();
852    let mut picked = std::collections::BTreeSet::new();
853    // n >= want, so this terminates quickly; bound the loop defensively against
854    // a pathological RNG rather than risk spinning.
855    let mut guard = 0u32;
856    while picked.len() < want && guard < count.saturating_mul(64).max(64) {
857        picked.insert(rng.gen_range(0..n));
858        guard = guard.saturating_add(1);
859    }
860    // Deterministic top-up if the RNG kept colliding (astronomically unlikely):
861    // fill the lowest missing indices so the sample is never silently short.
862    for idx in 0..n {
863        if picked.len() >= want {
864            break;
865        }
866        picked.insert(idx);
867    }
868    picked
869        .into_iter()
870        .filter_map(|idx| proof.leaves.get(idx))
871        .collect()
872}
873
874/// Draw a fresh-random 1 KiB block index in `0..block_count(content_len)`.
875///
876/// Called AFTER the round-1 proof is in hand, per sampled leaf, so the responder
877/// could not have prepared only the opened block (the cut-and-choose property,
878/// now at block granularity).
879fn random_block_index(content_len: u32) -> u32 {
880    let count = crate::replication::slice::block_count(u64::from(content_len));
881    if count <= 1 {
882        return 0;
883    }
884    rand::thread_rng().gen_range(0..count)
885}
886
887/// The two block indices opened for one sampled leaf: a fresh-random block (the
888/// cut-and-choose possession check) and the claimed final block.
889///
890/// The final block is opened so the auditor's Bao decode reaches EOF, which is
891/// where Bao authenticates the encoded length against the address. Without it a
892/// responder can forge a *shorter* `content_len` (which is not signed by the
893/// round-1 commitment), collapse the challenge space, and pass while storing only
894/// the prefix — the length header alone is not bound for a prefix slice that
895/// never touches EOF. Opening the final block pins the true length: a forged
896/// short length fails the final-block decode against the real address.
897///
898/// Returns one index when the random draw already lands on the final block (or
899/// the chunk is a single block), two otherwise, never more than two.
900fn block_indices_for_leaf(content_len: u32) -> Vec<u32> {
901    let count = crate::replication::slice::block_count(u64::from(content_len));
902    let final_index = count.saturating_sub(1);
903    let random = random_block_index(content_len);
904    if random == final_index {
905        vec![final_index]
906    } else {
907        vec![random, final_index]
908    }
909}
910
911/// Round-2 verdict (ADR-0002 / V2-685): the responder opened one 1 KiB block per
912/// sampled leaf with a Bao verified slice plus a nonced block-tree opening;
913/// verify possession from those.
914///
915/// `openings` pairs each sampled leaf with the block index the auditor drew for
916/// it. `items` is what the responder returned. For each opening the auditor:
917///   1. finds the responder's `Present` item for exactly this `(key, block_index)`
918///      (a missing, `Absent` or wrong-block item is a provable lie);
919///   2. **Chain 1** — decodes the Bao slice against `leaf.bytes_hash` (the chunk
920///      address), recovering the verified block bytes. This proves the block is
921///      the real content at that offset, without the auditor holding the chunk.
922///   3. **Chain 2** — folds the nonced block leaf (recomputed from those verified
923///      bytes under the audit nonce/peer/key/index) with the returned siblings to
924///      `leaf.nonced_root`. This proves the responder committed a nonced tree
925///      over the real content at round-1 time, so it held the bytes then.
926///
927/// Both chains are over the SAME block bytes and the auditor holds none of the
928/// peer's chunks. Every failure here is a confirmed one, split by what the
929/// responder actually did so the audit log can tell them apart:
930///
931/// - an explicit `Absent` for a key committed in round 1 is an admitted loss →
932///   [`AuditFailureReason::KeyAbsent`] (`absent_keys`);
933/// - a missing item, a wrong block, a slice that fails to decode against the
934///   address, or a nonced opening that does not fold to the committed root, is a
935///   proof failure → [`AuditFailureReason::DigestMismatch`]
936///   (`digest_mismatch_keys`).
937///
938/// Both reasons take the same trust penalty, clear the bootstrap claim and
939/// revoke holder credit, so the split is diagnostic and not an enforcement
940/// change. All openings verifying → `Pass { checked }`.
941pub(crate) fn verify_slice_response(
942    openings: &[(crate::replication::subtree::SubtreeLeaf, u32)],
943    nonce: &[u8; 32],
944    challenged_peer_bytes: &[u8; 32],
945    items: &[SubtreeSliceItem],
946) -> AuditVerdict {
947    // Validate the response shape before matching. A well-formed response has at
948    // most one item per SOLICITED identity; the per-opening `find_map` below
949    // returns the FIRST match, so a duplicate `(key, block_index)` `Present`, a
950    // key that is both `Present` and `Absent`, a repeated `Absent`, or an
951    // UNSOLICITED item would let the responder's item order (or padding) decide
952    // the verdict. Bounding `items.len()` to the request count also keeps this
953    // check (and the matching below) at O(openings) — a peer cannot pad the
954    // response with thousands of unique items to force quadratic validation work.
955    if items.len() > openings.len() {
956        return AuditVerdict::Fail(AuditFailureReason::MalformedResponse);
957    }
958    let requested_blocks: HashSet<(XorName, u32)> =
959        openings.iter().map(|(leaf, i)| (leaf.key, *i)).collect();
960    let requested_keys: HashSet<XorName> = openings.iter().map(|(leaf, _)| leaf.key).collect();
961    let mut present: HashSet<(XorName, u32)> = HashSet::new();
962    let mut absent: HashSet<XorName> = HashSet::new();
963    let mut records: HashSet<XorName> = HashSet::new();
964    for it in items {
965        let ok = match it {
966            SubtreeSliceItem::Present {
967                key, block_index, ..
968            } => {
969                requested_blocks.contains(&(*key, *block_index))
970                    && present.insert((*key, *block_index))
971                    && !absent.contains(key)
972                    && !records.contains(key)
973            }
974            SubtreeSliceItem::Absent { key } => {
975                requested_keys.contains(key)
976                    && absent.insert(*key)
977                    && !present.iter().any(|(k, _)| k == key)
978                    && !records.contains(key)
979            }
980            SubtreeSliceItem::PointerRecord {
981                key,
982                records: served,
983            } => {
984                requested_keys.contains(key)
985                    && (1..=MAX_POINTER_RECORDS_PER_ITEM).contains(&served.len())
986                    && records.insert(*key)
987                    && !absent.contains(key)
988                    && !present.iter().any(|(k, _)| k == key)
989            }
990        };
991        if !ok {
992            return AuditVerdict::Fail(AuditFailureReason::MalformedResponse);
993        }
994    }
995
996    let mut checked = 0usize;
997    for (leaf, block_index) in openings {
998        // A pointer leaf is proved by the whole signed record: it must verify,
999        // belong at the committed address, and be the record round 1 bound its
1000        // nonced root over, which the responder had to read before it knew what
1001        // would be sampled. An update between the rounds does not fail an
1002        // honest holder: it serves the record round 1 read (ADR-0019).
1003        if is_pointer_leaf(leaf) {
1004            if let Err(reason) = verify_pointer_item(nonce, challenged_peer_bytes, leaf, items) {
1005                return AuditVerdict::Fail(reason);
1006            }
1007            checked += 1;
1008            continue;
1009        }
1010        let block_index = *block_index;
1011        // Match the responder's item for exactly this (key, block_index). A
1012        // missing item, an explicit Absent, or a different block is a provable lie.
1013        let served = items.iter().find_map(|it| match it {
1014            SubtreeSliceItem::Present {
1015                key,
1016                block_index: served_index,
1017                bao_slice,
1018                nonced_siblings,
1019            } if key == &leaf.key && *served_index == block_index => {
1020                Some(Some((bao_slice.as_slice(), nonced_siblings.as_slice())))
1021            }
1022            SubtreeSliceItem::Absent { key } if key == &leaf.key => Some(None),
1023            _ => None,
1024        });
1025        let (bao_slice, nonced_siblings) = match served {
1026            Some(Some(opening)) => opening,
1027            // The responder explicitly answered "I do not hold this key", for a
1028            // key it committed to in round 1. That is an admitted loss, not a
1029            // broken proof, and it is reported as `KeyAbsent` so the failure log
1030            // line separates the two: `absent_keys` counts a peer that owned up
1031            // to missing data, `digest_mismatch_keys` counts one whose proof did
1032            // not verify. Both are confirmed failures and carry identical trust,
1033            // bootstrap-claim and holder-credit effects, so this changes what an
1034            // operator can see, not what the audit enforces.
1035            Some(None) => return AuditVerdict::Fail(AuditFailureReason::KeyAbsent),
1036            // No item at all for a solicited opening: the responder neither
1037            // served the block nor admitted the key is gone, so nothing about
1038            // possession was established. That stays a proof failure.
1039            None => return AuditVerdict::Fail(AuditFailureReason::DigestMismatch),
1040        };
1041
1042        // Chain 1: authenticate the block against the chunk address.
1043        let Some(block) = crate::replication::slice::verify_block_slice(
1044            bao_slice,
1045            &leaf.bytes_hash,
1046            u64::from(leaf.content_len),
1047            block_index,
1048        ) else {
1049            return AuditVerdict::Fail(AuditFailureReason::DigestMismatch);
1050        };
1051
1052        // Chain 2: prove the block was committed under round 1's fresh nonce,
1053        // with the sibling chain pinned to the canonical depth for the chunk's
1054        // block count (bound the claimed tree geometry).
1055        if !crate::replication::slice::verify_nonced_block(
1056            nonce,
1057            challenged_peer_bytes,
1058            &leaf.key,
1059            block_index,
1060            &block,
1061            nonced_siblings,
1062            &leaf.nonced_root,
1063            crate::replication::slice::block_count(u64::from(leaf.content_len)),
1064        ) {
1065            return AuditVerdict::Fail(AuditFailureReason::DigestMismatch);
1066        }
1067        checked += 1;
1068    }
1069    AuditVerdict::Pass { checked }
1070}
1071
1072/// The auditor's verdict on one subtree-audit response (ADR-0002), in the order
1073/// production runs the gates: round 1 ([`evaluate_subtree_structure`]: pin,
1074/// identity, signature, structure, content-address binding), then a
1075/// freshly-random round-2 sample, then [`verify_slice_response`] over what the
1076/// responder served for it.
1077///
1078/// `round2` performs round 2: it is handed the openings the auditor drew and
1079/// returns what came back. [`verify_subtree_response`] passes the network round
1080/// trip; the test-utils entry [`verify_subtree_response_for_tests`] passes a
1081/// modelled responder, so the attack proof-of-concept tests exercise this same
1082/// composition rather than a copy of it. Logs each failure; the caller acts on the verdict.
1083async fn subtree_audit_verdict<F, Fut>(
1084    commitment: &StorageCommitment,
1085    proof: &SubtreeProof,
1086    nonce: &[u8; 32],
1087    expected_commitment_hash: &[u8; 32],
1088    challenged_peer: &PeerId,
1089    spotcheck_count: u32,
1090    round2: F,
1091) -> AuditVerdict
1092where
1093    F: FnOnce(Vec<SubtreeSliceOpening>) -> Fut,
1094    Fut: std::future::Future<Output = SliceRound>,
1095{
1096    // -- Round 1: pin/identity/signature + structure (no bytes). --
1097    if let Err(reason) = evaluate_subtree_structure(
1098        commitment,
1099        proof,
1100        nonce,
1101        expected_commitment_hash,
1102        challenged_peer.as_bytes(),
1103    ) {
1104        warn!("Audit: {challenged_peer} failed subtree structure ({reason:?})");
1105        return AuditVerdict::Fail(reason);
1106    }
1107
1108    // -- Round 2: surprise slice challenge for a 3..=5 FRESHLY-RANDOM sample. --
1109    // The sample is chosen now, with CSPRNG randomness, AFTER the round-1 proof
1110    // is in hand — NOT derived from the round-1 nonce. The responder committed
1111    // every leaf's `nonced_root` in round 1 without knowing which leaves — or
1112    // which block within each — we will open, so it could not have prepared only
1113    // the opened blocks (cut-and-choose). The reply is a few KB per opening (a
1114    // 1 KiB block plus two short hash chains), so one round-2 message serves the
1115    // whole sample; no batching.
1116    let sample_n = spotcheck_count.clamp(BYTE_SPOTCHECK_MIN, BYTE_SPOTCHECK_MAX);
1117    let sampled = random_spotcheck_leaves(proof, sample_n);
1118    if sampled.is_empty() {
1119        // Cannot happen after a valid structure (subtree is never empty), but
1120        // guard rather than credit an unproven peer.
1121        warn!("Audit: {challenged_peer} produced an empty spot-check sample; rejecting");
1122        return AuditVerdict::Fail(AuditFailureReason::DigestMismatch);
1123    }
1124    // Pair each sampled leaf with up to two block indices: a fresh-random block
1125    // (possession) and the claimed final block (a length pin — see
1126    // `block_indices_for_leaf`). Own the leaves so the borrow on `proof` ends
1127    // before the await. The sample is <= BYTE_SPOTCHECK_MAX and each leaf yields
1128    // <= 2 openings, so the total is <= 2 * BYTE_SPOTCHECK_MAX <= MAX_SLICE_OPENINGS
1129    // (statically asserted); `take` is a defensive backstop.
1130    let openings_with_leaves: Vec<(crate::replication::subtree::SubtreeLeaf, u32)> = sampled
1131        .iter()
1132        .flat_map(|leaf| {
1133            let leaf = (*leaf).clone();
1134            // A pointer is served whole, so it takes one opening, at block 0.
1135            let indices = if is_pointer_leaf(&leaf) {
1136                vec![0]
1137            } else {
1138                block_indices_for_leaf(leaf.content_len)
1139            };
1140            indices
1141                .into_iter()
1142                .map(move |block_index| (leaf.clone(), block_index))
1143        })
1144        .take(MAX_SLICE_OPENINGS)
1145        .collect();
1146    let openings: Vec<SubtreeSliceOpening> = openings_with_leaves
1147        .iter()
1148        .map(|(leaf, block_index)| SubtreeSliceOpening {
1149            key: leaf.key,
1150            block_index: *block_index,
1151        })
1152        .collect();
1153
1154    let verdict = match round2(openings).await {
1155        // The responder served openings: verify both chains for every one. Any
1156        // failing chain is a confirmed cheat.
1157        SliceRound::Served(items) => verify_slice_response(
1158            &openings_with_leaves,
1159            nonce,
1160            challenged_peer.as_bytes(),
1161            &items,
1162        ),
1163        // Confirmed round-2 failures. `Rejected`: the responder repudiated the
1164        // slice challenge for a recently pinned commitment. `ResponsiveBootstrap`:
1165        // it claimed bootstrap AFTER producing a valid round-1 proof, which is a
1166        // self-contradiction (a bootstrapping node has no committed data to
1167        // prove). Both are classified as any other confirmed `Rejected`, which
1168        // revokes the peer's holder credit and takes the trust penalty downstream
1169        // (`apply_audit_failure_credit_revocation` → `forget_peer`).
1170        SliceRound::Rejected | SliceRound::ResponsiveBootstrap => {
1171            AuditVerdict::Fail(AuditFailureReason::Rejected)
1172        }
1173        // Round 2 produced no proof, either as an explicit `Transient` (a local
1174        // read error) or as silence. Both route to the timeout lane: no trust
1175        // penalty, the strike policy still graces them, and the caller has
1176        // already revoked the credit for the pinned commitment.
1177        SliceRound::TransientReject | SliceRound::Timeout => {
1178            AuditVerdict::Fail(AuditFailureReason::Timeout)
1179        }
1180        // Malformed/unexpected round-2 body.
1181        SliceRound::Malformed => AuditVerdict::Fail(AuditFailureReason::MalformedResponse),
1182    };
1183    if let AuditVerdict::Fail(reason) = &verdict {
1184        warn!("Audit: {challenged_peer} failed subtree audit ({reason:?})");
1185    }
1186    verdict
1187}
1188
1189/// The auditor's verdict on a subtree-audit response, with round 2 answered by
1190/// `serve` instead of the network.
1191///
1192/// It runs the same composition as `verify_subtree_response`. Test-only: it
1193/// lets the attack proof-of-concept tests check that the shipped gates, in the
1194/// shipped order, reject each attack.
1195///
1196/// `serve` gets the openings the auditor drew (fresh randomness, after round 1,
1197/// as in production) and returns the responder's items for them. Returns the
1198/// number of verified openings on a pass, or the confirmed failure reason.
1199///
1200/// # Errors
1201///
1202/// The [`AuditFailureReason`] production would record for this response.
1203#[cfg(any(test, feature = "test-utils"))]
1204pub async fn verify_subtree_response_for_tests(
1205    commitment: &StorageCommitment,
1206    proof: &SubtreeProof,
1207    nonce: &[u8; 32],
1208    expected_commitment_hash: &[u8; 32],
1209    challenged_peer_bytes: &[u8; 32],
1210    spotcheck_count: u32,
1211    serve: impl FnOnce(&[SubtreeSliceOpening]) -> Vec<SubtreeSliceItem>,
1212) -> Result<usize, AuditFailureReason> {
1213    let challenged_peer = PeerId::from_bytes(*challenged_peer_bytes);
1214    let verdict = subtree_audit_verdict(
1215        commitment,
1216        proof,
1217        nonce,
1218        expected_commitment_hash,
1219        &challenged_peer,
1220        spotcheck_count,
1221        |openings| {
1222            let items = serve(&openings);
1223            async move { SliceRound::Served(items) }
1224        },
1225    )
1226    .await;
1227    match verdict {
1228        AuditVerdict::Pass { checked } => Ok(checked),
1229        AuditVerdict::Fail(reason) => Err(reason),
1230    }
1231}
1232
1233/// Verify a subtree-proof response (auditor side), ADR-0002 two-round audit.
1234///
1235/// **Round 1** (this proof): pin + identity + signature + structure. If the
1236/// proof structurally rebuilds to the pinned root, the tree SHAPE is committed —
1237/// but not yet that the bytes are held. **Round 2**: the auditor picks a small
1238/// freshly-random (post-proof) sample of the just-proven leaves, draws a fresh
1239/// block index for each, and sends a [`SubtreeSliceChallenge`] opening those
1240/// blocks. It verifies each opened block against the committed `bytes_hash`
1241/// (Bao slice → content address) and `nonced_root` (nonced block-tree opening →
1242/// round-1 possession commit). A responder that committed to a chunk it no
1243/// longer held cannot have committed a correct `nonced_root`, so it fails —
1244/// regardless of what the auditor holds. On a full pass, credits the peer as a
1245/// proven holder.
1246async fn verify_subtree_response(
1247    ctx: &AuditCtx<'_>,
1248    commitment: &StorageCommitment,
1249    proof: &SubtreeProof,
1250) -> AuditTickResult {
1251    let challenged_peer = ctx.challenged_peer;
1252    let challenge_id = ctx.challenge_id;
1253
1254    // Round 1, the round-2 sample and the round-2 verdict all run in
1255    // `subtree_audit_verdict`, the composition the attack PoCs drive too
1256    // (`tests/poc_commitment_audit_attacks.rs`). Only the round-2 transport and
1257    // the credit revocation it triggers live here.
1258    let verdict = subtree_audit_verdict(
1259        commitment,
1260        proof,
1261        &ctx.nonce,
1262        &ctx.expected_commitment_hash,
1263        challenged_peer,
1264        ctx.config.audit_spotcheck_count(),
1265        |openings| async move {
1266            let round = request_slice_proof(ctx, &openings).await;
1267
1268            // Round 2 ended without a completed possession proof: drop the
1269            // holder credit this pinned commitment carries, before the outcome
1270            // is mapped to a verdict. Scoped to the commitment hash, so credit
1271            // the peer re-earned for a newer commitment survives.
1272            if round2_revokes_pinned_credit(&round) {
1273                if let Some(credit) = ctx.credit {
1274                    credit
1275                        .recent_provers
1276                        .write()
1277                        .await
1278                        .forget_commitment(&ctx.expected_commitment_hash);
1279                }
1280            }
1281            round
1282        },
1283    )
1284    .await;
1285
1286    match verdict {
1287        AuditVerdict::Fail(reason) => failed(challenged_peer, challenge_id, reason),
1288        AuditVerdict::Pass { checked } => {
1289            // Closeness (ADR-0002, soft/observe-only) — see observe_closeness.
1290            observe_closeness(ctx.p2p_node, ctx.config, challenged_peer, proof).await;
1291            // Credit the peer as a proven holder of its committed keys.
1292            if let (Some(credit), Some(pin)) = (ctx.credit, commitment_hash(commitment)) {
1293                let now = std::time::Instant::now();
1294                let mut provers = credit.recent_provers.write().await;
1295                for leaf in &proof.leaves {
1296                    provers.record_proof(leaf.key, *challenged_peer, pin, now);
1297                }
1298            }
1299            info!(
1300                "Audit: peer {challenged_peer} passed subtree audit ({} leaves, {checked} \
1301                 block openings verified)",
1302                proof.leaves.len()
1303            );
1304            AuditTickResult::Passed {
1305                challenged_peer: *challenged_peer,
1306                keys_checked: checked,
1307            }
1308        }
1309    }
1310}
1311
1312/// Soft, density-aware closeness observation (ADR-0002). Logs — never fails —
1313/// when a suspicious fraction of the proof's leaves are keys the auditor itself
1314/// is NOT responsible for (a proxy for "implausibly far from the peer").
1315///
1316/// Using the auditor's own `SelfInclusiveRT` responsibility as the yardstick
1317/// makes this density-aware for free: on a small/dense network the auditor is
1318/// close to nearly every key, so almost nothing reads as far and no honest peer
1319/// is ever flagged. Enforcement is intentionally deferred until a testnet
1320/// calibrates the density threshold.
1321async fn observe_closeness(
1322    p2p_node: &Arc<P2PNode>,
1323    config: &ReplicationConfig,
1324    challenged_peer: &PeerId,
1325    proof: &SubtreeProof,
1326) {
1327    /// Max leaves probed for the closeness estimate (bounds the DHT lookups).
1328    const CLOSENESS_SAMPLE_CAP: usize = 8;
1329
1330    // This is an observe-only DEBUG signal (never enforced). The check costs one
1331    // DHT responsibility lookup per inspected leaf, so (§12): (a) skip it
1332    // entirely unless debug logging is on — there is no other consumer — and
1333    // (b) inspect at most a bounded SAMPLE of leaves rather than all ~sqrt(N),
1334    // which still reveals the "mostly far" padding shape without N lookups.
1335    if !crate::logging::enabled!(crate::logging::Level::DEBUG) {
1336        return;
1337    }
1338
1339    let self_id = *p2p_node.peer_id();
1340    let inspected = proof.leaves.len().min(CLOSENESS_SAMPLE_CAP);
1341    let mut far = 0usize;
1342    for leaf in proof.leaves.iter().take(inspected) {
1343        if !crate::replication::admission::is_responsible(
1344            &self_id,
1345            &leaf.key,
1346            p2p_node,
1347            config.close_group_size,
1348        )
1349        .await
1350        {
1351            far += 1;
1352        }
1353    }
1354    // Only worth a line when MOST of the inspected sample is far — that's the
1355    // padding shape. A normal proof on a sparse network has some far keys.
1356    if inspected > 0 && far * 2 > inspected {
1357        debug!(
1358            "Audit: closeness signal — {far}/{inspected} sampled of {challenged_peer}'s proven \
1359             leaves are keys this auditor is not close to (observe-only; possible padding, not \
1360             penalized)"
1361        );
1362    }
1363}
1364
1365/// Build a confirmed-failure result. The auditor pinned a commitment the peer
1366/// committed to itself, so there is no per-key responsibility to re-confirm:
1367/// the failure is about the peer's own committed tree.
1368///
1369/// The subtree audit fails a peer as a whole (one challenge, one verdict) rather
1370/// than per-key, so the [`AuditFailureSummary`] is a single-failure rollup
1371/// mapped from `reason` — enough for the shared audit-failure diagnostics log
1372/// line (`absent_keys`/`digest_mismatch_keys`) without inventing per-key counts
1373/// this audit shape does not have.
1374fn failed(
1375    challenged_peer: &PeerId,
1376    challenge_id: u64,
1377    reason: AuditFailureReason,
1378) -> AuditTickResult {
1379    let summary = subtree_failure_summary(&reason);
1380    AuditTickResult::Failed {
1381        evidence: FailureEvidence::AuditFailure {
1382            challenge_id,
1383            challenged_peer: *challenged_peer,
1384            confirmed_failed_keys: Vec::new(),
1385            summary,
1386            reason,
1387        },
1388        no_response_class: None,
1389    }
1390}
1391
1392/// Map a subtree-audit `reason` to a single-failure [`AuditFailureSummary`].
1393///
1394/// A `Timeout` is not a confirmed failure (it is the non-response/timeout lane),
1395/// so it rolls up as zero confirmed failures; every other reason is one confirmed failure,
1396/// categorised where the category is meaningful (byte/nonce/root mismatch →
1397/// `digest_mismatch_keys`; explicit absent → `absent_keys`).
1398fn subtree_failure_summary(reason: &AuditFailureReason) -> AuditFailureSummary {
1399    let mut summary = AuditFailureSummary {
1400        challenged_keys: 1,
1401        ..AuditFailureSummary::default()
1402    };
1403    match reason {
1404        AuditFailureReason::Timeout => {}
1405        AuditFailureReason::DigestMismatch => {
1406            summary.failed_keys = 1;
1407            summary.digest_mismatch_keys = 1;
1408        }
1409        AuditFailureReason::KeyAbsent => {
1410            summary.failed_keys = 1;
1411            summary.absent_keys = 1;
1412        }
1413        AuditFailureReason::MalformedResponse | AuditFailureReason::Rejected => {
1414            summary.failed_keys = 1;
1415        }
1416    }
1417    summary
1418}
1419
1420// ---------------------------------------------------------------------------
1421// Responder side
1422// ---------------------------------------------------------------------------
1423
1424/// Handle an incoming subtree audit challenge (responder side).
1425///
1426/// Validates the challenge targets this node, looks up the pinned commitment in
1427/// the retained (in-window) set, and builds the subtree proof for the
1428/// nonce-selected branch. If this node is bootstrapping it says so; if it
1429/// genuinely does not retain the pinned commitment it rejects (which, with audit
1430/// grace removed, the auditor treats as a confirmed failure for an in-window pin).
1431pub async fn handle_subtree_challenge(
1432    challenge: &SubtreeAuditChallenge,
1433    storage: &ChunkStore,
1434    self_peer_id: &PeerId,
1435    is_bootstrapping: bool,
1436    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1437) -> SubtreeAuditResponse {
1438    handle_subtree_challenge_measured(
1439        challenge,
1440        storage,
1441        self_peer_id,
1442        is_bootstrapping,
1443        commitment_state,
1444    )
1445    .await
1446    .response
1447}
1448
1449/// A round-1 response together with the chunk bytes spent producing it.
1450pub struct Round1Work {
1451    /// What to send back.
1452    pub response: SubtreeAuditResponse,
1453    /// Chunk content read from the store and hashed BEFORE this response was
1454    /// produced.
1455    ///
1456    /// Counted on the rejecting paths too, which is the point. A subtree is read
1457    /// leaf by leaf, so a commitment holding one unreadable key still costs a
1458    /// full run of reads and keyed-BLAKE3 passes over every leaf before it. If
1459    /// only the `Proof` arm were charged, an attacker who found such a
1460    /// commitment could replay subtrees over it indefinitely for free — and
1461    /// since the per-peer cooldown is escapable by rotating identity, the
1462    /// responder-wide work budget is the only bound that would have caught it.
1463    pub content_bytes: i64,
1464    /// Committed chunks whose bytes, read for this proof, no longer hash to
1465    /// their key.
1466    ///
1467    /// The proof still carries what was read, so the auditor's verdict on them
1468    /// is unchanged. The caller reports them to the chunk store
1469    /// (`ChunkStore::report_corrupt`), whose recheck worker takes the ones its
1470    /// bounded queue admits out of service, so the node stops committing a chunk
1471    /// it cannot prove and replication can repair it, rather than failing every
1472    /// audit that lands on that key until a fetch of the same key happens to
1473    /// notice. A key the queue cannot take stays committed, so the next audit
1474    /// that reads it reports it again. Not done here, so the cleanup never delays
1475    /// the answer the auditor is waiting for.
1476    pub corrupt_keys: Vec<XorName>,
1477}
1478
1479/// [`handle_subtree_challenge`], additionally reporting the read-and-hash work
1480/// it performed so the caller can charge it on every exit path.
1481pub async fn handle_subtree_challenge_measured(
1482    challenge: &SubtreeAuditChallenge,
1483    storage: &ChunkStore,
1484    self_peer_id: &PeerId,
1485    is_bootstrapping: bool,
1486    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1487) -> Round1Work {
1488    handle_subtree_challenge_measured_with_pointers(
1489        challenge,
1490        storage,
1491        None,
1492        self_peer_id,
1493        is_bootstrapping,
1494        commitment_state,
1495    )
1496    .await
1497}
1498
1499/// [`handle_subtree_challenge_measured`] for a node that also commits pointers
1500/// (ADR-0016): committed pointer leaves are answered from `pointers`.
1501pub async fn handle_subtree_challenge_measured_with_pointers(
1502    challenge: &SubtreeAuditChallenge,
1503    storage: &ChunkStore,
1504    pointers: Option<&PointerStore>,
1505    self_peer_id: &PeerId,
1506    is_bootstrapping: bool,
1507    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1508) -> Round1Work {
1509    // The accumulator is threaded in rather than returned per-arm so that every
1510    // exit reports its work by construction: a new early return cannot forget to
1511    // account for the reads that already happened.
1512    let mut content_bytes = 0i64;
1513    let mut corrupt_keys = Vec::new();
1514    let response = subtree_challenge_response(
1515        challenge,
1516        storage,
1517        pointers,
1518        self_peer_id,
1519        is_bootstrapping,
1520        commitment_state,
1521        &mut content_bytes,
1522        &mut corrupt_keys,
1523    )
1524    .await;
1525    Round1Work {
1526        response,
1527        content_bytes,
1528        corrupt_keys,
1529    }
1530}
1531
1532/// The round-1 responder proper. `content_bytes` accrues the chunk content read
1533/// and hashed so far, and is meaningful on every return path, not just the
1534/// successful one. `corrupt_keys` collects the committed chunks whose bytes did
1535/// not hash to their key (see [`Round1Work::corrupt_keys`]).
1536#[allow(clippy::too_many_lines, clippy::too_many_arguments)]
1537async fn subtree_challenge_response(
1538    challenge: &SubtreeAuditChallenge,
1539    storage: &ChunkStore,
1540    pointers: Option<&PointerStore>,
1541    self_peer_id: &PeerId,
1542    is_bootstrapping: bool,
1543    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1544    content_bytes: &mut i64,
1545    corrupt_keys: &mut Vec<XorName>,
1546) -> SubtreeAuditResponse {
1547    if is_bootstrapping {
1548        return SubtreeAuditResponse::Bootstrapping {
1549            challenge_id: challenge.challenge_id,
1550        };
1551    }
1552
1553    if challenge.challenged_peer_id != *self_peer_id.as_bytes() {
1554        warn!(
1555            "Subtree audit challenge targeted wrong peer: expected {}, got {}",
1556            hex::encode(self_peer_id.as_bytes()),
1557            hex::encode(challenge.challenged_peer_id),
1558        );
1559        return SubtreeAuditResponse::Rejected {
1560            challenge_id: challenge.challenge_id,
1561            kind: RejectKind::Protocol,
1562            reason: "challenged_peer_id does not match this node".to_string(),
1563        };
1564    }
1565
1566    let Some(state) = commitment_state else {
1567        return SubtreeAuditResponse::Rejected {
1568            challenge_id: challenge.challenge_id,
1569            kind: RejectKind::Protocol,
1570            reason: "no commitment state".to_string(),
1571        };
1572    };
1573
1574    // Look up the pinned commitment among the in-window retained set (TTL-bounded
1575    // answerability with a MAX_RETAINED_GOSSIPED_SLOTS backstop).
1576    // A miss is `UnknownCommitment`. With audit grace removed (ADR-0004 A1) the
1577    // auditor treats a responsive miss on an in-window pin as a CONFIRMED failure:
1578    // answerability is restart-durable and pins are challenged only while in
1579    // window, so failing to answer is a real repudiation, not benign rotation.
1580    let Some(built) = state.lookup_by_hash(&challenge.expected_commitment_hash) else {
1581        return SubtreeAuditResponse::Rejected {
1582            challenge_id: challenge.challenge_id,
1583            kind: RejectKind::UnknownCommitment,
1584            reason: "unknown commitment hash".to_string(),
1585        };
1586    };
1587
1588    // Geometry first (no bytes touched): which leaves to prove + the sibling
1589    // cut-hashes from the committed tree.
1590    let plan = match subtree_plan(built.tree(), &challenge.nonce) {
1591        Ok(p) => p,
1592        Err(e) => {
1593            warn!("Subtree audit: failed to plan proof: {e:?}");
1594            return SubtreeAuditResponse::Rejected {
1595                challenge_id: challenge.challenge_id,
1596                kind: RejectKind::Protocol,
1597                reason: "could not build subtree proof".to_string(),
1598            };
1599        }
1600    };
1601
1602    // Read chunk bytes one leaf at a time so peak memory is bounded regardless
1603    // of subtree size, hashing each into its plain + nonced leaf.
1604    let mut leaves = Vec::with_capacity(plan.leaf_keys.len());
1605    for (position, key) in plan.leaf_keys.iter().enumerate() {
1606        // A pointer leaf (ADR-0016) commits no bytes in the tree, since its
1607        // bytes change with every update. Round 1 binds them here instead: the
1608        // nonced root over the record held now, which round 2 must reproduce.
1609        // So a node answers from records it holds, not ones it could fetch once
1610        // it learns which few are sampled. A loss is admitted exactly as a
1611        // missing chunk is, and a read error is transient as for a chunk.
1612        if plan.leaf_is_pointer.get(position).copied().unwrap_or(false) {
1613            *content_bytes = content_bytes.saturating_add(SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES);
1614            let key_hex = hex::encode(key);
1615            let read = match pointers {
1616                Some(store) => store.record_bytes(key).await,
1617                None => Ok(None),
1618            };
1619            let record = match read {
1620                Ok(Some(record)) => record,
1621                Ok(None) => {
1622                    warn!("Subtree audit: committed pointer {key_hex} is not held");
1623                    return SubtreeAuditResponse::Rejected {
1624                        challenge_id: challenge.challenge_id,
1625                        kind: RejectKind::Protocol,
1626                        reason: format!("missing bytes for committed key: {key_hex}"),
1627                    };
1628                }
1629                Err(e) => {
1630                    warn!(
1631                        "Subtree audit: read error for committed pointer {key_hex}: {e} \
1632                         (rejecting as transient, not a confirmed failure)"
1633                    );
1634                    return SubtreeAuditResponse::Rejected {
1635                        challenge_id: challenge.challenge_id,
1636                        kind: RejectKind::Transient,
1637                        reason: format!("transient storage read error: {e}"),
1638                    };
1639                }
1640            };
1641            // Top up to the record read, as for a chunk.
1642            let content = i64::try_from(record.len()).unwrap_or(i64::MAX);
1643            *content_bytes = content_bytes.saturating_add(
1644                content
1645                    .saturating_sub(SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES)
1646                    .max(0),
1647            );
1648            leaves.push(SubtreeLeaf {
1649                key: *key,
1650                bytes_hash: pointer_leaf_hash(key),
1651                content_len: u32::try_from(POINTER_WIRE_LEN).unwrap_or(u32::MAX),
1652                nonced_root: nonced_block_root(
1653                    &challenge.nonce,
1654                    &challenge.challenged_peer_id,
1655                    key,
1656                    &record,
1657                ),
1658            });
1659            continue;
1660        }
1661        // Charge the fixed cost of ATTEMPTING a leaf before the read, because
1662        // it is owed whether or not the read succeeds: the lookup and its
1663        // retries, and the blocking-task round trip below. Charging only
1664        // content bytes left both a failing leaf and a tiny one nearly free,
1665        // and nothing bounds a chunk from below, so a commitment of a million
1666        // small records could run a full subtree of lookups per audit against
1667        // almost no budget. The top-up after a successful read makes the total
1668        // `max(bytes, floor)` rather than a surcharge on honest chunks.
1669        *content_bytes = content_bytes.saturating_add(SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES);
1670        let bytes = match get_raw_retrying(storage, key).await {
1671            Ok(Some(bytes)) => bytes,
1672            // Key is in our committed tree but definitively NOT stored — real
1673            // storage loss / the classic deleter. For a recently gossiped pin
1674            // the auditor counts this as a CONFIRMED failure.
1675            Ok(None) => {
1676                warn!(
1677                    "Subtree audit: missing bytes for committed key {}",
1678                    hex::encode(key)
1679                );
1680                return SubtreeAuditResponse::Rejected {
1681                    challenge_id: challenge.challenge_id,
1682                    kind: RejectKind::Protocol,
1683                    reason: format!("missing bytes for committed key: {}", hex::encode(key)),
1684                };
1685            }
1686            // Persistent transient read error after retries — NOT proof of missing
1687            // data. Reject `Transient`; the auditor routes it to the timeout lane
1688            // (no confirmed penalty) so a genuinely flaky disk is not branded a
1689            // deleter, while gaining no positive standing.
1690            Err(e) => {
1691                warn!(
1692                    "Subtree audit: storage read error for committed key {}: {e} \
1693                     (rejecting as transient, not a confirmed failure)",
1694                    hex::encode(key)
1695                );
1696                return SubtreeAuditResponse::Rejected {
1697                    challenge_id: challenge.challenge_id,
1698                    kind: RejectKind::Transient,
1699                    reason: format!("transient storage read error: {e}"),
1700                };
1701            }
1702        };
1703        // Top up to the content actually read, above the floor already charged.
1704        // Charged at the READ, not at the end: the disk read and the
1705        // keyed-BLAKE3 pass below are both already owed at this point, and
1706        // every remaining exit from this loop — a later missing key, a
1707        // persistent read error, a failed hashing task — discards the leaves
1708        // but not the work. Accruing here is what makes a commitment with one
1709        // bad key cost the attacker something per replay instead of nothing.
1710        let content = i64::try_from(bytes.len()).unwrap_or(i64::MAX);
1711        *content_bytes = content_bytes.saturating_add(
1712            content
1713                .saturating_sub(SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES)
1714                .max(0),
1715        );
1716        // Hash the leaf (a full keyed-BLAKE3 pass over the chunk) on a blocking
1717        // thread, not the async worker: a maximal subtree is ~sqrt(N) leaves of up
1718        // to MAX_CHUNK_SIZE each, so doing this inline would tie up a Tokio worker
1719        // for the whole proof and let a few round-1 requests starve the runtime.
1720        // One chunk is resident at a time, so peak memory is bounded.
1721        let nonce = challenge.nonce;
1722        let peer = challenge.challenged_peer_id;
1723        let leaf_key = *key;
1724        let leaf = match tokio::task::spawn_blocking(move || {
1725            crate::replication::subtree::subtree_leaf(&nonce, &peer, &leaf_key, &bytes)
1726        })
1727        .await
1728        {
1729            Ok(leaf) => leaf,
1730            Err(e) => {
1731                warn!(
1732                    "Subtree audit: leaf hashing task failed for key {}: {e}",
1733                    hex::encode(key)
1734                );
1735                return SubtreeAuditResponse::Rejected {
1736                    challenge_id: challenge.challenge_id,
1737                    kind: RejectKind::Transient,
1738                    reason: format!("leaf hashing task error: {e}"),
1739                };
1740            }
1741        };
1742        // The leaf's plain hash is the content address of what was just read, so a
1743        // committed chunk whose file no longer matches its name shows up here at no
1744        // extra cost. See `Round1Work::corrupt_keys` for what happens to it.
1745        if leaf.bytes_hash != *key {
1746            warn!(
1747                "Subtree audit: committed key {} does not hash to its address; \
1748                 reporting it for a recheck so it can be taken out of service \
1749                 and repaired",
1750                hex::encode(key)
1751            );
1752            corrupt_keys.push(*key);
1753        }
1754        leaves.push(leaf);
1755    }
1756
1757    SubtreeAuditResponse::Proof {
1758        challenge_id: challenge.challenge_id,
1759        commitment: built.commitment().clone(),
1760        proof: SubtreeProof {
1761            leaves,
1762            sibling_cut_hashes: plan.sibling_cut_hashes,
1763        },
1764    }
1765}
1766
1767/// Build every requested opening for one committed key from a single hashing
1768/// pass over its bytes: a Bao verified slice (authenticity against the chunk
1769/// address) plus a nonced block-tree opening (possession against round 1's
1770/// `nonced_root`) per block index.
1771///
1772/// The Bao outboard and nonced tree each hash the full chunk, so this builds
1773/// them once (via [`ChunkOpener`]) and serves all `indices` from them rather
1774/// than re-hashing per opening (V2-685 round-2 amplification fix). `indices` is
1775/// deduplicated by the caller. CPU-heavy, so callers run it on a blocking thread.
1776///
1777/// Returns `Err((kind, reason))` for the terminal cases that abort the whole
1778/// response: a block index out of range (only a forged/buggy auditor sends one →
1779/// `Protocol`), or a surprise in-memory Bao extraction error (`Transient`, so an
1780/// honest holder is not branded a deleter).
1781fn build_slice_items_for_key(
1782    nonce: [u8; 32],
1783    peer: [u8; 32],
1784    key: XorName,
1785    bytes: &[u8],
1786    indices: &[u32],
1787) -> Result<Vec<SubtreeSliceItem>, (RejectKind, String)> {
1788    let opener = crate::replication::slice::ChunkOpener::new(&nonce, &peer, &key, bytes);
1789    let count = opener.block_count();
1790    let mut items = Vec::with_capacity(indices.len());
1791    for &block_index in indices {
1792        if block_index >= count {
1793            return Err((
1794                RejectKind::Protocol,
1795                format!(
1796                    "block index {block_index} out of range for key {}",
1797                    hex::encode(key)
1798                ),
1799            ));
1800        }
1801        let bao_slice = match opener.bao_slice(block_index) {
1802            Ok(slice) => slice,
1803            Err(e) => {
1804                warn!(
1805                    "Subtree slice audit: bao extraction failed for key {}: {e}",
1806                    hex::encode(key)
1807                );
1808                return Err((RejectKind::Transient, format!("bao extraction error: {e}")));
1809            }
1810        };
1811        // `block_index < count` was just checked, so siblings must exist. A
1812        // `None` here is an internal proof-building inconsistency, not an honest
1813        // condition: abort the whole response as `Transient` (routes to the
1814        // timeout lane) rather than emit an empty-siblings `Present` that would
1815        // make an honest holder fail its own audit.
1816        let Some(nonced_siblings) = opener.nonced_siblings(block_index) else {
1817            warn!(
1818                "Subtree slice audit: no nonced siblings for in-range block {block_index} of key {}",
1819                hex::encode(key)
1820            );
1821            return Err((
1822                RejectKind::Transient,
1823                format!("nonced sibling build inconsistency for block {block_index}"),
1824            ));
1825        };
1826        items.push(SubtreeSliceItem::Present {
1827            key,
1828            block_index,
1829            bao_slice,
1830            nonced_siblings,
1831        });
1832    }
1833    Ok(items)
1834}
1835
1836/// Handle a round-2 slice challenge (responder side), ADR-0002 / V2-685.
1837///
1838/// The auditor has already structurally verified this node's round-1 subtree
1839/// proof and now opens up to two 1 KiB blocks (a fresh-random block plus the
1840/// final block) of a small freshly-random sample of those leaves. For each
1841/// opening the responder reads the committed chunk and builds a two-chain
1842/// opening (a Bao verified slice for authenticity against the chunk address, and
1843/// a nonced block-tree opening for possession against round 1's `nonced_root`),
1844/// returning [`SubtreeSliceItem::Present`]. If it committed to the key but can no
1845/// longer
1846/// produce the bytes it returns [`SubtreeSliceItem::Absent`], which the auditor
1847/// counts as a provable failure.
1848///
1849/// Openings are authorised against the subtree round 1 actually proved, not
1850/// merely against the pinned commitment. A challenge naming any key outside that
1851/// subtree is refused whole, before any chunk is read, so the work this round can
1852/// cost is bounded by the work the caller already paid for in round 1. An honest
1853/// auditor cannot trip this: it samples only the leaves round 1 returned, and
1854/// without that leaf's `nonced_root` and `content_len` it has nothing to verify
1855/// an answer against.
1856pub async fn handle_subtree_slice_challenge(
1857    challenge: &SubtreeSliceChallenge,
1858    storage: &ChunkStore,
1859    self_peer_id: &PeerId,
1860    is_bootstrapping: bool,
1861    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1862) -> SubtreeSliceResponse {
1863    serve_slice_challenge(
1864        challenge,
1865        storage,
1866        None,
1867        None,
1868        self_peer_id,
1869        is_bootstrapping,
1870        commitment_state,
1871    )
1872    .await
1873}
1874
1875/// [`handle_subtree_slice_challenge`] for a node that also commits pointers
1876/// (ADR-0016), without what round 1 bound for them.
1877///
1878/// Kept for callers of the earlier signature, and answering as it did: a
1879/// committed pointer is served as the record held now and the newest one an
1880/// update replaced, and one no longer held is absent. That fails an honest holder after two updates between
1881/// the rounds, which is what ADR-0019 fixes; the engine uses
1882/// [`handle_subtree_slice_challenge_with_pointer_bindings`].
1883pub async fn handle_subtree_slice_challenge_with_pointers(
1884    challenge: &SubtreeSliceChallenge,
1885    storage: &ChunkStore,
1886    pointers: Option<&PointerStore>,
1887    self_peer_id: &PeerId,
1888    is_bootstrapping: bool,
1889    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1890) -> SubtreeSliceResponse {
1891    serve_slice_challenge(
1892        challenge,
1893        storage,
1894        pointers,
1895        None,
1896        self_peer_id,
1897        is_bootstrapping,
1898        commitment_state,
1899    )
1900    .await
1901}
1902
1903/// [`handle_subtree_slice_challenge`] for a node that also commits pointers
1904/// (ADR-0016): a committed pointer is answered with its whole signed record,
1905/// the one `bound` says round 1 read (ADR-0019).
1906pub async fn handle_subtree_slice_challenge_with_pointer_bindings(
1907    challenge: &SubtreeSliceChallenge,
1908    storage: &ChunkStore,
1909    pointers: Option<&PointerStore>,
1910    bound: &PointerBindings,
1911    self_peer_id: &PeerId,
1912    is_bootstrapping: bool,
1913    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1914) -> SubtreeSliceResponse {
1915    serve_slice_challenge(
1916        challenge,
1917        storage,
1918        pointers,
1919        Some(bound),
1920        self_peer_id,
1921        is_bootstrapping,
1922        commitment_state,
1923    )
1924    .await
1925}
1926
1927/// The body of the slice-challenge handlers. `bound` is `None` for the
1928/// earlier entry point, which serves pointers as it did before ADR-0019.
1929#[allow(clippy::too_many_lines, clippy::too_many_arguments)]
1930async fn serve_slice_challenge(
1931    challenge: &SubtreeSliceChallenge,
1932    storage: &ChunkStore,
1933    pointers: Option<&PointerStore>,
1934    bound: Option<&PointerBindings>,
1935    self_peer_id: &PeerId,
1936    is_bootstrapping: bool,
1937    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1938) -> SubtreeSliceResponse {
1939    if is_bootstrapping {
1940        return SubtreeSliceResponse::Bootstrapping {
1941            challenge_id: challenge.challenge_id,
1942        };
1943    }
1944
1945    if challenge.challenged_peer_id != *self_peer_id.as_bytes() {
1946        return SubtreeSliceResponse::Rejected {
1947            challenge_id: challenge.challenge_id,
1948            kind: RejectKind::Protocol,
1949            reason: "challenged_peer_id does not match this node".to_string(),
1950        };
1951    }
1952
1953    // An honest auditor opens at most MAX_SLICE_OPENINGS blocks per challenge.
1954    // Reject larger requests up front: each opening forces a full chunk read to
1955    // build its proof, so an oversized request is a disk-read amplification lever
1956    // for a forged auditor.
1957    if challenge.openings.len() > MAX_SLICE_OPENINGS {
1958        let requested = challenge.openings.len();
1959        return SubtreeSliceResponse::Rejected {
1960            challenge_id: challenge.challenge_id,
1961            kind: RejectKind::Protocol,
1962            reason: format!(
1963                "slice challenge requests {requested} openings; max {MAX_SLICE_OPENINGS} per challenge"
1964            ),
1965        };
1966    }
1967
1968    let Some(state) = commitment_state else {
1969        return SubtreeSliceResponse::Rejected {
1970            challenge_id: challenge.challenge_id,
1971            kind: RejectKind::Protocol,
1972            reason: "no commitment state".to_string(),
1973        };
1974    };
1975    // Resolve the SAME commitment the auditor pinned in round 1. If we no longer
1976    // retain it (rotated past it), reject as `UnknownCommitment`. With audit
1977    // grace removed (ADR-0004 A1) the auditor treats a responsive miss on an
1978    // in-window pin as a confirmed failure — answerability is restart-durable and
1979    // pins are challenged only in-window. We open blocks only for keys committed
1980    // under this pin.
1981    let Some(built) = state.lookup_by_hash(&challenge.expected_commitment_hash) else {
1982        return SubtreeSliceResponse::Rejected {
1983            challenge_id: challenge.challenge_id,
1984            kind: RejectKind::UnknownCommitment,
1985            reason: "unknown commitment hash".to_string(),
1986        };
1987    };
1988
1989    // Coalesce openings by key, preserving first-seen order and deduplicating
1990    // block indices per key, so each committed chunk is read from the store and hashed
1991    // at most once even when the auditor opens several of its blocks (the normal
1992    // random + final pair, or a forged duplicate). Without this a ten-opening
1993    // request could re-read and re-hash the same chunk ten times.
1994    let mut key_order: Vec<XorName> = Vec::new();
1995    let mut indices_by_key: HashMap<XorName, Vec<u32>> = HashMap::new();
1996    for opening in &challenge.openings {
1997        let entry = indices_by_key.entry(opening.key).or_default();
1998        if entry.is_empty() {
1999            key_order.push(opening.key);
2000        }
2001        if !entry.contains(&opening.block_index) {
2002            entry.push(opening.block_index);
2003        }
2004    }
2005
2006    // Coalescing only saves work when keys REPEAT. A forged auditor could still
2007    // spread its MAX_SLICE_OPENINGS across that many DISTINCT keys to force a
2008    // full-chunk read each (up to ~40 MiB). An honest auditor samples at most
2009    // BYTE_SPOTCHECK_MAX leaves, so cap distinct keys to that.
2010    if key_order.len() > BYTE_SPOTCHECK_MAX as usize {
2011        let distinct = key_order.len();
2012        return SubtreeSliceResponse::Rejected {
2013            challenge_id: challenge.challenge_id,
2014            kind: RejectKind::Protocol,
2015            reason: format!(
2016                "slice challenge spans {distinct} distinct keys; max {BYTE_SPOTCHECK_MAX}"
2017            ),
2018        };
2019    }
2020
2021    // Round 2 may open ONLY the leaves round 1 actually proved, not the whole
2022    // pinned commitment. Membership of the pinned tree is the weaker property:
2023    // it would let a cheap round 1 over small records authorise openings against
2024    // large records elsewhere in the commitment, so the work this round costs
2025    // would not be bounded by the work the caller paid for in round 1.
2026    //
2027    // The authorised set is recomputed from `(tree, nonce)` rather than carried
2028    // in the round-1 session. The subtree is a pure function of those two, both
2029    // of which are already pinned — the nonce was matched against the session
2030    // before this handler ran — so recomputing costs one tree walk with no chunk
2031    // reads, while storing the key list would cost up to a full subtree of keys
2032    // per live session.
2033    let plan = match subtree_plan(built.tree(), &challenge.nonce) {
2034        Ok(plan) => plan,
2035        // The tree is ours and round 1 already walked it, so a failure here is
2036        // local inconsistency rather than anything the caller did. Transient
2037        // routes the auditor to the graced timeout lane instead of branding this
2038        // node with a confirmed failure it did not earn.
2039        Err(e) => {
2040            warn!("Subtree slice audit: cannot rebuild the round-1 subtree plan: {e:?}");
2041            return SubtreeSliceResponse::Rejected {
2042                challenge_id: challenge.challenge_id,
2043                kind: RejectKind::Transient,
2044                reason: "cannot rebuild the audited subtree".to_string(),
2045            };
2046        }
2047    };
2048    let authorised: HashSet<XorName> = plan.leaf_keys.iter().copied().collect();
2049
2050    // Refuse the whole challenge before touching storage, matching how an
2051    // over-broad challenge is handled above. An honest auditor cannot reach this:
2052    // it samples only the leaves round 1 returned, and it has no `nonced_root` or
2053    // `content_len` to verify an answer for anything else against, so an opening
2054    // outside the subtree could not tell it anything even if served.
2055    if let Some(outside) = key_order.iter().find(|key| !authorised.contains(*key)) {
2056        return SubtreeSliceResponse::Rejected {
2057            challenge_id: challenge.challenge_id,
2058            kind: RejectKind::Protocol,
2059            reason: format!(
2060                "slice challenge opens {} which is outside the audited subtree",
2061                hex::encode(outside)
2062            ),
2063        };
2064    }
2065
2066    let mut items = Vec::with_capacity(challenge.openings.len());
2067    for key in key_order {
2068        let indices = indices_by_key.remove(&key).unwrap_or_default();
2069        if built.tree().commits_pointer(&key) {
2070            // The record round 1 read, found by the root it reported over it
2071            // among what is held now and every record updates have replaced
2072            // since. The auditor verifies whatever is served, so nothing is
2073            // verified here.
2074            let Some(store) = pointers else {
2075                items.push(SubtreeSliceItem::Absent { key });
2076                continue;
2077            };
2078            let current = match store.record_bytes(&key).await {
2079                Ok(current) => current,
2080                Err(e) => {
2081                    return SubtreeSliceResponse::Rejected {
2082                        challenge_id: challenge.challenge_id,
2083                        kind: RejectKind::Transient,
2084                        reason: format!("pointer read error: {e}"),
2085                    }
2086                }
2087            };
2088            let Some(bound) = bound else {
2089                // As before ADR-0019, the record held and the newest one an
2090                // update replaced; but a node that no longer holds the pointer
2091                // is absent, whatever replaced records it still keeps.
2092                match current {
2093                    Some(current) => {
2094                        let mut records = vec![current];
2095                        records.extend(store.superseded(&key));
2096                        items.push(SubtreeSliceItem::PointerRecord { key, records });
2097                    }
2098                    None => items.push(SubtreeSliceItem::Absent { key }),
2099                }
2100                continue;
2101            };
2102            match pointer_records(
2103                challenge,
2104                &key,
2105                bound.get(&key),
2106                current,
2107                store.superseded_all(&key),
2108            ) {
2109                PointerServe::Record(record) => {
2110                    items.push(SubtreeSliceItem::PointerRecord {
2111                        key,
2112                        records: vec![record],
2113                    });
2114                }
2115                PointerServe::Absent => items.push(SubtreeSliceItem::Absent { key }),
2116                PointerServe::Unavailable => {
2117                    return SubtreeSliceResponse::Rejected {
2118                        challenge_id: challenge.challenge_id,
2119                        kind: RejectKind::Transient,
2120                        reason: format!(
2121                            "cannot serve the record round 1 read for pointer {}",
2122                            hex::encode(key)
2123                        ),
2124                    }
2125                }
2126            }
2127            continue;
2128        }
2129        match serve_committed_key_openings(challenge, storage, key, indices).await {
2130            KeyServe::Items(mut built_items) => items.append(&mut built_items),
2131            KeyServe::Absent => items.push(SubtreeSliceItem::Absent { key }),
2132            KeyServe::Reject(reject) => return reject,
2133        }
2134    }
2135
2136    SubtreeSliceResponse::Items {
2137        challenge_id: challenge.challenge_id,
2138        items,
2139    }
2140}
2141
2142/// What round 2 serves for a committed pointer.
2143enum PointerServe {
2144    /// The record round 1 read.
2145    Record(Vec<u8>),
2146    /// The pointer is no longer held, which is a lost pointer, whatever
2147    /// replaced records this node still keeps in memory.
2148    Absent,
2149    /// The pointer is held, but this node cannot serve the record round 1
2150    /// read: it has aged out or been evicted to keep memory bounded, or no
2151    /// root for it was kept, which a session this node opened never lacks. A
2152    /// local limit, not a lost pointer, so it is reported as one rather than
2153    /// proved wrong.
2154    Unavailable,
2155}
2156
2157/// Choose what round 2 serves for the pointer at `key` (ADR-0019), from the
2158/// record held now and the records updates replaced: the one that reproduces
2159/// the root round 1 reported.
2160///
2161/// Without that root nothing is served for a pointer still held. Neither the
2162/// record held now nor the replaced records kept can show that no update came
2163/// since round 1 read it, since the kept ones are capped, so serving one would
2164/// be a guess that fails the node when it is wrong.
2165fn pointer_records(
2166    challenge: &SubtreeSliceChallenge,
2167    key: &XorName,
2168    bound: Option<&[u8; 32]>,
2169    current: Option<Vec<u8>>,
2170    replaced: Vec<Bytes>,
2171) -> PointerServe {
2172    // A node that no longer holds the pointer has lost it. Records an update
2173    // replaced are kept only to prove what round 1 read; they do not make up
2174    // for the pointer itself being gone.
2175    let Some(current) = current else {
2176        return PointerServe::Absent;
2177    };
2178    let Some(root) = bound else {
2179        return PointerServe::Unavailable;
2180    };
2181    let reproduces = |record: &[u8]| {
2182        nonced_block_root(&challenge.nonce, &challenge.challenged_peer_id, key, record) == *root
2183    };
2184    if reproduces(&current) {
2185        return PointerServe::Record(current);
2186    }
2187    replaced
2188        .into_iter()
2189        .find(|record| reproduces(record))
2190        .map_or(PointerServe::Unavailable, |record| {
2191            PointerServe::Record(Vec::from(record))
2192        })
2193}
2194
2195/// Outcome of serving all requested openings for one committed key.
2196enum KeyServe {
2197    /// Openings built for this key; append to the response.
2198    Items(Vec<SubtreeSliceItem>),
2199    /// Committed but the bytes are gone → provable `Absent`.
2200    Absent,
2201    /// A terminal condition (out-of-range index, read/build error) that aborts
2202    /// the whole response.
2203    Reject(SubtreeSliceResponse),
2204}
2205
2206/// Read a committed key's chunk once and build every requested opening from it.
2207///
2208/// The Bao outboard + nonced tree hash the whole chunk, so the CPU-heavy build
2209/// runs on a blocking thread to keep an audit-responder flood off the Tokio pool.
2210/// `indices` is already deduplicated by the caller.
2211async fn serve_committed_key_openings(
2212    challenge: &SubtreeSliceChallenge,
2213    storage: &ChunkStore,
2214    key: XorName,
2215    indices: Vec<u32>,
2216) -> KeyServe {
2217    let reject = |kind, reason| {
2218        KeyServe::Reject(SubtreeSliceResponse::Rejected {
2219            challenge_id: challenge.challenge_id,
2220            kind,
2221            reason,
2222        })
2223    };
2224    match get_raw_retrying(storage, &key).await {
2225        Ok(Some(bytes)) => {
2226            let nonce = challenge.nonce;
2227            let peer = challenge.challenged_peer_id;
2228            match tokio::task::spawn_blocking(move || {
2229                build_slice_items_for_key(nonce, peer, key, &bytes, &indices)
2230            })
2231            .await
2232            {
2233                Ok(Ok(built_items)) => KeyServe::Items(built_items),
2234                Ok(Err((kind, reason))) => reject(kind, reason),
2235                Err(e) => {
2236                    warn!(
2237                        "Subtree slice audit: proof build task failed for key {}: {e}",
2238                        hex::encode(key)
2239                    );
2240                    reject(
2241                        RejectKind::Transient,
2242                        format!("proof build task error: {e}"),
2243                    )
2244                }
2245            }
2246        }
2247        // Committed key, definitively absent → provable failure (§7: a real "I
2248        // don't hold it" answer, distinct from a read error).
2249        Ok(None) => {
2250            warn!(
2251                "Subtree slice audit: committed key {} requested but bytes absent",
2252                hex::encode(key)
2253            );
2254            KeyServe::Absent
2255        }
2256        // Persistent transient read error after retries → do NOT brand the peer a
2257        // deleter. Reject `Transient`; the auditor routes it to the timeout lane
2258        // so a flaky read never manufactures a confirmed possession failure
2259        // on an honest holder (which also gains no credit).
2260        Err(e) => {
2261            warn!(
2262                "Subtree slice audit: storage read error for committed key {}: {e} \
2263                 (rejecting as transient, not a confirmed failure)",
2264                hex::encode(key)
2265            );
2266            reject(
2267                RejectKind::Transient,
2268                format!("transient storage read error: {e}"),
2269            )
2270        }
2271    }
2272}
2273
2274#[cfg(test)]
2275#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
2276mod tests {
2277    use super::*;
2278    use crate::replication::commitment_state::BuiltCommitment;
2279    use crate::replication::subtree::{build_subtree_proof, SubtreeLeaf};
2280    use saorsa_pqc::api::sig::ml_dsa_65;
2281    use std::time::Instant;
2282
2283    /// ADR-0004 A1 grade flip (grace removed): a responsive `UnknownCommitment`
2284    /// or `Protocol` rejection is a CONFIRMED failure; only `Transient` routes to
2285    /// the timeout lane. This pure decision backs both audit rounds
2286    /// (`Confirmed → AuditFailureReason::Rejected` / `SliceRound::Rejected`;
2287    /// `TimeoutLane → AuditFailureReason::Timeout` + pinned-credit revocation).
2288    #[test]
2289    fn grade_reject_removes_grace_for_unknown_commitment() {
2290        assert_eq!(
2291            grade_reject(RejectKind::UnknownCommitment),
2292            RejectGrade::Confirmed,
2293            "an unanswerable pinned root is now a confirmed failure, not graced"
2294        );
2295        assert_eq!(grade_reject(RejectKind::Protocol), RejectGrade::Confirmed);
2296        assert_eq!(
2297            grade_reject(RejectKind::Transient),
2298            RejectGrade::TimeoutLane,
2299            "a transient read error routes to the timeout lane (no confirmed penalty)"
2300        );
2301    }
2302
2303    /// A peer id for classification tests (never dialled).
2304    fn classify_peer() -> PeerId {
2305        PeerId::from_bytes([0x5Au8; 32])
2306    }
2307
2308    // A node that answers round 1 with a valid signed proof and then claims
2309    // `Bootstrapping` in round 2 is contradicting itself: a bootstrapping node
2310    // has no committed data to prove. Grading that as a graced timeout would be
2311    // the cheapest possible way to dodge every possession check while KEEPING
2312    // the holder credit earned in round 1 — so it must be a confirmed failure.
2313    #[test]
2314    fn responsive_bootstrap_is_a_confirmed_failure_not_a_graced_timeout() {
2315        let id = 4242u64;
2316        let round = classify_slice_response(
2317            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Bootstrapping {
2318                challenge_id: id,
2319            }),
2320            id,
2321            &classify_peer(),
2322        );
2323        assert!(
2324            matches!(round, SliceRound::ResponsiveBootstrap),
2325            "mid-audit Bootstrapping must classify as ResponsiveBootstrap"
2326        );
2327
2328        // The production arm maps `ResponsiveBootstrap` alongside `Rejected` to
2329        // `AuditFailureReason::Rejected`, and THAT reason is what revokes the
2330        // peer's holder credit wholesale. Pin the policy both ways, since the
2331        // whole point of the classification is landing on the revoking side.
2332        assert!(
2333            super::super::audit_failure_revokes_holder_credit(&AuditFailureReason::Rejected),
2334            "a confirmed round-2 failure must revoke holder credit"
2335        );
2336        assert!(
2337            !super::super::audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
2338            "the timeout lane must not revoke credit WHOLESALE — the contrast that \
2339             makes classifying ResponsiveBootstrap as confirmed load-bearing. The \
2340             timeout lane still drops the pinned commitment's own credit; see \
2341             round2_revokes_pinned_credit"
2342        );
2343    }
2344
2345    /// A responder that answered round 1 and then goes quiet must not keep the
2346    /// holder credit for the commitment under audit.
2347    ///
2348    /// Round 2 names the blocks after the roots are committed, so a responder
2349    /// chooses whether to reply already knowing the draw. If silence kept
2350    /// credit, answering only favourable draws would be free and standing earned
2351    /// once would survive every dodged check afterwards. Both no-proof outcomes
2352    /// therefore drop the pinned credit, while the confirmed lanes are excluded
2353    /// here because they revoke the peer's credit wholesale downstream.
2354    #[test]
2355    fn round2_without_a_proof_drops_the_pinned_commitment_credit() {
2356        assert!(
2357            round2_revokes_pinned_credit(&SliceRound::Timeout),
2358            "silence after a valid round-1 proof must cost the pinned credit"
2359        );
2360        assert!(
2361            round2_revokes_pinned_credit(&SliceRound::TransientReject),
2362            "a transient reject also ends round 2 with no possession proof"
2363        );
2364        assert!(
2365            !round2_revokes_pinned_credit(&SliceRound::Served(vec![])),
2366            "a served response is judged on its contents, not here"
2367        );
2368        for confirmed in [
2369            SliceRound::Rejected,
2370            SliceRound::ResponsiveBootstrap,
2371            SliceRound::Malformed,
2372        ] {
2373            assert!(
2374                !round2_revokes_pinned_credit(&confirmed),
2375                "confirmed failures revoke wholesale downstream, not scoped here"
2376            );
2377        }
2378    }
2379
2380    /// The scoped revocation must not erase credit the peer re-earned under a
2381    /// different commitment: an unanswered round 2 costs the pin it was about,
2382    /// not the peer's whole standing.
2383    #[test]
2384    fn pinned_credit_revocation_is_scoped_to_the_audited_commitment() {
2385        let peer = classify_peer();
2386        let (audited, newer) = ([0x11u8; 32], [0x22u8; 32]);
2387        let key: XorName = [0xC3u8; 32];
2388        let now = Instant::now();
2389        let mut provers = RecentProvers::new();
2390        provers.record_proof(key, peer, audited, now);
2391        provers.record_proof(key, peer, newer, now);
2392
2393        // What `verify_subtree_response` does when round 2 yields no proof.
2394        provers.forget_commitment(&audited);
2395
2396        assert!(
2397            !provers.is_credited_holder(&key, &peer, &audited),
2398            "credit for the audited pin must be gone after an unanswered round 2"
2399        );
2400        assert!(
2401            provers.is_credited_holder(&key, &peer, &newer),
2402            "credit re-earned under a newer commitment must survive"
2403        );
2404    }
2405
2406    // Every classification arm is guarded on `challenge_id`. A responder must not
2407    // be able to answer the challenge it was actually sent with a body minted for
2408    // a different one — in particular it must not downgrade a live challenge by
2409    // replaying a `Bootstrapping` or `Transient` body from another exchange.
2410    #[test]
2411    fn slice_response_for_another_challenge_is_malformed() {
2412        let (sent, other) = (7u64, 8u64);
2413        let peer = classify_peer();
2414        let bodies = [
2415            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Bootstrapping {
2416                challenge_id: other,
2417            }),
2418            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Items {
2419                challenge_id: other,
2420                items: vec![],
2421            }),
2422            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Rejected {
2423                challenge_id: other,
2424                kind: RejectKind::Transient,
2425                reason: String::new(),
2426            }),
2427        ];
2428        for body in bodies {
2429            assert!(
2430                matches!(
2431                    classify_slice_response(body, sent, &peer),
2432                    SliceRound::Malformed
2433                ),
2434                "a body carrying another challenge_id must be malformed"
2435            );
2436        }
2437
2438        // A non-round-2 body on the round-2 path is malformed too.
2439        assert!(matches!(
2440            classify_slice_response(
2441                ReplicationMessageBody::SubtreeAuditResponse(
2442                    crate::replication::protocol::SubtreeAuditResponse::Bootstrapping {
2443                        challenge_id: sent,
2444                    }
2445                ),
2446                sent,
2447                &peer,
2448            ),
2449            SliceRound::Malformed
2450        ));
2451    }
2452
2453    // The two-round audit splits into SHIPPED pure functions exercised directly
2454    // here (no reimplementation that could drift):
2455    //   - round 1: `evaluate_subtree_structure` (pin/identity/signature +
2456    //     structural root rebuild),
2457    //   - sampling: `random_spotcheck_leaves` (3..=5 FRESHLY-RANDOM leaves chosen
2458    //     after the proof is in hand — see its doc for the soundness argument), and
2459    //   - round 2: `verify_slice_response` (decode the Bao slice against the chunk
2460    //     address + fold the nonced opening to the round-1 `nonced_root`, both from
2461    //     what the RESPONDER served — the auditor holds nothing).
2462
2463    fn key(i: u32) -> XorName {
2464        let mut k = [0u8; 32];
2465        k[..4].copy_from_slice(&i.to_be_bytes());
2466        k
2467    }
2468
2469    // The auditor's per-opening matcher returns the FIRST item with a matching
2470    // identity, so an oversized, unsolicited, or colliding response must be
2471    // rejected as malformed BEFORE matching — otherwise item order (or padding)
2472    // could decide the verdict or force quadratic validation work.
2473    #[test]
2474    fn verify_slice_response_rejects_malformed_item_sets() {
2475        let leaf = |k: XorName| SubtreeLeaf {
2476            key: k,
2477            bytes_hash: [0u8; 32],
2478            content_len: 0,
2479            nonced_root: [0u8; 32],
2480        };
2481        let present = |k: XorName, i: u32| SubtreeSliceItem::Present {
2482            key: k,
2483            block_index: i,
2484            bao_slice: vec![],
2485            nonced_siblings: vec![],
2486        };
2487        let malformed = |verdict| {
2488            matches!(
2489                verdict,
2490                AuditVerdict::Fail(AuditFailureReason::MalformedResponse)
2491            )
2492        };
2493        let nonce = [0u8; 32];
2494        let peer = [0u8; 32];
2495        // The auditor requested (key1, block 0), (key1, block 1), (key2, block 0).
2496        let openings = vec![(leaf(key(1)), 0u32), (leaf(key(1)), 1), (leaf(key(2)), 0)];
2497
2498        // More items than requested openings.
2499        let oversized = vec![
2500            present(key(1), 0),
2501            present(key(1), 1),
2502            present(key(2), 0),
2503            present(key(2), 0),
2504        ];
2505        assert!(malformed(verify_slice_response(
2506            &openings, &nonce, &peer, &oversized
2507        )));
2508
2509        // An item that was not requested.
2510        let unsolicited = vec![present(key(9), 0)];
2511        assert!(malformed(verify_slice_response(
2512            &openings,
2513            &nonce,
2514            &peer,
2515            &unsolicited
2516        )));
2517
2518        // Duplicate (key, block_index).
2519        let dup = vec![present(key(1), 0), present(key(1), 0)];
2520        assert!(malformed(verify_slice_response(
2521            &openings, &nonce, &peer, &dup
2522        )));
2523
2524        // A key that is both Present and Absent.
2525        let conflict = vec![present(key(1), 0), SubtreeSliceItem::Absent { key: key(1) }];
2526        assert!(malformed(verify_slice_response(
2527            &openings, &nonce, &peer, &conflict
2528        )));
2529
2530        // A well-formed, unique, solicited response passes the identity guard (the
2531        // empty proofs then fail verification as DigestMismatch, NOT malformed).
2532        let ok = vec![present(key(1), 0), present(key(1), 1), present(key(2), 0)];
2533        assert!(!malformed(verify_slice_response(
2534            &openings, &nonce, &peer, &ok
2535        )));
2536    }
2537    /// Deterministic chunk content for fixture index `i`. Fixture keys are
2538    /// CONTENT-ADDRESSED (`ckey(i) == BLAKE3(chunk_bytes(i))`), so a committed
2539    /// leaf is `(key, key)` exactly as production, and round 2 serves this content.
2540    fn chunk_bytes(i: u32) -> Vec<u8> {
2541        let mut v = b"chunk-body".to_vec();
2542        v.extend_from_slice(&i.to_le_bytes());
2543        v
2544    }
2545
2546    /// Content-addressed key for fixture index `i` (so `bytes_hash == key`).
2547    fn ckey(i: u32) -> XorName {
2548        *blake3::hash(&chunk_bytes(i)).as_bytes()
2549    }
2550
2551    /// The content behind a committed fixture key (reverse of `ckey`), so round-2
2552    /// fixtures can serve the real bytes for any sampled leaf.
2553    fn content_for_key(k: &XorName) -> Vec<u8> {
2554        (0..16_384u32)
2555            .find(|&i| &ckey(i) == k)
2556            .map(chunk_bytes)
2557            .expect("fixture content for committed key")
2558    }
2559
2560    /// Build an honest committed tree of `n` keys + a valid round-1 proof for
2561    /// `nonce`. Returns `(built, proof, peer_id)`. The auditor pins `built.hash()`.
2562    fn honest(n: u32, nonce: &[u8; 32]) -> (BuiltCommitment, SubtreeProof, [u8; 32]) {
2563        let (pk, sk) = ml_dsa_65().generate_keypair().unwrap();
2564        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
2565        let pk_b = pk.to_bytes();
2566        // Content-addressed: bytes_hash == key, exactly as production commits.
2567        let entries: Vec<_> = (0..n).map(|i| (ckey(i), ckey(i))).collect();
2568        let built = BuiltCommitment::build(entries, &peer_id, &sk, &pk_b).unwrap();
2569        let proof =
2570            build_subtree_proof(built.tree(), nonce, &peer_id, |k| Some(content_for_key(k)))
2571                .unwrap();
2572        (built, proof, peer_id)
2573    }
2574
2575    /// Round-1 verdict against the pinned commitment.
2576    fn structure(
2577        built: &BuiltCommitment,
2578        proof: &SubtreeProof,
2579        nonce: &[u8; 32],
2580        peer: &[u8; 32],
2581    ) -> Result<(), AuditFailureReason> {
2582        evaluate_subtree_structure(built.commitment(), proof, nonce, &built.hash(), peer)
2583    }
2584
2585    /// The 3..=5 spot-check leaves the auditor would open in round 2. Now
2586    /// freshly-random (post-proof) rather than nonce-derived; the `_nonce`/
2587    /// `_key_count` params are kept so existing call sites read unchanged.
2588    fn sample<'a>(
2589        proof: &'a SubtreeProof,
2590        _nonce: &[u8; 32],
2591        _key_count: u32,
2592    ) -> Vec<&'a SubtreeLeaf> {
2593        random_spotcheck_leaves(proof, 8u32.clamp(BYTE_SPOTCHECK_MIN, BYTE_SPOTCHECK_MAX))
2594    }
2595
2596    /// Pair each sampled leaf with a block index for round 2. The fixtures use
2597    /// short (single-block) chunks, so block 0 is the only block; the production
2598    /// auditor draws a fresh random index via `random_block_index`.
2599    fn openings_for(sample: &[&SubtreeLeaf]) -> Vec<(SubtreeLeaf, u32)> {
2600        sample.iter().map(|l| ((*l).clone(), 0u32)).collect()
2601    }
2602
2603    /// Honest responder: for each opening build a real Bao slice + nonced opening
2604    /// from the true chunk content, exactly as `handle_subtree_slice_challenge`
2605    /// would.
2606    fn served_honest_items(
2607        openings: &[(SubtreeLeaf, u32)],
2608        nonce: &[u8; 32],
2609        peer: &[u8; 32],
2610    ) -> Vec<SubtreeSliceItem> {
2611        openings
2612            .iter()
2613            .map(|(leaf, block_index)| {
2614                let content = content_for_key(&leaf.key);
2615                let bao_slice =
2616                    crate::replication::slice::extract_block_slice(&content, *block_index).unwrap();
2617                let nonced_siblings = crate::replication::slice::nonced_block_siblings(
2618                    nonce,
2619                    peer,
2620                    &leaf.key,
2621                    &content,
2622                    *block_index,
2623                )
2624                .unwrap();
2625                SubtreeSliceItem::Present {
2626                    key: leaf.key,
2627                    block_index: *block_index,
2628                    bao_slice,
2629                    nonced_siblings,
2630                }
2631            })
2632            .collect()
2633    }
2634
2635    // ---- round 1: structure --------------------------------------------------
2636
2637    #[test]
2638    fn honest_structure_then_bytes_passes() {
2639        let nonce = [9u8; 32];
2640        let (built, proof, peer) = honest(400, &nonce);
2641        // Round 1.
2642        assert!(structure(&built, &proof, &nonce, &peer).is_ok());
2643        // Round 2: honest responder opens real slices for the sample.
2644        let s = sample(&proof, &nonce, built.commitment().key_count);
2645        assert!(!s.is_empty(), "expected a non-empty sample");
2646        let openings = openings_for(&s);
2647        let items = served_honest_items(&openings, &nonce, &peer);
2648        match verify_slice_response(&openings, &nonce, &peer, &items) {
2649            AuditVerdict::Pass { checked } => assert!(checked >= 1, "must verify >=1 leaf"),
2650            other @ AuditVerdict::Fail(_) => panic!("expected Pass, got {other:?}"),
2651        }
2652    }
2653
2654    /// Possession-forgery guard: a peer that signs a commitment whose leaves
2655    /// decouple the credited `key` from the authenticated content hash
2656    /// (`bytes_hash != key`) is rejected at round 1 — even though the structural
2657    /// root still rebuilds from `(key, bytes_hash)`. Without the guard such a peer
2658    /// could earn holder credit for an expensive address `key` while only proving
2659    /// possession of an unrelated (e.g. one-byte) chunk hashing to `bytes_hash`.
2660    #[test]
2661    fn leaf_with_bytes_hash_decoupled_from_key_is_rejected() {
2662        let nonce = [5u8; 32];
2663        let (pk, sk) = ml_dsa_65().generate_keypair().unwrap();
2664        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
2665        let pk_b = pk.to_bytes();
2666        // Every leaf commits (key, bytes_hash) with bytes_hash != key.
2667        let entries: Vec<_> = (0..64u32).map(|i| (ckey(i), ckey(i + 10_000))).collect();
2668        let built = BuiltCommitment::build(entries, &peer_id, &sk, &pk_b).unwrap();
2669        let proof =
2670            build_subtree_proof(built.tree(), &nonce, &peer_id, |k| Some(content_for_key(k)))
2671                .unwrap();
2672        // The structural root rebuilds (it is a genuinely signed tree), so the
2673        // decoupled-address gate is what must reject it.
2674        assert_eq!(
2675            structure(&built, &proof, &nonce, &peer_id),
2676            Err(AuditFailureReason::DigestMismatch),
2677            "a leaf whose bytes_hash != key must be rejected at round 1"
2678        );
2679    }
2680
2681    #[test]
2682    fn commitment_bound_to_another_peer_rejected() {
2683        let nonce = [3u8; 32];
2684        let (built, proof, _peer) = honest(200, &nonce);
2685        let other = [0xAAu8; 32];
2686        assert_eq!(
2687            structure(&built, &proof, &nonce, &other),
2688            Err(AuditFailureReason::Rejected)
2689        );
2690    }
2691
2692    #[test]
2693    fn wrong_pinned_commitment_rejected() {
2694        let nonce = [3u8; 32];
2695        let (built, proof, peer) = honest(200, &nonce);
2696        let mut wrong_pin = built.hash();
2697        wrong_pin[0] ^= 0x01;
2698        assert_eq!(
2699            evaluate_subtree_structure(built.commitment(), &proof, &nonce, &wrong_pin, &peer),
2700            Err(AuditFailureReason::Rejected)
2701        );
2702    }
2703
2704    #[test]
2705    fn tampered_leaf_structure_rejected() {
2706        let nonce = [3u8; 32];
2707        let (built, mut proof, peer) = honest(200, &nonce);
2708        if let Some(first) = proof.leaves.first_mut() {
2709            first.bytes_hash[0] ^= 0x01; // breaks root reconstruction
2710        }
2711        assert_eq!(
2712            structure(&built, &proof, &nonce, &peer),
2713            Err(AuditFailureReason::DigestMismatch)
2714        );
2715    }
2716
2717    #[test]
2718    fn wrong_leaf_count_structure_rejected() {
2719        let nonce = [3u8; 32];
2720        let (built, mut proof, peer) = honest(200, &nonce);
2721        proof.leaves.pop();
2722        assert_eq!(
2723            structure(&built, &proof, &nonce, &peer),
2724            Err(AuditFailureReason::DigestMismatch)
2725        );
2726    }
2727
2728    // ---- round 2: responder-served bytes ------------------------------------
2729
2730    #[test]
2731    fn deleter_absent_bytes_is_confirmed_failure() {
2732        // THE headline fix: a node whose round-1 proof is structurally perfect
2733        // but which has DELETED a committed chunk cannot serve its bytes. It
2734        // signals `Absent` for the sampled key → provable lie → confirmed
2735        // failure, reported as `KeyAbsent` because the peer admitted the loss.
2736        // Crucially, the auditor holds NONE of the peer's chunks; the
2737        // verdict depends only on what the responder serves.
2738        let nonce = [9u8; 32];
2739        let (built, proof, peer) = honest(400, &nonce);
2740        assert!(structure(&built, &proof, &nonce, &peer).is_ok());
2741        let s = sample(&proof, &nonce, built.commitment().key_count);
2742        let openings = openings_for(&s);
2743        // Responder returns Absent for the FIRST opening, honest for the rest.
2744        let victim = openings.first().map(|(l, _)| l.key).unwrap();
2745        let mut items = served_honest_items(&openings, &nonce, &peer);
2746        if let Some(slot) = items.first_mut() {
2747            *slot = SubtreeSliceItem::Absent { key: victim };
2748        }
2749        let v = verify_slice_response(&openings, &nonce, &peer, &items);
2750        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::KeyAbsent));
2751    }
2752
2753    #[test]
2754    fn omitted_committed_key_is_confirmed_failure() {
2755        // A responder that simply omits a sampled committed opening from its items
2756        // (neither Present nor Absent) is a confirmed failure just like Absent,
2757        // but it never admitted the loss, so it is a proof failure rather than
2758        // `KeyAbsent`. This is the counterpart to
2759        // `deleter_absent_bytes_is_confirmed_failure`: together they pin that the
2760        // two reasons stay distinguishable in the audit-failure log line.
2761        let nonce = [9u8; 32];
2762        let (built, proof, peer) = honest(400, &nonce);
2763        let s = sample(&proof, &nonce, built.commitment().key_count);
2764        let openings = openings_for(&s);
2765        let mut items = served_honest_items(&openings, &nonce, &peer);
2766        items.remove(0); // omit the first opening entirely
2767        let v = verify_slice_response(&openings, &nonce, &peer, &items);
2768        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
2769    }
2770
2771    #[test]
2772    fn fake_storage_garbage_bytes_is_confirmed_failure() {
2773        // A "fake-storage" responder claims possession but opens a slice built
2774        // from garbage content. The garbage slice does not decode against the
2775        // committed content address (`bytes_hash`), so chain 1 fails → confirmed
2776        // failure. No auditor holdings involved.
2777        let nonce = [9u8; 32];
2778        let (built, proof, peer) = honest(400, &nonce);
2779        let s = sample(&proof, &nonce, built.commitment().key_count);
2780        let openings = openings_for(&s);
2781        let items: Vec<SubtreeSliceItem> = openings
2782            .iter()
2783            .map(|(leaf, bi)| {
2784                let mut garbage = blake3::hash(&leaf.key).as_bytes().to_vec();
2785                garbage.extend_from_slice(b"adversary-fake-storage");
2786                let bao_slice =
2787                    crate::replication::slice::extract_block_slice(&garbage, *bi).unwrap();
2788                let nonced_siblings = crate::replication::slice::nonced_block_siblings(
2789                    &nonce, &peer, &leaf.key, &garbage, *bi,
2790                )
2791                .unwrap();
2792                SubtreeSliceItem::Present {
2793                    key: leaf.key,
2794                    block_index: *bi,
2795                    bao_slice,
2796                    nonced_siblings,
2797                }
2798            })
2799            .collect();
2800        let v = verify_slice_response(&openings, &nonce, &peer, &items);
2801        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
2802    }
2803
2804    #[test]
2805    fn correct_content_address_but_stale_nonced_root_fails() {
2806        // A responder can serve the real block (chain 1, the Bao slice against the
2807        // address, passes), but if its committed `nonced_root` does not correspond
2808        // to the audit's nonce over that content, the nonced opening (chain 2)
2809        // cannot fold to it. We model a leaf whose committed `nonced_root` was
2810        // built under a DIFFERENT nonce; the honest opening under the audit nonce
2811        // then fails to match it.
2812        let nonce = [9u8; 32];
2813        let (built, mut proof, peer) = honest(400, &nonce);
2814        let other_nonce = [0xEEu8; 32];
2815        for leaf in &mut proof.leaves {
2816            leaf.nonced_root = crate::replication::slice::nonced_block_root(
2817                &other_nonce,
2818                &peer,
2819                &leaf.key,
2820                &content_for_key(&leaf.key),
2821            );
2822        }
2823        let s = sample(&proof, &nonce, built.commitment().key_count);
2824        let openings = openings_for(&s);
2825        let items = served_honest_items(&openings, &nonce, &peer);
2826        let v = verify_slice_response(&openings, &nonce, &peer, &items);
2827        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
2828    }
2829
2830    #[test]
2831    fn auditor_holds_nothing_still_catches_deleter() {
2832        // Explicit contract: the auditor's own storage is irrelevant. A deleter
2833        // is caught purely from its served (absent) response. (Compare the OLD
2834        // design, where an auditor holding none of the chunks went Inconclusive
2835        // and the deleter walked free.)
2836        let nonce = [0x21u8; 32];
2837        let (built, proof, peer) = honest(256, &nonce);
2838        assert!(structure(&built, &proof, &nonce, &peer).is_ok());
2839        let s = sample(&proof, &nonce, built.commitment().key_count);
2840        let openings = openings_for(&s);
2841        // Responder is a total deleter: Absent for every opening.
2842        let items: Vec<SubtreeSliceItem> = openings
2843            .iter()
2844            .map(|(l, _)| SubtreeSliceItem::Absent { key: l.key })
2845            .collect();
2846        let v = verify_slice_response(&openings, &nonce, &peer, &items);
2847        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::KeyAbsent));
2848    }
2849
2850    #[test]
2851    fn admitted_absence_and_failed_proof_are_reported_separately() {
2852        // ROLLOUT DIAGNOSTICS: the two ways a peer fails round 2 must stay
2853        // distinguishable in the failure summary, because they mean different
2854        // things operationally — a peer owning up to lost data versus one whose
2855        // proof did not verify. Before this was split, both rolled up as
2856        // `digest_mismatch_keys` and `absent_keys` was always 0, so a fleet-wide
2857        // audit regression and a fleet-wide data loss looked identical.
2858        let nonce = [0x33u8; 32];
2859        let (built, proof, peer) = honest(256, &nonce);
2860        let s = sample(&proof, &nonce, built.commitment().key_count);
2861        let openings = openings_for(&s);
2862
2863        // Admitted loss → KeyAbsent → counted under `absent_keys`.
2864        let absent_items: Vec<SubtreeSliceItem> = openings
2865            .iter()
2866            .map(|(l, _)| SubtreeSliceItem::Absent { key: l.key })
2867            .collect();
2868        assert_eq!(
2869            verify_slice_response(&openings, &nonce, &peer, &absent_items),
2870            AuditVerdict::Fail(AuditFailureReason::KeyAbsent),
2871        );
2872        let absent_summary = subtree_failure_summary(&AuditFailureReason::KeyAbsent);
2873        assert_eq!(absent_summary.absent_keys, 1);
2874        assert_eq!(absent_summary.digest_mismatch_keys, 0);
2875
2876        // Withheld without admission → DigestMismatch → `digest_mismatch_keys`.
2877        let withheld: Vec<SubtreeSliceItem> = served_honest_items(&openings, &nonce, &peer)
2878            .into_iter()
2879            .skip(1)
2880            .collect();
2881        assert_eq!(
2882            verify_slice_response(&openings, &nonce, &peer, &withheld),
2883            AuditVerdict::Fail(AuditFailureReason::DigestMismatch),
2884        );
2885        let mismatch_summary = subtree_failure_summary(&AuditFailureReason::DigestMismatch);
2886        assert_eq!(mismatch_summary.digest_mismatch_keys, 1);
2887        assert_eq!(mismatch_summary.absent_keys, 0);
2888
2889        // Both are confirmed failures with identical enforcement, so the split is
2890        // diagnostic only: it must not quietly soften what an absent key costs.
2891        assert_eq!(absent_summary.failed_keys, mismatch_summary.failed_keys);
2892    }
2893
2894    #[test]
2895    fn sample_size_is_in_3_to_5_band() {
2896        // ADR-0002: round-2 samples a SMALL surprise set (3..=5) of the proven
2897        // leaves. For a large subtree the sample is capped at 5.
2898        let nonce = [7u8; 32];
2899        let (built, proof, _peer) = honest(1024, &nonce);
2900        let s = sample(&proof, &nonce, built.commitment().key_count);
2901        assert!(
2902            (BYTE_SPOTCHECK_MIN as usize..=BYTE_SPOTCHECK_MAX as usize).contains(&s.len()),
2903            "sample {} must be within 3..=5",
2904            s.len()
2905        );
2906    }
2907
2908    #[test]
2909    fn full_pass_requires_every_sampled_leaf() {
2910        // checked must equal the number of sampled leaves on a pass (no leaf is
2911        // silently skipped — every sampled, committed key must verify).
2912        let nonce = [11u8; 32];
2913        let (built, proof, peer) = honest(400, &nonce);
2914        let s = sample(&proof, &nonce, built.commitment().key_count);
2915        let openings = openings_for(&s);
2916        let items = served_honest_items(&openings, &nonce, &peer);
2917        match verify_slice_response(&openings, &nonce, &peer, &items) {
2918            AuditVerdict::Pass { checked } => assert_eq!(checked, openings.len()),
2919            other @ AuditVerdict::Fail(_) => panic!("expected Pass, got {other:?}"),
2920        }
2921    }
2922
2923    // ---- end-to-end gate composition ----------------------------------------
2924
2925    #[test]
2926    fn structure_fail_short_circuits_before_round_2() {
2927        // A structurally invalid proof is rejected in round 1; the slice challenge
2928        // is never issued. We assert the round-1 gate returns Err so the auditor
2929        // (verify_subtree_response) never reaches request_slice_proof.
2930        let nonce = [5u8; 32];
2931        let (built, mut proof, peer) = honest(300, &nonce);
2932        if let Some(first) = proof.leaves.first_mut() {
2933            first.bytes_hash[0] ^= 0x01;
2934        }
2935        assert!(structure(&built, &proof, &nonce, &peer).is_err());
2936    }
2937
2938    /// Build an honest committed tree whose keys are content-addressed but biased
2939    /// to the FAR half of the XOR space (top bit set), so `observe_closeness`
2940    /// counts them toward `far`. Keys stay content-addressed (`bytes_hash == key`)
2941    /// so round 2 serves real bytes.
2942    fn honest_far(n: u32, nonce: &[u8; 32]) -> (BuiltCommitment, SubtreeProof, [u8; 32]) {
2943        let (pk, sk) = ml_dsa_65().generate_keypair().unwrap();
2944        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
2945        let pk_b = pk.to_bytes();
2946        let mut entries: Vec<(XorName, [u8; 32])> = Vec::new();
2947        let mut i = 0u32;
2948        while entries.len() < n as usize {
2949            let k = ckey(i);
2950            if k[0] >= 0x80 {
2951                entries.push((k, k));
2952            }
2953            i = i.saturating_add(1);
2954        }
2955        let built = BuiltCommitment::build(entries, &peer_id, &sk, &pk_b).unwrap();
2956        let proof =
2957            build_subtree_proof(built.tree(), nonce, &peer_id, |k| Some(content_for_key(k)))
2958                .unwrap();
2959        (built, proof, peer_id)
2960    }
2961
2962    /// ADR-0002 "Closeness" is OBSERVE-ONLY: far-keyed honest proofs verify
2963    /// exactly like near-keyed ones. The verdict (structure + served bytes) is
2964    /// closeness-blind, so a "far/padding" shape can never produce a Fail.
2965    #[test]
2966    fn closeness_is_observe_only_far_keys_still_pass() {
2967        let nonce = [9u8; 32];
2968
2969        let (built_far, proof_far, peer_far) = honest_far(400, &nonce);
2970        assert!(structure(&built_far, &proof_far, &nonce, &peer_far).is_ok());
2971        let sf = sample(&proof_far, &nonce, built_far.commitment().key_count);
2972        let of = openings_for(&sf);
2973        let v_far = verify_slice_response(
2974            &of,
2975            &nonce,
2976            &peer_far,
2977            &served_honest_items(&of, &nonce, &peer_far),
2978        );
2979
2980        let (built_near, proof_near, peer_near) = honest(400, &nonce);
2981        assert!(structure(&built_near, &proof_near, &nonce, &peer_near).is_ok());
2982        let sn = sample(&proof_near, &nonce, built_near.commitment().key_count);
2983        let on = openings_for(&sn);
2984        let v_near = verify_slice_response(
2985            &on,
2986            &nonce,
2987            &peer_near,
2988            &served_honest_items(&on, &nonce, &peer_near),
2989        );
2990
2991        match (&v_far, &v_near) {
2992            (AuditVerdict::Pass { checked: cf }, AuditVerdict::Pass { checked: cn }) => {
2993                assert!(*cf >= 1 && *cn >= 1);
2994            }
2995            other => panic!("both honest proofs must Pass regardless of closeness, got {other:?}"),
2996        }
2997        assert!(
2998            !matches!(v_far, AuditVerdict::Fail(_)),
2999            "far/padding-shaped honest proof must NEVER fail, got {v_far:?}"
3000        );
3001    }
3002
3003    // Unused-leaf constructor guard: keep SubtreeLeaf import meaningful.
3004    #[test]
3005    fn subtree_leaf_is_constructible() {
3006        let _l = SubtreeLeaf {
3007            key: key(1),
3008            bytes_hash: [0u8; 32],
3009            content_len: 0,
3010            nonced_root: [0u8; 32],
3011        };
3012    }
3013}
3014
3015/// Pointers in the storage audit (ADR-0016), driven through the live responders
3016/// against real stores and judged by the auditor's own checks, so a pass here
3017/// is a pass on the network.
3018#[cfg(test)]
3019#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
3020mod pointer_audit_tests {
3021    use super::*;
3022    use crate::replication::commitment::MerkleTree;
3023    use crate::replication::commitment::MAX_COMMITMENT_KEY_COUNT;
3024    use crate::replication::commitment_state::BuiltCommitment;
3025    use crate::replication::subtree::max_subtree_leaves;
3026    use crate::storage::chunk_store::CHUNKS_DIR_NAME;
3027    use crate::storage::ChunkStoreConfig;
3028    use ant_protocol::pointer::{PointerTarget, PointerTargetKind};
3029    use saorsa_pqc::api::sig::ml_dsa_65;
3030    use std::path::PathBuf;
3031    use tempfile::TempDir;
3032    use tokio_util::sync::CancellationToken;
3033
3034    const CHALLENGE_ID: u64 = 7;
3035
3036    /// A one-block chunk, distinct per `i`.
3037    fn chunk(i: u8) -> Vec<u8> {
3038        (0..=255u8).cycle().take(1024).map(|b| b ^ i).collect()
3039    }
3040
3041    /// `owner`'s pointer at `counter`.
3042    fn pointer(owner: u8, counter: u64) -> Pointer {
3043        let (pk, sk) = ml_dsa_65().generate_keypair_from_seed(&[owner; 32]);
3044        let target = PointerTarget::new(PointerTargetKind::Chunk, [owner; 32]);
3045        Pointer::sign(&sk, &pk, counter, target).expect("sign")
3046    }
3047
3048    /// A responder that holds and has committed to `chunks` chunks and
3049    /// `pointers` pointers.
3050    struct Responder {
3051        storage: ChunkStore,
3052        pointers: PointerStore,
3053        state: Arc<ResponderCommitmentState>,
3054        peer: PeerId,
3055        peer_bytes: [u8; 32],
3056        chunk_root: PathBuf,
3057        _dirs: (TempDir, TempDir),
3058    }
3059
3060    impl Responder {
3061        async fn new(chunks: u8, pointers: u8) -> Self {
3062            let chunk_dir = TempDir::new().expect("temp dir");
3063            let storage = ChunkStore::new(ChunkStoreConfig {
3064                root_dir: chunk_dir.path().to_path_buf(),
3065                ..ChunkStoreConfig::test_default()
3066            })
3067            .await
3068            .expect("chunk store");
3069            let pointer_dir = TempDir::new().expect("temp dir");
3070            let pointer_store = PointerStore::new(pointer_dir.path())
3071                .await
3072                .expect("pointer store");
3073
3074            let mut entries = Vec::new();
3075            for i in 0..chunks {
3076                let content = chunk(i);
3077                let address = ChunkStore::compute_address(&content);
3078                storage.put(&address, &content).await.expect("put chunk");
3079                entries.push((address, address));
3080            }
3081            for owner in 0..pointers {
3082                let record = pointer(owner, 1);
3083                pointer_store
3084                    .put_bytes(&record.to_bytes())
3085                    .await
3086                    .expect("put pointer");
3087                entries.push((record.address(), pointer_leaf_hash(&record.address())));
3088            }
3089
3090            let (pk, sk) = ml_dsa_65().generate_keypair().expect("keypair");
3091            let peer_bytes = *blake3::hash(&pk.to_bytes()).as_bytes();
3092            let built =
3093                BuiltCommitment::build(entries, &peer_bytes, &sk, &pk.to_bytes()).expect("build");
3094            let state = Arc::new(ResponderCommitmentState::new());
3095            state.rotate(built);
3096            Self {
3097                storage,
3098                pointers: pointer_store,
3099                state,
3100                peer: PeerId::from_bytes(peer_bytes),
3101                peer_bytes,
3102                chunk_root: chunk_dir.path().to_path_buf(),
3103                _dirs: (chunk_dir, pointer_dir),
3104            }
3105        }
3106
3107        /// Where the file store keeps `key`'s bytes, so a test can rot them.
3108        fn chunk_file(&self, key: &XorName) -> PathBuf {
3109            self.chunk_root
3110                .join(CHUNKS_DIR_NAME)
3111                .join(format!("{:02x}", key.last().copied().unwrap_or(0)))
3112                .join(hex::encode(key))
3113        }
3114
3115        fn committed(&self) -> Arc<BuiltCommitment> {
3116            self.state.current().expect("a current commitment")
3117        }
3118
3119        async fn round1(&self, nonce: [u8; 32]) -> SubtreeAuditResponse {
3120            self.round1_work(nonce).await.response
3121        }
3122
3123        async fn round1_work(&self, nonce: [u8; 32]) -> Round1Work {
3124            let challenge = SubtreeAuditChallenge {
3125                challenge_id: CHALLENGE_ID,
3126                nonce,
3127                challenged_peer_id: self.peer_bytes,
3128                expected_commitment_hash: self.committed().hash(),
3129            };
3130            handle_subtree_challenge_measured_with_pointers(
3131                &challenge,
3132                &self.storage,
3133                Some(&self.pointers),
3134                &self.peer,
3135                false,
3136                Some(&self.state),
3137            )
3138            .await
3139        }
3140
3141        /// Round 2 as the engine serves it: with what round 1 bound for each
3142        /// pointer it opens, as the live session carries it.
3143        async fn round2(
3144            &self,
3145            nonce: [u8; 32],
3146            openings: &[(SubtreeLeaf, u32)],
3147        ) -> Vec<SubtreeSliceItem> {
3148            let bound = openings
3149                .iter()
3150                .map(|(leaf, _)| leaf)
3151                .filter(|leaf| is_pointer_leaf(leaf))
3152                .map(|leaf| (leaf.key, leaf.nonced_root))
3153                .collect();
3154            self.round2_bound(nonce, openings, &bound).await
3155        }
3156
3157        async fn round2_bound(
3158            &self,
3159            nonce: [u8; 32],
3160            openings: &[(SubtreeLeaf, u32)],
3161            bound: &PointerBindings,
3162        ) -> Vec<SubtreeSliceItem> {
3163            match self.round2_response(nonce, openings, bound).await {
3164                SubtreeSliceResponse::Items { items, .. } => items,
3165                other => panic!("expected items, got {other:?}"),
3166            }
3167        }
3168
3169        async fn round2_response(
3170            &self,
3171            nonce: [u8; 32],
3172            openings: &[(SubtreeLeaf, u32)],
3173            bound: &PointerBindings,
3174        ) -> SubtreeSliceResponse {
3175            let challenge = SubtreeSliceChallenge {
3176                challenge_id: CHALLENGE_ID,
3177                nonce,
3178                challenged_peer_id: self.peer_bytes,
3179                expected_commitment_hash: self.committed().hash(),
3180                openings: openings
3181                    .iter()
3182                    .map(|(leaf, block_index)| SubtreeSliceOpening {
3183                        key: leaf.key,
3184                        block_index: *block_index,
3185                    })
3186                    .collect(),
3187            };
3188            handle_subtree_slice_challenge_with_pointer_bindings(
3189                &challenge,
3190                &self.storage,
3191                Some(&self.pointers),
3192                bound,
3193                &self.peer,
3194                false,
3195                Some(&self.state),
3196            )
3197            .await
3198        }
3199
3200        /// Round 1 as the auditor sees it: the proof, checked against the pin.
3201        async fn proved_leaves(&self, nonce: [u8; 32]) -> Vec<SubtreeLeaf> {
3202            let committed = self.committed();
3203            match self.round1(nonce).await {
3204                SubtreeAuditResponse::Proof {
3205                    commitment, proof, ..
3206                } => {
3207                    assert_eq!(
3208                        evaluate_subtree_structure(
3209                            &commitment,
3210                            &proof,
3211                            &nonce,
3212                            &committed.hash(),
3213                            &self.peer_bytes,
3214                        ),
3215                        Ok(()),
3216                        "the auditor must accept the round-1 proof"
3217                    );
3218                    proof.leaves
3219                }
3220                other => panic!("expected a proof, got {other:?}"),
3221            }
3222        }
3223    }
3224
3225    /// A nonce whose audited subtree holds both a pointer and a chunk.
3226    fn mixed_nonce(tree: &MerkleTree) -> [u8; 32] {
3227        (0..=255u8)
3228            .map(|b| [b; 32])
3229            .find(|nonce| {
3230                subtree_plan(tree, nonce).is_ok_and(|plan| {
3231                    plan.leaf_is_pointer.contains(&true) && plan.leaf_is_pointer.contains(&false)
3232                })
3233            })
3234            .expect("some nonce audits a mixed subtree")
3235    }
3236
3237    /// What the auditor opens: every pointer leaf, then chunks, up to the
3238    /// spot-check cap, with the block indices production draws.
3239    fn openings(leaves: &[SubtreeLeaf]) -> Vec<(SubtreeLeaf, u32)> {
3240        let (pointers, chunks): (Vec<_>, Vec<_>) =
3241            leaves.iter().partition(|leaf| is_pointer_leaf(leaf));
3242        pointers
3243            .into_iter()
3244            .take(3)
3245            .chain(chunks)
3246            .take(BYTE_SPOTCHECK_MAX as usize)
3247            .flat_map(|leaf| {
3248                let indices = if is_pointer_leaf(leaf) {
3249                    vec![0]
3250                } else {
3251                    block_indices_for_leaf(leaf.content_len)
3252                };
3253                indices.into_iter().map(|i| (leaf.clone(), i))
3254            })
3255            .collect()
3256    }
3257
3258    fn first_pointer(openings: &[(SubtreeLeaf, u32)]) -> XorName {
3259        openings
3260            .iter()
3261            .map(|(leaf, _)| leaf)
3262            .find(|leaf| is_pointer_leaf(leaf))
3263            .map(|leaf| leaf.key)
3264            .expect("a pointer is opened")
3265    }
3266
3267    #[tokio::test]
3268    async fn a_committed_pointer_is_proved_by_its_signed_record() {
3269        let responder = Responder::new(24, 24).await;
3270        let nonce = mixed_nonce(responder.committed().tree());
3271        let leaves = responder.proved_leaves(nonce).await;
3272        let openings = openings(&leaves);
3273        let items = responder.round2(nonce, &openings).await;
3274
3275        assert!(
3276            items
3277                .iter()
3278                .any(|item| matches!(item, SubtreeSliceItem::PointerRecord { .. })),
3279            "a pointer is proved by its record"
3280        );
3281        assert!(
3282            items
3283                .iter()
3284                .any(|item| matches!(item, SubtreeSliceItem::Present { .. })),
3285            "and the chunks beside it by their slices"
3286        );
3287        assert!(
3288            matches!(
3289                verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3290                AuditVerdict::Pass { .. }
3291            ),
3292            "the auditor must pass an honest holder of both"
3293        );
3294    }
3295
3296    /// A record an update replaces is kept for longer than the slowest audit
3297    /// can take: a round 1 over the largest subtree an auditor waits for,
3298    /// which may have read the pointer at its start, then the session its
3299    /// round 2 must arrive within.
3300    #[test]
3301    fn a_replaced_record_outlives_the_slowest_audit_by_default() {
3302        let largest =
3303            usize::try_from(max_subtree_leaves(MAX_COMMITMENT_KEY_COUNT)).expect("fits a usize");
3304        let slowest =
3305            ReplicationConfig::default().audit_response_timeout(largest) + SUBTREE_SESSION_TTL;
3306        assert!(
3307            SUPERSEDED_RETENTION > slowest,
3308            "{SUPERSEDED_RETENTION:?} must outlive {slowest:?}"
3309        );
3310    }
3311
3312    /// The earlier entry point knows nothing of round 1's roots, and answers
3313    /// as it did before them: an unchanged pointer is served, and passes,
3314    /// rather than reported as a transient failure.
3315    #[tokio::test]
3316    async fn the_earlier_entry_point_still_serves_an_unchanged_pointer() {
3317        let responder = Responder::new(24, 24).await;
3318        let nonce = mixed_nonce(responder.committed().tree());
3319        let openings = openings(&responder.proved_leaves(nonce).await);
3320        let items = legacy_round2(&responder, nonce, &openings).await;
3321        assert!(items
3322            .iter()
3323            .any(|item| matches!(item, SubtreeSliceItem::PointerRecord { .. })));
3324        assert!(matches!(
3325            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3326            AuditVerdict::Pass { .. }
3327        ));
3328    }
3329
3330    /// After one update between the rounds, the earlier entry point serves
3331    /// the record held and the one it replaced, newest first, and passes.
3332    #[tokio::test]
3333    async fn the_earlier_entry_point_still_serves_across_one_update() {
3334        let responder = Responder::new(24, 24).await;
3335        let nonce = mixed_nonce(responder.committed().tree());
3336        let openings = openings(&responder.proved_leaves(nonce).await);
3337        let updated = first_pointer(&openings);
3338        let owner = (0..24u8)
3339            .find(|owner| pointer(*owner, 1).address() == updated)
3340            .expect("the opened pointer is one of ours");
3341        let replaced = responder
3342            .pointers
3343            .record_bytes(&updated)
3344            .await
3345            .expect("read")
3346            .expect("held");
3347        let newer = pointer(owner, 2).to_bytes();
3348        responder.pointers.put_bytes(&newer).await.expect("update");
3349
3350        let items = legacy_round2(&responder, nonce, &openings).await;
3351        let served = items.iter().find_map(|item| match item {
3352            SubtreeSliceItem::PointerRecord { key, records } if *key == updated => {
3353                Some(records.clone())
3354            }
3355            _ => None,
3356        });
3357        assert_eq!(
3358            served,
3359            Some(vec![newer, replaced]),
3360            "the record held, then the one it replaced"
3361        );
3362        assert!(matches!(
3363            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3364            AuditVerdict::Pass { .. }
3365        ));
3366    }
3367
3368    /// Through the earlier entry point too, a pointer updated and then lost
3369    /// is absent, not proved by the record the update replaced.
3370    #[tokio::test]
3371    async fn the_earlier_entry_point_reports_a_lost_pointer_absent() {
3372        let responder = Responder::new(24, 24).await;
3373        let nonce = mixed_nonce(responder.committed().tree());
3374        let openings = openings(&responder.proved_leaves(nonce).await);
3375        let lost = first_pointer(&openings);
3376        let owner = (0..24u8)
3377            .find(|owner| pointer(*owner, 1).address() == lost)
3378            .expect("the opened pointer is one of ours");
3379        responder
3380            .pointers
3381            .put_bytes(&pointer(owner, 2).to_bytes())
3382            .await
3383            .expect("update");
3384        assert!(responder.pointers.delete(&lost).await.expect("delete"));
3385
3386        let items = legacy_round2(&responder, nonce, &openings).await;
3387        assert!(items
3388            .iter()
3389            .any(|item| matches!(item, SubtreeSliceItem::Absent { key } if *key == lost)));
3390        assert_eq!(
3391            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3392            AuditVerdict::Fail(AuditFailureReason::KeyAbsent)
3393        );
3394    }
3395
3396    /// Round 2 through the earlier entry point, which takes no bindings.
3397    async fn legacy_round2(
3398        responder: &Responder,
3399        nonce: [u8; 32],
3400        openings: &[(SubtreeLeaf, u32)],
3401    ) -> Vec<SubtreeSliceItem> {
3402        let challenge = SubtreeSliceChallenge {
3403            challenge_id: CHALLENGE_ID,
3404            nonce,
3405            challenged_peer_id: responder.peer_bytes,
3406            expected_commitment_hash: responder.committed().hash(),
3407            openings: openings
3408                .iter()
3409                .map(|(leaf, block_index)| SubtreeSliceOpening {
3410                    key: leaf.key,
3411                    block_index: *block_index,
3412                })
3413                .collect(),
3414        };
3415        let response = handle_subtree_slice_challenge_with_pointers(
3416            &challenge,
3417            &responder.storage,
3418            Some(&responder.pointers),
3419            &responder.peer,
3420            false,
3421            Some(&responder.state),
3422        )
3423        .await;
3424        let SubtreeSliceResponse::Items { items, .. } = response else {
3425            panic!("expected items, got {response:?}");
3426        };
3427        items
3428    }
3429
3430    /// Round 1 binds each pointer it proves, and nothing else.
3431    #[tokio::test]
3432    async fn round_one_binds_exactly_the_pointers_it_proves() {
3433        let responder = Responder::new(24, 24).await;
3434        let nonce = mixed_nonce(responder.committed().tree());
3435        let response = responder.round1(nonce).await;
3436        let SubtreeAuditResponse::Proof { proof, .. } = &response else {
3437            panic!("expected a proof, got {response:?}");
3438        };
3439        let expected: PointerBindings = proof
3440            .leaves
3441            .iter()
3442            .filter(|leaf| responder.committed().tree().commits_pointer(&leaf.key))
3443            .map(|leaf| (leaf.key, leaf.nonced_root))
3444            .collect();
3445        assert!(!expected.is_empty(), "the subtree holds a pointer");
3446        assert_eq!(pointer_bindings(&response), expected);
3447        assert!(
3448            pointer_bindings(&SubtreeAuditResponse::Bootstrapping {
3449                challenge_id: CHALLENGE_ID
3450            })
3451            .is_empty(),
3452            "only a proof binds anything"
3453        );
3454    }
3455
3456    /// Without the root round 1 reported, which a session this node opened
3457    /// never lacks but a direct caller can, a pointer still held is reported
3458    /// as a transient failure, updated or not: the node cannot show which
3459    /// record round 1 read, and guessing would risk a confirmed failure it did
3460    /// not earn.
3461    #[tokio::test]
3462    async fn without_the_bound_root_a_pointer_is_unavailable_not_failed() {
3463        let responder = Responder::new(24, 24).await;
3464        let nonce = mixed_nonce(responder.committed().tree());
3465        let openings = openings(&responder.proved_leaves(nonce).await);
3466        let unavailable = |response: SubtreeSliceResponse| {
3467            matches!(
3468                response,
3469                SubtreeSliceResponse::Rejected {
3470                    kind: RejectKind::Transient,
3471                    ..
3472                }
3473            )
3474        };
3475
3476        assert!(unavailable(
3477            responder
3478                .round2_response(nonce, &openings, &PointerBindings::new())
3479                .await
3480        ));
3481
3482        let updated = first_pointer(&openings);
3483        let owner = (0..24u8)
3484            .find(|owner| pointer(*owner, 1).address() == updated)
3485            .expect("the opened pointer is one of ours");
3486        responder
3487            .pointers
3488            .put_bytes(&pointer(owner, 2).to_bytes())
3489            .await
3490            .expect("update");
3491        assert!(unavailable(
3492            responder
3493                .round2_response(nonce, &openings, &PointerBindings::new())
3494                .await
3495        ));
3496    }
3497
3498    /// A root round 1 reported that nothing held now reproduces, as when the
3499    /// record it read has been evicted to keep memory bounded, is reported as
3500    /// a transient failure while the pointer is still held, and as absent
3501    /// once nothing at all is.
3502    #[tokio::test]
3503    async fn a_bound_record_no_longer_held_is_unavailable_not_failed() {
3504        let responder = Responder::new(24, 24).await;
3505        let nonce = mixed_nonce(responder.committed().tree());
3506        let openings = openings(&responder.proved_leaves(nonce).await);
3507        let target = first_pointer(&openings);
3508        let evicted: PointerBindings = openings
3509            .iter()
3510            .map(|(leaf, _)| leaf)
3511            .filter(|leaf| is_pointer_leaf(leaf))
3512            .map(|leaf| (leaf.key, [0xEE; 32]))
3513            .collect();
3514
3515        assert!(matches!(
3516            responder.round2_response(nonce, &openings, &evicted).await,
3517            SubtreeSliceResponse::Rejected {
3518                kind: RejectKind::Transient,
3519                ..
3520            }
3521        ));
3522
3523        for (leaf, _) in openings.iter().filter(|(leaf, _)| is_pointer_leaf(leaf)) {
3524            responder.pointers.delete(&leaf.key).await.expect("delete");
3525        }
3526        let items = responder.round2_bound(nonce, &openings, &evicted).await;
3527        assert!(items
3528            .iter()
3529            .any(|item| matches!(item, SubtreeSliceItem::Absent { key } if *key == target)));
3530        assert_eq!(
3531            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3532            AuditVerdict::Fail(AuditFailureReason::KeyAbsent),
3533            "a pointer lost outright is still a confirmed failure"
3534        );
3535    }
3536
3537    /// The commitment binds which pointers are held, not their state, so an
3538    /// owner updating a pointer mid-audit cannot fail the node holding it.
3539    #[tokio::test]
3540    async fn an_update_between_the_rounds_does_not_fail_an_honest_holder() {
3541        let responder = Responder::new(24, 24).await;
3542        let nonce = mixed_nonce(responder.committed().tree());
3543        let openings = openings(&responder.proved_leaves(nonce).await);
3544        let updated = first_pointer(&openings);
3545
3546        let owner = (0..24u8)
3547            .find(|owner| pointer(*owner, 1).address() == updated)
3548            .expect("the opened pointer is one of ours");
3549        responder
3550            .pointers
3551            .put_bytes(&pointer(owner, 2).to_bytes())
3552            .await
3553            .expect("update");
3554
3555        let items = responder.round2(nonce, &openings).await;
3556        assert!(matches!(
3557            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3558            AuditVerdict::Pass { .. }
3559        ));
3560    }
3561
3562    /// However many paid updates land between the rounds, the record round 1
3563    /// bound is the one round 2 serves: the owner's activity is not the
3564    /// holder's failure.
3565    #[tokio::test]
3566    async fn several_updates_between_the_rounds_do_not_fail_an_honest_holder() {
3567        let responder = Responder::new(24, 24).await;
3568        let nonce = mixed_nonce(responder.committed().tree());
3569        let openings = openings(&responder.proved_leaves(nonce).await);
3570        let updated = first_pointer(&openings);
3571
3572        let owner = (0..24u8)
3573            .find(|owner| pointer(*owner, 1).address() == updated)
3574            .expect("the opened pointer is one of ours");
3575        for counter in 2..=4 {
3576            responder
3577                .pointers
3578                .put_bytes(&pointer(owner, counter).to_bytes())
3579                .await
3580                .expect("update");
3581        }
3582
3583        let items = responder.round2(nonce, &openings).await;
3584        assert!(
3585            matches!(
3586                verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3587                AuditVerdict::Pass { .. }
3588            ),
3589            "three updates between the rounds must not fail the holder, got {:?}",
3590            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items)
3591        );
3592        let served = items.iter().find_map(|item| match item {
3593            SubtreeSliceItem::PointerRecord { key, records } if *key == updated => Some(records),
3594            _ => None,
3595        });
3596        assert_eq!(
3597            served,
3598            Some(&vec![pointer_record_bound_in_round_one(&responder, owner)]),
3599            "exactly the record round 1 read, and nothing else"
3600        );
3601    }
3602
3603    /// The record a responder held for `owner`'s pointer before any update:
3604    /// counter 1, as [`Responder::new`] stored it.
3605    fn pointer_record_bound_in_round_one(responder: &Responder, owner: u8) -> Vec<u8> {
3606        let address = pointer(owner, 1).address();
3607        responder
3608            .pointers
3609            .superseded_all(&address)
3610            .last()
3611            .map(|record| record.to_vec())
3612            .expect("the first record is kept")
3613    }
3614
3615    #[tokio::test]
3616    async fn a_node_that_lost_a_committed_pointer_fails_round_one() {
3617        let responder = Responder::new(24, 24).await;
3618        let nonce = mixed_nonce(responder.committed().tree());
3619        let plan = subtree_plan(responder.committed().tree(), &nonce).expect("plan");
3620        let lost = plan
3621            .leaf_keys
3622            .iter()
3623            .zip(&plan.leaf_is_pointer)
3624            .find_map(|(key, is_pointer)| is_pointer.then_some(*key))
3625            .expect("a pointer in the subtree");
3626        assert!(responder.pointers.delete(&lost).await.expect("delete"));
3627
3628        match responder.round1(nonce).await {
3629            SubtreeAuditResponse::Rejected { kind, .. } => {
3630                assert_eq!(
3631                    grade_reject(kind),
3632                    RejectGrade::Confirmed,
3633                    "a lost pointer is a confirmed failure, as a lost chunk is"
3634                );
3635            }
3636            other => panic!("expected a rejection, got {other:?}"),
3637        }
3638    }
3639
3640    /// A node that lost the pointer is absent, even while it still keeps in
3641    /// memory the record an update replaced, and even when that is the very
3642    /// record round 1 read: the replaced records prove what round 1 read, not
3643    /// that the node still holds the pointer.
3644    #[tokio::test]
3645    async fn a_lost_pointer_is_absent_whatever_replaced_records_remain() {
3646        let responder = Responder::new(24, 24).await;
3647        let nonce = mixed_nonce(responder.committed().tree());
3648        let openings = openings(&responder.proved_leaves(nonce).await);
3649        let lost = first_pointer(&openings);
3650        let owner = (0..24u8)
3651            .find(|owner| pointer(*owner, 1).address() == lost)
3652            .expect("the opened pointer is one of ours");
3653        responder
3654            .pointers
3655            .put_bytes(&pointer(owner, 2).to_bytes())
3656            .await
3657            .expect("update");
3658        assert!(responder.pointers.delete(&lost).await.expect("delete"));
3659        assert!(
3660            !responder.pointers.superseded_all(&lost).is_empty(),
3661            "the record round 1 read is still kept in memory"
3662        );
3663
3664        let items = responder.round2(nonce, &openings).await;
3665        assert!(items
3666            .iter()
3667            .any(|item| matches!(item, SubtreeSliceItem::Absent { key } if *key == lost)));
3668        assert_eq!(
3669            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3670            AuditVerdict::Fail(AuditFailureReason::KeyAbsent)
3671        );
3672    }
3673
3674    #[tokio::test]
3675    async fn a_pointer_lost_after_round_one_is_admitted_absent() {
3676        let responder = Responder::new(24, 24).await;
3677        let nonce = mixed_nonce(responder.committed().tree());
3678        let openings = openings(&responder.proved_leaves(nonce).await);
3679        assert!(responder
3680            .pointers
3681            .delete(&first_pointer(&openings))
3682            .await
3683            .expect("delete"));
3684
3685        let items = responder.round2(nonce, &openings).await;
3686        assert_eq!(
3687            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3688            AuditVerdict::Fail(AuditFailureReason::KeyAbsent)
3689        );
3690    }
3691
3692    /// A node cannot prove it holds one pointer with another, genuinely signed
3693    /// record: the record must belong at the committed address.
3694    #[tokio::test]
3695    async fn another_pointer_is_not_proof_of_the_one_committed() {
3696        let responder = Responder::new(24, 24).await;
3697        let nonce = mixed_nonce(responder.committed().tree());
3698        let openings = openings(&responder.proved_leaves(nonce).await);
3699        let target = first_pointer(&openings);
3700
3701        let mut items = responder.round2(nonce, &openings).await;
3702        replace_records(&mut items, &target, &[pointer(200, 1).to_bytes()]);
3703        assert_eq!(
3704            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3705            AuditVerdict::Fail(AuditFailureReason::DigestMismatch)
3706        );
3707    }
3708
3709    /// A committed chunk whose file has rotted fails round 1 exactly as before,
3710    /// but the responder reports it, and the chunk store's recheck worker then
3711    /// stops the node claiming it, so its next commitment leaves the chunk out
3712    /// and replication can repair it rather than the node failing every audit
3713    /// that lands on that key.
3714    #[tokio::test]
3715    async fn round_one_takes_a_rotted_committed_chunk_out_of_service() {
3716        let responder = Responder::new(24, 0).await;
3717        let committed = responder.committed();
3718        let nonce = [7u8; 32];
3719        let plan = subtree_plan(committed.tree(), &nonce).expect("plan");
3720        let victim = plan.leaf_keys.first().copied().expect("a selected chunk");
3721        let path = responder.chunk_file(&victim);
3722        std::fs::write(&path, b"rotted").expect("corrupt the file");
3723
3724        let work = responder.round1_work(nonce).await;
3725        assert_eq!(
3726            work.corrupt_keys,
3727            vec![victim],
3728            "the responder reports exactly the rotted chunk"
3729        );
3730        match work.response {
3731            SubtreeAuditResponse::Proof {
3732                commitment, proof, ..
3733            } => assert_eq!(
3734                evaluate_subtree_structure(
3735                    &commitment,
3736                    &proof,
3737                    &nonce,
3738                    &committed.hash(),
3739                    &responder.peer_bytes,
3740                ),
3741                Err(AuditFailureReason::DigestMismatch),
3742                "the auditor's verdict on the rotted chunk is unchanged"
3743            ),
3744            other => panic!("expected a proof, got {other:?}"),
3745        }
3746
3747        // What the replication engine does with the report: queue it for the chunk
3748        // store's recheck worker. The worker finishes the recheck it is on before it
3749        // stops, so once it returns the chunk has been dealt with.
3750        responder.storage.report_corrupt(&work.corrupt_keys);
3751        let stop = CancellationToken::new();
3752        let removed = async {
3753            let deadline = Instant::now() + Duration::from_secs(30);
3754            while path.exists() && Instant::now() < deadline {
3755                tokio::time::sleep(Duration::from_millis(5)).await;
3756            }
3757            stop.cancel();
3758        };
3759        tokio::join!(responder.storage.run_corrupt_rechecks(&stop), removed);
3760        let keys = responder.storage.all_keys().await.expect("keys");
3761        assert!(
3762            !keys.contains(&victim),
3763            "the rotted chunk leaves the view the next commitment is built from"
3764        );
3765        assert!(!path.exists(), "the rotted file is removed");
3766        assert_eq!(keys.len(), 23, "every intact chunk stays in service");
3767    }
3768
3769    /// An honest round 1 over intact chunks takes nothing out of service.
3770    #[tokio::test]
3771    async fn round_one_over_intact_chunks_keeps_every_chunk() {
3772        let responder = Responder::new(24, 0).await;
3773        for seed in 0..8u8 {
3774            let corrupt = responder.round1_work([seed; 32]).await.corrupt_keys;
3775            assert!(
3776                corrupt.is_empty(),
3777                "an intact chunk was reported rotted: {corrupt:?}"
3778            );
3779            let leaves = responder.proved_leaves([seed; 32]).await;
3780            assert!(!leaves.is_empty(), "expected round 1 to prove some leaves");
3781        }
3782        assert_eq!(responder.storage.all_keys().await.expect("keys").len(), 24);
3783    }
3784
3785    fn replace_records(items: &mut [SubtreeSliceItem], target: &XorName, with: &[Vec<u8>]) {
3786        for item in items {
3787            if let SubtreeSliceItem::PointerRecord { key, records } = item {
3788                if key == target {
3789                    *records = with.to_vec();
3790                }
3791            }
3792        }
3793    }
3794
3795    /// A node that holds no pointers cannot pass by fetching the few sampled
3796    /// records once round 2 names them: round 1 had to bind each record's
3797    /// bytes under the nonce before anything was sampled, and it had none.
3798    #[tokio::test]
3799    async fn a_relay_that_fetches_records_only_in_round_two_fails() {
3800        let responder = Responder::new(24, 24).await;
3801        let nonce = mixed_nonce(responder.committed().tree());
3802        let genuine = responder.proved_leaves(nonce).await;
3803        let held = openings(&genuine);
3804        // What a relay can say in round 1 without the bytes.
3805        let mut leaves = genuine;
3806        for leaf in leaves.iter_mut().filter(|leaf| is_pointer_leaf(leaf)) {
3807            leaf.nonced_root = [0u8; 32];
3808        }
3809        let openings = openings(&leaves);
3810        // And in round 2 it serves the genuine records, fetched on demand.
3811        let items = responder.round2(nonce, &held).await;
3812        assert_eq!(
3813            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3814            AuditVerdict::Fail(AuditFailureReason::DigestMismatch)
3815        );
3816    }
3817
3818    /// Nor can it pass with another replica's copy of the very state it
3819    /// committed: every signature is randomised, so each replica's bytes, and
3820    /// the nonced root over them, are its own.
3821    #[tokio::test]
3822    async fn another_replicas_copy_of_the_same_state_is_not_proof() {
3823        let responder = Responder::new(24, 24).await;
3824        let nonce = mixed_nonce(responder.committed().tree());
3825        let openings = openings(&responder.proved_leaves(nonce).await);
3826        let target = first_pointer(&openings);
3827        let owner = (0..24u8)
3828            .find(|owner| pointer(*owner, 1).address() == target)
3829            .expect("the opened pointer is one of ours");
3830        let replica = pointer(owner, 1);
3831        assert_eq!(
3832            replica.state_id(),
3833            responder.pointers.state(&target).expect("held").state_id,
3834            "the same state"
3835        );
3836
3837        let mut items = responder.round2(nonce, &openings).await;
3838        replace_records(&mut items, &target, &[replica.to_bytes()]);
3839        assert_eq!(
3840            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3841            AuditVerdict::Fail(AuditFailureReason::DigestMismatch)
3842        );
3843    }
3844
3845    /// A pointer item may carry at most two records. This build serves one;
3846    /// two is what a responder that kept no round-1 roots served (ADR-0016).
3847    #[tokio::test]
3848    async fn a_pointer_item_with_more_than_two_records_is_malformed() {
3849        let responder = Responder::new(24, 24).await;
3850        let nonce = mixed_nonce(responder.committed().tree());
3851        let openings = openings(&responder.proved_leaves(nonce).await);
3852        let target = first_pointer(&openings);
3853        let mut items = responder.round2(nonce, &openings).await;
3854        let held = responder
3855            .pointers
3856            .record_bytes(&target)
3857            .await
3858            .expect("read")
3859            .expect("held");
3860        replace_records(&mut items, &target, &[held.clone(), held.clone(), held]);
3861        assert_eq!(
3862            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3863            AuditVerdict::Fail(AuditFailureReason::MalformedResponse)
3864        );
3865    }
3866
3867    /// The pointer leaf shape is accepted only at a pointer's exact size, so it
3868    /// cannot stand in for a chunk of another length.
3869    #[tokio::test]
3870    async fn a_pointer_leaf_of_any_other_length_is_refused() {
3871        let responder = Responder::new(24, 24).await;
3872        let nonce = mixed_nonce(responder.committed().tree());
3873        let committed = responder.committed();
3874        let SubtreeAuditResponse::Proof {
3875            commitment,
3876            mut proof,
3877            ..
3878        } = responder.round1(nonce).await
3879        else {
3880            panic!("expected a proof");
3881        };
3882        let leaf = proof
3883            .leaves
3884            .iter_mut()
3885            .find(|leaf| is_pointer_leaf(leaf))
3886            .expect("a pointer leaf");
3887        leaf.content_len = leaf.content_len.saturating_add(1);
3888
3889        assert_eq!(
3890            evaluate_subtree_structure(
3891                &commitment,
3892                &proof,
3893                &nonce,
3894                &committed.hash(),
3895                &responder.peer_bytes,
3896            ),
3897            Err(AuditFailureReason::DigestMismatch)
3898        );
3899    }
3900}