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::sync::Arc;
13use std::time::Duration;
14
15use crate::logging::{debug, info, warn};
16use rand::Rng;
17
18use crate::ant_protocol::XorName;
19use crate::replication::commitment::{commitment_hash, StorageCommitment};
20use crate::replication::commitment_state::ResponderCommitmentState;
21use crate::replication::config::{
22    ReplicationConfig, MAX_BYTE_CHALLENGE_KEYS, REPLICATION_PROTOCOL_ID,
23};
24use crate::replication::protocol::{
25    RejectKind, ReplicationMessage, ReplicationMessageBody, SubtreeAuditChallenge,
26    SubtreeAuditResponse, SubtreeByteChallenge, SubtreeByteItem, SubtreeByteResponse,
27};
28use crate::replication::recent_provers::RecentProvers;
29use crate::replication::subtree::{
30    select_subtree_path, subtree_plan, verify_subtree_proof, StructureVerdict, SubtreeProof,
31};
32use crate::replication::types::{AuditFailureReason, AuditFailureSummary, FailureEvidence};
33use crate::storage::LmdbStorage;
34use saorsa_core::identity::PeerId;
35use saorsa_core::P2PNode;
36use tokio::sync::RwLock;
37
38// The gossip-triggered auditor shares the engine's [`AuditTickResult`] outcome
39// type with the responsible-chunk audit (defined in [`super::audit`]), so the
40// engine can dispatch both audits' results through one match.
41use crate::replication::audit::AuditTickResult;
42
43// ---------------------------------------------------------------------------
44// Auditor side
45// ---------------------------------------------------------------------------
46
47/// ADR-0002 round-2 byte challenge samples a SMALL surprise set of the proven
48/// leaves (3..=5). Small enough that the responder's honest local-disk read of
49/// the original chunks stays well inside the possession-in-time deadline, while
50/// a relay forced to fetch them over the network blows it; large enough that
51/// faking a fraction `x` of leaves survives only `(1 - x)^k`.
52const BYTE_SPOTCHECK_MIN: u32 = 3;
53const BYTE_SPOTCHECK_MAX: u32 = 5;
54
55/// ADR-0004 A1: with grace removed, the responder retries a TRANSIENT chunk-read
56/// error a few times before rejecting `Transient` (which routes to the timeout
57/// lane). A momentary disk blip usually clears within these attempts; only a
58/// persistent read failure — the node genuinely cannot serve committed bytes —
59/// falls through. Total added latency ((attempts − 1) × backoff) stays well inside the
60/// audit response deadline.
61const AUDIT_READ_RETRY_ATTEMPTS: u32 = 3;
62const AUDIT_READ_RETRY_BACKOFF: Duration = Duration::from_millis(200);
63
64/// Read a committed chunk's bytes, retrying a transient read error up to
65/// [`AUDIT_READ_RETRY_ATTEMPTS`] times with [`AUDIT_READ_RETRY_BACKOFF`] between
66/// tries. `Ok(None)` (bytes definitively absent — real loss) is NOT retried; only
67/// an `Err` (transient IO) is. A persistent `Err` is returned so the caller emits
68/// `RejectKind::Transient` (timeout lane).
69async fn get_raw_retrying(
70    storage: &LmdbStorage,
71    key: &XorName,
72) -> crate::error::Result<Option<Vec<u8>>> {
73    let mut attempt = 1u32;
74    loop {
75        match storage.get_raw(key).await {
76            Ok(v) => return Ok(v),
77            Err(e) if attempt < AUDIT_READ_RETRY_ATTEMPTS => {
78                debug!(
79                    "Audit: transient read error for {} (attempt {attempt}/{AUDIT_READ_RETRY_ATTEMPTS}): {e}; retrying",
80                    hex::encode(key)
81                );
82                attempt += 1;
83                tokio::time::sleep(AUDIT_READ_RETRY_BACKOFF).await;
84            }
85            Err(e) => return Err(e),
86        }
87    }
88}
89
90/// How the auditor grades a *responsive* audit rejection (ADR-0004 A1: grace
91/// removed). The decision is a pure function of the [`RejectKind`] so it can be
92/// unit-tested independently of the P2P/side-effect machinery.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94enum RejectGrade {
95    /// Provable misbehaviour → confirmed failure (trust penalty + credit
96    /// revocation downstream).
97    Confirmed,
98    /// Non-response/timeout lane: no trust penalty, but the pinned commitment's
99    /// holder credit is revoked (the peer answered but could not prove possession).
100    TimeoutLane,
101}
102
103/// Grade a responsive rejection. Repudiating a pinned root (`UnknownCommitment`)
104/// or an explicit protocol fault is a confirmed failure; a `Transient` read error
105/// (already retried by the responder) routes to the timeout lane.
106const fn grade_reject(kind: RejectKind) -> RejectGrade {
107    match kind {
108        RejectKind::UnknownCommitment | RejectKind::Protocol => RejectGrade::Confirmed,
109        RejectKind::Transient => RejectGrade::TimeoutLane,
110    }
111}
112
113/// Holder-eligibility cache the auditor credits on a passing audit.
114///
115/// Owned by [`crate::replication::ReplicationEngine`]; borrowed here so a
116/// passing audit can record `(peer, commitment_hash)` as a proven holder for
117/// downstream quorum / paid-list credit.
118pub struct AuditCredit<'a> {
119    /// Holder-eligibility cache.
120    pub recent_provers: &'a Arc<RwLock<RecentProvers>>,
121}
122
123/// The cross-cutting context for verifying one audit response, bundled so the
124/// response-dispatch and verification functions stay readable.
125struct AuditCtx<'a> {
126    p2p_node: &'a Arc<P2PNode>,
127    challenged_peer: &'a PeerId,
128    challenge_id: u64,
129    nonce: [u8; 32],
130    expected_commitment_hash: [u8; 32],
131    config: &'a ReplicationConfig,
132    credit: Option<&'a AuditCredit<'a>>,
133}
134
135/// Run one gossip-triggered subtree audit against `challenged_peer`, pinned to
136/// the commitment hash the peer just gossiped (`expected_commitment_hash`).
137///
138/// ADR-0002 two-round audit. The auditor sends a fresh random nonce and runs:
139///
140/// 1. **Structure** (round 1) — the returned subtree rebuilds to the pinned
141///    root, within a size-scaled deadline.
142/// 2. **Real bytes** (round 2) — the auditor demands the ORIGINAL chunk content
143///    for a 3..=5 FRESHLY-RANDOM sample of the proven leaves (chosen after the
144///    proof arrives, not nonce-derived — see `random_spotcheck_leaves`) FROM the
145///    responder, and recomputes both the content-address hash and the nonce
146///    freshness hash from that served content. The auditor holds none of the
147///    peer's chunks.
148/// 3. **Timing** — each round's deadline is sized to an honest local-disk read,
149///    so a relay forced to fetch over the network blows it.
150///
151/// A timeout (either round) is reported as [`AuditFailureReason::Timeout`] (the
152/// caller applies the strike/grace policy). Any structural failure, served
153/// content that fails a hash, an explicit `Absent` for a committed sampled key,
154/// or a rejection of a recently gossiped commitment, is a confirmed failure
155/// acted on immediately. On a full pass, records the peer as a proven holder.
156pub async fn run_subtree_audit(
157    p2p_node: &Arc<P2PNode>,
158    config: &ReplicationConfig,
159    challenged_peer: &PeerId,
160    expected_commitment_hash: [u8; 32],
161    key_count: u32,
162    credit: Option<&AuditCredit<'_>>,
163) -> AuditTickResult {
164    let (nonce, challenge_id) = {
165        let mut rng = rand::thread_rng();
166        (rng.gen::<[u8; 32]>(), rng.gen::<u64>())
167    };
168
169    let challenge = SubtreeAuditChallenge {
170        challenge_id,
171        nonce,
172        challenged_peer_id: *challenged_peer.as_bytes(),
173        expected_commitment_hash,
174    };
175    let msg = ReplicationMessage {
176        request_id: challenge_id,
177        body: ReplicationMessageBody::SubtreeAuditChallenge(challenge),
178    };
179    let encoded = match msg.encode() {
180        Ok(data) => data,
181        Err(e) => {
182            warn!("Audit: failed to encode subtree challenge for {challenged_peer}: {e}");
183            return AuditTickResult::Idle;
184        }
185    };
186
187    // Size the proof deadline from the ACTUAL selected subtree (its real-leaf
188    // count for this nonce + key_count), not a fixed worst-case hint. This keeps
189    // the deadline tight to "responder hashes ~sqrt(N) chunks at local-disk
190    // speed", so a relay that must fetch the subtree over the network blows it.
191    // The auditor and responder derive the same selection, so we know the leaf
192    // count before the response arrives.
193    let subtree_leaves = select_subtree_path(&nonce, key_count).map_or_else(
194        || config.subtree_audit_timeout_leaf_hint(),
195        |p| p.real_leaf_count() as usize,
196    );
197    let timeout = config.audit_response_timeout(subtree_leaves);
198
199    let response = match p2p_node
200        .send_request(challenged_peer, REPLICATION_PROTOCOL_ID, encoded, timeout)
201        .await
202    {
203        Ok(resp) => resp,
204        Err(e) => {
205            debug!("Audit: subtree challenge to {challenged_peer} timed out / failed: {e}");
206            return failed(challenged_peer, challenge_id, AuditFailureReason::Timeout);
207        }
208    };
209
210    let resp_msg = match ReplicationMessage::decode(&response.data) {
211        Ok(m) => m,
212        Err(e) => {
213            warn!("Audit: failed to decode subtree response from {challenged_peer}: {e}");
214            return failed(
215                challenged_peer,
216                challenge_id,
217                AuditFailureReason::MalformedResponse,
218            );
219        }
220    };
221
222    let ctx = AuditCtx {
223        p2p_node,
224        challenged_peer,
225        challenge_id,
226        nonce,
227        expected_commitment_hash,
228        config,
229        credit,
230    };
231    dispatch_subtree_response(resp_msg.body, &ctx).await
232}
233
234/// Outcome of the round-2 byte challenge round-trip (auditor side).
235enum ByteRound {
236    /// The responder returned per-key items (verified by the caller).
237    Served(Vec<SubtreeByteItem>),
238    /// The responder rejected the byte challenge (confirmed failure for a
239    /// recently pinned commitment).
240    Rejected,
241    /// The responder rejected with `Transient` (a local read error): routed to
242    /// the non-response/timeout lane — no trust penalty, but holder credit is
243    /// revoked, because the peer answered and could not prove possession, so it
244    /// must not keep stale credit. Distinct from a silent network `Timeout`,
245    /// which keeps credit (a dropped packet is not evidence of loss).
246    TransientReject,
247    /// No response within the byte deadline, or a transport error (graced
248    /// timeout). Keeps holder credit.
249    Timeout,
250    /// Malformed / unexpected round-2 response body.
251    Malformed,
252}
253
254/// Round 2: ask the responder for the ORIGINAL chunk content of one BATCH of
255/// auditor-selected spot-check `keys` (at most [`MAX_BYTE_CHALLENGE_KEYS`], so
256/// the worst-case response of max-size chunks fits the wire cap), sized to a
257/// possession-in-time deadline (honest local-disk read of `keys.len()` chunks).
258/// The responder cannot have predicted which keys are sampled.
259async fn request_byte_proof(ctx: &AuditCtx<'_>, keys: &[XorName]) -> ByteRound {
260    let challenge = SubtreeByteChallenge {
261        challenge_id: ctx.challenge_id,
262        nonce: ctx.nonce,
263        challenged_peer_id: *ctx.challenged_peer.as_bytes(),
264        expected_commitment_hash: ctx.expected_commitment_hash,
265        keys: keys.to_vec(),
266    };
267    let msg = ReplicationMessage {
268        request_id: ctx.challenge_id,
269        body: ReplicationMessageBody::SubtreeByteChallenge(challenge),
270    };
271    let encoded = match msg.encode() {
272        Ok(data) => data,
273        Err(e) => {
274            warn!("Audit: failed to encode byte challenge: {e}");
275            return ByteRound::Malformed;
276        }
277    };
278
279    // Deadline sized to "honest responder reads `keys.len()` local chunks AND
280    // ships them back": a relay forced to fetch them over the network blows it
281    // (graced timeout, never a confirmed failure — same possession-in-time
282    // principle as round 1). Uses the byte-round floor, which is high enough for
283    // the multi-MiB reply (handshake + upload + busy disk) — the round-1
284    // hashes-only floor would be too tight for 2 × 4 MiB (§4).
285    let timeout = ctx.config.byte_audit_response_timeout(keys.len());
286    let response = match ctx
287        .p2p_node
288        .send_request(
289            ctx.challenged_peer,
290            REPLICATION_PROTOCOL_ID,
291            encoded,
292            timeout,
293        )
294        .await
295    {
296        Ok(resp) => resp,
297        Err(e) => {
298            debug!(
299                "Audit: byte challenge to {} timed out / failed: {e}",
300                ctx.challenged_peer
301            );
302            return ByteRound::Timeout;
303        }
304    };
305
306    let resp_msg = match ReplicationMessage::decode(&response.data) {
307        Ok(m) => m,
308        Err(e) => {
309            warn!("Audit: failed to decode byte response: {e}");
310            return ByteRound::Malformed;
311        }
312    };
313
314    match resp_msg.body {
315        ReplicationMessageBody::SubtreeByteResponse(SubtreeByteResponse::Items {
316            challenge_id,
317            items,
318        }) if challenge_id == ctx.challenge_id => ByteRound::Served(items),
319        ReplicationMessageBody::SubtreeByteResponse(SubtreeByteResponse::Rejected {
320            challenge_id,
321            kind,
322            reason,
323        }) if challenge_id == ctx.challenge_id => {
324            // ADR-0004 A1: grace removed. UnknownCommitment/Protocol repudiation
325            // of a pinned root is a confirmed failure; a Transient read error
326            // routes to the timeout lane (credit revoked, no trust penalty) — the
327            // responder retries reads first, so a Transient reaching round 2 means
328            // it still could not serve committed bytes.
329            match grade_reject(kind) {
330                RejectGrade::Confirmed => {
331                    warn!(
332                        "Audit: {} rejected byte challenge ({kind:?}; confirmed): {reason}",
333                        ctx.challenged_peer
334                    );
335                    ByteRound::Rejected
336                }
337                RejectGrade::TimeoutLane => {
338                    debug!(
339                        "Audit: {} returned Transient for byte challenge (timeout lane): {reason}",
340                        ctx.challenged_peer
341                    );
342                    ByteRound::TransientReject
343                }
344            }
345        }
346        // A node claiming bootstrap MID-AUDIT (it answered round 1) is treated
347        // as a timeout: it didn't prove possession but the round-1 proof shows
348        // it isn't bootstrapping, so the bootstrap-claim-abuse detector (round 1)
349        // owns that lane; here we just don't credit it.
350        ReplicationMessageBody::SubtreeByteResponse(SubtreeByteResponse::Bootstrapping {
351            challenge_id,
352        }) if challenge_id == ctx.challenge_id => ByteRound::Timeout,
353        _ => ByteRound::Malformed,
354    }
355}
356
357/// Map a decoded response body to an audit outcome (auditor side). A response
358/// whose `challenge_id` doesn't match, or any non-subtree body, is malformed.
359async fn dispatch_subtree_response(
360    body: ReplicationMessageBody,
361    ctx: &AuditCtx<'_>,
362) -> AuditTickResult {
363    let challenged_peer = ctx.challenged_peer;
364    let challenge_id = ctx.challenge_id;
365    let malformed = || {
366        failed(
367            challenged_peer,
368            challenge_id,
369            AuditFailureReason::MalformedResponse,
370        )
371    };
372    match body {
373        ReplicationMessageBody::SubtreeAuditResponse(SubtreeAuditResponse::Bootstrapping {
374            challenge_id: resp_id,
375        }) => {
376            if resp_id != challenge_id {
377                return malformed();
378            }
379            AuditTickResult::BootstrapClaim {
380                peer: *challenged_peer,
381            }
382        }
383        ReplicationMessageBody::SubtreeAuditResponse(SubtreeAuditResponse::Rejected {
384            challenge_id: resp_id,
385            kind,
386            reason,
387        }) => {
388            if resp_id != challenge_id {
389                return malformed();
390            }
391            // ADR-0004 A1: audit grace is REMOVED. Answerability is now
392            // restart-durable (persisted retention) and the auditor only pins
393            // in-window roots, so an honest node can always answer a pin it could
394            // be challenged on. A responsive rejection is therefore graded on the
395            // kind, with no grace:
396            match grade_reject(kind) {
397                // Repudiating a pinned root the node published (`UnknownCommitment`)
398                // or an explicit protocol fault is provable misbehaviour →
399                // confirmed failure (trust penalty + credit revocation happen
400                // downstream in handle_subtree_failed_audit).
401                RejectGrade::Confirmed => {
402                    warn!(
403                        "Audit: peer {challenged_peer} rejected subtree challenge \
404                         ({kind:?}; confirmed — grace removed): {reason}"
405                    );
406                    failed(challenged_peer, challenge_id, AuditFailureReason::Rejected)
407                }
408                // A transient local read error (already retried by the responder)
409                // is not a provable cheat, but not graced-with-standing either:
410                // route it to the non-response/timeout lane — no trust penalty, but
411                // revoke the holder credit for THIS pinned commitment so it gains
412                // no positive standing (a Transient-spammer profits nothing).
413                // Scoped to the commitment hash, not the whole peer, so a stale
414                // audit of an old commitment cannot erase credit re-earned for a
415                // newer one.
416                RejectGrade::TimeoutLane => {
417                    if let Some(credit) = ctx.credit {
418                        credit
419                            .recent_provers
420                            .write()
421                            .await
422                            .forget_commitment(&ctx.expected_commitment_hash);
423                    }
424                    debug!(
425                        "Audit: peer {challenged_peer} returned Transient for subtree challenge \
426                         (timeout lane; credit for the pinned commitment revoked): {reason}"
427                    );
428                    failed(challenged_peer, challenge_id, AuditFailureReason::Timeout)
429                }
430            }
431        }
432        ReplicationMessageBody::SubtreeAuditResponse(SubtreeAuditResponse::Proof {
433            challenge_id: resp_id,
434            commitment,
435            proof,
436        }) => {
437            if resp_id != challenge_id {
438                return malformed();
439            }
440            verify_subtree_response(ctx, &commitment, &proof).await
441        }
442        _ => {
443            warn!("Audit: unexpected response type from {challenged_peer}");
444            malformed()
445        }
446    }
447}
448
449/// The pure verdict of evaluating a subtree-audit response, independent of
450/// storage/network. Tests call this directly so the SHIPPED gate logic is what
451/// gets exercised (no reimplementation that could drift).
452#[derive(Debug, Clone, PartialEq, Eq)]
453pub(crate) enum AuditVerdict {
454    /// All gates passed and at least one leaf was byte-verified.
455    Pass {
456        /// Number of leaves whose real bytes were verified in round 2.
457        checked: usize,
458    },
459    /// A confirmed failure with this reason (penalizable / acted upon).
460    Fail(AuditFailureReason),
461}
462
463/// Round-1 structural evaluation of a subtree-audit proof (ADR-0002).
464///
465/// Runs the cheap gates in fail-fast order: pin / identity / signature →
466/// structure (the returned subtree rebuilds to the pinned root). It does **not**
467/// prove byte possession — the leaves carry only the public `bytes_hash` (the
468/// chunk address) and a `nonced_hash` the responder computed itself. Possession
469/// is proven in round 2 ([`verify_byte_response`]), where the auditor demands
470/// the original chunk bytes for a freshly-random (post-proof) sample and
471/// recomputes both hashes from the SERVED content. This removes any dependency
472/// on the auditor holding the peer's chunks.
473///
474/// Returns [`StructureVerdict::Valid`] (proceed to round 2) or a confirmed
475/// [`AuditFailureReason`] mapped from the failing gate.
476pub(crate) fn evaluate_subtree_structure(
477    commitment: &StorageCommitment,
478    proof: &SubtreeProof,
479    nonce: &[u8; 32],
480    expected_commitment_hash: &[u8; 32],
481    challenged_peer_bytes: &[u8; 32],
482) -> Result<(), AuditFailureReason> {
483    // -- Pin + identity + signature --
484    if &commitment.sender_peer_id != challenged_peer_bytes {
485        return Err(AuditFailureReason::Rejected);
486    }
487    let derived_peer_id = *blake3::hash(&commitment.sender_public_key).as_bytes();
488    if derived_peer_id != commitment.sender_peer_id {
489        return Err(AuditFailureReason::Rejected);
490    }
491    match commitment_hash(commitment) {
492        Some(h) if &h == expected_commitment_hash => {}
493        _ => return Err(AuditFailureReason::Rejected),
494    }
495    if !crate::replication::commitment::verify_commitment_signature(commitment) {
496        return Err(AuditFailureReason::Rejected);
497    }
498
499    // -- Structure --
500    if let StructureVerdict::Invalid(_) = verify_subtree_proof(proof, nonce, commitment) {
501        return Err(AuditFailureReason::DigestMismatch);
502    }
503    Ok(())
504}
505
506/// The auditor's **freshly-randomised** spot-check sample of the round-1 proof:
507/// `count` distinct leaves (deduplicated, in increasing-index order) whose
508/// original bytes the auditor will demand in round 2.
509///
510/// CRITICAL (ADR-0002 soundness): the sample MUST NOT be derivable from
511/// anything the responder knew when it built the round-1 proof. The structural
512/// root check binds only `(key, bytes_hash)` (both public — `bytes_hash` is the
513/// chunk's network address), NOT `nonced_hash`. So a relay holding only public
514/// addresses can fabricate a structurally-valid proof with bogus `nonced_hash`
515/// on every leaf and, if it could predict which leaves round 2 opens, fetch
516/// only those and pass — earning holder credit for leaves it never held.
517///
518/// Picking the sample with fresh CSPRNG randomness AFTER the proof is received
519/// turns round 1 into a commitment and round 2 into an unpredictable challenge
520/// (cut-and-choose): to pass with probability above `(1 - faked_fraction)^count`
521/// the responder must have produced a correct `nonced_hash` — which requires the
522/// real bytes — for essentially every leaf at round-1 commit time. The auditor
523/// still holds none of the peer's chunks.
524fn random_spotcheck_leaves(
525    proof: &SubtreeProof,
526    count: u32,
527) -> Vec<&crate::replication::subtree::SubtreeLeaf> {
528    let n = proof.leaves.len();
529    if n == 0 {
530        return Vec::new();
531    }
532    let want = (count as usize).min(n);
533    let mut rng = rand::thread_rng();
534    let mut picked = std::collections::BTreeSet::new();
535    // n >= want, so this terminates quickly; bound the loop defensively against
536    // a pathological RNG rather than risk spinning.
537    let mut guard = 0u32;
538    while picked.len() < want && guard < count.saturating_mul(64).max(64) {
539        picked.insert(rng.gen_range(0..n));
540        guard = guard.saturating_add(1);
541    }
542    // Deterministic top-up if the RNG kept colliding (astronomically unlikely):
543    // fill the lowest missing indices so the sample is never silently short.
544    for idx in 0..n {
545        if picked.len() >= want {
546            break;
547        }
548        picked.insert(idx);
549    }
550    picked
551        .into_iter()
552        .filter_map(|idx| proof.leaves.get(idx))
553        .collect()
554}
555
556/// Round-2 verdict (ADR-0002): the responder served the original chunk content
557/// for the auditor's spot-check sample; verify possession from THAT content.
558///
559/// `served(key)` returns what the responder returned for a requested key:
560/// `Some(Some(bytes))` for [`SubtreeByteItem::Present`], `Some(None)` for an
561/// explicit [`SubtreeByteItem::Absent`], and `None` if the responder omitted the
562/// key entirely (treated like `Absent` — a committed key it would not serve).
563///
564/// For each sampled leaf the auditor recomputes, from the SERVED content:
565///   - `BLAKE3(content) == leaf.bytes_hash` (the chunk's content address), AND
566///   - `BLAKE3(nonce ‖ peer ‖ key ‖ content) == leaf.nonced_hash` (freshness),
567///     i.e. `compute_audit_digest(nonce, peer, key, content)`.
568///
569/// The freshness inputs are byte-identical to what the responder used to BUILD
570/// the leaf in round 1 (`subtree_leaf` → `nonced_leaf_hash`): the SAME four
571/// inputs, so an honest holder's served content reproduces `nonced_hash`
572/// exactly. Round 1 commits over the data (the `nonced_hash` is uncomputable
573/// without the bytes); round 2 reveals a random subset to prove the commitment
574/// was not fabricated.
575///
576/// Both checks are over the content the responder sent, so the auditor needs to
577/// hold none of the peer's chunks. Any `Absent`/omitted committed key, or any
578/// served content that fails a hash, is a provable lie → confirmed
579/// [`AuditFailureReason::DigestMismatch`]. All sampled leaves verifying →
580/// `Pass { checked }`.
581pub(crate) fn verify_byte_response(
582    leaves: &[&crate::replication::subtree::SubtreeLeaf],
583    nonce: &[u8; 32],
584    challenged_peer_bytes: &[u8; 32],
585    served: impl Fn(&XorName) -> Option<Option<Vec<u8>>>,
586) -> AuditVerdict {
587    let mut checked = 0usize;
588    for leaf in leaves {
589        // Present{bytes} -> Some(Some(bytes)); Absent -> Some(None); omitted -> None.
590        // A committed key the responder cannot / will not serve is a provable lie.
591        let Some(Some(content)) = served(&leaf.key) else {
592            return AuditVerdict::Fail(AuditFailureReason::DigestMismatch);
593        };
594        let plain = *blake3::hash(&content).as_bytes();
595        let nonced = crate::replication::subtree::nonced_leaf_hash(
596            nonce,
597            challenged_peer_bytes,
598            &leaf.key,
599            &content,
600        );
601        if leaf.bytes_hash != plain || leaf.nonced_hash != nonced {
602            // Served content does not hash to the committed address / freshness
603            // hash: cannot be the chunk it committed to.
604            return AuditVerdict::Fail(AuditFailureReason::DigestMismatch);
605        }
606        checked += 1;
607    }
608    AuditVerdict::Pass { checked }
609}
610
611/// Verify a subtree-proof response (auditor side), ADR-0002 two-round audit.
612///
613/// **Round 1** (this proof): pin + identity + signature + structure. If the
614/// proof structurally rebuilds to the pinned root, the tree SHAPE is committed —
615/// but not yet that the bytes are held. **Round 2**: the auditor picks a small
616/// freshly-random (post-proof) sample of the just-proven leaves and sends a
617/// [`SubtreeByteChallenge`] demanding their original chunk content FROM the
618/// responder, then verifies that content against the committed `bytes_hash`
619/// (content address) and `nonced_hash` (freshness). A responder that committed
620/// to a chunk it no longer holds cannot serve content that hashes to the
621/// committed address, so it fails — regardless of what the auditor holds. On a
622/// full pass, credits the peer as a proven holder.
623async fn verify_subtree_response(
624    ctx: &AuditCtx<'_>,
625    commitment: &StorageCommitment,
626    proof: &SubtreeProof,
627) -> AuditTickResult {
628    let challenged_peer = ctx.challenged_peer;
629    let challenge_id = ctx.challenge_id;
630
631    // -- Round 1: pin/identity/signature + structure (no bytes). --
632    if let Err(reason) = evaluate_subtree_structure(
633        commitment,
634        proof,
635        &ctx.nonce,
636        &ctx.expected_commitment_hash,
637        challenged_peer.as_bytes(),
638    ) {
639        warn!("Audit: {challenged_peer} failed subtree structure ({reason:?})");
640        return failed(challenged_peer, challenge_id, reason);
641    }
642
643    // -- Round 2: surprise byte challenge for a 3..=5 FRESHLY-RANDOM sample. --
644    // The sample is chosen now, with CSPRNG randomness, AFTER the round-1 proof
645    // is in hand — NOT derived from the round-1 nonce. The responder committed
646    // every leaf's `nonced_hash` in round 1 without knowing which leaves we will
647    // open, so it cannot have fabricated the un-opened ones (cut-and-choose).
648    // We cap the sample at the ADR's 3..=5 band (clamped to the subtree size) so
649    // the round-2 message and the responder's disk read stay cheap.
650    let sample_n = ctx
651        .config
652        .audit_spotcheck_count()
653        .clamp(BYTE_SPOTCHECK_MIN, BYTE_SPOTCHECK_MAX);
654    let sampled = random_spotcheck_leaves(proof, sample_n);
655    if sampled.is_empty() {
656        // Cannot happen after a valid structure (subtree is never empty), but
657        // guard rather than credit an unproven peer.
658        warn!("Audit: {challenged_peer} produced an empty spot-check sample; rejecting");
659        return failed(
660            challenged_peer,
661            challenge_id,
662            AuditFailureReason::DigestMismatch,
663        );
664    }
665    // The sample is challenged in batches of MAX_BYTE_CHALLENGE_KEYS so each
666    // response — worst case, every requested chunk at MAX_CHUNK_SIZE — still
667    // encodes under MAX_REPLICATION_MESSAGE_SIZE. Each batch carries its own
668    // possession-in-time deadline (sized to its own length), so splitting does
669    // not widen the per-chunk window a relay would need to fetch over the
670    // network.
671    //
672    // CRITICAL: verify each batch's served bytes AS IT ARRIVES, against that
673    // batch's own sampled leaves, and return a CONFIRMED failure immediately.
674    // Deferring all verification until every batch is collected would let a
675    // later batch's timeout-lane Timeout (`round_failure`) mask a deterministic
676    // failure already proven by an earlier batch (an absent committed key or a
677    // hash mismatch) — a confirmed cheat would be downgraded to a timeout. A
678    // Timeout/Rejected/Malformed only becomes the verdict if NO earlier batch
679    // already produced confirmed bad bytes.
680    let verdict = 'rounds: {
681        for batch in sampled.chunks(MAX_BYTE_CHALLENGE_KEYS) {
682            let batch_keys: Vec<XorName> = batch.iter().map(|l| l.key).collect();
683            match request_byte_proof(ctx, &batch_keys).await {
684                ByteRound::Served(items) => {
685                    // Verify THIS batch now. A confirmed failure here is final —
686                    // a later batch's timeout must not be able to overwrite it.
687                    let v = verify_byte_response(
688                        batch,
689                        &ctx.nonce,
690                        challenged_peer.as_bytes(),
691                        |key| {
692                            items.iter().find_map(|it| match it {
693                                SubtreeByteItem::Present { key: k, bytes } if k == key => {
694                                    Some(Some(bytes.clone()))
695                                }
696                                SubtreeByteItem::Absent { key: k } if k == key => Some(None),
697                                _ => None,
698                            })
699                        },
700                    );
701                    if let AuditVerdict::Fail(reason) = v {
702                        break 'rounds AuditVerdict::Fail(reason);
703                    }
704                }
705                // The responder rejected the byte challenge for a recently
706                // pinned commitment → confirmed failure, same as round 1.
707                ByteRound::Rejected => {
708                    break 'rounds AuditVerdict::Fail(AuditFailureReason::Rejected)
709                }
710                // Transient reject (a local read error): ADR-0004 A1 routes it to
711                // the timeout lane — no trust penalty, but revoke the holder
712                // credit for THIS pinned commitment (the peer answered and could
713                // not prove possession) before taking the Timeout verdict. Scoped
714                // to the commitment hash, not the whole peer, so it never erases
715                // credit the peer re-earned for a newer commitment.
716                ByteRound::TransientReject => {
717                    if let Some(credit) = ctx.credit {
718                        credit
719                            .recent_provers
720                            .write()
721                            .await
722                            .forget_commitment(&ctx.expected_commitment_hash);
723                    }
724                    break 'rounds AuditVerdict::Fail(AuditFailureReason::Timeout);
725                }
726                // No response within the byte deadline (or transport error) →
727                // timeout (graced by the caller's strike policy — could be
728                // honest slowness). Keeps credit (a dropped packet is not
729                // evidence of loss). Only reached when no earlier batch already
730                // confirmed bad bytes.
731                ByteRound::Timeout => {
732                    break 'rounds AuditVerdict::Fail(AuditFailureReason::Timeout)
733                }
734                // Malformed/unexpected round-2 body.
735                ByteRound::Malformed => {
736                    break 'rounds AuditVerdict::Fail(AuditFailureReason::MalformedResponse)
737                }
738            }
739        }
740        // Every batch served bytes that verified.
741        AuditVerdict::Pass {
742            checked: sampled.len(),
743        }
744    };
745
746    match verdict {
747        AuditVerdict::Fail(reason) => {
748            warn!("Audit: {challenged_peer} failed subtree audit ({reason:?})");
749            failed(challenged_peer, challenge_id, reason)
750        }
751        AuditVerdict::Pass { checked } => {
752            // Closeness (ADR-0002, soft/observe-only) — see observe_closeness.
753            observe_closeness(ctx.p2p_node, ctx.config, challenged_peer, proof).await;
754            // Credit the peer as a proven holder of its committed keys.
755            if let (Some(credit), Some(pin)) = (ctx.credit, commitment_hash(commitment)) {
756                let now = std::time::Instant::now();
757                let mut provers = credit.recent_provers.write().await;
758                for leaf in &proof.leaves {
759                    provers.record_proof(leaf.key, *challenged_peer, pin, now);
760                }
761            }
762            info!(
763                "Audit: peer {challenged_peer} passed subtree audit ({} leaves, {checked} \
764                 byte-checked)",
765                proof.leaves.len()
766            );
767            AuditTickResult::Passed {
768                challenged_peer: *challenged_peer,
769                keys_checked: checked,
770            }
771        }
772    }
773}
774
775/// Soft, density-aware closeness observation (ADR-0002). Logs — never fails —
776/// when a suspicious fraction of the proof's leaves are keys the auditor itself
777/// is NOT responsible for (a proxy for "implausibly far from the peer").
778///
779/// Using the auditor's own `SelfInclusiveRT` responsibility as the yardstick
780/// makes this density-aware for free: on a small/dense network the auditor is
781/// close to nearly every key, so almost nothing reads as far and no honest peer
782/// is ever flagged. Enforcement is intentionally deferred until a testnet
783/// calibrates the density threshold.
784async fn observe_closeness(
785    p2p_node: &Arc<P2PNode>,
786    config: &ReplicationConfig,
787    challenged_peer: &PeerId,
788    proof: &SubtreeProof,
789) {
790    /// Max leaves probed for the closeness estimate (bounds the DHT lookups).
791    const CLOSENESS_SAMPLE_CAP: usize = 8;
792
793    // This is an observe-only DEBUG signal (never enforced). The check costs one
794    // DHT responsibility lookup per inspected leaf, so (§12): (a) skip it
795    // entirely unless debug logging is on — there is no other consumer — and
796    // (b) inspect at most a bounded SAMPLE of leaves rather than all ~sqrt(N),
797    // which still reveals the "mostly far" padding shape without N lookups.
798    if !crate::logging::enabled!(crate::logging::Level::DEBUG) {
799        return;
800    }
801
802    let self_id = *p2p_node.peer_id();
803    let inspected = proof.leaves.len().min(CLOSENESS_SAMPLE_CAP);
804    let mut far = 0usize;
805    for leaf in proof.leaves.iter().take(inspected) {
806        if !crate::replication::admission::is_responsible(
807            &self_id,
808            &leaf.key,
809            p2p_node,
810            config.close_group_size,
811        )
812        .await
813        {
814            far += 1;
815        }
816    }
817    // Only worth a line when MOST of the inspected sample is far — that's the
818    // padding shape. A normal proof on a sparse network has some far keys.
819    if inspected > 0 && far * 2 > inspected {
820        debug!(
821            "Audit: closeness signal — {far}/{inspected} sampled of {challenged_peer}'s proven \
822             leaves are keys this auditor is not close to (observe-only; possible padding, not \
823             penalized)"
824        );
825    }
826}
827
828/// Build a confirmed-failure result. The auditor pinned a commitment the peer
829/// committed to itself, so there is no per-key responsibility to re-confirm:
830/// the failure is about the peer's own committed tree.
831///
832/// The subtree audit fails a peer as a whole (one challenge, one verdict) rather
833/// than per-key, so the [`AuditFailureSummary`] is a single-failure rollup
834/// mapped from `reason` — enough for the shared audit-failure diagnostics log
835/// line (`absent_keys`/`digest_mismatch_keys`) without inventing per-key counts
836/// this audit shape does not have.
837fn failed(
838    challenged_peer: &PeerId,
839    challenge_id: u64,
840    reason: AuditFailureReason,
841) -> AuditTickResult {
842    let summary = subtree_failure_summary(&reason);
843    AuditTickResult::Failed {
844        evidence: FailureEvidence::AuditFailure {
845            challenge_id,
846            challenged_peer: *challenged_peer,
847            confirmed_failed_keys: Vec::new(),
848            summary,
849            reason,
850        },
851    }
852}
853
854/// Map a subtree-audit `reason` to a single-failure [`AuditFailureSummary`].
855///
856/// A `Timeout` is not a confirmed failure (it is the non-response/timeout lane),
857/// so it rolls up as zero confirmed failures; every other reason is one confirmed failure,
858/// categorised where the category is meaningful (byte/nonce/root mismatch →
859/// `digest_mismatch_keys`; explicit absent → `absent_keys`).
860fn subtree_failure_summary(reason: &AuditFailureReason) -> AuditFailureSummary {
861    let mut summary = AuditFailureSummary {
862        challenged_keys: 1,
863        ..AuditFailureSummary::default()
864    };
865    match reason {
866        AuditFailureReason::Timeout => {}
867        AuditFailureReason::DigestMismatch => {
868            summary.failed_keys = 1;
869            summary.digest_mismatch_keys = 1;
870        }
871        AuditFailureReason::KeyAbsent => {
872            summary.failed_keys = 1;
873            summary.absent_keys = 1;
874        }
875        AuditFailureReason::MalformedResponse | AuditFailureReason::Rejected => {
876            summary.failed_keys = 1;
877        }
878    }
879    summary
880}
881
882// ---------------------------------------------------------------------------
883// Responder side
884// ---------------------------------------------------------------------------
885
886/// Handle an incoming subtree audit challenge (responder side).
887///
888/// Validates the challenge targets this node, looks up the pinned commitment in
889/// the retained (in-window) set, and builds the subtree proof for the
890/// nonce-selected branch. If this node is bootstrapping it says so; if it
891/// genuinely does not retain the pinned commitment it rejects (which, with audit
892/// grace removed, the auditor treats as a confirmed failure for an in-window pin).
893pub async fn handle_subtree_challenge(
894    challenge: &SubtreeAuditChallenge,
895    storage: &LmdbStorage,
896    self_peer_id: &PeerId,
897    is_bootstrapping: bool,
898    commitment_state: Option<&Arc<ResponderCommitmentState>>,
899) -> SubtreeAuditResponse {
900    if is_bootstrapping {
901        return SubtreeAuditResponse::Bootstrapping {
902            challenge_id: challenge.challenge_id,
903        };
904    }
905
906    if challenge.challenged_peer_id != *self_peer_id.as_bytes() {
907        warn!(
908            "Subtree audit challenge targeted wrong peer: expected {}, got {}",
909            hex::encode(self_peer_id.as_bytes()),
910            hex::encode(challenge.challenged_peer_id),
911        );
912        return SubtreeAuditResponse::Rejected {
913            challenge_id: challenge.challenge_id,
914            kind: RejectKind::Protocol,
915            reason: "challenged_peer_id does not match this node".to_string(),
916        };
917    }
918
919    let Some(state) = commitment_state else {
920        return SubtreeAuditResponse::Rejected {
921            challenge_id: challenge.challenge_id,
922            kind: RejectKind::Protocol,
923            reason: "no commitment state".to_string(),
924        };
925    };
926
927    // Look up the pinned commitment among the in-window retained set (TTL-bounded
928    // answerability with a MAX_RETAINED_GOSSIPED_SLOTS backstop).
929    // A miss is `UnknownCommitment`. With audit grace removed (ADR-0004 A1) the
930    // auditor treats a responsive miss on an in-window pin as a CONFIRMED failure:
931    // answerability is restart-durable and pins are challenged only while in
932    // window, so failing to answer is a real repudiation, not benign rotation.
933    let Some(built) = state.lookup_by_hash(&challenge.expected_commitment_hash) else {
934        return SubtreeAuditResponse::Rejected {
935            challenge_id: challenge.challenge_id,
936            kind: RejectKind::UnknownCommitment,
937            reason: "unknown commitment hash".to_string(),
938        };
939    };
940
941    // Geometry first (no bytes touched): which leaves to prove + the sibling
942    // cut-hashes from the committed tree.
943    let plan = match subtree_plan(built.tree(), &challenge.nonce) {
944        Ok(p) => p,
945        Err(e) => {
946            warn!("Subtree audit: failed to plan proof: {e:?}");
947            return SubtreeAuditResponse::Rejected {
948                challenge_id: challenge.challenge_id,
949                kind: RejectKind::Protocol,
950                reason: "could not build subtree proof".to_string(),
951            };
952        }
953    };
954
955    // Read chunk bytes one leaf at a time so peak memory is bounded regardless
956    // of subtree size, hashing each into its plain + nonced leaf.
957    let mut leaves = Vec::with_capacity(plan.leaf_keys.len());
958    for key in &plan.leaf_keys {
959        let bytes = match get_raw_retrying(storage, key).await {
960            Ok(Some(bytes)) => bytes,
961            // Key is in our committed tree but definitively NOT stored — real
962            // storage loss / the classic deleter. For a recently gossiped pin
963            // the auditor counts this as a CONFIRMED failure.
964            Ok(None) => {
965                warn!(
966                    "Subtree audit: missing bytes for committed key {}",
967                    hex::encode(key)
968                );
969                return SubtreeAuditResponse::Rejected {
970                    challenge_id: challenge.challenge_id,
971                    kind: RejectKind::Protocol,
972                    reason: format!("missing bytes for committed key: {}", hex::encode(key)),
973                };
974            }
975            // Persistent transient read error after retries — NOT proof of missing
976            // data. Reject `Transient`; the auditor routes it to the timeout lane
977            // (no confirmed penalty) so a genuinely flaky disk is not branded a
978            // deleter, while gaining no positive standing.
979            Err(e) => {
980                warn!(
981                    "Subtree audit: storage read error for committed key {}: {e} \
982                     (rejecting as transient, not a confirmed failure)",
983                    hex::encode(key)
984                );
985                return SubtreeAuditResponse::Rejected {
986                    challenge_id: challenge.challenge_id,
987                    kind: RejectKind::Transient,
988                    reason: format!("transient storage read error: {e}"),
989                };
990            }
991        };
992        leaves.push(crate::replication::subtree::subtree_leaf(
993            &challenge.nonce,
994            &challenge.challenged_peer_id,
995            key,
996            &bytes,
997        ));
998        // bytes drops here.
999    }
1000
1001    SubtreeAuditResponse::Proof {
1002        challenge_id: challenge.challenge_id,
1003        commitment: built.commitment().clone(),
1004        proof: SubtreeProof {
1005            leaves,
1006            sibling_cut_hashes: plan.sibling_cut_hashes,
1007        },
1008    }
1009}
1010
1011/// Handle a round-2 byte challenge (responder side), ADR-0002.
1012///
1013/// The auditor has already structurally verified this node's round-1 subtree
1014/// proof and now demands the ORIGINAL chunk bytes for a small freshly-random
1015/// sample of those leaves. For each requested key the responder either returns
1016/// the bytes ([`SubtreeByteItem::Present`]) or — if it committed to the key but
1017/// can no longer produce it — an explicit [`SubtreeByteItem::Absent`], which the
1018/// auditor counts as a provable failure (committing to bytes you don't hold).
1019///
1020/// A key the responder never committed to (not in the pinned tree) is also
1021/// returned `Absent`: the auditor only ever samples keys it saw in round 1, so
1022/// in practice this guards against a malformed/forged byte challenge rather than
1023/// an honest mismatch.
1024pub async fn handle_subtree_byte_challenge(
1025    challenge: &SubtreeByteChallenge,
1026    storage: &LmdbStorage,
1027    self_peer_id: &PeerId,
1028    is_bootstrapping: bool,
1029    commitment_state: Option<&Arc<ResponderCommitmentState>>,
1030) -> SubtreeByteResponse {
1031    if is_bootstrapping {
1032        return SubtreeByteResponse::Bootstrapping {
1033            challenge_id: challenge.challenge_id,
1034        };
1035    }
1036
1037    if challenge.challenged_peer_id != *self_peer_id.as_bytes() {
1038        return SubtreeByteResponse::Rejected {
1039            challenge_id: challenge.challenge_id,
1040            kind: RejectKind::Protocol,
1041            reason: "challenged_peer_id does not match this node".to_string(),
1042        };
1043    }
1044
1045    // An honest auditor batches its sample to MAX_BYTE_CHALLENGE_KEYS per
1046    // challenge so the worst-case response fits the wire cap. Reject larger
1047    // requests up front: serving them could only produce an unencodable
1048    // response (and invites disk-read amplification from a forged auditor).
1049    if challenge.keys.len() > MAX_BYTE_CHALLENGE_KEYS {
1050        let requested = challenge.keys.len();
1051        return SubtreeByteResponse::Rejected {
1052            challenge_id: challenge.challenge_id,
1053            kind: RejectKind::Protocol,
1054            reason: format!(
1055                "byte challenge requests {requested} keys; max {MAX_BYTE_CHALLENGE_KEYS} per challenge"
1056            ),
1057        };
1058    }
1059
1060    let Some(state) = commitment_state else {
1061        return SubtreeByteResponse::Rejected {
1062            challenge_id: challenge.challenge_id,
1063            kind: RejectKind::Protocol,
1064            reason: "no commitment state".to_string(),
1065        };
1066    };
1067    // Resolve the SAME commitment the auditor pinned in round 1. If we no longer
1068    // retain it (rotated past it), reject as `UnknownCommitment`. With audit
1069    // grace removed (ADR-0004 A1) the auditor treats a responsive miss on an
1070    // in-window pin as a confirmed failure — answerability is restart-durable and
1071    // pins are challenged only in-window. We serve bytes only for keys committed
1072    // under this pin.
1073    let Some(built) = state.lookup_by_hash(&challenge.expected_commitment_hash) else {
1074        return SubtreeByteResponse::Rejected {
1075            challenge_id: challenge.challenge_id,
1076            kind: RejectKind::UnknownCommitment,
1077            reason: "unknown commitment hash".to_string(),
1078        };
1079    };
1080
1081    let mut items = Vec::with_capacity(challenge.keys.len());
1082    for key in &challenge.keys {
1083        // Serve ONLY keys committed under this pin. A key the auditor asks for
1084        // that is not in the pinned tree is `Absent` — never served from local
1085        // storage just because we happen to hold it (§15: serving an
1086        // uncommitted-but-held key would let a forged challenge harvest bytes
1087        // and muddy the possession proof, which must be about THIS commitment).
1088        if built.proof_for(key).is_none() {
1089            items.push(SubtreeByteItem::Absent { key: *key });
1090            continue;
1091        }
1092        match get_raw_retrying(storage, key).await {
1093            // Committed key, bytes present → serve them.
1094            Ok(Some(bytes)) => items.push(SubtreeByteItem::Present { key: *key, bytes }),
1095            // Committed key, definitively absent → provable failure (§7: this is
1096            // a real "I don't hold it" answer, distinct from a read error).
1097            Ok(None) => {
1098                warn!(
1099                    "Subtree byte audit: committed key {} requested but bytes absent",
1100                    hex::encode(key)
1101                );
1102                items.push(SubtreeByteItem::Absent { key: *key });
1103            }
1104            // Persistent transient read error after retries → do NOT brand the
1105            // peer a deleter. Reject `Transient`; the auditor routes it to the
1106            // timeout lane so a flaky LMDB read never manufactures a confirmed
1107            // possession failure on an honest holder (which also gains no credit).
1108            Err(e) => {
1109                warn!(
1110                    "Subtree byte audit: storage read error for committed key {}: {e} \
1111                     (rejecting as transient, not a confirmed failure)",
1112                    hex::encode(key)
1113                );
1114                return SubtreeByteResponse::Rejected {
1115                    challenge_id: challenge.challenge_id,
1116                    kind: RejectKind::Transient,
1117                    reason: format!("transient storage read error: {e}"),
1118                };
1119            }
1120        }
1121    }
1122
1123    SubtreeByteResponse::Items {
1124        challenge_id: challenge.challenge_id,
1125        items,
1126    }
1127}
1128
1129#[cfg(test)]
1130#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1131mod tests {
1132    use super::*;
1133    use crate::replication::commitment_state::BuiltCommitment;
1134    use crate::replication::subtree::{build_subtree_proof, nonced_leaf_hash, SubtreeLeaf};
1135    use saorsa_pqc::api::sig::ml_dsa_65;
1136
1137    /// ADR-0004 A1 grade flip (grace removed): a responsive `UnknownCommitment`
1138    /// or `Protocol` rejection is a CONFIRMED failure; only `Transient` routes to
1139    /// the timeout lane. This pure decision backs both audit rounds
1140    /// (`Confirmed → AuditFailureReason::Rejected` / `ByteRound::Rejected`;
1141    /// `TimeoutLane → AuditFailureReason::Timeout` + pinned-credit revocation).
1142    #[test]
1143    fn grade_reject_removes_grace_for_unknown_commitment() {
1144        assert_eq!(
1145            grade_reject(RejectKind::UnknownCommitment),
1146            RejectGrade::Confirmed,
1147            "an unanswerable pinned root is now a confirmed failure, not graced"
1148        );
1149        assert_eq!(grade_reject(RejectKind::Protocol), RejectGrade::Confirmed);
1150        assert_eq!(
1151            grade_reject(RejectKind::Transient),
1152            RejectGrade::TimeoutLane,
1153            "a transient read error routes to the timeout lane (no confirmed penalty)"
1154        );
1155    }
1156
1157    // The two-round audit splits into SHIPPED pure functions exercised directly
1158    // here (no reimplementation that could drift):
1159    //   - round 1: `evaluate_subtree_structure` (pin/identity/signature +
1160    //     structural root rebuild),
1161    //   - sampling: `random_spotcheck_leaves` (3..=5 FRESHLY-RANDOM leaves chosen
1162    //     after the proof is in hand — see its doc for the soundness argument), and
1163    //   - round 2: `verify_byte_response` (recompute content-address + freshness
1164    //     from the bytes the RESPONDER served — the auditor holds nothing).
1165
1166    fn key(i: u32) -> XorName {
1167        let mut k = [0u8; 32];
1168        k[..4].copy_from_slice(&i.to_be_bytes());
1169        k
1170    }
1171    /// The "chunk content" for a key in these fixtures. The committed tree's leaf
1172    /// `bytes_hash` is `BLAKE3(chunk_bytes(key))`, mirroring the general
1173    /// `(key, BLAKE3(content))` commitment; round 2 serves exactly this content.
1174    fn chunk_bytes(k: &XorName) -> Vec<u8> {
1175        let mut v = k.to_vec();
1176        v.extend_from_slice(b"chunk-body");
1177        v
1178    }
1179
1180    /// Build an honest committed tree of `n` keys + a valid round-1 proof for
1181    /// `nonce`. Returns `(built, proof, peer_id)`. The auditor pins `built.hash()`.
1182    fn honest(n: u32, nonce: &[u8; 32]) -> (BuiltCommitment, SubtreeProof, [u8; 32]) {
1183        let (pk, sk) = ml_dsa_65().generate_keypair().unwrap();
1184        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
1185        let pk_b = pk.to_bytes();
1186        let entries: Vec<_> = (0..n)
1187            .map(|i| {
1188                let k = key(i);
1189                (k, *blake3::hash(&chunk_bytes(&k)).as_bytes())
1190            })
1191            .collect();
1192        let built = BuiltCommitment::build(entries, &peer_id, &sk, &pk_b).unwrap();
1193        let proof =
1194            build_subtree_proof(built.tree(), nonce, &peer_id, |k| Some(chunk_bytes(k))).unwrap();
1195        (built, proof, peer_id)
1196    }
1197
1198    /// Round-1 verdict against the pinned commitment.
1199    fn structure(
1200        built: &BuiltCommitment,
1201        proof: &SubtreeProof,
1202        nonce: &[u8; 32],
1203        peer: &[u8; 32],
1204    ) -> Result<(), AuditFailureReason> {
1205        evaluate_subtree_structure(built.commitment(), proof, nonce, &built.hash(), peer)
1206    }
1207
1208    /// The 3..=5 spot-check leaves the auditor would demand bytes for in round 2.
1209    /// Now freshly-random (post-proof) rather than nonce-derived; the `_nonce`/
1210    /// `_key_count` params are kept so existing call sites read unchanged.
1211    fn sample<'a>(
1212        proof: &'a SubtreeProof,
1213        _nonce: &[u8; 32],
1214        _key_count: u32,
1215    ) -> Vec<&'a SubtreeLeaf> {
1216        random_spotcheck_leaves(proof, 8u32.clamp(BYTE_SPOTCHECK_MIN, BYTE_SPOTCHECK_MAX))
1217    }
1218
1219    // A round-2 `served` closure that returns the HONEST content for every key.
1220    // The nested-Option shape is the `verify_byte_response` callback contract:
1221    // Present{bytes} -> Some(Some(bytes)); Absent -> Some(None); omitted -> None.
1222    #[allow(clippy::option_option, clippy::unnecessary_wraps)]
1223    fn served_honest(key: &XorName) -> Option<Option<Vec<u8>>> {
1224        Some(Some(chunk_bytes(key)))
1225    }
1226
1227    // ---- round 1: structure --------------------------------------------------
1228
1229    #[test]
1230    fn honest_structure_then_bytes_passes() {
1231        let nonce = [9u8; 32];
1232        let (built, proof, peer) = honest(400, &nonce);
1233        // Round 1.
1234        assert!(structure(&built, &proof, &nonce, &peer).is_ok());
1235        // Round 2: honest responder serves the real content for the sample.
1236        let s = sample(&proof, &nonce, built.commitment().key_count);
1237        assert!(!s.is_empty());
1238        match verify_byte_response(&s, &nonce, &peer, served_honest) {
1239            AuditVerdict::Pass { checked } => assert!(checked >= 1, "must verify >=1 leaf"),
1240            other @ AuditVerdict::Fail(_) => panic!("expected Pass, got {other:?}"),
1241        }
1242    }
1243
1244    #[test]
1245    fn commitment_bound_to_another_peer_rejected() {
1246        let nonce = [3u8; 32];
1247        let (built, proof, _peer) = honest(200, &nonce);
1248        let other = [0xAAu8; 32];
1249        assert_eq!(
1250            structure(&built, &proof, &nonce, &other),
1251            Err(AuditFailureReason::Rejected)
1252        );
1253    }
1254
1255    #[test]
1256    fn wrong_pinned_commitment_rejected() {
1257        let nonce = [3u8; 32];
1258        let (built, proof, peer) = honest(200, &nonce);
1259        let mut wrong_pin = built.hash();
1260        wrong_pin[0] ^= 0x01;
1261        assert_eq!(
1262            evaluate_subtree_structure(built.commitment(), &proof, &nonce, &wrong_pin, &peer),
1263            Err(AuditFailureReason::Rejected)
1264        );
1265    }
1266
1267    #[test]
1268    fn tampered_leaf_structure_rejected() {
1269        let nonce = [3u8; 32];
1270        let (built, mut proof, peer) = honest(200, &nonce);
1271        if let Some(first) = proof.leaves.first_mut() {
1272            first.bytes_hash[0] ^= 0x01; // breaks root reconstruction
1273        }
1274        assert_eq!(
1275            structure(&built, &proof, &nonce, &peer),
1276            Err(AuditFailureReason::DigestMismatch)
1277        );
1278    }
1279
1280    #[test]
1281    fn wrong_leaf_count_structure_rejected() {
1282        let nonce = [3u8; 32];
1283        let (built, mut proof, peer) = honest(200, &nonce);
1284        proof.leaves.pop();
1285        assert_eq!(
1286            structure(&built, &proof, &nonce, &peer),
1287            Err(AuditFailureReason::DigestMismatch)
1288        );
1289    }
1290
1291    // ---- round 2: responder-served bytes ------------------------------------
1292
1293    #[test]
1294    fn deleter_absent_bytes_is_confirmed_failure() {
1295        // THE headline fix: a node whose round-1 proof is structurally perfect
1296        // but which has DELETED a committed chunk cannot serve its bytes. It
1297        // signals `Absent` for the sampled key → provable lie → confirmed
1298        // failure. Crucially, the auditor holds NONE of the peer's chunks; the
1299        // verdict depends only on what the responder serves.
1300        let nonce = [9u8; 32];
1301        let (built, proof, peer) = honest(400, &nonce);
1302        assert!(structure(&built, &proof, &nonce, &peer).is_ok());
1303        let s = sample(&proof, &nonce, built.commitment().key_count);
1304        // Responder returns Absent for the FIRST sampled key, honest for the rest.
1305        let victim = s.first().map(|l| l.key).unwrap();
1306        let v = verify_byte_response(&s, &nonce, &peer, |k| {
1307            if *k == victim {
1308                Some(None) // explicit Absent
1309            } else {
1310                Some(Some(chunk_bytes(k)))
1311            }
1312        });
1313        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
1314    }
1315
1316    #[test]
1317    fn omitted_committed_key_is_confirmed_failure() {
1318        // A responder that simply omits a sampled committed key from its items
1319        // (neither Present nor Absent) is treated identically to Absent: it
1320        // committed to the key and won't serve it → confirmed failure.
1321        let nonce = [9u8; 32];
1322        let (built, proof, peer) = honest(400, &nonce);
1323        let s = sample(&proof, &nonce, built.commitment().key_count);
1324        let victim = s.first().map(|l| l.key).unwrap();
1325        let v = verify_byte_response(&s, &nonce, &peer, |k| {
1326            if *k == victim {
1327                None // omitted entirely
1328            } else {
1329                Some(Some(chunk_bytes(k)))
1330            }
1331        });
1332        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
1333    }
1334
1335    #[test]
1336    fn fake_storage_garbage_bytes_is_confirmed_failure() {
1337        // A "fake-storage" responder claims possession but serves garbage. The
1338        // garbage does not hash to the committed content address (`bytes_hash`),
1339        // so the round-2 content-address check fails → confirmed failure. No
1340        // auditor holdings involved.
1341        let nonce = [9u8; 32];
1342        let (built, proof, peer) = honest(400, &nonce);
1343        let s = sample(&proof, &nonce, built.commitment().key_count);
1344        let v = verify_byte_response(&s, &nonce, &peer, |k| {
1345            let mut garbage = blake3::hash(k).as_bytes().to_vec();
1346            garbage.extend_from_slice(b"adversary-fake-storage");
1347            Some(Some(garbage))
1348        });
1349        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
1350    }
1351
1352    #[test]
1353    fn correct_content_address_but_stale_freshness_fails() {
1354        // Suppose a responder could serve bytes that hash to the content address
1355        // (it holds the chunk) — then BOTH checks pass; that is honest. But if
1356        // it serves bytes whose freshness hash does not match (e.g. replaying a
1357        // different nonce's digest is impossible since we recompute it here), the
1358        // freshness check must catch any content that doesn't reproduce the
1359        // committed `nonced_hash`. We model a leaf whose committed nonced_hash was
1360        // built under a DIFFERENT nonce, so the audit nonce's recompute differs.
1361        let nonce = [9u8; 32];
1362        let (built, mut proof, peer) = honest(400, &nonce);
1363        // Rewrite EVERY leaf's nonced_hash to one bound to a different nonce but
1364        // keep its bytes_hash correct (so each leaf's content-address check is
1365        // fine; only freshness is wrong). Tampering all leaves means the
1366        // freshly-random sample is guaranteed to land on a stale-freshness leaf.
1367        let other_nonce = [0xEEu8; 32];
1368        for leaf in &mut proof.leaves {
1369            leaf.nonced_hash =
1370                nonced_leaf_hash(&other_nonce, &peer, &leaf.key, &chunk_bytes(&leaf.key));
1371        }
1372        let s = sample(&proof, &nonce, built.commitment().key_count);
1373        let v = verify_byte_response(&s, &nonce, &peer, served_honest);
1374        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
1375    }
1376
1377    #[test]
1378    fn auditor_holds_nothing_still_catches_deleter() {
1379        // Explicit contract: the auditor's own storage is irrelevant. A deleter
1380        // is caught purely from its served (absent) response. (Compare the OLD
1381        // design, where an auditor holding none of the chunks went Inconclusive
1382        // and the deleter walked free.)
1383        let nonce = [0x21u8; 32];
1384        let (built, proof, peer) = honest(256, &nonce);
1385        assert!(structure(&built, &proof, &nonce, &peer).is_ok());
1386        let s = sample(&proof, &nonce, built.commitment().key_count);
1387        // Responder is a total deleter: Absent for everything.
1388        let v = verify_byte_response(&s, &nonce, &peer, |_| Some(None));
1389        assert_eq!(v, AuditVerdict::Fail(AuditFailureReason::DigestMismatch));
1390    }
1391
1392    #[test]
1393    fn sample_size_is_in_3_to_5_band() {
1394        // ADR-0002: round-2 samples a SMALL surprise set (3..=5) of the proven
1395        // leaves. For a large subtree the sample is capped at 5.
1396        let nonce = [7u8; 32];
1397        let (built, proof, _peer) = honest(1024, &nonce);
1398        let s = sample(&proof, &nonce, built.commitment().key_count);
1399        assert!(
1400            (BYTE_SPOTCHECK_MIN as usize..=BYTE_SPOTCHECK_MAX as usize).contains(&s.len()),
1401            "sample {} must be within 3..=5",
1402            s.len()
1403        );
1404    }
1405
1406    #[test]
1407    fn full_pass_requires_every_sampled_leaf() {
1408        // checked must equal the number of sampled leaves on a pass (no leaf is
1409        // silently skipped — every sampled, committed key must verify).
1410        let nonce = [11u8; 32];
1411        let (built, proof, peer) = honest(400, &nonce);
1412        let s = sample(&proof, &nonce, built.commitment().key_count);
1413        match verify_byte_response(&s, &nonce, &peer, served_honest) {
1414            AuditVerdict::Pass { checked } => assert_eq!(checked, s.len()),
1415            other @ AuditVerdict::Fail(_) => panic!("expected Pass, got {other:?}"),
1416        }
1417    }
1418
1419    // ---- end-to-end gate composition ----------------------------------------
1420
1421    #[test]
1422    fn structure_fail_short_circuits_before_round_2() {
1423        // A structurally invalid proof is rejected in round 1; the byte challenge
1424        // is never issued. We assert the round-1 gate returns Err so the auditor
1425        // (verify_subtree_response) never reaches request_byte_proof.
1426        let nonce = [5u8; 32];
1427        let (built, mut proof, peer) = honest(300, &nonce);
1428        if let Some(first) = proof.leaves.first_mut() {
1429            first.bytes_hash[0] ^= 0x01;
1430        }
1431        assert!(structure(&built, &proof, &nonce, &peer).is_err());
1432    }
1433
1434    /// Build an honest committed tree whose keys are deliberately "FAR": their
1435    /// addresses live at the high end of the XOR space (top bytes = 0xFF). On the
1436    /// auditor side these are the leaves `observe_closeness` counts toward `far`.
1437    fn honest_far(n: u32, nonce: &[u8; 32]) -> (BuiltCommitment, SubtreeProof, [u8; 32]) {
1438        let (pk, sk) = ml_dsa_65().generate_keypair().unwrap();
1439        let peer_id = *blake3::hash(&pk.to_bytes()).as_bytes();
1440        let pk_b = pk.to_bytes();
1441        let entries: Vec<_> = (0..n)
1442            .map(|i| {
1443                let mut k = [0xFFu8; 32];
1444                k[28..].copy_from_slice(&i.to_be_bytes());
1445                (k, *blake3::hash(&chunk_bytes(&k)).as_bytes())
1446            })
1447            .collect();
1448        let built = BuiltCommitment::build(entries, &peer_id, &sk, &pk_b).unwrap();
1449        let proof =
1450            build_subtree_proof(built.tree(), nonce, &peer_id, |k| Some(chunk_bytes(k))).unwrap();
1451        (built, proof, peer_id)
1452    }
1453
1454    /// ADR-0002 "Closeness" is OBSERVE-ONLY: far-keyed honest proofs verify
1455    /// exactly like near-keyed ones. The verdict (structure + served bytes) is
1456    /// closeness-blind, so a "far/padding" shape can never produce a Fail.
1457    #[test]
1458    fn closeness_is_observe_only_far_keys_still_pass() {
1459        let nonce = [9u8; 32];
1460
1461        let (built_far, proof_far, peer_far) = honest_far(400, &nonce);
1462        assert!(structure(&built_far, &proof_far, &nonce, &peer_far).is_ok());
1463        let sf = sample(&proof_far, &nonce, built_far.commitment().key_count);
1464        let v_far = verify_byte_response(&sf, &nonce, &peer_far, served_honest);
1465
1466        let (built_near, proof_near, peer_near) = honest(400, &nonce);
1467        assert!(structure(&built_near, &proof_near, &nonce, &peer_near).is_ok());
1468        let sn = sample(&proof_near, &nonce, built_near.commitment().key_count);
1469        let v_near = verify_byte_response(&sn, &nonce, &peer_near, served_honest);
1470
1471        match (&v_far, &v_near) {
1472            (AuditVerdict::Pass { checked: cf }, AuditVerdict::Pass { checked: cn }) => {
1473                assert!(*cf >= 1 && *cn >= 1);
1474            }
1475            other => panic!("both honest proofs must Pass regardless of closeness, got {other:?}"),
1476        }
1477        assert!(
1478            !matches!(v_far, AuditVerdict::Fail(_)),
1479            "far/padding-shaped honest proof must NEVER fail, got {v_far:?}"
1480        );
1481    }
1482
1483    // Unused-leaf constructor guard: keep SubtreeLeaf import meaningful.
1484    #[test]
1485    fn subtree_leaf_is_constructible() {
1486        let _l = SubtreeLeaf {
1487            key: key(1),
1488            bytes_hash: [0u8; 32],
1489            nonced_hash: [0u8; 32],
1490        };
1491    }
1492}