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/// Verify a subtree-proof response (auditor side), ADR-0002 two-round audit.
1073///
1074/// **Round 1** (this proof): pin + identity + signature + structure. If the
1075/// proof structurally rebuilds to the pinned root, the tree SHAPE is committed —
1076/// but not yet that the bytes are held. **Round 2**: the auditor picks a small
1077/// freshly-random (post-proof) sample of the just-proven leaves, draws a fresh
1078/// block index for each, and sends a [`SubtreeSliceChallenge`] opening those
1079/// blocks. It verifies each opened block against the committed `bytes_hash`
1080/// (Bao slice → content address) and `nonced_root` (nonced block-tree opening →
1081/// round-1 possession commit). A responder that committed to a chunk it no
1082/// longer held cannot have committed a correct `nonced_root`, so it fails —
1083/// regardless of what the auditor holds. On a full pass, credits the peer as a
1084/// proven holder.
1085async fn verify_subtree_response(
1086    ctx: &AuditCtx<'_>,
1087    commitment: &StorageCommitment,
1088    proof: &SubtreeProof,
1089) -> AuditTickResult {
1090    let challenged_peer = ctx.challenged_peer;
1091    let challenge_id = ctx.challenge_id;
1092
1093    // -- Round 1: pin/identity/signature + structure (no bytes). --
1094    if let Err(reason) = evaluate_subtree_structure(
1095        commitment,
1096        proof,
1097        &ctx.nonce,
1098        &ctx.expected_commitment_hash,
1099        challenged_peer.as_bytes(),
1100    ) {
1101        warn!("Audit: {challenged_peer} failed subtree structure ({reason:?})");
1102        return failed(challenged_peer, challenge_id, reason);
1103    }
1104
1105    // -- Round 2: surprise slice challenge for a 3..=5 FRESHLY-RANDOM sample. --
1106    // The sample is chosen now, with CSPRNG randomness, AFTER the round-1 proof
1107    // is in hand — NOT derived from the round-1 nonce. The responder committed
1108    // every leaf's `nonced_root` in round 1 without knowing which leaves — or
1109    // which block within each — we will open, so it could not have prepared only
1110    // the opened blocks (cut-and-choose). The reply is a few KB per opening (a
1111    // 1 KiB block plus two short hash chains), so one round-2 message serves the
1112    // whole sample; no batching.
1113    let sample_n = ctx
1114        .config
1115        .audit_spotcheck_count()
1116        .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 failed(
1123            challenged_peer,
1124            challenge_id,
1125            AuditFailureReason::DigestMismatch,
1126        );
1127    }
1128    // Pair each sampled leaf with up to two block indices: a fresh-random block
1129    // (possession) and the claimed final block (a length pin — see
1130    // `block_indices_for_leaf`). Own the leaves so the borrow on `proof` ends
1131    // before the await. The sample is <= BYTE_SPOTCHECK_MAX and each leaf yields
1132    // <= 2 openings, so the total is <= 2 * BYTE_SPOTCHECK_MAX <= MAX_SLICE_OPENINGS
1133    // (statically asserted); `take` is a defensive backstop.
1134    let openings_with_leaves: Vec<(crate::replication::subtree::SubtreeLeaf, u32)> = sampled
1135        .iter()
1136        .flat_map(|leaf| {
1137            let leaf = (*leaf).clone();
1138            // A pointer is served whole, so it takes one opening, at block 0.
1139            let indices = if is_pointer_leaf(&leaf) {
1140                vec![0]
1141            } else {
1142                block_indices_for_leaf(leaf.content_len)
1143            };
1144            indices
1145                .into_iter()
1146                .map(move |block_index| (leaf.clone(), block_index))
1147        })
1148        .take(MAX_SLICE_OPENINGS)
1149        .collect();
1150    let openings: Vec<SubtreeSliceOpening> = openings_with_leaves
1151        .iter()
1152        .map(|(leaf, block_index)| SubtreeSliceOpening {
1153            key: leaf.key,
1154            block_index: *block_index,
1155        })
1156        .collect();
1157
1158    let round = request_slice_proof(ctx, &openings).await;
1159
1160    // Round 2 ended without a completed possession proof: drop the holder credit
1161    // this pinned commitment carries, before mapping the outcome to a verdict.
1162    // Scoped to the commitment hash, so credit the peer re-earned for a newer
1163    // commitment survives.
1164    if round2_revokes_pinned_credit(&round) {
1165        if let Some(credit) = ctx.credit {
1166            credit
1167                .recent_provers
1168                .write()
1169                .await
1170                .forget_commitment(&ctx.expected_commitment_hash);
1171        }
1172    }
1173
1174    let verdict = match round {
1175        // The responder served openings: verify both chains for every one. Any
1176        // failing chain is a confirmed cheat.
1177        SliceRound::Served(items) => verify_slice_response(
1178            &openings_with_leaves,
1179            &ctx.nonce,
1180            challenged_peer.as_bytes(),
1181            &items,
1182        ),
1183        // Confirmed round-2 failures. `Rejected`: the responder repudiated the
1184        // slice challenge for a recently pinned commitment. `ResponsiveBootstrap`:
1185        // it claimed bootstrap AFTER producing a valid round-1 proof, which is a
1186        // self-contradiction (a bootstrapping node has no committed data to
1187        // prove). Both are classified as any other confirmed `Rejected`, which
1188        // revokes the peer's holder credit and takes the trust penalty downstream
1189        // (`apply_audit_failure_credit_revocation` → `forget_peer`).
1190        SliceRound::Rejected | SliceRound::ResponsiveBootstrap => {
1191            AuditVerdict::Fail(AuditFailureReason::Rejected)
1192        }
1193        // Round 2 produced no proof, either as an explicit `Transient` (a local
1194        // read error) or as silence. Both route to the timeout lane: no trust
1195        // penalty, the strike policy still graces them, and the credit for the
1196        // pinned commitment was already revoked above.
1197        SliceRound::TransientReject | SliceRound::Timeout => {
1198            AuditVerdict::Fail(AuditFailureReason::Timeout)
1199        }
1200        // Malformed/unexpected round-2 body.
1201        SliceRound::Malformed => AuditVerdict::Fail(AuditFailureReason::MalformedResponse),
1202    };
1203
1204    match verdict {
1205        AuditVerdict::Fail(reason) => {
1206            warn!("Audit: {challenged_peer} failed subtree audit ({reason:?})");
1207            failed(challenged_peer, challenge_id, reason)
1208        }
1209        AuditVerdict::Pass { checked } => {
1210            // Closeness (ADR-0002, soft/observe-only) — see observe_closeness.
1211            observe_closeness(ctx.p2p_node, ctx.config, challenged_peer, proof).await;
1212            // Credit the peer as a proven holder of its committed keys.
1213            if let (Some(credit), Some(pin)) = (ctx.credit, commitment_hash(commitment)) {
1214                let now = std::time::Instant::now();
1215                let mut provers = credit.recent_provers.write().await;
1216                for leaf in &proof.leaves {
1217                    provers.record_proof(leaf.key, *challenged_peer, pin, now);
1218                }
1219            }
1220            info!(
1221                "Audit: peer {challenged_peer} passed subtree audit ({} leaves, {checked} \
1222                 block openings verified)",
1223                proof.leaves.len()
1224            );
1225            AuditTickResult::Passed {
1226                challenged_peer: *challenged_peer,
1227                keys_checked: checked,
1228            }
1229        }
1230    }
1231}
1232
1233/// Soft, density-aware closeness observation (ADR-0002). Logs — never fails —
1234/// when a suspicious fraction of the proof's leaves are keys the auditor itself
1235/// is NOT responsible for (a proxy for "implausibly far from the peer").
1236///
1237/// Using the auditor's own `SelfInclusiveRT` responsibility as the yardstick
1238/// makes this density-aware for free: on a small/dense network the auditor is
1239/// close to nearly every key, so almost nothing reads as far and no honest peer
1240/// is ever flagged. Enforcement is intentionally deferred until a testnet
1241/// calibrates the density threshold.
1242async fn observe_closeness(
1243    p2p_node: &Arc<P2PNode>,
1244    config: &ReplicationConfig,
1245    challenged_peer: &PeerId,
1246    proof: &SubtreeProof,
1247) {
1248    /// Max leaves probed for the closeness estimate (bounds the DHT lookups).
1249    const CLOSENESS_SAMPLE_CAP: usize = 8;
1250
1251    // This is an observe-only DEBUG signal (never enforced). The check costs one
1252    // DHT responsibility lookup per inspected leaf, so (§12): (a) skip it
1253    // entirely unless debug logging is on — there is no other consumer — and
1254    // (b) inspect at most a bounded SAMPLE of leaves rather than all ~sqrt(N),
1255    // which still reveals the "mostly far" padding shape without N lookups.
1256    if !crate::logging::enabled!(crate::logging::Level::DEBUG) {
1257        return;
1258    }
1259
1260    let self_id = *p2p_node.peer_id();
1261    let inspected = proof.leaves.len().min(CLOSENESS_SAMPLE_CAP);
1262    let mut far = 0usize;
1263    for leaf in proof.leaves.iter().take(inspected) {
1264        if !crate::replication::admission::is_responsible(
1265            &self_id,
1266            &leaf.key,
1267            p2p_node,
1268            config.close_group_size,
1269        )
1270        .await
1271        {
1272            far += 1;
1273        }
1274    }
1275    // Only worth a line when MOST of the inspected sample is far — that's the
1276    // padding shape. A normal proof on a sparse network has some far keys.
1277    if inspected > 0 && far * 2 > inspected {
1278        debug!(
1279            "Audit: closeness signal — {far}/{inspected} sampled of {challenged_peer}'s proven \
1280             leaves are keys this auditor is not close to (observe-only; possible padding, not \
1281             penalized)"
1282        );
1283    }
1284}
1285
1286/// Build a confirmed-failure result. The auditor pinned a commitment the peer
1287/// committed to itself, so there is no per-key responsibility to re-confirm:
1288/// the failure is about the peer's own committed tree.
1289///
1290/// The subtree audit fails a peer as a whole (one challenge, one verdict) rather
1291/// than per-key, so the [`AuditFailureSummary`] is a single-failure rollup
1292/// mapped from `reason` — enough for the shared audit-failure diagnostics log
1293/// line (`absent_keys`/`digest_mismatch_keys`) without inventing per-key counts
1294/// this audit shape does not have.
1295fn failed(
1296    challenged_peer: &PeerId,
1297    challenge_id: u64,
1298    reason: AuditFailureReason,
1299) -> AuditTickResult {
1300    let summary = subtree_failure_summary(&reason);
1301    AuditTickResult::Failed {
1302        evidence: FailureEvidence::AuditFailure {
1303            challenge_id,
1304            challenged_peer: *challenged_peer,
1305            confirmed_failed_keys: Vec::new(),
1306            summary,
1307            reason,
1308        },
1309        no_response_class: None,
1310    }
1311}
1312
1313/// Map a subtree-audit `reason` to a single-failure [`AuditFailureSummary`].
1314///
1315/// A `Timeout` is not a confirmed failure (it is the non-response/timeout lane),
1316/// so it rolls up as zero confirmed failures; every other reason is one confirmed failure,
1317/// categorised where the category is meaningful (byte/nonce/root mismatch →
1318/// `digest_mismatch_keys`; explicit absent → `absent_keys`).
1319fn subtree_failure_summary(reason: &AuditFailureReason) -> AuditFailureSummary {
1320    let mut summary = AuditFailureSummary {
1321        challenged_keys: 1,
1322        ..AuditFailureSummary::default()
1323    };
1324    match reason {
1325        AuditFailureReason::Timeout => {}
1326        AuditFailureReason::DigestMismatch => {
1327            summary.failed_keys = 1;
1328            summary.digest_mismatch_keys = 1;
1329        }
1330        AuditFailureReason::KeyAbsent => {
1331            summary.failed_keys = 1;
1332            summary.absent_keys = 1;
1333        }
1334        AuditFailureReason::MalformedResponse | AuditFailureReason::Rejected => {
1335            summary.failed_keys = 1;
1336        }
1337    }
1338    summary
1339}
1340
1341// ---------------------------------------------------------------------------
1342// Responder side
1343// ---------------------------------------------------------------------------
1344
1345/// Handle an incoming subtree audit challenge (responder side).
1346///
1347/// Validates the challenge targets this node, looks up the pinned commitment in
1348/// the retained (in-window) set, and builds the subtree proof for the
1349/// nonce-selected branch. If this node is bootstrapping it says so; if it
1350/// genuinely does not retain the pinned commitment it rejects (which, with audit
1351/// grace removed, the auditor treats as a confirmed failure for an in-window pin).
1352pub async fn handle_subtree_challenge(
1353    challenge: &SubtreeAuditChallenge,
1354    storage: &ChunkStore,
1355    self_peer_id: &PeerId,
1356    is_bootstrapping: bool,
1357    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1358) -> SubtreeAuditResponse {
1359    handle_subtree_challenge_measured(
1360        challenge,
1361        storage,
1362        self_peer_id,
1363        is_bootstrapping,
1364        commitment_state,
1365    )
1366    .await
1367    .response
1368}
1369
1370/// A round-1 response together with the chunk bytes spent producing it.
1371pub struct Round1Work {
1372    /// What to send back.
1373    pub response: SubtreeAuditResponse,
1374    /// Chunk content read from the store and hashed BEFORE this response was
1375    /// produced.
1376    ///
1377    /// Counted on the rejecting paths too, which is the point. A subtree is read
1378    /// leaf by leaf, so a commitment holding one unreadable key still costs a
1379    /// full run of reads and keyed-BLAKE3 passes over every leaf before it. If
1380    /// only the `Proof` arm were charged, an attacker who found such a
1381    /// commitment could replay subtrees over it indefinitely for free — and
1382    /// since the per-peer cooldown is escapable by rotating identity, the
1383    /// responder-wide work budget is the only bound that would have caught it.
1384    pub content_bytes: i64,
1385    /// Committed chunks whose bytes, read for this proof, no longer hash to
1386    /// their key.
1387    ///
1388    /// The proof still carries what was read, so the auditor's verdict on them
1389    /// is unchanged. The caller reports them to the chunk store
1390    /// (`ChunkStore::report_corrupt`), whose recheck worker takes the ones its
1391    /// bounded queue admits out of service, so the node stops committing a chunk
1392    /// it cannot prove and replication can repair it, rather than failing every
1393    /// audit that lands on that key until a fetch of the same key happens to
1394    /// notice. A key the queue cannot take stays committed, so the next audit
1395    /// that reads it reports it again. Not done here, so the cleanup never delays
1396    /// the answer the auditor is waiting for.
1397    pub corrupt_keys: Vec<XorName>,
1398}
1399
1400/// [`handle_subtree_challenge`], additionally reporting the read-and-hash work
1401/// it performed so the caller can charge it on every exit path.
1402pub async fn handle_subtree_challenge_measured(
1403    challenge: &SubtreeAuditChallenge,
1404    storage: &ChunkStore,
1405    self_peer_id: &PeerId,
1406    is_bootstrapping: bool,
1407    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1408) -> Round1Work {
1409    handle_subtree_challenge_measured_with_pointers(
1410        challenge,
1411        storage,
1412        None,
1413        self_peer_id,
1414        is_bootstrapping,
1415        commitment_state,
1416    )
1417    .await
1418}
1419
1420/// [`handle_subtree_challenge_measured`] for a node that also commits pointers
1421/// (ADR-0016): committed pointer leaves are answered from `pointers`.
1422pub async fn handle_subtree_challenge_measured_with_pointers(
1423    challenge: &SubtreeAuditChallenge,
1424    storage: &ChunkStore,
1425    pointers: Option<&PointerStore>,
1426    self_peer_id: &PeerId,
1427    is_bootstrapping: bool,
1428    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1429) -> Round1Work {
1430    // The accumulator is threaded in rather than returned per-arm so that every
1431    // exit reports its work by construction: a new early return cannot forget to
1432    // account for the reads that already happened.
1433    let mut content_bytes = 0i64;
1434    let mut corrupt_keys = Vec::new();
1435    let response = subtree_challenge_response(
1436        challenge,
1437        storage,
1438        pointers,
1439        self_peer_id,
1440        is_bootstrapping,
1441        commitment_state,
1442        &mut content_bytes,
1443        &mut corrupt_keys,
1444    )
1445    .await;
1446    Round1Work {
1447        response,
1448        content_bytes,
1449        corrupt_keys,
1450    }
1451}
1452
1453/// The round-1 responder proper. `content_bytes` accrues the chunk content read
1454/// and hashed so far, and is meaningful on every return path, not just the
1455/// successful one. `corrupt_keys` collects the committed chunks whose bytes did
1456/// not hash to their key (see [`Round1Work::corrupt_keys`]).
1457#[allow(clippy::too_many_lines, clippy::too_many_arguments)]
1458async fn subtree_challenge_response(
1459    challenge: &SubtreeAuditChallenge,
1460    storage: &ChunkStore,
1461    pointers: Option<&PointerStore>,
1462    self_peer_id: &PeerId,
1463    is_bootstrapping: bool,
1464    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1465    content_bytes: &mut i64,
1466    corrupt_keys: &mut Vec<XorName>,
1467) -> SubtreeAuditResponse {
1468    if is_bootstrapping {
1469        return SubtreeAuditResponse::Bootstrapping {
1470            challenge_id: challenge.challenge_id,
1471        };
1472    }
1473
1474    if challenge.challenged_peer_id != *self_peer_id.as_bytes() {
1475        warn!(
1476            "Subtree audit challenge targeted wrong peer: expected {}, got {}",
1477            hex::encode(self_peer_id.as_bytes()),
1478            hex::encode(challenge.challenged_peer_id),
1479        );
1480        return SubtreeAuditResponse::Rejected {
1481            challenge_id: challenge.challenge_id,
1482            kind: RejectKind::Protocol,
1483            reason: "challenged_peer_id does not match this node".to_string(),
1484        };
1485    }
1486
1487    let Some(state) = commitment_state else {
1488        return SubtreeAuditResponse::Rejected {
1489            challenge_id: challenge.challenge_id,
1490            kind: RejectKind::Protocol,
1491            reason: "no commitment state".to_string(),
1492        };
1493    };
1494
1495    // Look up the pinned commitment among the in-window retained set (TTL-bounded
1496    // answerability with a MAX_RETAINED_GOSSIPED_SLOTS backstop).
1497    // A miss is `UnknownCommitment`. With audit grace removed (ADR-0004 A1) the
1498    // auditor treats a responsive miss on an in-window pin as a CONFIRMED failure:
1499    // answerability is restart-durable and pins are challenged only while in
1500    // window, so failing to answer is a real repudiation, not benign rotation.
1501    let Some(built) = state.lookup_by_hash(&challenge.expected_commitment_hash) else {
1502        return SubtreeAuditResponse::Rejected {
1503            challenge_id: challenge.challenge_id,
1504            kind: RejectKind::UnknownCommitment,
1505            reason: "unknown commitment hash".to_string(),
1506        };
1507    };
1508
1509    // Geometry first (no bytes touched): which leaves to prove + the sibling
1510    // cut-hashes from the committed tree.
1511    let plan = match subtree_plan(built.tree(), &challenge.nonce) {
1512        Ok(p) => p,
1513        Err(e) => {
1514            warn!("Subtree audit: failed to plan proof: {e:?}");
1515            return SubtreeAuditResponse::Rejected {
1516                challenge_id: challenge.challenge_id,
1517                kind: RejectKind::Protocol,
1518                reason: "could not build subtree proof".to_string(),
1519            };
1520        }
1521    };
1522
1523    // Read chunk bytes one leaf at a time so peak memory is bounded regardless
1524    // of subtree size, hashing each into its plain + nonced leaf.
1525    let mut leaves = Vec::with_capacity(plan.leaf_keys.len());
1526    for (position, key) in plan.leaf_keys.iter().enumerate() {
1527        // A pointer leaf (ADR-0016) commits no bytes in the tree, since its
1528        // bytes change with every update. Round 1 binds them here instead: the
1529        // nonced root over the record held now, which round 2 must reproduce.
1530        // So a node answers from records it holds, not ones it could fetch once
1531        // it learns which few are sampled. A loss is admitted exactly as a
1532        // missing chunk is, and a read error is transient as for a chunk.
1533        if plan.leaf_is_pointer.get(position).copied().unwrap_or(false) {
1534            *content_bytes = content_bytes.saturating_add(SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES);
1535            let key_hex = hex::encode(key);
1536            let read = match pointers {
1537                Some(store) => store.record_bytes(key).await,
1538                None => Ok(None),
1539            };
1540            let record = match read {
1541                Ok(Some(record)) => record,
1542                Ok(None) => {
1543                    warn!("Subtree audit: committed pointer {key_hex} is not held");
1544                    return SubtreeAuditResponse::Rejected {
1545                        challenge_id: challenge.challenge_id,
1546                        kind: RejectKind::Protocol,
1547                        reason: format!("missing bytes for committed key: {key_hex}"),
1548                    };
1549                }
1550                Err(e) => {
1551                    warn!(
1552                        "Subtree audit: read error for committed pointer {key_hex}: {e} \
1553                         (rejecting as transient, not a confirmed failure)"
1554                    );
1555                    return SubtreeAuditResponse::Rejected {
1556                        challenge_id: challenge.challenge_id,
1557                        kind: RejectKind::Transient,
1558                        reason: format!("transient storage read error: {e}"),
1559                    };
1560                }
1561            };
1562            // Top up to the record read, as for a chunk.
1563            let content = i64::try_from(record.len()).unwrap_or(i64::MAX);
1564            *content_bytes = content_bytes.saturating_add(
1565                content
1566                    .saturating_sub(SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES)
1567                    .max(0),
1568            );
1569            leaves.push(SubtreeLeaf {
1570                key: *key,
1571                bytes_hash: pointer_leaf_hash(key),
1572                content_len: u32::try_from(POINTER_WIRE_LEN).unwrap_or(u32::MAX),
1573                nonced_root: nonced_block_root(
1574                    &challenge.nonce,
1575                    &challenge.challenged_peer_id,
1576                    key,
1577                    &record,
1578                ),
1579            });
1580            continue;
1581        }
1582        // Charge the fixed cost of ATTEMPTING a leaf before the read, because
1583        // it is owed whether or not the read succeeds: the lookup and its
1584        // retries, and the blocking-task round trip below. Charging only
1585        // content bytes left both a failing leaf and a tiny one nearly free,
1586        // and nothing bounds a chunk from below, so a commitment of a million
1587        // small records could run a full subtree of lookups per audit against
1588        // almost no budget. The top-up after a successful read makes the total
1589        // `max(bytes, floor)` rather than a surcharge on honest chunks.
1590        *content_bytes = content_bytes.saturating_add(SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES);
1591        let bytes = match get_raw_retrying(storage, key).await {
1592            Ok(Some(bytes)) => bytes,
1593            // Key is in our committed tree but definitively NOT stored — real
1594            // storage loss / the classic deleter. For a recently gossiped pin
1595            // the auditor counts this as a CONFIRMED failure.
1596            Ok(None) => {
1597                warn!(
1598                    "Subtree audit: missing bytes for committed key {}",
1599                    hex::encode(key)
1600                );
1601                return SubtreeAuditResponse::Rejected {
1602                    challenge_id: challenge.challenge_id,
1603                    kind: RejectKind::Protocol,
1604                    reason: format!("missing bytes for committed key: {}", hex::encode(key)),
1605                };
1606            }
1607            // Persistent transient read error after retries — NOT proof of missing
1608            // data. Reject `Transient`; the auditor routes it to the timeout lane
1609            // (no confirmed penalty) so a genuinely flaky disk is not branded a
1610            // deleter, while gaining no positive standing.
1611            Err(e) => {
1612                warn!(
1613                    "Subtree audit: storage read error for committed key {}: {e} \
1614                     (rejecting as transient, not a confirmed failure)",
1615                    hex::encode(key)
1616                );
1617                return SubtreeAuditResponse::Rejected {
1618                    challenge_id: challenge.challenge_id,
1619                    kind: RejectKind::Transient,
1620                    reason: format!("transient storage read error: {e}"),
1621                };
1622            }
1623        };
1624        // Top up to the content actually read, above the floor already charged.
1625        // Charged at the READ, not at the end: the disk read and the
1626        // keyed-BLAKE3 pass below are both already owed at this point, and
1627        // every remaining exit from this loop — a later missing key, a
1628        // persistent read error, a failed hashing task — discards the leaves
1629        // but not the work. Accruing here is what makes a commitment with one
1630        // bad key cost the attacker something per replay instead of nothing.
1631        let content = i64::try_from(bytes.len()).unwrap_or(i64::MAX);
1632        *content_bytes = content_bytes.saturating_add(
1633            content
1634                .saturating_sub(SUBTREE_ROUND1_LEAF_WORK_FLOOR_BYTES)
1635                .max(0),
1636        );
1637        // Hash the leaf (a full keyed-BLAKE3 pass over the chunk) on a blocking
1638        // thread, not the async worker: a maximal subtree is ~sqrt(N) leaves of up
1639        // to MAX_CHUNK_SIZE each, so doing this inline would tie up a Tokio worker
1640        // for the whole proof and let a few round-1 requests starve the runtime.
1641        // One chunk is resident at a time, so peak memory is bounded.
1642        let nonce = challenge.nonce;
1643        let peer = challenge.challenged_peer_id;
1644        let leaf_key = *key;
1645        let leaf = match tokio::task::spawn_blocking(move || {
1646            crate::replication::subtree::subtree_leaf(&nonce, &peer, &leaf_key, &bytes)
1647        })
1648        .await
1649        {
1650            Ok(leaf) => leaf,
1651            Err(e) => {
1652                warn!(
1653                    "Subtree audit: leaf hashing task failed for key {}: {e}",
1654                    hex::encode(key)
1655                );
1656                return SubtreeAuditResponse::Rejected {
1657                    challenge_id: challenge.challenge_id,
1658                    kind: RejectKind::Transient,
1659                    reason: format!("leaf hashing task error: {e}"),
1660                };
1661            }
1662        };
1663        // The leaf's plain hash is the content address of what was just read, so a
1664        // committed chunk whose file no longer matches its name shows up here at no
1665        // extra cost. See `Round1Work::corrupt_keys` for what happens to it.
1666        if leaf.bytes_hash != *key {
1667            warn!(
1668                "Subtree audit: committed key {} does not hash to its address; \
1669                 reporting it for a recheck so it can be taken out of service \
1670                 and repaired",
1671                hex::encode(key)
1672            );
1673            corrupt_keys.push(*key);
1674        }
1675        leaves.push(leaf);
1676    }
1677
1678    SubtreeAuditResponse::Proof {
1679        challenge_id: challenge.challenge_id,
1680        commitment: built.commitment().clone(),
1681        proof: SubtreeProof {
1682            leaves,
1683            sibling_cut_hashes: plan.sibling_cut_hashes,
1684        },
1685    }
1686}
1687
1688/// Build every requested opening for one committed key from a single hashing
1689/// pass over its bytes: a Bao verified slice (authenticity against the chunk
1690/// address) plus a nonced block-tree opening (possession against round 1's
1691/// `nonced_root`) per block index.
1692///
1693/// The Bao outboard and nonced tree each hash the full chunk, so this builds
1694/// them once (via [`ChunkOpener`]) and serves all `indices` from them rather
1695/// than re-hashing per opening (V2-685 round-2 amplification fix). `indices` is
1696/// deduplicated by the caller. CPU-heavy, so callers run it on a blocking thread.
1697///
1698/// Returns `Err((kind, reason))` for the terminal cases that abort the whole
1699/// response: a block index out of range (only a forged/buggy auditor sends one →
1700/// `Protocol`), or a surprise in-memory Bao extraction error (`Transient`, so an
1701/// honest holder is not branded a deleter).
1702fn build_slice_items_for_key(
1703    nonce: [u8; 32],
1704    peer: [u8; 32],
1705    key: XorName,
1706    bytes: &[u8],
1707    indices: &[u32],
1708) -> Result<Vec<SubtreeSliceItem>, (RejectKind, String)> {
1709    let opener = crate::replication::slice::ChunkOpener::new(&nonce, &peer, &key, bytes);
1710    let count = opener.block_count();
1711    let mut items = Vec::with_capacity(indices.len());
1712    for &block_index in indices {
1713        if block_index >= count {
1714            return Err((
1715                RejectKind::Protocol,
1716                format!(
1717                    "block index {block_index} out of range for key {}",
1718                    hex::encode(key)
1719                ),
1720            ));
1721        }
1722        let bao_slice = match opener.bao_slice(block_index) {
1723            Ok(slice) => slice,
1724            Err(e) => {
1725                warn!(
1726                    "Subtree slice audit: bao extraction failed for key {}: {e}",
1727                    hex::encode(key)
1728                );
1729                return Err((RejectKind::Transient, format!("bao extraction error: {e}")));
1730            }
1731        };
1732        // `block_index < count` was just checked, so siblings must exist. A
1733        // `None` here is an internal proof-building inconsistency, not an honest
1734        // condition: abort the whole response as `Transient` (routes to the
1735        // timeout lane) rather than emit an empty-siblings `Present` that would
1736        // make an honest holder fail its own audit.
1737        let Some(nonced_siblings) = opener.nonced_siblings(block_index) else {
1738            warn!(
1739                "Subtree slice audit: no nonced siblings for in-range block {block_index} of key {}",
1740                hex::encode(key)
1741            );
1742            return Err((
1743                RejectKind::Transient,
1744                format!("nonced sibling build inconsistency for block {block_index}"),
1745            ));
1746        };
1747        items.push(SubtreeSliceItem::Present {
1748            key,
1749            block_index,
1750            bao_slice,
1751            nonced_siblings,
1752        });
1753    }
1754    Ok(items)
1755}
1756
1757/// Handle a round-2 slice challenge (responder side), ADR-0002 / V2-685.
1758///
1759/// The auditor has already structurally verified this node's round-1 subtree
1760/// proof and now opens up to two 1 KiB blocks (a fresh-random block plus the
1761/// final block) of a small freshly-random sample of those leaves. For each
1762/// opening the responder reads the committed chunk and builds a two-chain
1763/// opening (a Bao verified slice for authenticity against the chunk address, and
1764/// a nonced block-tree opening for possession against round 1's `nonced_root`),
1765/// returning [`SubtreeSliceItem::Present`]. If it committed to the key but can no
1766/// longer
1767/// produce the bytes it returns [`SubtreeSliceItem::Absent`], which the auditor
1768/// counts as a provable failure.
1769///
1770/// Openings are authorised against the subtree round 1 actually proved, not
1771/// merely against the pinned commitment. A challenge naming any key outside that
1772/// subtree is refused whole, before any chunk is read, so the work this round can
1773/// cost is bounded by the work the caller already paid for in round 1. An honest
1774/// auditor cannot trip this: it samples only the leaves round 1 returned, and
1775/// without that leaf's `nonced_root` and `content_len` it has nothing to verify
1776/// an answer against.
1777pub async fn handle_subtree_slice_challenge(
1778    challenge: &SubtreeSliceChallenge,
1779    storage: &ChunkStore,
1780    self_peer_id: &PeerId,
1781    is_bootstrapping: bool,
1782    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1783) -> SubtreeSliceResponse {
1784    serve_slice_challenge(
1785        challenge,
1786        storage,
1787        None,
1788        None,
1789        self_peer_id,
1790        is_bootstrapping,
1791        commitment_state,
1792    )
1793    .await
1794}
1795
1796/// [`handle_subtree_slice_challenge`] for a node that also commits pointers
1797/// (ADR-0016), without what round 1 bound for them.
1798///
1799/// Kept for callers of the earlier signature, and answering as it did: a
1800/// committed pointer is served as the record held now and the newest one an
1801/// update replaced, and one no longer held is absent. That fails an honest holder after two updates between
1802/// the rounds, which is what ADR-0019 fixes; the engine uses
1803/// [`handle_subtree_slice_challenge_with_pointer_bindings`].
1804pub async fn handle_subtree_slice_challenge_with_pointers(
1805    challenge: &SubtreeSliceChallenge,
1806    storage: &ChunkStore,
1807    pointers: Option<&PointerStore>,
1808    self_peer_id: &PeerId,
1809    is_bootstrapping: bool,
1810    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1811) -> SubtreeSliceResponse {
1812    serve_slice_challenge(
1813        challenge,
1814        storage,
1815        pointers,
1816        None,
1817        self_peer_id,
1818        is_bootstrapping,
1819        commitment_state,
1820    )
1821    .await
1822}
1823
1824/// [`handle_subtree_slice_challenge`] for a node that also commits pointers
1825/// (ADR-0016): a committed pointer is answered with its whole signed record,
1826/// the one `bound` says round 1 read (ADR-0019).
1827pub async fn handle_subtree_slice_challenge_with_pointer_bindings(
1828    challenge: &SubtreeSliceChallenge,
1829    storage: &ChunkStore,
1830    pointers: Option<&PointerStore>,
1831    bound: &PointerBindings,
1832    self_peer_id: &PeerId,
1833    is_bootstrapping: bool,
1834    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1835) -> SubtreeSliceResponse {
1836    serve_slice_challenge(
1837        challenge,
1838        storage,
1839        pointers,
1840        Some(bound),
1841        self_peer_id,
1842        is_bootstrapping,
1843        commitment_state,
1844    )
1845    .await
1846}
1847
1848/// The body of the slice-challenge handlers. `bound` is `None` for the
1849/// earlier entry point, which serves pointers as it did before ADR-0019.
1850#[allow(clippy::too_many_lines, clippy::too_many_arguments)]
1851async fn serve_slice_challenge(
1852    challenge: &SubtreeSliceChallenge,
1853    storage: &ChunkStore,
1854    pointers: Option<&PointerStore>,
1855    bound: Option<&PointerBindings>,
1856    self_peer_id: &PeerId,
1857    is_bootstrapping: bool,
1858    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1859) -> SubtreeSliceResponse {
1860    if is_bootstrapping {
1861        return SubtreeSliceResponse::Bootstrapping {
1862            challenge_id: challenge.challenge_id,
1863        };
1864    }
1865
1866    if challenge.challenged_peer_id != *self_peer_id.as_bytes() {
1867        return SubtreeSliceResponse::Rejected {
1868            challenge_id: challenge.challenge_id,
1869            kind: RejectKind::Protocol,
1870            reason: "challenged_peer_id does not match this node".to_string(),
1871        };
1872    }
1873
1874    // An honest auditor opens at most MAX_SLICE_OPENINGS blocks per challenge.
1875    // Reject larger requests up front: each opening forces a full chunk read to
1876    // build its proof, so an oversized request is a disk-read amplification lever
1877    // for a forged auditor.
1878    if challenge.openings.len() > MAX_SLICE_OPENINGS {
1879        let requested = challenge.openings.len();
1880        return SubtreeSliceResponse::Rejected {
1881            challenge_id: challenge.challenge_id,
1882            kind: RejectKind::Protocol,
1883            reason: format!(
1884                "slice challenge requests {requested} openings; max {MAX_SLICE_OPENINGS} per challenge"
1885            ),
1886        };
1887    }
1888
1889    let Some(state) = commitment_state else {
1890        return SubtreeSliceResponse::Rejected {
1891            challenge_id: challenge.challenge_id,
1892            kind: RejectKind::Protocol,
1893            reason: "no commitment state".to_string(),
1894        };
1895    };
1896    // Resolve the SAME commitment the auditor pinned in round 1. If we no longer
1897    // retain it (rotated past it), reject as `UnknownCommitment`. With audit
1898    // grace removed (ADR-0004 A1) the auditor treats a responsive miss on an
1899    // in-window pin as a confirmed failure — answerability is restart-durable and
1900    // pins are challenged only in-window. We open blocks only for keys committed
1901    // under this pin.
1902    let Some(built) = state.lookup_by_hash(&challenge.expected_commitment_hash) else {
1903        return SubtreeSliceResponse::Rejected {
1904            challenge_id: challenge.challenge_id,
1905            kind: RejectKind::UnknownCommitment,
1906            reason: "unknown commitment hash".to_string(),
1907        };
1908    };
1909
1910    // Coalesce openings by key, preserving first-seen order and deduplicating
1911    // block indices per key, so each committed chunk is read from the store and hashed
1912    // at most once even when the auditor opens several of its blocks (the normal
1913    // random + final pair, or a forged duplicate). Without this a ten-opening
1914    // request could re-read and re-hash the same chunk ten times.
1915    let mut key_order: Vec<XorName> = Vec::new();
1916    let mut indices_by_key: HashMap<XorName, Vec<u32>> = HashMap::new();
1917    for opening in &challenge.openings {
1918        let entry = indices_by_key.entry(opening.key).or_default();
1919        if entry.is_empty() {
1920            key_order.push(opening.key);
1921        }
1922        if !entry.contains(&opening.block_index) {
1923            entry.push(opening.block_index);
1924        }
1925    }
1926
1927    // Coalescing only saves work when keys REPEAT. A forged auditor could still
1928    // spread its MAX_SLICE_OPENINGS across that many DISTINCT keys to force a
1929    // full-chunk read each (up to ~40 MiB). An honest auditor samples at most
1930    // BYTE_SPOTCHECK_MAX leaves, so cap distinct keys to that.
1931    if key_order.len() > BYTE_SPOTCHECK_MAX as usize {
1932        let distinct = key_order.len();
1933        return SubtreeSliceResponse::Rejected {
1934            challenge_id: challenge.challenge_id,
1935            kind: RejectKind::Protocol,
1936            reason: format!(
1937                "slice challenge spans {distinct} distinct keys; max {BYTE_SPOTCHECK_MAX}"
1938            ),
1939        };
1940    }
1941
1942    // Round 2 may open ONLY the leaves round 1 actually proved, not the whole
1943    // pinned commitment. Membership of the pinned tree is the weaker property:
1944    // it would let a cheap round 1 over small records authorise openings against
1945    // large records elsewhere in the commitment, so the work this round costs
1946    // would not be bounded by the work the caller paid for in round 1.
1947    //
1948    // The authorised set is recomputed from `(tree, nonce)` rather than carried
1949    // in the round-1 session. The subtree is a pure function of those two, both
1950    // of which are already pinned — the nonce was matched against the session
1951    // before this handler ran — so recomputing costs one tree walk with no chunk
1952    // reads, while storing the key list would cost up to a full subtree of keys
1953    // per live session.
1954    let plan = match subtree_plan(built.tree(), &challenge.nonce) {
1955        Ok(plan) => plan,
1956        // The tree is ours and round 1 already walked it, so a failure here is
1957        // local inconsistency rather than anything the caller did. Transient
1958        // routes the auditor to the graced timeout lane instead of branding this
1959        // node with a confirmed failure it did not earn.
1960        Err(e) => {
1961            warn!("Subtree slice audit: cannot rebuild the round-1 subtree plan: {e:?}");
1962            return SubtreeSliceResponse::Rejected {
1963                challenge_id: challenge.challenge_id,
1964                kind: RejectKind::Transient,
1965                reason: "cannot rebuild the audited subtree".to_string(),
1966            };
1967        }
1968    };
1969    let authorised: HashSet<XorName> = plan.leaf_keys.iter().copied().collect();
1970
1971    // Refuse the whole challenge before touching storage, matching how an
1972    // over-broad challenge is handled above. An honest auditor cannot reach this:
1973    // it samples only the leaves round 1 returned, and it has no `nonced_root` or
1974    // `content_len` to verify an answer for anything else against, so an opening
1975    // outside the subtree could not tell it anything even if served.
1976    if let Some(outside) = key_order.iter().find(|key| !authorised.contains(*key)) {
1977        return SubtreeSliceResponse::Rejected {
1978            challenge_id: challenge.challenge_id,
1979            kind: RejectKind::Protocol,
1980            reason: format!(
1981                "slice challenge opens {} which is outside the audited subtree",
1982                hex::encode(outside)
1983            ),
1984        };
1985    }
1986
1987    let mut items = Vec::with_capacity(challenge.openings.len());
1988    for key in key_order {
1989        let indices = indices_by_key.remove(&key).unwrap_or_default();
1990        if built.tree().commits_pointer(&key) {
1991            // The record round 1 read, found by the root it reported over it
1992            // among what is held now and every record updates have replaced
1993            // since. The auditor verifies whatever is served, so nothing is
1994            // verified here.
1995            let Some(store) = pointers else {
1996                items.push(SubtreeSliceItem::Absent { key });
1997                continue;
1998            };
1999            let current = match store.record_bytes(&key).await {
2000                Ok(current) => current,
2001                Err(e) => {
2002                    return SubtreeSliceResponse::Rejected {
2003                        challenge_id: challenge.challenge_id,
2004                        kind: RejectKind::Transient,
2005                        reason: format!("pointer read error: {e}"),
2006                    }
2007                }
2008            };
2009            let Some(bound) = bound else {
2010                // As before ADR-0019, the record held and the newest one an
2011                // update replaced; but a node that no longer holds the pointer
2012                // is absent, whatever replaced records it still keeps.
2013                match current {
2014                    Some(current) => {
2015                        let mut records = vec![current];
2016                        records.extend(store.superseded(&key));
2017                        items.push(SubtreeSliceItem::PointerRecord { key, records });
2018                    }
2019                    None => items.push(SubtreeSliceItem::Absent { key }),
2020                }
2021                continue;
2022            };
2023            match pointer_records(
2024                challenge,
2025                &key,
2026                bound.get(&key),
2027                current,
2028                store.superseded_all(&key),
2029            ) {
2030                PointerServe::Record(record) => {
2031                    items.push(SubtreeSliceItem::PointerRecord {
2032                        key,
2033                        records: vec![record],
2034                    });
2035                }
2036                PointerServe::Absent => items.push(SubtreeSliceItem::Absent { key }),
2037                PointerServe::Unavailable => {
2038                    return SubtreeSliceResponse::Rejected {
2039                        challenge_id: challenge.challenge_id,
2040                        kind: RejectKind::Transient,
2041                        reason: format!(
2042                            "cannot serve the record round 1 read for pointer {}",
2043                            hex::encode(key)
2044                        ),
2045                    }
2046                }
2047            }
2048            continue;
2049        }
2050        match serve_committed_key_openings(challenge, storage, key, indices).await {
2051            KeyServe::Items(mut built_items) => items.append(&mut built_items),
2052            KeyServe::Absent => items.push(SubtreeSliceItem::Absent { key }),
2053            KeyServe::Reject(reject) => return reject,
2054        }
2055    }
2056
2057    SubtreeSliceResponse::Items {
2058        challenge_id: challenge.challenge_id,
2059        items,
2060    }
2061}
2062
2063/// What round 2 serves for a committed pointer.
2064enum PointerServe {
2065    /// The record round 1 read.
2066    Record(Vec<u8>),
2067    /// The pointer is no longer held, which is a lost pointer, whatever
2068    /// replaced records this node still keeps in memory.
2069    Absent,
2070    /// The pointer is held, but this node cannot serve the record round 1
2071    /// read: it has aged out or been evicted to keep memory bounded, or no
2072    /// root for it was kept, which a session this node opened never lacks. A
2073    /// local limit, not a lost pointer, so it is reported as one rather than
2074    /// proved wrong.
2075    Unavailable,
2076}
2077
2078/// Choose what round 2 serves for the pointer at `key` (ADR-0019), from the
2079/// record held now and the records updates replaced: the one that reproduces
2080/// the root round 1 reported.
2081///
2082/// Without that root nothing is served for a pointer still held. Neither the
2083/// record held now nor the replaced records kept can show that no update came
2084/// since round 1 read it, since the kept ones are capped, so serving one would
2085/// be a guess that fails the node when it is wrong.
2086fn pointer_records(
2087    challenge: &SubtreeSliceChallenge,
2088    key: &XorName,
2089    bound: Option<&[u8; 32]>,
2090    current: Option<Vec<u8>>,
2091    replaced: Vec<Bytes>,
2092) -> PointerServe {
2093    // A node that no longer holds the pointer has lost it. Records an update
2094    // replaced are kept only to prove what round 1 read; they do not make up
2095    // for the pointer itself being gone.
2096    let Some(current) = current else {
2097        return PointerServe::Absent;
2098    };
2099    let Some(root) = bound else {
2100        return PointerServe::Unavailable;
2101    };
2102    let reproduces = |record: &[u8]| {
2103        nonced_block_root(&challenge.nonce, &challenge.challenged_peer_id, key, record) == *root
2104    };
2105    if reproduces(&current) {
2106        return PointerServe::Record(current);
2107    }
2108    replaced
2109        .into_iter()
2110        .find(|record| reproduces(record))
2111        .map_or(PointerServe::Unavailable, |record| {
2112            PointerServe::Record(Vec::from(record))
2113        })
2114}
2115
2116/// Outcome of serving all requested openings for one committed key.
2117enum KeyServe {
2118    /// Openings built for this key; append to the response.
2119    Items(Vec<SubtreeSliceItem>),
2120    /// Committed but the bytes are gone → provable `Absent`.
2121    Absent,
2122    /// A terminal condition (out-of-range index, read/build error) that aborts
2123    /// the whole response.
2124    Reject(SubtreeSliceResponse),
2125}
2126
2127/// Read a committed key's chunk once and build every requested opening from it.
2128///
2129/// The Bao outboard + nonced tree hash the whole chunk, so the CPU-heavy build
2130/// runs on a blocking thread to keep an audit-responder flood off the Tokio pool.
2131/// `indices` is already deduplicated by the caller.
2132async fn serve_committed_key_openings(
2133    challenge: &SubtreeSliceChallenge,
2134    storage: &ChunkStore,
2135    key: XorName,
2136    indices: Vec<u32>,
2137) -> KeyServe {
2138    let reject = |kind, reason| {
2139        KeyServe::Reject(SubtreeSliceResponse::Rejected {
2140            challenge_id: challenge.challenge_id,
2141            kind,
2142            reason,
2143        })
2144    };
2145    match get_raw_retrying(storage, &key).await {
2146        Ok(Some(bytes)) => {
2147            let nonce = challenge.nonce;
2148            let peer = challenge.challenged_peer_id;
2149            match tokio::task::spawn_blocking(move || {
2150                build_slice_items_for_key(nonce, peer, key, &bytes, &indices)
2151            })
2152            .await
2153            {
2154                Ok(Ok(built_items)) => KeyServe::Items(built_items),
2155                Ok(Err((kind, reason))) => reject(kind, reason),
2156                Err(e) => {
2157                    warn!(
2158                        "Subtree slice audit: proof build task failed for key {}: {e}",
2159                        hex::encode(key)
2160                    );
2161                    reject(
2162                        RejectKind::Transient,
2163                        format!("proof build task error: {e}"),
2164                    )
2165                }
2166            }
2167        }
2168        // Committed key, definitively absent → provable failure (§7: a real "I
2169        // don't hold it" answer, distinct from a read error).
2170        Ok(None) => {
2171            warn!(
2172                "Subtree slice audit: committed key {} requested but bytes absent",
2173                hex::encode(key)
2174            );
2175            KeyServe::Absent
2176        }
2177        // Persistent transient read error after retries → do NOT brand the peer a
2178        // deleter. Reject `Transient`; the auditor routes it to the timeout lane
2179        // so a flaky read never manufactures a confirmed possession failure
2180        // on an honest holder (which also gains no credit).
2181        Err(e) => {
2182            warn!(
2183                "Subtree slice audit: storage read error for committed key {}: {e} \
2184                 (rejecting as transient, not a confirmed failure)",
2185                hex::encode(key)
2186            );
2187            reject(
2188                RejectKind::Transient,
2189                format!("transient storage read error: {e}"),
2190            )
2191        }
2192    }
2193}
2194
2195#[cfg(test)]
2196#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
2197mod tests {
2198    use super::*;
2199    use crate::replication::commitment_state::BuiltCommitment;
2200    use crate::replication::subtree::{build_subtree_proof, SubtreeLeaf};
2201    use saorsa_pqc::api::sig::ml_dsa_65;
2202    use std::time::Instant;
2203
2204    /// ADR-0004 A1 grade flip (grace removed): a responsive `UnknownCommitment`
2205    /// or `Protocol` rejection is a CONFIRMED failure; only `Transient` routes to
2206    /// the timeout lane. This pure decision backs both audit rounds
2207    /// (`Confirmed → AuditFailureReason::Rejected` / `SliceRound::Rejected`;
2208    /// `TimeoutLane → AuditFailureReason::Timeout` + pinned-credit revocation).
2209    #[test]
2210    fn grade_reject_removes_grace_for_unknown_commitment() {
2211        assert_eq!(
2212            grade_reject(RejectKind::UnknownCommitment),
2213            RejectGrade::Confirmed,
2214            "an unanswerable pinned root is now a confirmed failure, not graced"
2215        );
2216        assert_eq!(grade_reject(RejectKind::Protocol), RejectGrade::Confirmed);
2217        assert_eq!(
2218            grade_reject(RejectKind::Transient),
2219            RejectGrade::TimeoutLane,
2220            "a transient read error routes to the timeout lane (no confirmed penalty)"
2221        );
2222    }
2223
2224    /// A peer id for classification tests (never dialled).
2225    fn classify_peer() -> PeerId {
2226        PeerId::from_bytes([0x5Au8; 32])
2227    }
2228
2229    // A node that answers round 1 with a valid signed proof and then claims
2230    // `Bootstrapping` in round 2 is contradicting itself: a bootstrapping node
2231    // has no committed data to prove. Grading that as a graced timeout would be
2232    // the cheapest possible way to dodge every possession check while KEEPING
2233    // the holder credit earned in round 1 — so it must be a confirmed failure.
2234    #[test]
2235    fn responsive_bootstrap_is_a_confirmed_failure_not_a_graced_timeout() {
2236        let id = 4242u64;
2237        let round = classify_slice_response(
2238            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Bootstrapping {
2239                challenge_id: id,
2240            }),
2241            id,
2242            &classify_peer(),
2243        );
2244        assert!(
2245            matches!(round, SliceRound::ResponsiveBootstrap),
2246            "mid-audit Bootstrapping must classify as ResponsiveBootstrap"
2247        );
2248
2249        // The production arm maps `ResponsiveBootstrap` alongside `Rejected` to
2250        // `AuditFailureReason::Rejected`, and THAT reason is what revokes the
2251        // peer's holder credit wholesale. Pin the policy both ways, since the
2252        // whole point of the classification is landing on the revoking side.
2253        assert!(
2254            super::super::audit_failure_revokes_holder_credit(&AuditFailureReason::Rejected),
2255            "a confirmed round-2 failure must revoke holder credit"
2256        );
2257        assert!(
2258            !super::super::audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
2259            "the timeout lane must not revoke credit WHOLESALE — the contrast that \
2260             makes classifying ResponsiveBootstrap as confirmed load-bearing. The \
2261             timeout lane still drops the pinned commitment's own credit; see \
2262             round2_revokes_pinned_credit"
2263        );
2264    }
2265
2266    /// A responder that answered round 1 and then goes quiet must not keep the
2267    /// holder credit for the commitment under audit.
2268    ///
2269    /// Round 2 names the blocks after the roots are committed, so a responder
2270    /// chooses whether to reply already knowing the draw. If silence kept
2271    /// credit, answering only favourable draws would be free and standing earned
2272    /// once would survive every dodged check afterwards. Both no-proof outcomes
2273    /// therefore drop the pinned credit, while the confirmed lanes are excluded
2274    /// here because they revoke the peer's credit wholesale downstream.
2275    #[test]
2276    fn round2_without_a_proof_drops_the_pinned_commitment_credit() {
2277        assert!(
2278            round2_revokes_pinned_credit(&SliceRound::Timeout),
2279            "silence after a valid round-1 proof must cost the pinned credit"
2280        );
2281        assert!(
2282            round2_revokes_pinned_credit(&SliceRound::TransientReject),
2283            "a transient reject also ends round 2 with no possession proof"
2284        );
2285        assert!(
2286            !round2_revokes_pinned_credit(&SliceRound::Served(vec![])),
2287            "a served response is judged on its contents, not here"
2288        );
2289        for confirmed in [
2290            SliceRound::Rejected,
2291            SliceRound::ResponsiveBootstrap,
2292            SliceRound::Malformed,
2293        ] {
2294            assert!(
2295                !round2_revokes_pinned_credit(&confirmed),
2296                "confirmed failures revoke wholesale downstream, not scoped here"
2297            );
2298        }
2299    }
2300
2301    /// The scoped revocation must not erase credit the peer re-earned under a
2302    /// different commitment: an unanswered round 2 costs the pin it was about,
2303    /// not the peer's whole standing.
2304    #[test]
2305    fn pinned_credit_revocation_is_scoped_to_the_audited_commitment() {
2306        let peer = classify_peer();
2307        let (audited, newer) = ([0x11u8; 32], [0x22u8; 32]);
2308        let key: XorName = [0xC3u8; 32];
2309        let now = Instant::now();
2310        let mut provers = RecentProvers::new();
2311        provers.record_proof(key, peer, audited, now);
2312        provers.record_proof(key, peer, newer, now);
2313
2314        // What `verify_subtree_response` does when round 2 yields no proof.
2315        provers.forget_commitment(&audited);
2316
2317        assert!(
2318            !provers.is_credited_holder(&key, &peer, &audited),
2319            "credit for the audited pin must be gone after an unanswered round 2"
2320        );
2321        assert!(
2322            provers.is_credited_holder(&key, &peer, &newer),
2323            "credit re-earned under a newer commitment must survive"
2324        );
2325    }
2326
2327    // Every classification arm is guarded on `challenge_id`. A responder must not
2328    // be able to answer the challenge it was actually sent with a body minted for
2329    // a different one — in particular it must not downgrade a live challenge by
2330    // replaying a `Bootstrapping` or `Transient` body from another exchange.
2331    #[test]
2332    fn slice_response_for_another_challenge_is_malformed() {
2333        let (sent, other) = (7u64, 8u64);
2334        let peer = classify_peer();
2335        let bodies = [
2336            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Bootstrapping {
2337                challenge_id: other,
2338            }),
2339            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Items {
2340                challenge_id: other,
2341                items: vec![],
2342            }),
2343            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Rejected {
2344                challenge_id: other,
2345                kind: RejectKind::Transient,
2346                reason: String::new(),
2347            }),
2348        ];
2349        for body in bodies {
2350            assert!(
2351                matches!(
2352                    classify_slice_response(body, sent, &peer),
2353                    SliceRound::Malformed
2354                ),
2355                "a body carrying another challenge_id must be malformed"
2356            );
2357        }
2358
2359        // A non-round-2 body on the round-2 path is malformed too.
2360        assert!(matches!(
2361            classify_slice_response(
2362                ReplicationMessageBody::SubtreeAuditResponse(
2363                    crate::replication::protocol::SubtreeAuditResponse::Bootstrapping {
2364                        challenge_id: sent,
2365                    }
2366                ),
2367                sent,
2368                &peer,
2369            ),
2370            SliceRound::Malformed
2371        ));
2372    }
2373
2374    // The two-round audit splits into SHIPPED pure functions exercised directly
2375    // here (no reimplementation that could drift):
2376    //   - round 1: `evaluate_subtree_structure` (pin/identity/signature +
2377    //     structural root rebuild),
2378    //   - sampling: `random_spotcheck_leaves` (3..=5 FRESHLY-RANDOM leaves chosen
2379    //     after the proof is in hand — see its doc for the soundness argument), and
2380    //   - round 2: `verify_slice_response` (decode the Bao slice against the chunk
2381    //     address + fold the nonced opening to the round-1 `nonced_root`, both from
2382    //     what the RESPONDER served — the auditor holds nothing).
2383
2384    fn key(i: u32) -> XorName {
2385        let mut k = [0u8; 32];
2386        k[..4].copy_from_slice(&i.to_be_bytes());
2387        k
2388    }
2389
2390    // The auditor's per-opening matcher returns the FIRST item with a matching
2391    // identity, so an oversized, unsolicited, or colliding response must be
2392    // rejected as malformed BEFORE matching — otherwise item order (or padding)
2393    // could decide the verdict or force quadratic validation work.
2394    #[test]
2395    fn verify_slice_response_rejects_malformed_item_sets() {
2396        let leaf = |k: XorName| SubtreeLeaf {
2397            key: k,
2398            bytes_hash: [0u8; 32],
2399            content_len: 0,
2400            nonced_root: [0u8; 32],
2401        };
2402        let present = |k: XorName, i: u32| SubtreeSliceItem::Present {
2403            key: k,
2404            block_index: i,
2405            bao_slice: vec![],
2406            nonced_siblings: vec![],
2407        };
2408        let malformed = |verdict| {
2409            matches!(
2410                verdict,
2411                AuditVerdict::Fail(AuditFailureReason::MalformedResponse)
2412            )
2413        };
2414        let nonce = [0u8; 32];
2415        let peer = [0u8; 32];
2416        // The auditor requested (key1, block 0), (key1, block 1), (key2, block 0).
2417        let openings = vec![(leaf(key(1)), 0u32), (leaf(key(1)), 1), (leaf(key(2)), 0)];
2418
2419        // More items than requested openings.
2420        let oversized = vec![
2421            present(key(1), 0),
2422            present(key(1), 1),
2423            present(key(2), 0),
2424            present(key(2), 0),
2425        ];
2426        assert!(malformed(verify_slice_response(
2427            &openings, &nonce, &peer, &oversized
2428        )));
2429
2430        // An item that was not requested.
2431        let unsolicited = vec![present(key(9), 0)];
2432        assert!(malformed(verify_slice_response(
2433            &openings,
2434            &nonce,
2435            &peer,
2436            &unsolicited
2437        )));
2438
2439        // Duplicate (key, block_index).
2440        let dup = vec![present(key(1), 0), present(key(1), 0)];
2441        assert!(malformed(verify_slice_response(
2442            &openings, &nonce, &peer, &dup
2443        )));
2444
2445        // A key that is both Present and Absent.
2446        let conflict = vec![present(key(1), 0), SubtreeSliceItem::Absent { key: key(1) }];
2447        assert!(malformed(verify_slice_response(
2448            &openings, &nonce, &peer, &conflict
2449        )));
2450
2451        // A well-formed, unique, solicited response passes the identity guard (the
2452        // empty proofs then fail verification as DigestMismatch, NOT malformed).
2453        let ok = vec![present(key(1), 0), present(key(1), 1), present(key(2), 0)];
2454        assert!(!malformed(verify_slice_response(
2455            &openings, &nonce, &peer, &ok
2456        )));
2457    }
2458    /// Deterministic chunk content for fixture index `i`. Fixture keys are
2459    /// CONTENT-ADDRESSED (`ckey(i) == BLAKE3(chunk_bytes(i))`), so a committed
2460    /// leaf is `(key, key)` exactly as production, and round 2 serves this content.
2461    fn chunk_bytes(i: u32) -> Vec<u8> {
2462        let mut v = b"chunk-body".to_vec();
2463        v.extend_from_slice(&i.to_le_bytes());
2464        v
2465    }
2466
2467    /// Content-addressed key for fixture index `i` (so `bytes_hash == key`).
2468    fn ckey(i: u32) -> XorName {
2469        *blake3::hash(&chunk_bytes(i)).as_bytes()
2470    }
2471
2472    /// The content behind a committed fixture key (reverse of `ckey`), so round-2
2473    /// fixtures can serve the real bytes for any sampled leaf.
2474    fn content_for_key(k: &XorName) -> Vec<u8> {
2475        (0..16_384u32)
2476            .find(|&i| &ckey(i) == k)
2477            .map(chunk_bytes)
2478            .expect("fixture content for committed key")
2479    }
2480
2481    /// Build an honest committed tree of `n` keys + a valid round-1 proof for
2482    /// `nonce`. Returns `(built, proof, peer_id)`. The auditor pins `built.hash()`.
2483    fn honest(n: u32, nonce: &[u8; 32]) -> (BuiltCommitment, SubtreeProof, [u8; 32]) {
2484        let (pk, sk) = ml_dsa_65().generate_keypair().unwrap();
2485        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
2486        let pk_b = pk.to_bytes();
2487        // Content-addressed: bytes_hash == key, exactly as production commits.
2488        let entries: Vec<_> = (0..n).map(|i| (ckey(i), ckey(i))).collect();
2489        let built = BuiltCommitment::build(entries, &peer_id, &sk, &pk_b).unwrap();
2490        let proof =
2491            build_subtree_proof(built.tree(), nonce, &peer_id, |k| Some(content_for_key(k)))
2492                .unwrap();
2493        (built, proof, peer_id)
2494    }
2495
2496    /// Round-1 verdict against the pinned commitment.
2497    fn structure(
2498        built: &BuiltCommitment,
2499        proof: &SubtreeProof,
2500        nonce: &[u8; 32],
2501        peer: &[u8; 32],
2502    ) -> Result<(), AuditFailureReason> {
2503        evaluate_subtree_structure(built.commitment(), proof, nonce, &built.hash(), peer)
2504    }
2505
2506    /// The 3..=5 spot-check leaves the auditor would open in round 2. Now
2507    /// freshly-random (post-proof) rather than nonce-derived; the `_nonce`/
2508    /// `_key_count` params are kept so existing call sites read unchanged.
2509    fn sample<'a>(
2510        proof: &'a SubtreeProof,
2511        _nonce: &[u8; 32],
2512        _key_count: u32,
2513    ) -> Vec<&'a SubtreeLeaf> {
2514        random_spotcheck_leaves(proof, 8u32.clamp(BYTE_SPOTCHECK_MIN, BYTE_SPOTCHECK_MAX))
2515    }
2516
2517    /// Pair each sampled leaf with a block index for round 2. The fixtures use
2518    /// short (single-block) chunks, so block 0 is the only block; the production
2519    /// auditor draws a fresh random index via `random_block_index`.
2520    fn openings_for(sample: &[&SubtreeLeaf]) -> Vec<(SubtreeLeaf, u32)> {
2521        sample.iter().map(|l| ((*l).clone(), 0u32)).collect()
2522    }
2523
2524    /// Honest responder: for each opening build a real Bao slice + nonced opening
2525    /// from the true chunk content, exactly as `handle_subtree_slice_challenge`
2526    /// would.
2527    fn served_honest_items(
2528        openings: &[(SubtreeLeaf, u32)],
2529        nonce: &[u8; 32],
2530        peer: &[u8; 32],
2531    ) -> Vec<SubtreeSliceItem> {
2532        openings
2533            .iter()
2534            .map(|(leaf, block_index)| {
2535                let content = content_for_key(&leaf.key);
2536                let bao_slice =
2537                    crate::replication::slice::extract_block_slice(&content, *block_index).unwrap();
2538                let nonced_siblings = crate::replication::slice::nonced_block_siblings(
2539                    nonce,
2540                    peer,
2541                    &leaf.key,
2542                    &content,
2543                    *block_index,
2544                )
2545                .unwrap();
2546                SubtreeSliceItem::Present {
2547                    key: leaf.key,
2548                    block_index: *block_index,
2549                    bao_slice,
2550                    nonced_siblings,
2551                }
2552            })
2553            .collect()
2554    }
2555
2556    // ---- round 1: structure --------------------------------------------------
2557
2558    #[test]
2559    fn honest_structure_then_bytes_passes() {
2560        let nonce = [9u8; 32];
2561        let (built, proof, peer) = honest(400, &nonce);
2562        // Round 1.
2563        assert!(structure(&built, &proof, &nonce, &peer).is_ok());
2564        // Round 2: honest responder opens real slices for the sample.
2565        let s = sample(&proof, &nonce, built.commitment().key_count);
2566        assert!(!s.is_empty(), "expected a non-empty sample");
2567        let openings = openings_for(&s);
2568        let items = served_honest_items(&openings, &nonce, &peer);
2569        match verify_slice_response(&openings, &nonce, &peer, &items) {
2570            AuditVerdict::Pass { checked } => assert!(checked >= 1, "must verify >=1 leaf"),
2571            other @ AuditVerdict::Fail(_) => panic!("expected Pass, got {other:?}"),
2572        }
2573    }
2574
2575    /// Possession-forgery guard: a peer that signs a commitment whose leaves
2576    /// decouple the credited `key` from the authenticated content hash
2577    /// (`bytes_hash != key`) is rejected at round 1 — even though the structural
2578    /// root still rebuilds from `(key, bytes_hash)`. Without the guard such a peer
2579    /// could earn holder credit for an expensive address `key` while only proving
2580    /// possession of an unrelated (e.g. one-byte) chunk hashing to `bytes_hash`.
2581    #[test]
2582    fn leaf_with_bytes_hash_decoupled_from_key_is_rejected() {
2583        let nonce = [5u8; 32];
2584        let (pk, sk) = ml_dsa_65().generate_keypair().unwrap();
2585        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
2586        let pk_b = pk.to_bytes();
2587        // Every leaf commits (key, bytes_hash) with bytes_hash != key.
2588        let entries: Vec<_> = (0..64u32).map(|i| (ckey(i), ckey(i + 10_000))).collect();
2589        let built = BuiltCommitment::build(entries, &peer_id, &sk, &pk_b).unwrap();
2590        let proof =
2591            build_subtree_proof(built.tree(), &nonce, &peer_id, |k| Some(content_for_key(k)))
2592                .unwrap();
2593        // The structural root rebuilds (it is a genuinely signed tree), so the
2594        // decoupled-address gate is what must reject it.
2595        assert_eq!(
2596            structure(&built, &proof, &nonce, &peer_id),
2597            Err(AuditFailureReason::DigestMismatch),
2598            "a leaf whose bytes_hash != key must be rejected at round 1"
2599        );
2600    }
2601
2602    #[test]
2603    fn commitment_bound_to_another_peer_rejected() {
2604        let nonce = [3u8; 32];
2605        let (built, proof, _peer) = honest(200, &nonce);
2606        let other = [0xAAu8; 32];
2607        assert_eq!(
2608            structure(&built, &proof, &nonce, &other),
2609            Err(AuditFailureReason::Rejected)
2610        );
2611    }
2612
2613    #[test]
2614    fn wrong_pinned_commitment_rejected() {
2615        let nonce = [3u8; 32];
2616        let (built, proof, peer) = honest(200, &nonce);
2617        let mut wrong_pin = built.hash();
2618        wrong_pin[0] ^= 0x01;
2619        assert_eq!(
2620            evaluate_subtree_structure(built.commitment(), &proof, &nonce, &wrong_pin, &peer),
2621            Err(AuditFailureReason::Rejected)
2622        );
2623    }
2624
2625    #[test]
2626    fn tampered_leaf_structure_rejected() {
2627        let nonce = [3u8; 32];
2628        let (built, mut proof, peer) = honest(200, &nonce);
2629        if let Some(first) = proof.leaves.first_mut() {
2630            first.bytes_hash[0] ^= 0x01; // breaks root reconstruction
2631        }
2632        assert_eq!(
2633            structure(&built, &proof, &nonce, &peer),
2634            Err(AuditFailureReason::DigestMismatch)
2635        );
2636    }
2637
2638    #[test]
2639    fn wrong_leaf_count_structure_rejected() {
2640        let nonce = [3u8; 32];
2641        let (built, mut proof, peer) = honest(200, &nonce);
2642        proof.leaves.pop();
2643        assert_eq!(
2644            structure(&built, &proof, &nonce, &peer),
2645            Err(AuditFailureReason::DigestMismatch)
2646        );
2647    }
2648
2649    // ---- round 2: responder-served bytes ------------------------------------
2650
2651    #[test]
2652    fn deleter_absent_bytes_is_confirmed_failure() {
2653        // THE headline fix: a node whose round-1 proof is structurally perfect
2654        // but which has DELETED a committed chunk cannot serve its bytes. It
2655        // signals `Absent` for the sampled key → provable lie → confirmed
2656        // failure, reported as `KeyAbsent` because the peer admitted the loss.
2657        // Crucially, the auditor holds NONE of the peer's chunks; the
2658        // verdict depends only on what the responder serves.
2659        let nonce = [9u8; 32];
2660        let (built, proof, peer) = honest(400, &nonce);
2661        assert!(structure(&built, &proof, &nonce, &peer).is_ok());
2662        let s = sample(&proof, &nonce, built.commitment().key_count);
2663        let openings = openings_for(&s);
2664        // Responder returns Absent for the FIRST opening, honest for the rest.
2665        let victim = openings.first().map(|(l, _)| l.key).unwrap();
2666        let mut items = served_honest_items(&openings, &nonce, &peer);
2667        if let Some(slot) = items.first_mut() {
2668            *slot = SubtreeSliceItem::Absent { key: victim };
2669        }
2670        let v = verify_slice_response(&openings, &nonce, &peer, &items);
2671        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::KeyAbsent));
2672    }
2673
2674    #[test]
2675    fn omitted_committed_key_is_confirmed_failure() {
2676        // A responder that simply omits a sampled committed opening from its items
2677        // (neither Present nor Absent) is a confirmed failure just like Absent,
2678        // but it never admitted the loss, so it is a proof failure rather than
2679        // `KeyAbsent`. This is the counterpart to
2680        // `deleter_absent_bytes_is_confirmed_failure`: together they pin that the
2681        // two reasons stay distinguishable in the audit-failure log line.
2682        let nonce = [9u8; 32];
2683        let (built, proof, peer) = honest(400, &nonce);
2684        let s = sample(&proof, &nonce, built.commitment().key_count);
2685        let openings = openings_for(&s);
2686        let mut items = served_honest_items(&openings, &nonce, &peer);
2687        items.remove(0); // omit the first opening entirely
2688        let v = verify_slice_response(&openings, &nonce, &peer, &items);
2689        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
2690    }
2691
2692    #[test]
2693    fn fake_storage_garbage_bytes_is_confirmed_failure() {
2694        // A "fake-storage" responder claims possession but opens a slice built
2695        // from garbage content. The garbage slice does not decode against the
2696        // committed content address (`bytes_hash`), so chain 1 fails → confirmed
2697        // failure. No auditor holdings involved.
2698        let nonce = [9u8; 32];
2699        let (built, proof, peer) = honest(400, &nonce);
2700        let s = sample(&proof, &nonce, built.commitment().key_count);
2701        let openings = openings_for(&s);
2702        let items: Vec<SubtreeSliceItem> = openings
2703            .iter()
2704            .map(|(leaf, bi)| {
2705                let mut garbage = blake3::hash(&leaf.key).as_bytes().to_vec();
2706                garbage.extend_from_slice(b"adversary-fake-storage");
2707                let bao_slice =
2708                    crate::replication::slice::extract_block_slice(&garbage, *bi).unwrap();
2709                let nonced_siblings = crate::replication::slice::nonced_block_siblings(
2710                    &nonce, &peer, &leaf.key, &garbage, *bi,
2711                )
2712                .unwrap();
2713                SubtreeSliceItem::Present {
2714                    key: leaf.key,
2715                    block_index: *bi,
2716                    bao_slice,
2717                    nonced_siblings,
2718                }
2719            })
2720            .collect();
2721        let v = verify_slice_response(&openings, &nonce, &peer, &items);
2722        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
2723    }
2724
2725    #[test]
2726    fn correct_content_address_but_stale_nonced_root_fails() {
2727        // A responder can serve the real block (chain 1, the Bao slice against the
2728        // address, passes), but if its committed `nonced_root` does not correspond
2729        // to the audit's nonce over that content, the nonced opening (chain 2)
2730        // cannot fold to it. We model a leaf whose committed `nonced_root` was
2731        // built under a DIFFERENT nonce; the honest opening under the audit nonce
2732        // then fails to match it.
2733        let nonce = [9u8; 32];
2734        let (built, mut proof, peer) = honest(400, &nonce);
2735        let other_nonce = [0xEEu8; 32];
2736        for leaf in &mut proof.leaves {
2737            leaf.nonced_root = crate::replication::slice::nonced_block_root(
2738                &other_nonce,
2739                &peer,
2740                &leaf.key,
2741                &content_for_key(&leaf.key),
2742            );
2743        }
2744        let s = sample(&proof, &nonce, built.commitment().key_count);
2745        let openings = openings_for(&s);
2746        let items = served_honest_items(&openings, &nonce, &peer);
2747        let v = verify_slice_response(&openings, &nonce, &peer, &items);
2748        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
2749    }
2750
2751    #[test]
2752    fn auditor_holds_nothing_still_catches_deleter() {
2753        // Explicit contract: the auditor's own storage is irrelevant. A deleter
2754        // is caught purely from its served (absent) response. (Compare the OLD
2755        // design, where an auditor holding none of the chunks went Inconclusive
2756        // and the deleter walked free.)
2757        let nonce = [0x21u8; 32];
2758        let (built, proof, peer) = honest(256, &nonce);
2759        assert!(structure(&built, &proof, &nonce, &peer).is_ok());
2760        let s = sample(&proof, &nonce, built.commitment().key_count);
2761        let openings = openings_for(&s);
2762        // Responder is a total deleter: Absent for every opening.
2763        let items: Vec<SubtreeSliceItem> = openings
2764            .iter()
2765            .map(|(l, _)| SubtreeSliceItem::Absent { key: l.key })
2766            .collect();
2767        let v = verify_slice_response(&openings, &nonce, &peer, &items);
2768        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::KeyAbsent));
2769    }
2770
2771    #[test]
2772    fn admitted_absence_and_failed_proof_are_reported_separately() {
2773        // ROLLOUT DIAGNOSTICS: the two ways a peer fails round 2 must stay
2774        // distinguishable in the failure summary, because they mean different
2775        // things operationally — a peer owning up to lost data versus one whose
2776        // proof did not verify. Before this was split, both rolled up as
2777        // `digest_mismatch_keys` and `absent_keys` was always 0, so a fleet-wide
2778        // audit regression and a fleet-wide data loss looked identical.
2779        let nonce = [0x33u8; 32];
2780        let (built, proof, peer) = honest(256, &nonce);
2781        let s = sample(&proof, &nonce, built.commitment().key_count);
2782        let openings = openings_for(&s);
2783
2784        // Admitted loss → KeyAbsent → counted under `absent_keys`.
2785        let absent_items: Vec<SubtreeSliceItem> = openings
2786            .iter()
2787            .map(|(l, _)| SubtreeSliceItem::Absent { key: l.key })
2788            .collect();
2789        assert_eq!(
2790            verify_slice_response(&openings, &nonce, &peer, &absent_items),
2791            AuditVerdict::Fail(AuditFailureReason::KeyAbsent),
2792        );
2793        let absent_summary = subtree_failure_summary(&AuditFailureReason::KeyAbsent);
2794        assert_eq!(absent_summary.absent_keys, 1);
2795        assert_eq!(absent_summary.digest_mismatch_keys, 0);
2796
2797        // Withheld without admission → DigestMismatch → `digest_mismatch_keys`.
2798        let withheld: Vec<SubtreeSliceItem> = served_honest_items(&openings, &nonce, &peer)
2799            .into_iter()
2800            .skip(1)
2801            .collect();
2802        assert_eq!(
2803            verify_slice_response(&openings, &nonce, &peer, &withheld),
2804            AuditVerdict::Fail(AuditFailureReason::DigestMismatch),
2805        );
2806        let mismatch_summary = subtree_failure_summary(&AuditFailureReason::DigestMismatch);
2807        assert_eq!(mismatch_summary.digest_mismatch_keys, 1);
2808        assert_eq!(mismatch_summary.absent_keys, 0);
2809
2810        // Both are confirmed failures with identical enforcement, so the split is
2811        // diagnostic only: it must not quietly soften what an absent key costs.
2812        assert_eq!(absent_summary.failed_keys, mismatch_summary.failed_keys);
2813    }
2814
2815    #[test]
2816    fn sample_size_is_in_3_to_5_band() {
2817        // ADR-0002: round-2 samples a SMALL surprise set (3..=5) of the proven
2818        // leaves. For a large subtree the sample is capped at 5.
2819        let nonce = [7u8; 32];
2820        let (built, proof, _peer) = honest(1024, &nonce);
2821        let s = sample(&proof, &nonce, built.commitment().key_count);
2822        assert!(
2823            (BYTE_SPOTCHECK_MIN as usize..=BYTE_SPOTCHECK_MAX as usize).contains(&s.len()),
2824            "sample {} must be within 3..=5",
2825            s.len()
2826        );
2827    }
2828
2829    #[test]
2830    fn full_pass_requires_every_sampled_leaf() {
2831        // checked must equal the number of sampled leaves on a pass (no leaf is
2832        // silently skipped — every sampled, committed key must verify).
2833        let nonce = [11u8; 32];
2834        let (built, proof, peer) = honest(400, &nonce);
2835        let s = sample(&proof, &nonce, built.commitment().key_count);
2836        let openings = openings_for(&s);
2837        let items = served_honest_items(&openings, &nonce, &peer);
2838        match verify_slice_response(&openings, &nonce, &peer, &items) {
2839            AuditVerdict::Pass { checked } => assert_eq!(checked, openings.len()),
2840            other @ AuditVerdict::Fail(_) => panic!("expected Pass, got {other:?}"),
2841        }
2842    }
2843
2844    // ---- end-to-end gate composition ----------------------------------------
2845
2846    #[test]
2847    fn structure_fail_short_circuits_before_round_2() {
2848        // A structurally invalid proof is rejected in round 1; the slice challenge
2849        // is never issued. We assert the round-1 gate returns Err so the auditor
2850        // (verify_subtree_response) never reaches request_slice_proof.
2851        let nonce = [5u8; 32];
2852        let (built, mut proof, peer) = honest(300, &nonce);
2853        if let Some(first) = proof.leaves.first_mut() {
2854            first.bytes_hash[0] ^= 0x01;
2855        }
2856        assert!(structure(&built, &proof, &nonce, &peer).is_err());
2857    }
2858
2859    /// Build an honest committed tree whose keys are content-addressed but biased
2860    /// to the FAR half of the XOR space (top bit set), so `observe_closeness`
2861    /// counts them toward `far`. Keys stay content-addressed (`bytes_hash == key`)
2862    /// so round 2 serves real bytes.
2863    fn honest_far(n: u32, nonce: &[u8; 32]) -> (BuiltCommitment, SubtreeProof, [u8; 32]) {
2864        let (pk, sk) = ml_dsa_65().generate_keypair().unwrap();
2865        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
2866        let pk_b = pk.to_bytes();
2867        let mut entries: Vec<(XorName, [u8; 32])> = Vec::new();
2868        let mut i = 0u32;
2869        while entries.len() < n as usize {
2870            let k = ckey(i);
2871            if k[0] >= 0x80 {
2872                entries.push((k, k));
2873            }
2874            i = i.saturating_add(1);
2875        }
2876        let built = BuiltCommitment::build(entries, &peer_id, &sk, &pk_b).unwrap();
2877        let proof =
2878            build_subtree_proof(built.tree(), nonce, &peer_id, |k| Some(content_for_key(k)))
2879                .unwrap();
2880        (built, proof, peer_id)
2881    }
2882
2883    /// ADR-0002 "Closeness" is OBSERVE-ONLY: far-keyed honest proofs verify
2884    /// exactly like near-keyed ones. The verdict (structure + served bytes) is
2885    /// closeness-blind, so a "far/padding" shape can never produce a Fail.
2886    #[test]
2887    fn closeness_is_observe_only_far_keys_still_pass() {
2888        let nonce = [9u8; 32];
2889
2890        let (built_far, proof_far, peer_far) = honest_far(400, &nonce);
2891        assert!(structure(&built_far, &proof_far, &nonce, &peer_far).is_ok());
2892        let sf = sample(&proof_far, &nonce, built_far.commitment().key_count);
2893        let of = openings_for(&sf);
2894        let v_far = verify_slice_response(
2895            &of,
2896            &nonce,
2897            &peer_far,
2898            &served_honest_items(&of, &nonce, &peer_far),
2899        );
2900
2901        let (built_near, proof_near, peer_near) = honest(400, &nonce);
2902        assert!(structure(&built_near, &proof_near, &nonce, &peer_near).is_ok());
2903        let sn = sample(&proof_near, &nonce, built_near.commitment().key_count);
2904        let on = openings_for(&sn);
2905        let v_near = verify_slice_response(
2906            &on,
2907            &nonce,
2908            &peer_near,
2909            &served_honest_items(&on, &nonce, &peer_near),
2910        );
2911
2912        match (&v_far, &v_near) {
2913            (AuditVerdict::Pass { checked: cf }, AuditVerdict::Pass { checked: cn }) => {
2914                assert!(*cf >= 1 && *cn >= 1);
2915            }
2916            other => panic!("both honest proofs must Pass regardless of closeness, got {other:?}"),
2917        }
2918        assert!(
2919            !matches!(v_far, AuditVerdict::Fail(_)),
2920            "far/padding-shaped honest proof must NEVER fail, got {v_far:?}"
2921        );
2922    }
2923
2924    // Unused-leaf constructor guard: keep SubtreeLeaf import meaningful.
2925    #[test]
2926    fn subtree_leaf_is_constructible() {
2927        let _l = SubtreeLeaf {
2928            key: key(1),
2929            bytes_hash: [0u8; 32],
2930            content_len: 0,
2931            nonced_root: [0u8; 32],
2932        };
2933    }
2934}
2935
2936/// Pointers in the storage audit (ADR-0016), driven through the live responders
2937/// against real stores and judged by the auditor's own checks, so a pass here
2938/// is a pass on the network.
2939#[cfg(test)]
2940#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
2941mod pointer_audit_tests {
2942    use super::*;
2943    use crate::replication::commitment::MerkleTree;
2944    use crate::replication::commitment::MAX_COMMITMENT_KEY_COUNT;
2945    use crate::replication::commitment_state::BuiltCommitment;
2946    use crate::replication::subtree::max_subtree_leaves;
2947    use crate::storage::chunk_store::CHUNKS_DIR_NAME;
2948    use crate::storage::ChunkStoreConfig;
2949    use ant_protocol::pointer::{PointerTarget, PointerTargetKind};
2950    use saorsa_pqc::api::sig::ml_dsa_65;
2951    use std::path::PathBuf;
2952    use tempfile::TempDir;
2953    use tokio_util::sync::CancellationToken;
2954
2955    const CHALLENGE_ID: u64 = 7;
2956
2957    /// A one-block chunk, distinct per `i`.
2958    fn chunk(i: u8) -> Vec<u8> {
2959        (0..=255u8).cycle().take(1024).map(|b| b ^ i).collect()
2960    }
2961
2962    /// `owner`'s pointer at `counter`.
2963    fn pointer(owner: u8, counter: u64) -> Pointer {
2964        let (pk, sk) = ml_dsa_65().generate_keypair_from_seed(&[owner; 32]);
2965        let target = PointerTarget::new(PointerTargetKind::Chunk, [owner; 32]);
2966        Pointer::sign(&sk, &pk, counter, target).expect("sign")
2967    }
2968
2969    /// A responder that holds and has committed to `chunks` chunks and
2970    /// `pointers` pointers.
2971    struct Responder {
2972        storage: ChunkStore,
2973        pointers: PointerStore,
2974        state: Arc<ResponderCommitmentState>,
2975        peer: PeerId,
2976        peer_bytes: [u8; 32],
2977        chunk_root: PathBuf,
2978        _dirs: (TempDir, TempDir),
2979    }
2980
2981    impl Responder {
2982        async fn new(chunks: u8, pointers: u8) -> Self {
2983            let chunk_dir = TempDir::new().expect("temp dir");
2984            let storage = ChunkStore::new(ChunkStoreConfig {
2985                root_dir: chunk_dir.path().to_path_buf(),
2986                ..ChunkStoreConfig::test_default()
2987            })
2988            .await
2989            .expect("chunk store");
2990            let pointer_dir = TempDir::new().expect("temp dir");
2991            let pointer_store = PointerStore::new(pointer_dir.path())
2992                .await
2993                .expect("pointer store");
2994
2995            let mut entries = Vec::new();
2996            for i in 0..chunks {
2997                let content = chunk(i);
2998                let address = ChunkStore::compute_address(&content);
2999                storage.put(&address, &content).await.expect("put chunk");
3000                entries.push((address, address));
3001            }
3002            for owner in 0..pointers {
3003                let record = pointer(owner, 1);
3004                pointer_store
3005                    .put_bytes(&record.to_bytes())
3006                    .await
3007                    .expect("put pointer");
3008                entries.push((record.address(), pointer_leaf_hash(&record.address())));
3009            }
3010
3011            let (pk, sk) = ml_dsa_65().generate_keypair().expect("keypair");
3012            let peer_bytes = *blake3::hash(&pk.to_bytes()).as_bytes();
3013            let built =
3014                BuiltCommitment::build(entries, &peer_bytes, &sk, &pk.to_bytes()).expect("build");
3015            let state = Arc::new(ResponderCommitmentState::new());
3016            state.rotate(built);
3017            Self {
3018                storage,
3019                pointers: pointer_store,
3020                state,
3021                peer: PeerId::from_bytes(peer_bytes),
3022                peer_bytes,
3023                chunk_root: chunk_dir.path().to_path_buf(),
3024                _dirs: (chunk_dir, pointer_dir),
3025            }
3026        }
3027
3028        /// Where the file store keeps `key`'s bytes, so a test can rot them.
3029        fn chunk_file(&self, key: &XorName) -> PathBuf {
3030            self.chunk_root
3031                .join(CHUNKS_DIR_NAME)
3032                .join(format!("{:02x}", key.last().copied().unwrap_or(0)))
3033                .join(hex::encode(key))
3034        }
3035
3036        fn committed(&self) -> Arc<BuiltCommitment> {
3037            self.state.current().expect("a current commitment")
3038        }
3039
3040        async fn round1(&self, nonce: [u8; 32]) -> SubtreeAuditResponse {
3041            self.round1_work(nonce).await.response
3042        }
3043
3044        async fn round1_work(&self, nonce: [u8; 32]) -> Round1Work {
3045            let challenge = SubtreeAuditChallenge {
3046                challenge_id: CHALLENGE_ID,
3047                nonce,
3048                challenged_peer_id: self.peer_bytes,
3049                expected_commitment_hash: self.committed().hash(),
3050            };
3051            handle_subtree_challenge_measured_with_pointers(
3052                &challenge,
3053                &self.storage,
3054                Some(&self.pointers),
3055                &self.peer,
3056                false,
3057                Some(&self.state),
3058            )
3059            .await
3060        }
3061
3062        /// Round 2 as the engine serves it: with what round 1 bound for each
3063        /// pointer it opens, as the live session carries it.
3064        async fn round2(
3065            &self,
3066            nonce: [u8; 32],
3067            openings: &[(SubtreeLeaf, u32)],
3068        ) -> Vec<SubtreeSliceItem> {
3069            let bound = openings
3070                .iter()
3071                .map(|(leaf, _)| leaf)
3072                .filter(|leaf| is_pointer_leaf(leaf))
3073                .map(|leaf| (leaf.key, leaf.nonced_root))
3074                .collect();
3075            self.round2_bound(nonce, openings, &bound).await
3076        }
3077
3078        async fn round2_bound(
3079            &self,
3080            nonce: [u8; 32],
3081            openings: &[(SubtreeLeaf, u32)],
3082            bound: &PointerBindings,
3083        ) -> Vec<SubtreeSliceItem> {
3084            match self.round2_response(nonce, openings, bound).await {
3085                SubtreeSliceResponse::Items { items, .. } => items,
3086                other => panic!("expected items, got {other:?}"),
3087            }
3088        }
3089
3090        async fn round2_response(
3091            &self,
3092            nonce: [u8; 32],
3093            openings: &[(SubtreeLeaf, u32)],
3094            bound: &PointerBindings,
3095        ) -> SubtreeSliceResponse {
3096            let challenge = SubtreeSliceChallenge {
3097                challenge_id: CHALLENGE_ID,
3098                nonce,
3099                challenged_peer_id: self.peer_bytes,
3100                expected_commitment_hash: self.committed().hash(),
3101                openings: openings
3102                    .iter()
3103                    .map(|(leaf, block_index)| SubtreeSliceOpening {
3104                        key: leaf.key,
3105                        block_index: *block_index,
3106                    })
3107                    .collect(),
3108            };
3109            handle_subtree_slice_challenge_with_pointer_bindings(
3110                &challenge,
3111                &self.storage,
3112                Some(&self.pointers),
3113                bound,
3114                &self.peer,
3115                false,
3116                Some(&self.state),
3117            )
3118            .await
3119        }
3120
3121        /// Round 1 as the auditor sees it: the proof, checked against the pin.
3122        async fn proved_leaves(&self, nonce: [u8; 32]) -> Vec<SubtreeLeaf> {
3123            let committed = self.committed();
3124            match self.round1(nonce).await {
3125                SubtreeAuditResponse::Proof {
3126                    commitment, proof, ..
3127                } => {
3128                    assert_eq!(
3129                        evaluate_subtree_structure(
3130                            &commitment,
3131                            &proof,
3132                            &nonce,
3133                            &committed.hash(),
3134                            &self.peer_bytes,
3135                        ),
3136                        Ok(()),
3137                        "the auditor must accept the round-1 proof"
3138                    );
3139                    proof.leaves
3140                }
3141                other => panic!("expected a proof, got {other:?}"),
3142            }
3143        }
3144    }
3145
3146    /// A nonce whose audited subtree holds both a pointer and a chunk.
3147    fn mixed_nonce(tree: &MerkleTree) -> [u8; 32] {
3148        (0..=255u8)
3149            .map(|b| [b; 32])
3150            .find(|nonce| {
3151                subtree_plan(tree, nonce).is_ok_and(|plan| {
3152                    plan.leaf_is_pointer.contains(&true) && plan.leaf_is_pointer.contains(&false)
3153                })
3154            })
3155            .expect("some nonce audits a mixed subtree")
3156    }
3157
3158    /// What the auditor opens: every pointer leaf, then chunks, up to the
3159    /// spot-check cap, with the block indices production draws.
3160    fn openings(leaves: &[SubtreeLeaf]) -> Vec<(SubtreeLeaf, u32)> {
3161        let (pointers, chunks): (Vec<_>, Vec<_>) =
3162            leaves.iter().partition(|leaf| is_pointer_leaf(leaf));
3163        pointers
3164            .into_iter()
3165            .take(3)
3166            .chain(chunks)
3167            .take(BYTE_SPOTCHECK_MAX as usize)
3168            .flat_map(|leaf| {
3169                let indices = if is_pointer_leaf(leaf) {
3170                    vec![0]
3171                } else {
3172                    block_indices_for_leaf(leaf.content_len)
3173                };
3174                indices.into_iter().map(|i| (leaf.clone(), i))
3175            })
3176            .collect()
3177    }
3178
3179    fn first_pointer(openings: &[(SubtreeLeaf, u32)]) -> XorName {
3180        openings
3181            .iter()
3182            .map(|(leaf, _)| leaf)
3183            .find(|leaf| is_pointer_leaf(leaf))
3184            .map(|leaf| leaf.key)
3185            .expect("a pointer is opened")
3186    }
3187
3188    #[tokio::test]
3189    async fn a_committed_pointer_is_proved_by_its_signed_record() {
3190        let responder = Responder::new(24, 24).await;
3191        let nonce = mixed_nonce(responder.committed().tree());
3192        let leaves = responder.proved_leaves(nonce).await;
3193        let openings = openings(&leaves);
3194        let items = responder.round2(nonce, &openings).await;
3195
3196        assert!(
3197            items
3198                .iter()
3199                .any(|item| matches!(item, SubtreeSliceItem::PointerRecord { .. })),
3200            "a pointer is proved by its record"
3201        );
3202        assert!(
3203            items
3204                .iter()
3205                .any(|item| matches!(item, SubtreeSliceItem::Present { .. })),
3206            "and the chunks beside it by their slices"
3207        );
3208        assert!(
3209            matches!(
3210                verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3211                AuditVerdict::Pass { .. }
3212            ),
3213            "the auditor must pass an honest holder of both"
3214        );
3215    }
3216
3217    /// A record an update replaces is kept for longer than the slowest audit
3218    /// can take: a round 1 over the largest subtree an auditor waits for,
3219    /// which may have read the pointer at its start, then the session its
3220    /// round 2 must arrive within.
3221    #[test]
3222    fn a_replaced_record_outlives_the_slowest_audit_by_default() {
3223        let largest =
3224            usize::try_from(max_subtree_leaves(MAX_COMMITMENT_KEY_COUNT)).expect("fits a usize");
3225        let slowest =
3226            ReplicationConfig::default().audit_response_timeout(largest) + SUBTREE_SESSION_TTL;
3227        assert!(
3228            SUPERSEDED_RETENTION > slowest,
3229            "{SUPERSEDED_RETENTION:?} must outlive {slowest:?}"
3230        );
3231    }
3232
3233    /// The earlier entry point knows nothing of round 1's roots, and answers
3234    /// as it did before them: an unchanged pointer is served, and passes,
3235    /// rather than reported as a transient failure.
3236    #[tokio::test]
3237    async fn the_earlier_entry_point_still_serves_an_unchanged_pointer() {
3238        let responder = Responder::new(24, 24).await;
3239        let nonce = mixed_nonce(responder.committed().tree());
3240        let openings = openings(&responder.proved_leaves(nonce).await);
3241        let items = legacy_round2(&responder, nonce, &openings).await;
3242        assert!(items
3243            .iter()
3244            .any(|item| matches!(item, SubtreeSliceItem::PointerRecord { .. })));
3245        assert!(matches!(
3246            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3247            AuditVerdict::Pass { .. }
3248        ));
3249    }
3250
3251    /// After one update between the rounds, the earlier entry point serves
3252    /// the record held and the one it replaced, newest first, and passes.
3253    #[tokio::test]
3254    async fn the_earlier_entry_point_still_serves_across_one_update() {
3255        let responder = Responder::new(24, 24).await;
3256        let nonce = mixed_nonce(responder.committed().tree());
3257        let openings = openings(&responder.proved_leaves(nonce).await);
3258        let updated = first_pointer(&openings);
3259        let owner = (0..24u8)
3260            .find(|owner| pointer(*owner, 1).address() == updated)
3261            .expect("the opened pointer is one of ours");
3262        let replaced = responder
3263            .pointers
3264            .record_bytes(&updated)
3265            .await
3266            .expect("read")
3267            .expect("held");
3268        let newer = pointer(owner, 2).to_bytes();
3269        responder.pointers.put_bytes(&newer).await.expect("update");
3270
3271        let items = legacy_round2(&responder, nonce, &openings).await;
3272        let served = items.iter().find_map(|item| match item {
3273            SubtreeSliceItem::PointerRecord { key, records } if *key == updated => {
3274                Some(records.clone())
3275            }
3276            _ => None,
3277        });
3278        assert_eq!(
3279            served,
3280            Some(vec![newer, replaced]),
3281            "the record held, then the one it replaced"
3282        );
3283        assert!(matches!(
3284            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3285            AuditVerdict::Pass { .. }
3286        ));
3287    }
3288
3289    /// Through the earlier entry point too, a pointer updated and then lost
3290    /// is absent, not proved by the record the update replaced.
3291    #[tokio::test]
3292    async fn the_earlier_entry_point_reports_a_lost_pointer_absent() {
3293        let responder = Responder::new(24, 24).await;
3294        let nonce = mixed_nonce(responder.committed().tree());
3295        let openings = openings(&responder.proved_leaves(nonce).await);
3296        let lost = first_pointer(&openings);
3297        let owner = (0..24u8)
3298            .find(|owner| pointer(*owner, 1).address() == lost)
3299            .expect("the opened pointer is one of ours");
3300        responder
3301            .pointers
3302            .put_bytes(&pointer(owner, 2).to_bytes())
3303            .await
3304            .expect("update");
3305        assert!(responder.pointers.delete(&lost).await.expect("delete"));
3306
3307        let items = legacy_round2(&responder, nonce, &openings).await;
3308        assert!(items
3309            .iter()
3310            .any(|item| matches!(item, SubtreeSliceItem::Absent { key } if *key == lost)));
3311        assert_eq!(
3312            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3313            AuditVerdict::Fail(AuditFailureReason::KeyAbsent)
3314        );
3315    }
3316
3317    /// Round 2 through the earlier entry point, which takes no bindings.
3318    async fn legacy_round2(
3319        responder: &Responder,
3320        nonce: [u8; 32],
3321        openings: &[(SubtreeLeaf, u32)],
3322    ) -> Vec<SubtreeSliceItem> {
3323        let challenge = SubtreeSliceChallenge {
3324            challenge_id: CHALLENGE_ID,
3325            nonce,
3326            challenged_peer_id: responder.peer_bytes,
3327            expected_commitment_hash: responder.committed().hash(),
3328            openings: openings
3329                .iter()
3330                .map(|(leaf, block_index)| SubtreeSliceOpening {
3331                    key: leaf.key,
3332                    block_index: *block_index,
3333                })
3334                .collect(),
3335        };
3336        let response = handle_subtree_slice_challenge_with_pointers(
3337            &challenge,
3338            &responder.storage,
3339            Some(&responder.pointers),
3340            &responder.peer,
3341            false,
3342            Some(&responder.state),
3343        )
3344        .await;
3345        let SubtreeSliceResponse::Items { items, .. } = response else {
3346            panic!("expected items, got {response:?}");
3347        };
3348        items
3349    }
3350
3351    /// Round 1 binds each pointer it proves, and nothing else.
3352    #[tokio::test]
3353    async fn round_one_binds_exactly_the_pointers_it_proves() {
3354        let responder = Responder::new(24, 24).await;
3355        let nonce = mixed_nonce(responder.committed().tree());
3356        let response = responder.round1(nonce).await;
3357        let SubtreeAuditResponse::Proof { proof, .. } = &response else {
3358            panic!("expected a proof, got {response:?}");
3359        };
3360        let expected: PointerBindings = proof
3361            .leaves
3362            .iter()
3363            .filter(|leaf| responder.committed().tree().commits_pointer(&leaf.key))
3364            .map(|leaf| (leaf.key, leaf.nonced_root))
3365            .collect();
3366        assert!(!expected.is_empty(), "the subtree holds a pointer");
3367        assert_eq!(pointer_bindings(&response), expected);
3368        assert!(
3369            pointer_bindings(&SubtreeAuditResponse::Bootstrapping {
3370                challenge_id: CHALLENGE_ID
3371            })
3372            .is_empty(),
3373            "only a proof binds anything"
3374        );
3375    }
3376
3377    /// Without the root round 1 reported, which a session this node opened
3378    /// never lacks but a direct caller can, a pointer still held is reported
3379    /// as a transient failure, updated or not: the node cannot show which
3380    /// record round 1 read, and guessing would risk a confirmed failure it did
3381    /// not earn.
3382    #[tokio::test]
3383    async fn without_the_bound_root_a_pointer_is_unavailable_not_failed() {
3384        let responder = Responder::new(24, 24).await;
3385        let nonce = mixed_nonce(responder.committed().tree());
3386        let openings = openings(&responder.proved_leaves(nonce).await);
3387        let unavailable = |response: SubtreeSliceResponse| {
3388            matches!(
3389                response,
3390                SubtreeSliceResponse::Rejected {
3391                    kind: RejectKind::Transient,
3392                    ..
3393                }
3394            )
3395        };
3396
3397        assert!(unavailable(
3398            responder
3399                .round2_response(nonce, &openings, &PointerBindings::new())
3400                .await
3401        ));
3402
3403        let updated = first_pointer(&openings);
3404        let owner = (0..24u8)
3405            .find(|owner| pointer(*owner, 1).address() == updated)
3406            .expect("the opened pointer is one of ours");
3407        responder
3408            .pointers
3409            .put_bytes(&pointer(owner, 2).to_bytes())
3410            .await
3411            .expect("update");
3412        assert!(unavailable(
3413            responder
3414                .round2_response(nonce, &openings, &PointerBindings::new())
3415                .await
3416        ));
3417    }
3418
3419    /// A root round 1 reported that nothing held now reproduces, as when the
3420    /// record it read has been evicted to keep memory bounded, is reported as
3421    /// a transient failure while the pointer is still held, and as absent
3422    /// once nothing at all is.
3423    #[tokio::test]
3424    async fn a_bound_record_no_longer_held_is_unavailable_not_failed() {
3425        let responder = Responder::new(24, 24).await;
3426        let nonce = mixed_nonce(responder.committed().tree());
3427        let openings = openings(&responder.proved_leaves(nonce).await);
3428        let target = first_pointer(&openings);
3429        let evicted: PointerBindings = openings
3430            .iter()
3431            .map(|(leaf, _)| leaf)
3432            .filter(|leaf| is_pointer_leaf(leaf))
3433            .map(|leaf| (leaf.key, [0xEE; 32]))
3434            .collect();
3435
3436        assert!(matches!(
3437            responder.round2_response(nonce, &openings, &evicted).await,
3438            SubtreeSliceResponse::Rejected {
3439                kind: RejectKind::Transient,
3440                ..
3441            }
3442        ));
3443
3444        for (leaf, _) in openings.iter().filter(|(leaf, _)| is_pointer_leaf(leaf)) {
3445            responder.pointers.delete(&leaf.key).await.expect("delete");
3446        }
3447        let items = responder.round2_bound(nonce, &openings, &evicted).await;
3448        assert!(items
3449            .iter()
3450            .any(|item| matches!(item, SubtreeSliceItem::Absent { key } if *key == target)));
3451        assert_eq!(
3452            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3453            AuditVerdict::Fail(AuditFailureReason::KeyAbsent),
3454            "a pointer lost outright is still a confirmed failure"
3455        );
3456    }
3457
3458    /// The commitment binds which pointers are held, not their state, so an
3459    /// owner updating a pointer mid-audit cannot fail the node holding it.
3460    #[tokio::test]
3461    async fn an_update_between_the_rounds_does_not_fail_an_honest_holder() {
3462        let responder = Responder::new(24, 24).await;
3463        let nonce = mixed_nonce(responder.committed().tree());
3464        let openings = openings(&responder.proved_leaves(nonce).await);
3465        let updated = first_pointer(&openings);
3466
3467        let owner = (0..24u8)
3468            .find(|owner| pointer(*owner, 1).address() == updated)
3469            .expect("the opened pointer is one of ours");
3470        responder
3471            .pointers
3472            .put_bytes(&pointer(owner, 2).to_bytes())
3473            .await
3474            .expect("update");
3475
3476        let items = responder.round2(nonce, &openings).await;
3477        assert!(matches!(
3478            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3479            AuditVerdict::Pass { .. }
3480        ));
3481    }
3482
3483    /// However many paid updates land between the rounds, the record round 1
3484    /// bound is the one round 2 serves: the owner's activity is not the
3485    /// holder's failure.
3486    #[tokio::test]
3487    async fn several_updates_between_the_rounds_do_not_fail_an_honest_holder() {
3488        let responder = Responder::new(24, 24).await;
3489        let nonce = mixed_nonce(responder.committed().tree());
3490        let openings = openings(&responder.proved_leaves(nonce).await);
3491        let updated = first_pointer(&openings);
3492
3493        let owner = (0..24u8)
3494            .find(|owner| pointer(*owner, 1).address() == updated)
3495            .expect("the opened pointer is one of ours");
3496        for counter in 2..=4 {
3497            responder
3498                .pointers
3499                .put_bytes(&pointer(owner, counter).to_bytes())
3500                .await
3501                .expect("update");
3502        }
3503
3504        let items = responder.round2(nonce, &openings).await;
3505        assert!(
3506            matches!(
3507                verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3508                AuditVerdict::Pass { .. }
3509            ),
3510            "three updates between the rounds must not fail the holder, got {:?}",
3511            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items)
3512        );
3513        let served = items.iter().find_map(|item| match item {
3514            SubtreeSliceItem::PointerRecord { key, records } if *key == updated => Some(records),
3515            _ => None,
3516        });
3517        assert_eq!(
3518            served,
3519            Some(&vec![pointer_record_bound_in_round_one(&responder, owner)]),
3520            "exactly the record round 1 read, and nothing else"
3521        );
3522    }
3523
3524    /// The record a responder held for `owner`'s pointer before any update:
3525    /// counter 1, as [`Responder::new`] stored it.
3526    fn pointer_record_bound_in_round_one(responder: &Responder, owner: u8) -> Vec<u8> {
3527        let address = pointer(owner, 1).address();
3528        responder
3529            .pointers
3530            .superseded_all(&address)
3531            .last()
3532            .map(|record| record.to_vec())
3533            .expect("the first record is kept")
3534    }
3535
3536    #[tokio::test]
3537    async fn a_node_that_lost_a_committed_pointer_fails_round_one() {
3538        let responder = Responder::new(24, 24).await;
3539        let nonce = mixed_nonce(responder.committed().tree());
3540        let plan = subtree_plan(responder.committed().tree(), &nonce).expect("plan");
3541        let lost = plan
3542            .leaf_keys
3543            .iter()
3544            .zip(&plan.leaf_is_pointer)
3545            .find_map(|(key, is_pointer)| is_pointer.then_some(*key))
3546            .expect("a pointer in the subtree");
3547        assert!(responder.pointers.delete(&lost).await.expect("delete"));
3548
3549        match responder.round1(nonce).await {
3550            SubtreeAuditResponse::Rejected { kind, .. } => {
3551                assert_eq!(
3552                    grade_reject(kind),
3553                    RejectGrade::Confirmed,
3554                    "a lost pointer is a confirmed failure, as a lost chunk is"
3555                );
3556            }
3557            other => panic!("expected a rejection, got {other:?}"),
3558        }
3559    }
3560
3561    /// A node that lost the pointer is absent, even while it still keeps in
3562    /// memory the record an update replaced, and even when that is the very
3563    /// record round 1 read: the replaced records prove what round 1 read, not
3564    /// that the node still holds the pointer.
3565    #[tokio::test]
3566    async fn a_lost_pointer_is_absent_whatever_replaced_records_remain() {
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 lost = first_pointer(&openings);
3571        let owner = (0..24u8)
3572            .find(|owner| pointer(*owner, 1).address() == lost)
3573            .expect("the opened pointer is one of ours");
3574        responder
3575            .pointers
3576            .put_bytes(&pointer(owner, 2).to_bytes())
3577            .await
3578            .expect("update");
3579        assert!(responder.pointers.delete(&lost).await.expect("delete"));
3580        assert!(
3581            !responder.pointers.superseded_all(&lost).is_empty(),
3582            "the record round 1 read is still kept in memory"
3583        );
3584
3585        let items = responder.round2(nonce, &openings).await;
3586        assert!(items
3587            .iter()
3588            .any(|item| matches!(item, SubtreeSliceItem::Absent { key } if *key == lost)));
3589        assert_eq!(
3590            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3591            AuditVerdict::Fail(AuditFailureReason::KeyAbsent)
3592        );
3593    }
3594
3595    #[tokio::test]
3596    async fn a_pointer_lost_after_round_one_is_admitted_absent() {
3597        let responder = Responder::new(24, 24).await;
3598        let nonce = mixed_nonce(responder.committed().tree());
3599        let openings = openings(&responder.proved_leaves(nonce).await);
3600        assert!(responder
3601            .pointers
3602            .delete(&first_pointer(&openings))
3603            .await
3604            .expect("delete"));
3605
3606        let items = responder.round2(nonce, &openings).await;
3607        assert_eq!(
3608            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3609            AuditVerdict::Fail(AuditFailureReason::KeyAbsent)
3610        );
3611    }
3612
3613    /// A node cannot prove it holds one pointer with another, genuinely signed
3614    /// record: the record must belong at the committed address.
3615    #[tokio::test]
3616    async fn another_pointer_is_not_proof_of_the_one_committed() {
3617        let responder = Responder::new(24, 24).await;
3618        let nonce = mixed_nonce(responder.committed().tree());
3619        let openings = openings(&responder.proved_leaves(nonce).await);
3620        let target = first_pointer(&openings);
3621
3622        let mut items = responder.round2(nonce, &openings).await;
3623        replace_records(&mut items, &target, &[pointer(200, 1).to_bytes()]);
3624        assert_eq!(
3625            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3626            AuditVerdict::Fail(AuditFailureReason::DigestMismatch)
3627        );
3628    }
3629
3630    /// A committed chunk whose file has rotted fails round 1 exactly as before,
3631    /// but the responder reports it, and the chunk store's recheck worker then
3632    /// stops the node claiming it, so its next commitment leaves the chunk out
3633    /// and replication can repair it rather than the node failing every audit
3634    /// that lands on that key.
3635    #[tokio::test]
3636    async fn round_one_takes_a_rotted_committed_chunk_out_of_service() {
3637        let responder = Responder::new(24, 0).await;
3638        let committed = responder.committed();
3639        let nonce = [7u8; 32];
3640        let plan = subtree_plan(committed.tree(), &nonce).expect("plan");
3641        let victim = plan.leaf_keys.first().copied().expect("a selected chunk");
3642        let path = responder.chunk_file(&victim);
3643        std::fs::write(&path, b"rotted").expect("corrupt the file");
3644
3645        let work = responder.round1_work(nonce).await;
3646        assert_eq!(
3647            work.corrupt_keys,
3648            vec![victim],
3649            "the responder reports exactly the rotted chunk"
3650        );
3651        match work.response {
3652            SubtreeAuditResponse::Proof {
3653                commitment, proof, ..
3654            } => assert_eq!(
3655                evaluate_subtree_structure(
3656                    &commitment,
3657                    &proof,
3658                    &nonce,
3659                    &committed.hash(),
3660                    &responder.peer_bytes,
3661                ),
3662                Err(AuditFailureReason::DigestMismatch),
3663                "the auditor's verdict on the rotted chunk is unchanged"
3664            ),
3665            other => panic!("expected a proof, got {other:?}"),
3666        }
3667
3668        // What the replication engine does with the report: queue it for the chunk
3669        // store's recheck worker. The worker finishes the recheck it is on before it
3670        // stops, so once it returns the chunk has been dealt with.
3671        responder.storage.report_corrupt(&work.corrupt_keys);
3672        let stop = CancellationToken::new();
3673        let removed = async {
3674            let deadline = Instant::now() + Duration::from_secs(30);
3675            while path.exists() && Instant::now() < deadline {
3676                tokio::time::sleep(Duration::from_millis(5)).await;
3677            }
3678            stop.cancel();
3679        };
3680        tokio::join!(responder.storage.run_corrupt_rechecks(&stop), removed);
3681        let keys = responder.storage.all_keys().await.expect("keys");
3682        assert!(
3683            !keys.contains(&victim),
3684            "the rotted chunk leaves the view the next commitment is built from"
3685        );
3686        assert!(!path.exists(), "the rotted file is removed");
3687        assert_eq!(keys.len(), 23, "every intact chunk stays in service");
3688    }
3689
3690    /// An honest round 1 over intact chunks takes nothing out of service.
3691    #[tokio::test]
3692    async fn round_one_over_intact_chunks_keeps_every_chunk() {
3693        let responder = Responder::new(24, 0).await;
3694        for seed in 0..8u8 {
3695            let corrupt = responder.round1_work([seed; 32]).await.corrupt_keys;
3696            assert!(
3697                corrupt.is_empty(),
3698                "an intact chunk was reported rotted: {corrupt:?}"
3699            );
3700            let leaves = responder.proved_leaves([seed; 32]).await;
3701            assert!(!leaves.is_empty(), "expected round 1 to prove some leaves");
3702        }
3703        assert_eq!(responder.storage.all_keys().await.expect("keys").len(), 24);
3704    }
3705
3706    fn replace_records(items: &mut [SubtreeSliceItem], target: &XorName, with: &[Vec<u8>]) {
3707        for item in items {
3708            if let SubtreeSliceItem::PointerRecord { key, records } = item {
3709                if key == target {
3710                    *records = with.to_vec();
3711                }
3712            }
3713        }
3714    }
3715
3716    /// A node that holds no pointers cannot pass by fetching the few sampled
3717    /// records once round 2 names them: round 1 had to bind each record's
3718    /// bytes under the nonce before anything was sampled, and it had none.
3719    #[tokio::test]
3720    async fn a_relay_that_fetches_records_only_in_round_two_fails() {
3721        let responder = Responder::new(24, 24).await;
3722        let nonce = mixed_nonce(responder.committed().tree());
3723        let genuine = responder.proved_leaves(nonce).await;
3724        let held = openings(&genuine);
3725        // What a relay can say in round 1 without the bytes.
3726        let mut leaves = genuine;
3727        for leaf in leaves.iter_mut().filter(|leaf| is_pointer_leaf(leaf)) {
3728            leaf.nonced_root = [0u8; 32];
3729        }
3730        let openings = openings(&leaves);
3731        // And in round 2 it serves the genuine records, fetched on demand.
3732        let items = responder.round2(nonce, &held).await;
3733        assert_eq!(
3734            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3735            AuditVerdict::Fail(AuditFailureReason::DigestMismatch)
3736        );
3737    }
3738
3739    /// Nor can it pass with another replica's copy of the very state it
3740    /// committed: every signature is randomised, so each replica's bytes, and
3741    /// the nonced root over them, are its own.
3742    #[tokio::test]
3743    async fn another_replicas_copy_of_the_same_state_is_not_proof() {
3744        let responder = Responder::new(24, 24).await;
3745        let nonce = mixed_nonce(responder.committed().tree());
3746        let openings = openings(&responder.proved_leaves(nonce).await);
3747        let target = first_pointer(&openings);
3748        let owner = (0..24u8)
3749            .find(|owner| pointer(*owner, 1).address() == target)
3750            .expect("the opened pointer is one of ours");
3751        let replica = pointer(owner, 1);
3752        assert_eq!(
3753            replica.state_id(),
3754            responder.pointers.state(&target).expect("held").state_id,
3755            "the same state"
3756        );
3757
3758        let mut items = responder.round2(nonce, &openings).await;
3759        replace_records(&mut items, &target, &[replica.to_bytes()]);
3760        assert_eq!(
3761            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3762            AuditVerdict::Fail(AuditFailureReason::DigestMismatch)
3763        );
3764    }
3765
3766    /// A pointer item may carry at most two records. This build serves one;
3767    /// two is what a responder that kept no round-1 roots served (ADR-0016).
3768    #[tokio::test]
3769    async fn a_pointer_item_with_more_than_two_records_is_malformed() {
3770        let responder = Responder::new(24, 24).await;
3771        let nonce = mixed_nonce(responder.committed().tree());
3772        let openings = openings(&responder.proved_leaves(nonce).await);
3773        let target = first_pointer(&openings);
3774        let mut items = responder.round2(nonce, &openings).await;
3775        let held = responder
3776            .pointers
3777            .record_bytes(&target)
3778            .await
3779            .expect("read")
3780            .expect("held");
3781        replace_records(&mut items, &target, &[held.clone(), held.clone(), held]);
3782        assert_eq!(
3783            verify_slice_response(&openings, &nonce, &responder.peer_bytes, &items),
3784            AuditVerdict::Fail(AuditFailureReason::MalformedResponse)
3785        );
3786    }
3787
3788    /// The pointer leaf shape is accepted only at a pointer's exact size, so it
3789    /// cannot stand in for a chunk of another length.
3790    #[tokio::test]
3791    async fn a_pointer_leaf_of_any_other_length_is_refused() {
3792        let responder = Responder::new(24, 24).await;
3793        let nonce = mixed_nonce(responder.committed().tree());
3794        let committed = responder.committed();
3795        let SubtreeAuditResponse::Proof {
3796            commitment,
3797            mut proof,
3798            ..
3799        } = responder.round1(nonce).await
3800        else {
3801            panic!("expected a proof");
3802        };
3803        let leaf = proof
3804            .leaves
3805            .iter_mut()
3806            .find(|leaf| is_pointer_leaf(leaf))
3807            .expect("a pointer leaf");
3808        leaf.content_len = leaf.content_len.saturating_add(1);
3809
3810        assert_eq!(
3811            evaluate_subtree_structure(
3812                &commitment,
3813                &proof,
3814                &nonce,
3815                &committed.hash(),
3816                &responder.peer_bytes,
3817            ),
3818            Err(AuditFailureReason::DigestMismatch)
3819        );
3820    }
3821}