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