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/// Openings are authorised against the subtree round 1 actually proved, not
1542/// merely against the pinned commitment. A challenge naming any key outside that
1543/// subtree is refused whole, before any chunk is read, so the work this round can
1544/// cost is bounded by the work the caller already paid for in round 1. An honest
1545/// auditor cannot trip this: it samples only the leaves round 1 returned, and
1546/// without that leaf's `nonced_root` and `content_len` it has nothing to verify
1547/// an answer against.
1548pub async fn handle_subtree_slice_challenge(
1549    challenge: &SubtreeSliceChallenge,
1550    storage: &LmdbStorage,
1551    self_peer_id: &PeerId,
1552    is_bootstrapping: bool,
1553    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1554) -> SubtreeSliceResponse {
1555    if is_bootstrapping {
1556        return SubtreeSliceResponse::Bootstrapping {
1557            challenge_id: challenge.challenge_id,
1558        };
1559    }
1560
1561    if challenge.challenged_peer_id != *self_peer_id.as_bytes() {
1562        return SubtreeSliceResponse::Rejected {
1563            challenge_id: challenge.challenge_id,
1564            kind: RejectKind::Protocol,
1565            reason: "challenged_peer_id does not match this node".to_string(),
1566        };
1567    }
1568
1569    // An honest auditor opens at most MAX_SLICE_OPENINGS blocks per challenge.
1570    // Reject larger requests up front: each opening forces a full chunk read to
1571    // build its proof, so an oversized request is a disk-read amplification lever
1572    // for a forged auditor.
1573    if challenge.openings.len() > MAX_SLICE_OPENINGS {
1574        let requested = challenge.openings.len();
1575        return SubtreeSliceResponse::Rejected {
1576            challenge_id: challenge.challenge_id,
1577            kind: RejectKind::Protocol,
1578            reason: format!(
1579                "slice challenge requests {requested} openings; max {MAX_SLICE_OPENINGS} per challenge"
1580            ),
1581        };
1582    }
1583
1584    let Some(state) = commitment_state else {
1585        return SubtreeSliceResponse::Rejected {
1586            challenge_id: challenge.challenge_id,
1587            kind: RejectKind::Protocol,
1588            reason: "no commitment state".to_string(),
1589        };
1590    };
1591    // Resolve the SAME commitment the auditor pinned in round 1. If we no longer
1592    // retain it (rotated past it), reject as `UnknownCommitment`. With audit
1593    // grace removed (ADR-0004 A1) the auditor treats a responsive miss on an
1594    // in-window pin as a confirmed failure — answerability is restart-durable and
1595    // pins are challenged only in-window. We open blocks only for keys committed
1596    // under this pin.
1597    let Some(built) = state.lookup_by_hash(&challenge.expected_commitment_hash) else {
1598        return SubtreeSliceResponse::Rejected {
1599            challenge_id: challenge.challenge_id,
1600            kind: RejectKind::UnknownCommitment,
1601            reason: "unknown commitment hash".to_string(),
1602        };
1603    };
1604
1605    // Coalesce openings by key, preserving first-seen order and deduplicating
1606    // block indices per key, so each committed chunk is read from LMDB and hashed
1607    // at most once even when the auditor opens several of its blocks (the normal
1608    // random + final pair, or a forged duplicate). Without this a ten-opening
1609    // request could re-read and re-hash the same chunk ten times.
1610    let mut key_order: Vec<XorName> = Vec::new();
1611    let mut indices_by_key: HashMap<XorName, Vec<u32>> = HashMap::new();
1612    for opening in &challenge.openings {
1613        let entry = indices_by_key.entry(opening.key).or_default();
1614        if entry.is_empty() {
1615            key_order.push(opening.key);
1616        }
1617        if !entry.contains(&opening.block_index) {
1618            entry.push(opening.block_index);
1619        }
1620    }
1621
1622    // Coalescing only saves work when keys REPEAT. A forged auditor could still
1623    // spread its MAX_SLICE_OPENINGS across that many DISTINCT keys to force a
1624    // full-chunk read each (up to ~40 MiB). An honest auditor samples at most
1625    // BYTE_SPOTCHECK_MAX leaves, so cap distinct keys to that.
1626    if key_order.len() > BYTE_SPOTCHECK_MAX as usize {
1627        let distinct = key_order.len();
1628        return SubtreeSliceResponse::Rejected {
1629            challenge_id: challenge.challenge_id,
1630            kind: RejectKind::Protocol,
1631            reason: format!(
1632                "slice challenge spans {distinct} distinct keys; max {BYTE_SPOTCHECK_MAX}"
1633            ),
1634        };
1635    }
1636
1637    // Round 2 may open ONLY the leaves round 1 actually proved, not the whole
1638    // pinned commitment. Membership of the pinned tree is the weaker property:
1639    // it would let a cheap round 1 over small records authorise openings against
1640    // large records elsewhere in the commitment, so the work this round costs
1641    // would not be bounded by the work the caller paid for in round 1.
1642    //
1643    // The authorised set is recomputed from `(tree, nonce)` rather than carried
1644    // in the round-1 session. The subtree is a pure function of those two, both
1645    // of which are already pinned — the nonce was matched against the session
1646    // before this handler ran — so recomputing costs one tree walk with no chunk
1647    // reads, while storing the key list would cost up to a full subtree of keys
1648    // per live session.
1649    let plan = match subtree_plan(built.tree(), &challenge.nonce) {
1650        Ok(plan) => plan,
1651        // The tree is ours and round 1 already walked it, so a failure here is
1652        // local inconsistency rather than anything the caller did. Transient
1653        // routes the auditor to the graced timeout lane instead of branding this
1654        // node with a confirmed failure it did not earn.
1655        Err(e) => {
1656            warn!("Subtree slice audit: cannot rebuild the round-1 subtree plan: {e:?}");
1657            return SubtreeSliceResponse::Rejected {
1658                challenge_id: challenge.challenge_id,
1659                kind: RejectKind::Transient,
1660                reason: "cannot rebuild the audited subtree".to_string(),
1661            };
1662        }
1663    };
1664    let authorised: HashSet<XorName> = plan.leaf_keys.iter().copied().collect();
1665
1666    // Refuse the whole challenge before touching storage, matching how an
1667    // over-broad challenge is handled above. An honest auditor cannot reach this:
1668    // it samples only the leaves round 1 returned, and it has no `nonced_root` or
1669    // `content_len` to verify an answer for anything else against, so an opening
1670    // outside the subtree could not tell it anything even if served.
1671    if let Some(outside) = key_order.iter().find(|key| !authorised.contains(*key)) {
1672        return SubtreeSliceResponse::Rejected {
1673            challenge_id: challenge.challenge_id,
1674            kind: RejectKind::Protocol,
1675            reason: format!(
1676                "slice challenge opens {} which is outside the audited subtree",
1677                hex::encode(outside)
1678            ),
1679        };
1680    }
1681
1682    let mut items = Vec::with_capacity(challenge.openings.len());
1683    for key in key_order {
1684        let indices = indices_by_key.remove(&key).unwrap_or_default();
1685        match serve_committed_key_openings(challenge, storage, key, indices).await {
1686            KeyServe::Items(mut built_items) => items.append(&mut built_items),
1687            KeyServe::Absent => items.push(SubtreeSliceItem::Absent { key }),
1688            KeyServe::Reject(reject) => return reject,
1689        }
1690    }
1691
1692    SubtreeSliceResponse::Items {
1693        challenge_id: challenge.challenge_id,
1694        items,
1695    }
1696}
1697
1698/// Outcome of serving all requested openings for one committed key.
1699enum KeyServe {
1700    /// Openings built for this key; append to the response.
1701    Items(Vec<SubtreeSliceItem>),
1702    /// Committed but the bytes are gone → provable `Absent`.
1703    Absent,
1704    /// A terminal condition (out-of-range index, read/build error) that aborts
1705    /// the whole response.
1706    Reject(SubtreeSliceResponse),
1707}
1708
1709/// Read a committed key's chunk once and build every requested opening from it.
1710///
1711/// The Bao outboard + nonced tree hash the whole chunk, so the CPU-heavy build
1712/// runs on a blocking thread to keep an audit-responder flood off the Tokio pool.
1713/// `indices` is already deduplicated by the caller.
1714async fn serve_committed_key_openings(
1715    challenge: &SubtreeSliceChallenge,
1716    storage: &LmdbStorage,
1717    key: XorName,
1718    indices: Vec<u32>,
1719) -> KeyServe {
1720    let reject = |kind, reason| {
1721        KeyServe::Reject(SubtreeSliceResponse::Rejected {
1722            challenge_id: challenge.challenge_id,
1723            kind,
1724            reason,
1725        })
1726    };
1727    match get_raw_retrying(storage, &key).await {
1728        Ok(Some(bytes)) => {
1729            let nonce = challenge.nonce;
1730            let peer = challenge.challenged_peer_id;
1731            match tokio::task::spawn_blocking(move || {
1732                build_slice_items_for_key(nonce, peer, key, &bytes, &indices)
1733            })
1734            .await
1735            {
1736                Ok(Ok(built_items)) => KeyServe::Items(built_items),
1737                Ok(Err((kind, reason))) => reject(kind, reason),
1738                Err(e) => {
1739                    warn!(
1740                        "Subtree slice audit: proof build task failed for key {}: {e}",
1741                        hex::encode(key)
1742                    );
1743                    reject(
1744                        RejectKind::Transient,
1745                        format!("proof build task error: {e}"),
1746                    )
1747                }
1748            }
1749        }
1750        // Committed key, definitively absent → provable failure (§7: a real "I
1751        // don't hold it" answer, distinct from a read error).
1752        Ok(None) => {
1753            warn!(
1754                "Subtree slice audit: committed key {} requested but bytes absent",
1755                hex::encode(key)
1756            );
1757            KeyServe::Absent
1758        }
1759        // Persistent transient read error after retries → do NOT brand the peer a
1760        // deleter. Reject `Transient`; the auditor routes it to the timeout lane
1761        // so a flaky LMDB read never manufactures a confirmed possession failure
1762        // on an honest holder (which also gains no credit).
1763        Err(e) => {
1764            warn!(
1765                "Subtree slice audit: storage read error for committed key {}: {e} \
1766                 (rejecting as transient, not a confirmed failure)",
1767                hex::encode(key)
1768            );
1769            reject(
1770                RejectKind::Transient,
1771                format!("transient storage read error: {e}"),
1772            )
1773        }
1774    }
1775}
1776
1777#[cfg(test)]
1778#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1779mod tests {
1780    use super::*;
1781    use crate::replication::commitment_state::BuiltCommitment;
1782    use crate::replication::subtree::{build_subtree_proof, SubtreeLeaf};
1783    use saorsa_pqc::api::sig::ml_dsa_65;
1784    use std::time::Instant;
1785
1786    /// ADR-0004 A1 grade flip (grace removed): a responsive `UnknownCommitment`
1787    /// or `Protocol` rejection is a CONFIRMED failure; only `Transient` routes to
1788    /// the timeout lane. This pure decision backs both audit rounds
1789    /// (`Confirmed → AuditFailureReason::Rejected` / `SliceRound::Rejected`;
1790    /// `TimeoutLane → AuditFailureReason::Timeout` + pinned-credit revocation).
1791    #[test]
1792    fn grade_reject_removes_grace_for_unknown_commitment() {
1793        assert_eq!(
1794            grade_reject(RejectKind::UnknownCommitment),
1795            RejectGrade::Confirmed,
1796            "an unanswerable pinned root is now a confirmed failure, not graced"
1797        );
1798        assert_eq!(grade_reject(RejectKind::Protocol), RejectGrade::Confirmed);
1799        assert_eq!(
1800            grade_reject(RejectKind::Transient),
1801            RejectGrade::TimeoutLane,
1802            "a transient read error routes to the timeout lane (no confirmed penalty)"
1803        );
1804    }
1805
1806    /// A peer id for classification tests (never dialled).
1807    fn classify_peer() -> PeerId {
1808        PeerId::from_bytes([0x5Au8; 32])
1809    }
1810
1811    // A node that answers round 1 with a valid signed proof and then claims
1812    // `Bootstrapping` in round 2 is contradicting itself: a bootstrapping node
1813    // has no committed data to prove. Grading that as a graced timeout would be
1814    // the cheapest possible way to dodge every possession check while KEEPING
1815    // the holder credit earned in round 1 — so it must be a confirmed failure.
1816    #[test]
1817    fn responsive_bootstrap_is_a_confirmed_failure_not_a_graced_timeout() {
1818        let id = 4242u64;
1819        let round = classify_slice_response(
1820            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Bootstrapping {
1821                challenge_id: id,
1822            }),
1823            id,
1824            &classify_peer(),
1825        );
1826        assert!(
1827            matches!(round, SliceRound::ResponsiveBootstrap),
1828            "mid-audit Bootstrapping must classify as ResponsiveBootstrap"
1829        );
1830
1831        // The production arm maps `ResponsiveBootstrap` alongside `Rejected` to
1832        // `AuditFailureReason::Rejected`, and THAT reason is what revokes the
1833        // peer's holder credit wholesale. Pin the policy both ways, since the
1834        // whole point of the classification is landing on the revoking side.
1835        assert!(
1836            super::super::audit_failure_revokes_holder_credit(&AuditFailureReason::Rejected),
1837            "a confirmed round-2 failure must revoke holder credit"
1838        );
1839        assert!(
1840            !super::super::audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
1841            "the timeout lane must not revoke credit WHOLESALE — the contrast that \
1842             makes classifying ResponsiveBootstrap as confirmed load-bearing. The \
1843             timeout lane still drops the pinned commitment's own credit; see \
1844             round2_revokes_pinned_credit"
1845        );
1846    }
1847
1848    /// A responder that answered round 1 and then goes quiet must not keep the
1849    /// holder credit for the commitment under audit.
1850    ///
1851    /// Round 2 names the blocks after the roots are committed, so a responder
1852    /// chooses whether to reply already knowing the draw. If silence kept
1853    /// credit, answering only favourable draws would be free and standing earned
1854    /// once would survive every dodged check afterwards. Both no-proof outcomes
1855    /// therefore drop the pinned credit, while the confirmed lanes are excluded
1856    /// here because they revoke the peer's credit wholesale downstream.
1857    #[test]
1858    fn round2_without_a_proof_drops_the_pinned_commitment_credit() {
1859        assert!(
1860            round2_revokes_pinned_credit(&SliceRound::Timeout),
1861            "silence after a valid round-1 proof must cost the pinned credit"
1862        );
1863        assert!(
1864            round2_revokes_pinned_credit(&SliceRound::TransientReject),
1865            "a transient reject also ends round 2 with no possession proof"
1866        );
1867        assert!(
1868            !round2_revokes_pinned_credit(&SliceRound::Served(vec![])),
1869            "a served response is judged on its contents, not here"
1870        );
1871        for confirmed in [
1872            SliceRound::Rejected,
1873            SliceRound::ResponsiveBootstrap,
1874            SliceRound::Malformed,
1875        ] {
1876            assert!(
1877                !round2_revokes_pinned_credit(&confirmed),
1878                "confirmed failures revoke wholesale downstream, not scoped here"
1879            );
1880        }
1881    }
1882
1883    /// The scoped revocation must not erase credit the peer re-earned under a
1884    /// different commitment: an unanswered round 2 costs the pin it was about,
1885    /// not the peer's whole standing.
1886    #[test]
1887    fn pinned_credit_revocation_is_scoped_to_the_audited_commitment() {
1888        let peer = classify_peer();
1889        let (audited, newer) = ([0x11u8; 32], [0x22u8; 32]);
1890        let key: XorName = [0xC3u8; 32];
1891        let now = Instant::now();
1892        let mut provers = RecentProvers::new();
1893        provers.record_proof(key, peer, audited, now);
1894        provers.record_proof(key, peer, newer, now);
1895
1896        // What `verify_subtree_response` does when round 2 yields no proof.
1897        provers.forget_commitment(&audited);
1898
1899        assert!(
1900            !provers.is_credited_holder(&key, &peer, &audited),
1901            "credit for the audited pin must be gone after an unanswered round 2"
1902        );
1903        assert!(
1904            provers.is_credited_holder(&key, &peer, &newer),
1905            "credit re-earned under a newer commitment must survive"
1906        );
1907    }
1908
1909    // Every classification arm is guarded on `challenge_id`. A responder must not
1910    // be able to answer the challenge it was actually sent with a body minted for
1911    // a different one — in particular it must not downgrade a live challenge by
1912    // replaying a `Bootstrapping` or `Transient` body from another exchange.
1913    #[test]
1914    fn slice_response_for_another_challenge_is_malformed() {
1915        let (sent, other) = (7u64, 8u64);
1916        let peer = classify_peer();
1917        let bodies = [
1918            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Bootstrapping {
1919                challenge_id: other,
1920            }),
1921            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Items {
1922                challenge_id: other,
1923                items: vec![],
1924            }),
1925            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Rejected {
1926                challenge_id: other,
1927                kind: RejectKind::Transient,
1928                reason: String::new(),
1929            }),
1930        ];
1931        for body in bodies {
1932            assert!(
1933                matches!(
1934                    classify_slice_response(body, sent, &peer),
1935                    SliceRound::Malformed
1936                ),
1937                "a body carrying another challenge_id must be malformed"
1938            );
1939        }
1940
1941        // A non-round-2 body on the round-2 path is malformed too.
1942        assert!(matches!(
1943            classify_slice_response(
1944                ReplicationMessageBody::SubtreeAuditResponse(
1945                    crate::replication::protocol::SubtreeAuditResponse::Bootstrapping {
1946                        challenge_id: sent,
1947                    }
1948                ),
1949                sent,
1950                &peer,
1951            ),
1952            SliceRound::Malformed
1953        ));
1954    }
1955
1956    // The two-round audit splits into SHIPPED pure functions exercised directly
1957    // here (no reimplementation that could drift):
1958    //   - round 1: `evaluate_subtree_structure` (pin/identity/signature +
1959    //     structural root rebuild),
1960    //   - sampling: `random_spotcheck_leaves` (3..=5 FRESHLY-RANDOM leaves chosen
1961    //     after the proof is in hand — see its doc for the soundness argument), and
1962    //   - round 2: `verify_slice_response` (decode the Bao slice against the chunk
1963    //     address + fold the nonced opening to the round-1 `nonced_root`, both from
1964    //     what the RESPONDER served — the auditor holds nothing).
1965
1966    fn key(i: u32) -> XorName {
1967        let mut k = [0u8; 32];
1968        k[..4].copy_from_slice(&i.to_be_bytes());
1969        k
1970    }
1971
1972    // The auditor's per-opening matcher returns the FIRST item with a matching
1973    // identity, so an oversized, unsolicited, or colliding response must be
1974    // rejected as malformed BEFORE matching — otherwise item order (or padding)
1975    // could decide the verdict or force quadratic validation work.
1976    #[test]
1977    fn verify_slice_response_rejects_malformed_item_sets() {
1978        let leaf = |k: XorName| SubtreeLeaf {
1979            key: k,
1980            bytes_hash: [0u8; 32],
1981            content_len: 0,
1982            nonced_root: [0u8; 32],
1983        };
1984        let present = |k: XorName, i: u32| SubtreeSliceItem::Present {
1985            key: k,
1986            block_index: i,
1987            bao_slice: vec![],
1988            nonced_siblings: vec![],
1989        };
1990        let malformed = |verdict| {
1991            matches!(
1992                verdict,
1993                AuditVerdict::Fail(AuditFailureReason::MalformedResponse)
1994            )
1995        };
1996        let nonce = [0u8; 32];
1997        let peer = [0u8; 32];
1998        // The auditor requested (key1, block 0), (key1, block 1), (key2, block 0).
1999        let openings = vec![(leaf(key(1)), 0u32), (leaf(key(1)), 1), (leaf(key(2)), 0)];
2000
2001        // More items than requested openings.
2002        let oversized = vec![
2003            present(key(1), 0),
2004            present(key(1), 1),
2005            present(key(2), 0),
2006            present(key(2), 0),
2007        ];
2008        assert!(malformed(verify_slice_response(
2009            &openings, &nonce, &peer, &oversized
2010        )));
2011
2012        // An item that was not requested.
2013        let unsolicited = vec![present(key(9), 0)];
2014        assert!(malformed(verify_slice_response(
2015            &openings,
2016            &nonce,
2017            &peer,
2018            &unsolicited
2019        )));
2020
2021        // Duplicate (key, block_index).
2022        let dup = vec![present(key(1), 0), present(key(1), 0)];
2023        assert!(malformed(verify_slice_response(
2024            &openings, &nonce, &peer, &dup
2025        )));
2026
2027        // A key that is both Present and Absent.
2028        let conflict = vec![present(key(1), 0), SubtreeSliceItem::Absent { key: key(1) }];
2029        assert!(malformed(verify_slice_response(
2030            &openings, &nonce, &peer, &conflict
2031        )));
2032
2033        // A well-formed, unique, solicited response passes the identity guard (the
2034        // empty proofs then fail verification as DigestMismatch, NOT malformed).
2035        let ok = vec![present(key(1), 0), present(key(1), 1), present(key(2), 0)];
2036        assert!(!malformed(verify_slice_response(
2037            &openings, &nonce, &peer, &ok
2038        )));
2039    }
2040    /// Deterministic chunk content for fixture index `i`. Fixture keys are
2041    /// CONTENT-ADDRESSED (`ckey(i) == BLAKE3(chunk_bytes(i))`), so a committed
2042    /// leaf is `(key, key)` exactly as production, and round 2 serves this content.
2043    fn chunk_bytes(i: u32) -> Vec<u8> {
2044        let mut v = b"chunk-body".to_vec();
2045        v.extend_from_slice(&i.to_le_bytes());
2046        v
2047    }
2048
2049    /// Content-addressed key for fixture index `i` (so `bytes_hash == key`).
2050    fn ckey(i: u32) -> XorName {
2051        *blake3::hash(&chunk_bytes(i)).as_bytes()
2052    }
2053
2054    /// The content behind a committed fixture key (reverse of `ckey`), so round-2
2055    /// fixtures can serve the real bytes for any sampled leaf.
2056    fn content_for_key(k: &XorName) -> Vec<u8> {
2057        (0..16_384u32)
2058            .find(|&i| &ckey(i) == k)
2059            .map(chunk_bytes)
2060            .expect("fixture content for committed key")
2061    }
2062
2063    /// Build an honest committed tree of `n` keys + a valid round-1 proof for
2064    /// `nonce`. Returns `(built, proof, peer_id)`. The auditor pins `built.hash()`.
2065    fn honest(n: u32, nonce: &[u8; 32]) -> (BuiltCommitment, SubtreeProof, [u8; 32]) {
2066        let (pk, sk) = ml_dsa_65().generate_keypair().unwrap();
2067        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
2068        let pk_b = pk.to_bytes();
2069        // Content-addressed: bytes_hash == key, exactly as production commits.
2070        let entries: Vec<_> = (0..n).map(|i| (ckey(i), ckey(i))).collect();
2071        let built = BuiltCommitment::build(entries, &peer_id, &sk, &pk_b).unwrap();
2072        let proof =
2073            build_subtree_proof(built.tree(), nonce, &peer_id, |k| Some(content_for_key(k)))
2074                .unwrap();
2075        (built, proof, peer_id)
2076    }
2077
2078    /// Round-1 verdict against the pinned commitment.
2079    fn structure(
2080        built: &BuiltCommitment,
2081        proof: &SubtreeProof,
2082        nonce: &[u8; 32],
2083        peer: &[u8; 32],
2084    ) -> Result<(), AuditFailureReason> {
2085        evaluate_subtree_structure(built.commitment(), proof, nonce, &built.hash(), peer)
2086    }
2087
2088    /// The 3..=5 spot-check leaves the auditor would open in round 2. Now
2089    /// freshly-random (post-proof) rather than nonce-derived; the `_nonce`/
2090    /// `_key_count` params are kept so existing call sites read unchanged.
2091    fn sample<'a>(
2092        proof: &'a SubtreeProof,
2093        _nonce: &[u8; 32],
2094        _key_count: u32,
2095    ) -> Vec<&'a SubtreeLeaf> {
2096        random_spotcheck_leaves(proof, 8u32.clamp(BYTE_SPOTCHECK_MIN, BYTE_SPOTCHECK_MAX))
2097    }
2098
2099    /// Pair each sampled leaf with a block index for round 2. The fixtures use
2100    /// short (single-block) chunks, so block 0 is the only block; the production
2101    /// auditor draws a fresh random index via `random_block_index`.
2102    fn openings_for(sample: &[&SubtreeLeaf]) -> Vec<(SubtreeLeaf, u32)> {
2103        sample.iter().map(|l| ((*l).clone(), 0u32)).collect()
2104    }
2105
2106    /// Honest responder: for each opening build a real Bao slice + nonced opening
2107    /// from the true chunk content, exactly as `handle_subtree_slice_challenge`
2108    /// would.
2109    fn served_honest_items(
2110        openings: &[(SubtreeLeaf, u32)],
2111        nonce: &[u8; 32],
2112        peer: &[u8; 32],
2113    ) -> Vec<SubtreeSliceItem> {
2114        openings
2115            .iter()
2116            .map(|(leaf, block_index)| {
2117                let content = content_for_key(&leaf.key);
2118                let bao_slice =
2119                    crate::replication::slice::extract_block_slice(&content, *block_index).unwrap();
2120                let nonced_siblings = crate::replication::slice::nonced_block_siblings(
2121                    nonce,
2122                    peer,
2123                    &leaf.key,
2124                    &content,
2125                    *block_index,
2126                )
2127                .unwrap();
2128                SubtreeSliceItem::Present {
2129                    key: leaf.key,
2130                    block_index: *block_index,
2131                    bao_slice,
2132                    nonced_siblings,
2133                }
2134            })
2135            .collect()
2136    }
2137
2138    // ---- round 1: structure --------------------------------------------------
2139
2140    #[test]
2141    fn honest_structure_then_bytes_passes() {
2142        let nonce = [9u8; 32];
2143        let (built, proof, peer) = honest(400, &nonce);
2144        // Round 1.
2145        assert!(structure(&built, &proof, &nonce, &peer).is_ok());
2146        // Round 2: honest responder opens real slices for the sample.
2147        let s = sample(&proof, &nonce, built.commitment().key_count);
2148        assert!(!s.is_empty());
2149        let openings = openings_for(&s);
2150        let items = served_honest_items(&openings, &nonce, &peer);
2151        match verify_slice_response(&openings, &nonce, &peer, &items) {
2152            AuditVerdict::Pass { checked } => assert!(checked >= 1, "must verify >=1 leaf"),
2153            other @ AuditVerdict::Fail(_) => panic!("expected Pass, got {other:?}"),
2154        }
2155    }
2156
2157    /// Possession-forgery guard: a peer that signs a commitment whose leaves
2158    /// decouple the credited `key` from the authenticated content hash
2159    /// (`bytes_hash != key`) is rejected at round 1 — even though the structural
2160    /// root still rebuilds from `(key, bytes_hash)`. Without the guard such a peer
2161    /// could earn holder credit for an expensive address `key` while only proving
2162    /// possession of an unrelated (e.g. one-byte) chunk hashing to `bytes_hash`.
2163    #[test]
2164    fn leaf_with_bytes_hash_decoupled_from_key_is_rejected() {
2165        let nonce = [5u8; 32];
2166        let (pk, sk) = ml_dsa_65().generate_keypair().unwrap();
2167        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
2168        let pk_b = pk.to_bytes();
2169        // Every leaf commits (key, bytes_hash) with bytes_hash != key.
2170        let entries: Vec<_> = (0..64u32).map(|i| (ckey(i), ckey(i + 10_000))).collect();
2171        let built = BuiltCommitment::build(entries, &peer_id, &sk, &pk_b).unwrap();
2172        let proof =
2173            build_subtree_proof(built.tree(), &nonce, &peer_id, |k| Some(content_for_key(k)))
2174                .unwrap();
2175        // The structural root rebuilds (it is a genuinely signed tree), so the
2176        // decoupled-address gate is what must reject it.
2177        assert_eq!(
2178            structure(&built, &proof, &nonce, &peer_id),
2179            Err(AuditFailureReason::DigestMismatch),
2180            "a leaf whose bytes_hash != key must be rejected at round 1"
2181        );
2182    }
2183
2184    #[test]
2185    fn commitment_bound_to_another_peer_rejected() {
2186        let nonce = [3u8; 32];
2187        let (built, proof, _peer) = honest(200, &nonce);
2188        let other = [0xAAu8; 32];
2189        assert_eq!(
2190            structure(&built, &proof, &nonce, &other),
2191            Err(AuditFailureReason::Rejected)
2192        );
2193    }
2194
2195    #[test]
2196    fn wrong_pinned_commitment_rejected() {
2197        let nonce = [3u8; 32];
2198        let (built, proof, peer) = honest(200, &nonce);
2199        let mut wrong_pin = built.hash();
2200        wrong_pin[0] ^= 0x01;
2201        assert_eq!(
2202            evaluate_subtree_structure(built.commitment(), &proof, &nonce, &wrong_pin, &peer),
2203            Err(AuditFailureReason::Rejected)
2204        );
2205    }
2206
2207    #[test]
2208    fn tampered_leaf_structure_rejected() {
2209        let nonce = [3u8; 32];
2210        let (built, mut proof, peer) = honest(200, &nonce);
2211        if let Some(first) = proof.leaves.first_mut() {
2212            first.bytes_hash[0] ^= 0x01; // breaks root reconstruction
2213        }
2214        assert_eq!(
2215            structure(&built, &proof, &nonce, &peer),
2216            Err(AuditFailureReason::DigestMismatch)
2217        );
2218    }
2219
2220    #[test]
2221    fn wrong_leaf_count_structure_rejected() {
2222        let nonce = [3u8; 32];
2223        let (built, mut proof, peer) = honest(200, &nonce);
2224        proof.leaves.pop();
2225        assert_eq!(
2226            structure(&built, &proof, &nonce, &peer),
2227            Err(AuditFailureReason::DigestMismatch)
2228        );
2229    }
2230
2231    // ---- round 2: responder-served bytes ------------------------------------
2232
2233    #[test]
2234    fn deleter_absent_bytes_is_confirmed_failure() {
2235        // THE headline fix: a node whose round-1 proof is structurally perfect
2236        // but which has DELETED a committed chunk cannot serve its bytes. It
2237        // signals `Absent` for the sampled key → provable lie → confirmed
2238        // failure, reported as `KeyAbsent` because the peer admitted the loss.
2239        // Crucially, the auditor holds NONE of the peer's chunks; the
2240        // verdict depends only on what the responder serves.
2241        let nonce = [9u8; 32];
2242        let (built, proof, peer) = honest(400, &nonce);
2243        assert!(structure(&built, &proof, &nonce, &peer).is_ok());
2244        let s = sample(&proof, &nonce, built.commitment().key_count);
2245        let openings = openings_for(&s);
2246        // Responder returns Absent for the FIRST opening, honest for the rest.
2247        let victim = openings.first().map(|(l, _)| l.key).unwrap();
2248        let mut items = served_honest_items(&openings, &nonce, &peer);
2249        if let Some(slot) = items.first_mut() {
2250            *slot = SubtreeSliceItem::Absent { key: victim };
2251        }
2252        let v = verify_slice_response(&openings, &nonce, &peer, &items);
2253        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::KeyAbsent));
2254    }
2255
2256    #[test]
2257    fn omitted_committed_key_is_confirmed_failure() {
2258        // A responder that simply omits a sampled committed opening from its items
2259        // (neither Present nor Absent) is a confirmed failure just like Absent,
2260        // but it never admitted the loss, so it is a proof failure rather than
2261        // `KeyAbsent`. This is the counterpart to
2262        // `deleter_absent_bytes_is_confirmed_failure`: together they pin that the
2263        // two reasons stay distinguishable in the audit-failure log line.
2264        let nonce = [9u8; 32];
2265        let (built, proof, peer) = honest(400, &nonce);
2266        let s = sample(&proof, &nonce, built.commitment().key_count);
2267        let openings = openings_for(&s);
2268        let mut items = served_honest_items(&openings, &nonce, &peer);
2269        items.remove(0); // omit the first opening entirely
2270        let v = verify_slice_response(&openings, &nonce, &peer, &items);
2271        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
2272    }
2273
2274    #[test]
2275    fn fake_storage_garbage_bytes_is_confirmed_failure() {
2276        // A "fake-storage" responder claims possession but opens a slice built
2277        // from garbage content. The garbage slice does not decode against the
2278        // committed content address (`bytes_hash`), so chain 1 fails → confirmed
2279        // failure. No auditor holdings involved.
2280        let nonce = [9u8; 32];
2281        let (built, proof, peer) = honest(400, &nonce);
2282        let s = sample(&proof, &nonce, built.commitment().key_count);
2283        let openings = openings_for(&s);
2284        let items: Vec<SubtreeSliceItem> = openings
2285            .iter()
2286            .map(|(leaf, bi)| {
2287                let mut garbage = blake3::hash(&leaf.key).as_bytes().to_vec();
2288                garbage.extend_from_slice(b"adversary-fake-storage");
2289                let bao_slice =
2290                    crate::replication::slice::extract_block_slice(&garbage, *bi).unwrap();
2291                let nonced_siblings = crate::replication::slice::nonced_block_siblings(
2292                    &nonce, &peer, &leaf.key, &garbage, *bi,
2293                )
2294                .unwrap();
2295                SubtreeSliceItem::Present {
2296                    key: leaf.key,
2297                    block_index: *bi,
2298                    bao_slice,
2299                    nonced_siblings,
2300                }
2301            })
2302            .collect();
2303        let v = verify_slice_response(&openings, &nonce, &peer, &items);
2304        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
2305    }
2306
2307    #[test]
2308    fn correct_content_address_but_stale_nonced_root_fails() {
2309        // A responder can serve the real block (chain 1, the Bao slice against the
2310        // address, passes), but if its committed `nonced_root` does not correspond
2311        // to the audit's nonce over that content, the nonced opening (chain 2)
2312        // cannot fold to it. We model a leaf whose committed `nonced_root` was
2313        // built under a DIFFERENT nonce; the honest opening under the audit nonce
2314        // then fails to match it.
2315        let nonce = [9u8; 32];
2316        let (built, mut proof, peer) = honest(400, &nonce);
2317        let other_nonce = [0xEEu8; 32];
2318        for leaf in &mut proof.leaves {
2319            leaf.nonced_root = crate::replication::slice::nonced_block_root(
2320                &other_nonce,
2321                &peer,
2322                &leaf.key,
2323                &content_for_key(&leaf.key),
2324            );
2325        }
2326        let s = sample(&proof, &nonce, built.commitment().key_count);
2327        let openings = openings_for(&s);
2328        let items = served_honest_items(&openings, &nonce, &peer);
2329        let v = verify_slice_response(&openings, &nonce, &peer, &items);
2330        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
2331    }
2332
2333    #[test]
2334    fn auditor_holds_nothing_still_catches_deleter() {
2335        // Explicit contract: the auditor's own storage is irrelevant. A deleter
2336        // is caught purely from its served (absent) response. (Compare the OLD
2337        // design, where an auditor holding none of the chunks went Inconclusive
2338        // and the deleter walked free.)
2339        let nonce = [0x21u8; 32];
2340        let (built, proof, peer) = honest(256, &nonce);
2341        assert!(structure(&built, &proof, &nonce, &peer).is_ok());
2342        let s = sample(&proof, &nonce, built.commitment().key_count);
2343        let openings = openings_for(&s);
2344        // Responder is a total deleter: Absent for every opening.
2345        let items: Vec<SubtreeSliceItem> = openings
2346            .iter()
2347            .map(|(l, _)| SubtreeSliceItem::Absent { key: l.key })
2348            .collect();
2349        let v = verify_slice_response(&openings, &nonce, &peer, &items);
2350        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::KeyAbsent));
2351    }
2352
2353    #[test]
2354    fn admitted_absence_and_failed_proof_are_reported_separately() {
2355        // ROLLOUT DIAGNOSTICS: the two ways a peer fails round 2 must stay
2356        // distinguishable in the failure summary, because they mean different
2357        // things operationally — a peer owning up to lost data versus one whose
2358        // proof did not verify. Before this was split, both rolled up as
2359        // `digest_mismatch_keys` and `absent_keys` was always 0, so a fleet-wide
2360        // audit regression and a fleet-wide data loss looked identical.
2361        let nonce = [0x33u8; 32];
2362        let (built, proof, peer) = honest(256, &nonce);
2363        let s = sample(&proof, &nonce, built.commitment().key_count);
2364        let openings = openings_for(&s);
2365
2366        // Admitted loss → KeyAbsent → counted under `absent_keys`.
2367        let absent_items: Vec<SubtreeSliceItem> = openings
2368            .iter()
2369            .map(|(l, _)| SubtreeSliceItem::Absent { key: l.key })
2370            .collect();
2371        assert_eq!(
2372            verify_slice_response(&openings, &nonce, &peer, &absent_items),
2373            AuditVerdict::Fail(AuditFailureReason::KeyAbsent),
2374        );
2375        let absent_summary = subtree_failure_summary(&AuditFailureReason::KeyAbsent);
2376        assert_eq!(absent_summary.absent_keys, 1);
2377        assert_eq!(absent_summary.digest_mismatch_keys, 0);
2378
2379        // Withheld without admission → DigestMismatch → `digest_mismatch_keys`.
2380        let withheld: Vec<SubtreeSliceItem> = served_honest_items(&openings, &nonce, &peer)
2381            .into_iter()
2382            .skip(1)
2383            .collect();
2384        assert_eq!(
2385            verify_slice_response(&openings, &nonce, &peer, &withheld),
2386            AuditVerdict::Fail(AuditFailureReason::DigestMismatch),
2387        );
2388        let mismatch_summary = subtree_failure_summary(&AuditFailureReason::DigestMismatch);
2389        assert_eq!(mismatch_summary.digest_mismatch_keys, 1);
2390        assert_eq!(mismatch_summary.absent_keys, 0);
2391
2392        // Both are confirmed failures with identical enforcement, so the split is
2393        // diagnostic only: it must not quietly soften what an absent key costs.
2394        assert_eq!(absent_summary.failed_keys, mismatch_summary.failed_keys);
2395    }
2396
2397    #[test]
2398    fn sample_size_is_in_3_to_5_band() {
2399        // ADR-0002: round-2 samples a SMALL surprise set (3..=5) of the proven
2400        // leaves. For a large subtree the sample is capped at 5.
2401        let nonce = [7u8; 32];
2402        let (built, proof, _peer) = honest(1024, &nonce);
2403        let s = sample(&proof, &nonce, built.commitment().key_count);
2404        assert!(
2405            (BYTE_SPOTCHECK_MIN as usize..=BYTE_SPOTCHECK_MAX as usize).contains(&s.len()),
2406            "sample {} must be within 3..=5",
2407            s.len()
2408        );
2409    }
2410
2411    #[test]
2412    fn full_pass_requires_every_sampled_leaf() {
2413        // checked must equal the number of sampled leaves on a pass (no leaf is
2414        // silently skipped — every sampled, committed key must verify).
2415        let nonce = [11u8; 32];
2416        let (built, proof, peer) = honest(400, &nonce);
2417        let s = sample(&proof, &nonce, built.commitment().key_count);
2418        let openings = openings_for(&s);
2419        let items = served_honest_items(&openings, &nonce, &peer);
2420        match verify_slice_response(&openings, &nonce, &peer, &items) {
2421            AuditVerdict::Pass { checked } => assert_eq!(checked, openings.len()),
2422            other @ AuditVerdict::Fail(_) => panic!("expected Pass, got {other:?}"),
2423        }
2424    }
2425
2426    // ---- end-to-end gate composition ----------------------------------------
2427
2428    #[test]
2429    fn structure_fail_short_circuits_before_round_2() {
2430        // A structurally invalid proof is rejected in round 1; the slice challenge
2431        // is never issued. We assert the round-1 gate returns Err so the auditor
2432        // (verify_subtree_response) never reaches request_slice_proof.
2433        let nonce = [5u8; 32];
2434        let (built, mut proof, peer) = honest(300, &nonce);
2435        if let Some(first) = proof.leaves.first_mut() {
2436            first.bytes_hash[0] ^= 0x01;
2437        }
2438        assert!(structure(&built, &proof, &nonce, &peer).is_err());
2439    }
2440
2441    /// Build an honest committed tree whose keys are content-addressed but biased
2442    /// to the FAR half of the XOR space (top bit set), so `observe_closeness`
2443    /// counts them toward `far`. Keys stay content-addressed (`bytes_hash == key`)
2444    /// so round 2 serves real bytes.
2445    fn honest_far(n: u32, nonce: &[u8; 32]) -> (BuiltCommitment, SubtreeProof, [u8; 32]) {
2446        let (pk, sk) = ml_dsa_65().generate_keypair().unwrap();
2447        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
2448        let pk_b = pk.to_bytes();
2449        let mut entries: Vec<(XorName, [u8; 32])> = Vec::new();
2450        let mut i = 0u32;
2451        while entries.len() < n as usize {
2452            let k = ckey(i);
2453            if k[0] >= 0x80 {
2454                entries.push((k, k));
2455            }
2456            i = i.saturating_add(1);
2457        }
2458        let built = BuiltCommitment::build(entries, &peer_id, &sk, &pk_b).unwrap();
2459        let proof =
2460            build_subtree_proof(built.tree(), nonce, &peer_id, |k| Some(content_for_key(k)))
2461                .unwrap();
2462        (built, proof, peer_id)
2463    }
2464
2465    /// ADR-0002 "Closeness" is OBSERVE-ONLY: far-keyed honest proofs verify
2466    /// exactly like near-keyed ones. The verdict (structure + served bytes) is
2467    /// closeness-blind, so a "far/padding" shape can never produce a Fail.
2468    #[test]
2469    fn closeness_is_observe_only_far_keys_still_pass() {
2470        let nonce = [9u8; 32];
2471
2472        let (built_far, proof_far, peer_far) = honest_far(400, &nonce);
2473        assert!(structure(&built_far, &proof_far, &nonce, &peer_far).is_ok());
2474        let sf = sample(&proof_far, &nonce, built_far.commitment().key_count);
2475        let of = openings_for(&sf);
2476        let v_far = verify_slice_response(
2477            &of,
2478            &nonce,
2479            &peer_far,
2480            &served_honest_items(&of, &nonce, &peer_far),
2481        );
2482
2483        let (built_near, proof_near, peer_near) = honest(400, &nonce);
2484        assert!(structure(&built_near, &proof_near, &nonce, &peer_near).is_ok());
2485        let sn = sample(&proof_near, &nonce, built_near.commitment().key_count);
2486        let on = openings_for(&sn);
2487        let v_near = verify_slice_response(
2488            &on,
2489            &nonce,
2490            &peer_near,
2491            &served_honest_items(&on, &nonce, &peer_near),
2492        );
2493
2494        match (&v_far, &v_near) {
2495            (AuditVerdict::Pass { checked: cf }, AuditVerdict::Pass { checked: cn }) => {
2496                assert!(*cf >= 1 && *cn >= 1);
2497            }
2498            other => panic!("both honest proofs must Pass regardless of closeness, got {other:?}"),
2499        }
2500        assert!(
2501            !matches!(v_far, AuditVerdict::Fail(_)),
2502            "far/padding-shaped honest proof must NEVER fail, got {v_far:?}"
2503        );
2504    }
2505
2506    // Unused-leaf constructor guard: keep SubtreeLeaf import meaningful.
2507    #[test]
2508    fn subtree_leaf_is_constructible() {
2509        let _l = SubtreeLeaf {
2510            key: key(1),
2511            bytes_hash: [0u8; 32],
2512            content_len: 0,
2513            nonced_root: [0u8; 32],
2514        };
2515    }
2516}