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