Skip to main content

ant_node/replication/
audit.rs

1//! Storage audit protocol (Section 15).
2//!
3//! Challenge-response for claimed holders. Anti-outsourcing protection.
4
5use std::collections::{HashMap, HashSet};
6use std::sync::Arc;
7use std::time::Instant;
8
9use crate::logging::{debug, enabled, info, warn};
10use rand::seq::SliceRandom;
11use rand::Rng;
12
13use crate::ant_protocol::XorName;
14use crate::replication::audit_coordinator::AuditChallengeCoordinator;
15use crate::replication::audit_metrics::{self, AuditFailureClass, AuditType};
16use crate::replication::config::{ReplicationConfig, REPLICATION_PROTOCOL_ID};
17use crate::replication::protocol::{
18    compute_audit_digest, AuditChallenge, AuditResponse, ReplicationMessage,
19    ReplicationMessageBody, ABSENT_KEY_DIGEST,
20};
21use crate::replication::types::{
22    AuditFailureReason, AuditFailureSummary, FailureEvidence, PeerSyncRecord, RepairProofs,
23};
24use crate::storage::ChunkStore;
25use saorsa_core::identity::PeerId;
26use saorsa_core::P2PNode;
27use tokio::sync::RwLock;
28
29// Test-only imports. Kept here rather than inside `mod tests` so every `use` in
30// this file lives at the top, and `#[cfg(test)]`-gated so non-test builds do
31// not carry them.
32#[cfg(test)]
33use crate::replication::config::REPAIR_HINT_MIN_AGE;
34#[cfg(test)]
35use crate::replication::types::{BootstrapClaimObservation, NeighborSyncState};
36#[cfg(test)]
37use crate::storage::chunk_store::CHUNKS_DIR_NAME;
38#[cfg(test)]
39use crate::storage::ChunkStoreConfig;
40#[cfg(test)]
41use tempfile::TempDir;
42
43// ---------------------------------------------------------------------------
44// Audit tick result
45// ---------------------------------------------------------------------------
46
47/// Result of an audit tick.
48#[derive(Debug)]
49pub enum AuditTickResult {
50    /// Audit completed successfully (all digests matched).
51    Passed {
52        /// The peer that was challenged.
53        challenged_peer: PeerId,
54        /// Number of keys verified.
55        keys_checked: usize,
56    },
57    /// Audit found failures (after responsibility confirmation).
58    Failed {
59        /// Evidence of the failure for trust engine.
60        evidence: FailureEvidence,
61        /// Node-local no-response class for metrics/logs. This is deliberately
62        /// kept out of [`FailureEvidence`] so no serialized evidence format or
63        /// wire protocol changes.
64        no_response_class: Option<&'static str>,
65    },
66    /// Audit target claimed bootstrapping.
67    BootstrapClaim {
68        /// The peer claiming bootstrap status.
69        peer: PeerId,
70    },
71    /// No eligible peers for audit this tick.
72    Idle,
73    /// Audit skipped (not enough local keys).
74    InsufficientKeys,
75}
76
77/// Format the first challenged key as a short stable correlation label.
78fn first_challenged_key_label(keys: &[XorName]) -> String {
79    keys.first().map_or_else(
80        || "0x".to_string(),
81        |k| format!("0x{}", hex::encode(&k[..8])),
82    )
83}
84
85/// Best-effort coarse class for the transport/request error returned by
86/// `P2PNode::send_request`.
87///
88/// The current core networking layer can wrap request deadline timeouts inside
89/// display strings, so this deliberately remains a bounded heuristic for logs
90/// rather than protocol/trust semantics.
91fn classify_audit_send_error(error: &str) -> (&'static str, AuditFailureClass) {
92    audit_metrics::classify_audit_send_error(error)
93}
94
95pub(crate) fn responsible_audit_response_timeout(
96    config: &ReplicationConfig,
97    key_count: usize,
98) -> std::time::Duration {
99    config.audit_response_timeout(key_count)
100}
101
102// ---------------------------------------------------------------------------
103// Main audit tick
104// ---------------------------------------------------------------------------
105
106/// Execute one repair-proof-gated audit tick.
107///
108/// This is the production path used by the replication engine. Direct
109/// callers that have not adopted repair proofs remain conservative and do not
110/// audit peers for unproven keys.
111#[allow(
112    clippy::implicit_hasher,
113    clippy::too_many_arguments,
114    clippy::too_many_lines
115)]
116pub async fn audit_tick_with_repair_proofs(
117    p2p_node: &Arc<P2PNode>,
118    storage: &Arc<ChunkStore>,
119    config: &ReplicationConfig,
120    sync_history: &HashMap<PeerId, PeerSyncRecord>,
121    repair_proofs: &Arc<RwLock<RepairProofs>>,
122    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
123    current_sync_epoch: u64,
124    is_bootstrapping: bool,
125) -> AuditTickResult {
126    // Invariant 19: never audit while still bootstrapping.
127    if is_bootstrapping {
128        return AuditTickResult::Idle;
129    }
130
131    let dht = p2p_node.dht_manager();
132
133    // Step 2: Select one eligible peer (has RepairOpportunity) at random.
134    // Peers with active bootstrap claims remain eligible. A follow-up audit is
135    // how we observe a continued claim and apply past-grace abuse handling.
136    let eligible_peers = eligible_audit_peers(sync_history);
137
138    if eligible_peers.is_empty() {
139        return AuditTickResult::Idle;
140    }
141
142    let (challenged_peer, nonce, challenge_id) = {
143        let mut rng = rand::thread_rng();
144        let selected = match eligible_peers.choose(&mut rng) {
145            Some(p) => *p,
146            None => return AuditTickResult::Idle,
147        };
148        let n: [u8; 32] = rng.gen();
149        let c: u64 = rng.gen();
150        (selected, n, c)
151    };
152
153    // Step 3: Sample keys from local store and keep those the peer is
154    // responsible for (appears in the close group via local RT lookup).
155    let all_keys = match storage.all_keys().await {
156        Ok(keys) => keys,
157        Err(e) => {
158            warn!("Audit: failed to read local keys: {e}");
159            return AuditTickResult::Idle;
160        }
161    };
162
163    if all_keys.is_empty() {
164        return AuditTickResult::Idle;
165    }
166
167    let sample_count = ReplicationConfig::responsible_audit_key_limit(all_keys.len());
168    let sampled_keys: Vec<XorName> = {
169        let mut rng = rand::thread_rng();
170        all_keys
171            .choose_multiple(&mut rng, sample_count)
172            .copied()
173            .collect()
174    };
175
176    // Step 4: Filter to keys where the chosen peer is in the close group and
177    // this node has proof that it already sent the peer a repair hint for the
178    // specific key.
179    let mut sampled_key_groups = Vec::new();
180    for key in &sampled_keys {
181        let closest = dht
182            .find_closest_nodes_local_with_self(key, config.close_group_size)
183            .await;
184        let close_peers: HashSet<PeerId> = closest.iter().map(|node| node.peer_id).collect();
185        if close_peers.contains(&challenged_peer) {
186            sampled_key_groups.push((*key, close_peers));
187        }
188    }
189
190    let peer_keys = {
191        let mut proofs = repair_proofs.write().await;
192        let now = Instant::now();
193        mature_audit_keys_for_peer(
194            &challenged_peer,
195            sampled_key_groups,
196            &mut proofs,
197            current_sync_epoch,
198            now,
199        )
200    };
201
202    if peer_keys.is_empty() {
203        return AuditTickResult::Idle;
204    }
205
206    // peer_keys is naturally bounded by audit_sample_count (sqrt-scaled),
207    // so no explicit truncation needed.
208
209    // Step 6: Send challenge.
210
211    let challenge = AuditChallenge {
212        challenge_id,
213        nonce,
214        challenged_peer_id: *challenged_peer.as_bytes(),
215        keys: peer_keys.clone(),
216    };
217
218    let msg = ReplicationMessage {
219        request_id: challenge_id,
220        body: ReplicationMessageBody::AuditChallenge(challenge),
221    };
222
223    let encoded = match msg.encode() {
224        Ok(data) => data,
225        Err(e) => {
226            warn!("Audit: failed to encode challenge: {e}");
227            return AuditTickResult::Idle;
228        }
229    };
230
231    let Some(_slot) = audit_challenge_coordinator.acquire(challenged_peer).await else {
232        warn!("Audit: failed to acquire outbound audit coordinator slot for {challenged_peer}");
233        return AuditTickResult::Idle;
234    };
235    let encoded_len = encoded.len();
236    let audit_timeout = responsible_audit_response_timeout(config, peer_keys.len());
237    info!(
238        target: "ant_node::replication::audit_requester",
239        event = "started",
240        audit_origin = AuditType::ResponsibleChunk.as_str(),
241        audit_round = "digest",
242        challenged_peer = %challenged_peer,
243        challenge_id,
244        work_items = peer_keys.len(),
245        timeout_ms = audit_timeout.as_millis(),
246        "Outbound audit request started"
247    );
248    let audit_started = Instant::now();
249    let response = match p2p_node
250        .send_request(
251            &challenged_peer,
252            REPLICATION_PROTOCOL_ID,
253            encoded,
254            audit_timeout,
255        )
256        .await
257    {
258        Ok(resp) => {
259            info!(
260                target: "ant_node::replication::audit_requester",
261                event = "completed",
262                audit_origin = AuditType::ResponsibleChunk.as_str(),
263                audit_round = "digest",
264                challenged_peer = %challenged_peer,
265                challenge_id,
266                work_items = peer_keys.len(),
267                elapsed_ms = audit_started.elapsed().as_millis(),
268                outcome = "response",
269                "Outbound audit request completed"
270            );
271            resp
272        }
273        Err(e) => {
274            let send_error = e.to_string();
275            let (send_error_class, audit_failure_class) = classify_audit_send_error(&send_error);
276            audit_metrics::record_audit_no_response(
277                AuditType::ResponsibleChunk,
278                audit_failure_class,
279            );
280            if enabled!(crate::logging::Level::WARN) {
281                let elapsed = audit_started.elapsed();
282                let first_key = first_challenged_key_label(&peer_keys);
283                warn!(
284                    target: "ant_node::replication::audit_requester",
285                    event = "completed",
286                    audit_origin = AuditType::ResponsibleChunk.as_str(),
287                    audit_round = "digest",
288                    outcome = "no_response",
289                    audit_type = AuditType::ResponsibleChunk.as_str(),
290                    audit_phase = "challenge_send",
291                    audit_outcome = "send_request_failed",
292                    audit_failure_class = audit_failure_class.as_str(),
293                    challenged_peer = %challenged_peer,
294                    challenge_id,
295                    key_count = peer_keys.len(),
296                    timeout_ms = audit_timeout.as_millis(),
297                    elapsed_ms = elapsed.as_millis(),
298                    first_key = %first_key,
299                    encoded_len,
300                    send_error_class,
301                    "Audit challenge send_request failed: audit_type=responsible_chunk, audit_phase=challenge_send, audit_outcome=send_request_failed, audit_failure_class={}, challenged_peer={challenged_peer}, challenge_id={challenge_id}, key_count={}, timeout_ms={}, elapsed_ms={}, first_key={first_key}, encoded_len={encoded_len}, send_error_class={send_error_class}",
302                    audit_failure_class.as_str(),
303                    peer_keys.len(),
304                    audit_timeout.as_millis(),
305                    elapsed.as_millis(),
306                );
307            }
308            debug!(
309                challenged_peer = %challenged_peer,
310                challenge_id,
311                send_error = %e,
312                audit_failure_class = audit_failure_class.as_str(),
313                "Audit challenge raw send_request error"
314            );
315            // No-response verdicts still use the existing Timeout evidence
316            // reason; the class is node-local observability only.
317            return handle_audit_timeout(
318                &challenged_peer,
319                challenge_id,
320                &peer_keys,
321                audit_failure_class,
322                p2p_node,
323                config,
324            )
325            .await;
326        }
327    };
328
329    // Step 7: Parse response.
330    let resp_msg = match ReplicationMessage::decode(&response.data) {
331        Ok(m) => m,
332        Err(e) => {
333            warn!("Audit: failed to decode response from {challenged_peer}: {e}");
334            return handle_audit_failure(
335                &challenged_peer,
336                challenge_id,
337                &peer_keys,
338                AuditFailureReason::MalformedResponse,
339                p2p_node,
340                config,
341            )
342            .await;
343        }
344    };
345
346    match resp_msg.body {
347        ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping {
348            challenge_id: resp_id,
349        }) => {
350            if resp_id != challenge_id {
351                warn!("Audit: challenge ID mismatch on Bootstrapping from {challenged_peer}");
352                return handle_audit_failure(
353                    &challenged_peer,
354                    challenge_id,
355                    &peer_keys,
356                    AuditFailureReason::MalformedResponse,
357                    p2p_node,
358                    config,
359                )
360                .await;
361            }
362            // Step 7b: Bootstrapping claim.
363            AuditTickResult::BootstrapClaim {
364                peer: challenged_peer,
365            }
366        }
367        ReplicationMessageBody::AuditResponse(AuditResponse::Digests {
368            challenge_id: resp_id,
369            digests,
370        }) => {
371            if resp_id != challenge_id {
372                warn!("Audit: challenge ID mismatch from {challenged_peer}");
373                return handle_audit_failure(
374                    &challenged_peer,
375                    challenge_id,
376                    &peer_keys,
377                    AuditFailureReason::MalformedResponse,
378                    p2p_node,
379                    config,
380                )
381                .await;
382            }
383            verify_digests(
384                &challenged_peer,
385                challenge_id,
386                &nonce,
387                &peer_keys,
388                &digests,
389                storage,
390                p2p_node,
391                config,
392            )
393            .await
394        }
395        ReplicationMessageBody::AuditResponse(AuditResponse::Rejected {
396            challenge_id: resp_id,
397            reason,
398        }) => {
399            if resp_id != challenge_id {
400                warn!("Audit: challenge ID mismatch on Rejected from {challenged_peer}");
401                return handle_audit_failure(
402                    &challenged_peer,
403                    challenge_id,
404                    &peer_keys,
405                    AuditFailureReason::MalformedResponse,
406                    p2p_node,
407                    config,
408                )
409                .await;
410            }
411            warn!("Audit: challenge rejected by {challenged_peer}: {reason}");
412            handle_audit_failure(
413                &challenged_peer,
414                challenge_id,
415                &peer_keys,
416                AuditFailureReason::Rejected,
417                p2p_node,
418                config,
419            )
420            .await
421        }
422        _ => {
423            warn!("Audit: unexpected response type from {challenged_peer}");
424            handle_audit_failure(
425                &challenged_peer,
426                challenge_id,
427                &peer_keys,
428                AuditFailureReason::MalformedResponse,
429                p2p_node,
430                config,
431            )
432            .await
433        }
434    }
435}
436
437fn eligible_audit_peers(sync_history: &HashMap<PeerId, PeerSyncRecord>) -> Vec<PeerId> {
438    sync_history
439        .iter()
440        .filter(|(_, record)| record.has_repair_opportunity())
441        .map(|(peer, _)| *peer)
442        .collect()
443}
444
445fn mature_audit_keys_for_peer(
446    challenged_peer: &PeerId,
447    sampled_key_groups: Vec<(XorName, HashSet<PeerId>)>,
448    repair_proofs: &mut RepairProofs,
449    current_sync_epoch: u64,
450    now: Instant,
451) -> Vec<XorName> {
452    sampled_key_groups
453        .into_iter()
454        .filter_map(|(key, close_peers)| {
455            repair_proofs
456                .has_mature_replica_hint(
457                    challenged_peer,
458                    &key,
459                    &close_peers,
460                    current_sync_epoch,
461                    now,
462                )
463                .then_some(key)
464        })
465        .collect()
466}
467
468#[derive(Debug, Clone, Copy, PartialEq, Eq)]
469enum AuditKeyFailureKind {
470    Absent,
471    DigestMismatch,
472    Unclassified,
473}
474
475#[derive(Debug, Clone, Copy, PartialEq, Eq)]
476struct AuditKeyFailure {
477    key: XorName,
478    kind: AuditKeyFailureKind,
479}
480
481impl AuditKeyFailure {
482    fn absent(key: XorName) -> Self {
483        Self {
484            key,
485            kind: AuditKeyFailureKind::Absent,
486        }
487    }
488
489    fn digest_mismatch(key: XorName) -> Self {
490        Self {
491            key,
492            kind: AuditKeyFailureKind::DigestMismatch,
493        }
494    }
495
496    fn unclassified(key: XorName) -> Self {
497        Self {
498            key,
499            kind: AuditKeyFailureKind::Unclassified,
500        }
501    }
502}
503
504fn build_audit_failure_summary(
505    challenged_key_count: usize,
506    confirmed_failures: &[AuditKeyFailure],
507) -> AuditFailureSummary {
508    let mut summary = AuditFailureSummary {
509        challenged_keys: challenged_key_count,
510        failed_keys: confirmed_failures.len(),
511        ..AuditFailureSummary::default()
512    };
513
514    for failure in confirmed_failures {
515        match failure.kind {
516            AuditKeyFailureKind::Absent => summary.absent_keys += 1,
517            AuditKeyFailureKind::DigestMismatch => summary.digest_mismatch_keys += 1,
518            AuditKeyFailureKind::Unclassified => {}
519        }
520    }
521
522    summary
523}
524
525fn audit_digest_failure_reason(confirmed_failures: &[AuditKeyFailure]) -> AuditFailureReason {
526    if confirmed_failures
527        .iter()
528        .all(|failure| failure.kind == AuditKeyFailureKind::Absent)
529    {
530        AuditFailureReason::KeyAbsent
531    } else {
532        AuditFailureReason::DigestMismatch
533    }
534}
535
536// ---------------------------------------------------------------------------
537// Digest verification
538// ---------------------------------------------------------------------------
539
540/// Verify per-key digests from audit response (Step 8).
541#[allow(clippy::too_many_arguments)]
542async fn verify_digests(
543    challenged_peer: &PeerId,
544    challenge_id: u64,
545    nonce: &[u8; 32],
546    keys: &[XorName],
547    digests: &[[u8; 32]],
548    storage: &Arc<ChunkStore>,
549    p2p_node: &Arc<P2PNode>,
550    config: &ReplicationConfig,
551) -> AuditTickResult {
552    // Requirement: response must have exactly one digest per key.
553    if digests.len() != keys.len() {
554        warn!(
555            "Audit: malformed response from {challenged_peer}: {} digests for {} keys",
556            digests.len(),
557            keys.len()
558        );
559        return handle_audit_failure(
560            challenged_peer,
561            challenge_id,
562            keys,
563            AuditFailureReason::MalformedResponse,
564            p2p_node,
565            config,
566        )
567        .await;
568    }
569
570    let DigestComparison {
571        failed_keys,
572        verified,
573    } = compare_with_local_copies(storage, nonce, challenged_peer.as_bytes(), keys, digests).await;
574
575    if failed_keys.is_empty() {
576        return unfailed_audit_verdict(challenged_peer, keys.len(), verified);
577    }
578
579    // Step 9: Responsibility confirmation for failed keys.
580    handle_classified_audit_failure(
581        challenged_peer,
582        challenge_id,
583        &failed_keys,
584        AuditFailureReason::DigestMismatch,
585        keys.len(),
586        None,
587        p2p_node,
588        config,
589    )
590    .await
591}
592
593/// What comparing a peer's digests with this node's own copies found.
594struct DigestComparison {
595    /// Keys the peer admitted missing, or whose digest did not match.
596    failed_keys: Vec<AuditKeyFailure>,
597    /// Keys whose digest matched one recomputed from a good local copy.
598    verified: usize,
599}
600
601/// Compare per-key digests with ones recomputed from this node's own copies.
602///
603/// The local copy is the reference the peer is judged against, so it is read
604/// through the verifying path: a local file that no longer hashes to its key
605/// must not fail an honest peer. Such a copy is taken out of service by the read
606/// (replication repairs it) and the key is skipped, like any other key this node
607/// cannot read. A skipped key is neither a failure nor a verification.
608async fn compare_with_local_copies(
609    storage: &ChunkStore,
610    nonce: &[u8; 32],
611    challenged_peer_bytes: &[u8; 32],
612    keys: &[XorName],
613    digests: &[[u8; 32]],
614) -> DigestComparison {
615    let mut failed_keys = Vec::new();
616    let mut verified = 0usize;
617
618    for (key, received_digest) in keys.iter().zip(digests) {
619        // Check for absent sentinel.
620        if *received_digest == ABSENT_KEY_DIGEST {
621            failed_keys.push(AuditKeyFailure::absent(*key));
622            continue;
623        }
624
625        let local_bytes = match storage.get(key).await {
626            Ok(Some(bytes)) => bytes,
627            Ok(None) => {
628                // We should hold this key (we sampled it), but it's gone.
629                warn!(
630                    "Audit: local key {} disappeared during audit",
631                    hex::encode(key)
632                );
633                continue;
634            }
635            Err(e) => {
636                warn!("Audit: failed to read local key {}: {e}", hex::encode(key));
637                continue;
638            }
639        };
640
641        let expected = compute_audit_digest(nonce, challenged_peer_bytes, key, &local_bytes);
642        if *received_digest == expected {
643            verified += 1;
644        } else {
645            failed_keys.push(AuditKeyFailure::digest_mismatch(*key));
646        }
647    }
648
649    DigestComparison {
650        failed_keys,
651        verified,
652    }
653}
654
655/// The verdict on an audit in which no key failed.
656///
657/// A pass needs at least one key actually checked: when every key was skipped for
658/// want of a good local copy, nothing is known about the peer, so it earns no pass
659/// (and no trust credit) and the audit is idle instead.
660fn unfailed_audit_verdict(
661    challenged_peer: &PeerId,
662    key_count: usize,
663    verified: usize,
664) -> AuditTickResult {
665    if verified == 0 {
666        debug!(
667            "Audit: no key could be checked against a local copy for {challenged_peer}; \
668             not counted as a pass"
669        );
670        return AuditTickResult::Idle;
671    }
672    if verified == key_count {
673        info!("Audit: peer {challenged_peer} passed (all {verified} keys verified)");
674    } else {
675        info!(
676            "Audit: peer {challenged_peer} passed ({verified} of {key_count} keys verified, \
677             the rest skipped for want of a good local copy)"
678        );
679    }
680    AuditTickResult::Passed {
681        challenged_peer: *challenged_peer,
682        keys_checked: verified,
683    }
684}
685
686// ---------------------------------------------------------------------------
687// Failure handling with responsibility confirmation
688// ---------------------------------------------------------------------------
689
690/// Handle audit failure: confirm responsibility before emitting evidence (Step 9).
691async fn handle_audit_failure(
692    challenged_peer: &PeerId,
693    challenge_id: u64,
694    failed_keys: &[XorName],
695    reason: AuditFailureReason,
696    p2p_node: &Arc<P2PNode>,
697    config: &ReplicationConfig,
698) -> AuditTickResult {
699    let failures = failed_keys
700        .iter()
701        .copied()
702        .map(AuditKeyFailure::unclassified)
703        .collect::<Vec<_>>();
704    handle_classified_audit_failure(
705        challenged_peer,
706        challenge_id,
707        &failures,
708        reason,
709        failed_keys.len(),
710        None,
711        p2p_node,
712        config,
713    )
714    .await
715}
716
717#[allow(clippy::too_many_arguments)]
718async fn handle_classified_audit_failure(
719    challenged_peer: &PeerId,
720    challenge_id: u64,
721    failed_keys: &[AuditKeyFailure],
722    reason: AuditFailureReason,
723    challenged_key_count: usize,
724    no_response_class: Option<&'static str>,
725    p2p_node: &Arc<P2PNode>,
726    config: &ReplicationConfig,
727) -> AuditTickResult {
728    let dht = p2p_node.dht_manager();
729    let mut confirmed_failures = Vec::new();
730
731    // Step 9a-b: Fresh local RT lookup for each failed key.
732    for failure in failed_keys {
733        let closest = dht
734            .find_closest_nodes_local_with_self(&failure.key, config.close_group_size)
735            .await;
736        if closest.iter().any(|n| n.peer_id == *challenged_peer) {
737            confirmed_failures.push(*failure);
738        } else {
739            debug!(
740                "Audit: peer {challenged_peer} not responsible for {} (removed from failure set)",
741                hex::encode(failure.key)
742            );
743        }
744    }
745
746    // Step 9c: Empty confirmed set -> peer is no longer responsible for any
747    // of the failed keys (topology churn). This is NOT a pass — the peer did
748    // not prove it stores the data. Return Idle to avoid granting unearned
749    // positive trust.
750    if confirmed_failures.is_empty() {
751        info!("Audit: all failures for {challenged_peer} cleared by responsibility confirmation");
752        return AuditTickResult::Idle;
753    }
754
755    let summary = build_audit_failure_summary(challenged_key_count, &confirmed_failures);
756    let reason = if reason == AuditFailureReason::DigestMismatch {
757        audit_digest_failure_reason(&confirmed_failures)
758    } else {
759        reason
760    };
761    let confirmed_failed_keys = confirmed_failures
762        .iter()
763        .map(|failure| failure.key)
764        .collect();
765
766    // Step 9d: Non-empty confirmed set -> emit evidence.
767    let evidence = FailureEvidence::AuditFailure {
768        challenge_id,
769        challenged_peer: *challenged_peer,
770        confirmed_failed_keys,
771        summary,
772        reason,
773    };
774
775    AuditTickResult::Failed {
776        evidence,
777        no_response_class,
778    }
779}
780
781/// Handle audit timeout (no response received).
782async fn handle_audit_timeout(
783    challenged_peer: &PeerId,
784    challenge_id: u64,
785    keys: &[XorName],
786    no_response_class: AuditFailureClass,
787    p2p_node: &Arc<P2PNode>,
788    config: &ReplicationConfig,
789) -> AuditTickResult {
790    let failures = keys
791        .iter()
792        .copied()
793        .map(AuditKeyFailure::unclassified)
794        .collect::<Vec<_>>();
795    handle_classified_audit_failure(
796        challenged_peer,
797        challenge_id,
798        &failures,
799        AuditFailureReason::Timeout,
800        keys.len(),
801        Some(no_response_class.as_str()),
802        p2p_node,
803        config,
804    )
805    .await
806}
807
808// ---------------------------------------------------------------------------
809// Responder-side handler
810// ---------------------------------------------------------------------------
811
812/// Handle an incoming audit challenge (responder side).
813///
814/// Validates that the challenge targets this node, computes per-key digests,
815/// and returns the response.  Rejects challenges where
816/// `challenged_peer_id` does not match `self_peer_id` to prevent an oracle
817/// attack where a malicious challenger forges digests for a different peer.
818pub async fn handle_audit_challenge(
819    challenge: &AuditChallenge,
820    storage: &ChunkStore,
821    self_peer_id: &PeerId,
822    is_bootstrapping: bool,
823    stored_chunks: usize,
824) -> AuditResponse {
825    if is_bootstrapping {
826        return AuditResponse::Bootstrapping {
827            challenge_id: challenge.challenge_id,
828        };
829    }
830
831    if challenge.challenged_peer_id != *self_peer_id.as_bytes() {
832        warn!(
833            "Audit challenge targeted wrong peer: expected {}, got {}",
834            hex::encode(self_peer_id.as_bytes()),
835            hex::encode(challenge.challenged_peer_id),
836        );
837        return AuditResponse::Rejected {
838            challenge_id: challenge.challenge_id,
839            reason: "challenged_peer_id does not match this node".to_string(),
840        };
841    }
842
843    let max_keys = ReplicationConfig::max_incoming_audit_keys(stored_chunks);
844    if challenge.keys.len() > max_keys {
845        warn!(
846            "Audit challenge rejected: {} keys exceeds dynamic limit of {max_keys} \
847             (stored_chunks={stored_chunks})",
848            challenge.keys.len(),
849        );
850        return AuditResponse::Rejected {
851            challenge_id: challenge.challenge_id,
852            reason: format!(
853                "challenge contains {} keys, limit is {max_keys}",
854                challenge.keys.len()
855            ),
856        };
857    }
858
859    let mut digests = Vec::with_capacity(challenge.keys.len());
860
861    for key in &challenge.keys {
862        match storage.get_raw(key).await {
863            Ok(Some(data)) => {
864                let digest = compute_audit_digest(
865                    &challenge.nonce,
866                    &challenge.challenged_peer_id,
867                    key,
868                    &data,
869                );
870                digests.push(digest);
871            }
872            Ok(None) => {
873                digests.push(ABSENT_KEY_DIGEST);
874            }
875            Err(e) => {
876                warn!(
877                    "Audit responder: failed to read key {}: {e}",
878                    hex::encode(key)
879                );
880                digests.push(ABSENT_KEY_DIGEST);
881            }
882        }
883    }
884
885    AuditResponse::Digests {
886        challenge_id: challenge.challenge_id,
887        digests,
888    }
889}
890
891// ---------------------------------------------------------------------------
892// Tests
893// ---------------------------------------------------------------------------
894
895#[cfg(test)]
896#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
897mod tests {
898    use super::*;
899
900    /// Simulated stored chunk count for tests. Large enough that the dynamic
901    /// incoming audit limit (`2 * sqrt(N)`) never rejects small test challenges.
902    const TEST_STORED_CHUNKS: usize = 1_000_000;
903
904    #[test]
905    fn first_challenged_key_label_truncates_to_16_hex_chars() {
906        let mut key = [0u8; 32];
907        key[0] = 0xAB;
908        key[7] = 0xCD;
909        key[8] = 0xEF;
910
911        assert_eq!(first_challenged_key_label(&[key]), "0xab000000000000cd");
912    }
913
914    #[test]
915    fn first_challenged_key_label_falls_back_when_empty() {
916        assert_eq!(first_challenged_key_label(&[]), "0x");
917    }
918
919    #[test]
920    fn classify_audit_send_error_uses_bounded_classes() {
921        assert_eq!(
922            classify_audit_send_error("request to peer timed out after 10s"),
923            ("response_timeout", AuditFailureClass::Timeout)
924        );
925        assert_eq!(
926            classify_audit_send_error("peer not found in active channels"),
927            ("peer_unavailable", AuditFailureClass::Unreachable)
928        );
929        assert_eq!(
930            classify_audit_send_error("dial failed for all candidate addresses"),
931            ("connection_failed", AuditFailureClass::Unreachable)
932        );
933        assert_eq!(
934            classify_audit_send_error("response receiver dropped before delivery"),
935            ("connection_closed", AuditFailureClass::Unreachable)
936        );
937        assert_eq!(
938            classify_audit_send_error("transport stream error"),
939            ("transport_error", AuditFailureClass::Unreachable)
940        );
941        assert_eq!(
942            classify_audit_send_error("operation timed out after 10s"),
943            ("transport_timeout", AuditFailureClass::Unreachable)
944        );
945        assert_eq!(
946            classify_audit_send_error("unexpected error"),
947            ("other", AuditFailureClass::Unreachable)
948        );
949    }
950
951    /// Create a test `ChunkStore` backed by a temp directory.
952    async fn create_test_storage() -> (ChunkStore, TempDir) {
953        let temp_dir = TempDir::new().expect("create temp dir");
954        let config = ChunkStoreConfig {
955            root_dir: temp_dir.path().to_path_buf(),
956            verify_on_read: false,
957            disk_reserve: 0,
958        };
959        let storage = ChunkStore::new(config).await.expect("create storage");
960        (storage, temp_dir)
961    }
962
963    /// Build a challenge with the given parameters.
964    fn make_challenge(
965        challenge_id: u64,
966        nonce: [u8; 32],
967        peer_id: [u8; 32],
968        keys: Vec<XorName>,
969    ) -> AuditChallenge {
970        AuditChallenge {
971            challenge_id,
972            nonce,
973            challenged_peer_id: peer_id,
974            keys,
975        }
976    }
977
978    /// Build a `PeerId` matching the raw bytes used in a challenge.
979    fn peer_id_from_bytes(bytes: [u8; 32]) -> PeerId {
980        PeerId::from_bytes(bytes)
981    }
982
983    // -- handle_audit_challenge: present keys ---------------------------------
984
985    #[tokio::test]
986    async fn handle_challenge_present_keys_returns_correct_digests() {
987        let (storage, _temp) = create_test_storage().await;
988
989        // Store two chunks.
990        let content_a = b"chunk alpha";
991        let addr_a = ChunkStore::compute_address(content_a);
992        storage.put(&addr_a, content_a).await.expect("put a");
993
994        let content_b = b"chunk beta";
995        let addr_b = ChunkStore::compute_address(content_b);
996        storage.put(&addr_b, content_b).await.expect("put b");
997
998        let nonce = [0xAA; 32];
999        let peer_id = [0xBB; 32];
1000        let challenge = make_challenge(42, nonce, peer_id, vec![addr_a, addr_b]);
1001        let self_id = peer_id_from_bytes(peer_id);
1002
1003        let response =
1004            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1005
1006        match response {
1007            AuditResponse::Digests {
1008                challenge_id,
1009                digests,
1010            } => {
1011                assert_eq!(challenge_id, 42);
1012                assert_eq!(digests.len(), 2);
1013
1014                let expected_a = compute_audit_digest(&nonce, &peer_id, &addr_a, content_a);
1015                let expected_b = compute_audit_digest(&nonce, &peer_id, &addr_b, content_b);
1016                assert_eq!(digests[0], expected_a);
1017                assert_eq!(digests[1], expected_b);
1018            }
1019            AuditResponse::Bootstrapping { .. } => {
1020                panic!("expected Digests, got Bootstrapping");
1021            }
1022            AuditResponse::Rejected { .. } => {
1023                panic!("Unexpected Rejected response");
1024            }
1025        }
1026    }
1027
1028    // -- handle_audit_challenge: absent keys ----------------------------------
1029
1030    #[tokio::test]
1031    async fn handle_challenge_absent_keys_returns_sentinel() {
1032        let (storage, _temp) = create_test_storage().await;
1033
1034        let absent_key = [0xFF; 32];
1035        let nonce = [0x11; 32];
1036        let peer_id = [0x22; 32];
1037        let challenge = make_challenge(99, nonce, peer_id, vec![absent_key]);
1038        let self_id = peer_id_from_bytes(peer_id);
1039
1040        let response =
1041            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1042
1043        match response {
1044            AuditResponse::Digests {
1045                challenge_id,
1046                digests,
1047            } => {
1048                assert_eq!(challenge_id, 99);
1049                assert_eq!(digests.len(), 1);
1050                assert_eq!(
1051                    digests[0], ABSENT_KEY_DIGEST,
1052                    "absent key should produce sentinel digest"
1053                );
1054            }
1055            AuditResponse::Bootstrapping { .. } => {
1056                panic!("expected Digests, got Bootstrapping");
1057            }
1058            AuditResponse::Rejected { .. } => {
1059                panic!("Unexpected Rejected response");
1060            }
1061        }
1062    }
1063
1064    // -- handle_audit_challenge: mixed present and absent ---------------------
1065
1066    #[tokio::test]
1067    async fn handle_challenge_mixed_present_and_absent() {
1068        let (storage, _temp) = create_test_storage().await;
1069
1070        let content = b"present chunk";
1071        let addr_present = ChunkStore::compute_address(content);
1072        storage.put(&addr_present, content).await.expect("put");
1073
1074        let addr_absent = [0xDE; 32];
1075        let nonce = [0x33; 32];
1076        let peer_id = [0x44; 32];
1077        let challenge = make_challenge(7, nonce, peer_id, vec![addr_present, addr_absent]);
1078        let self_id = peer_id_from_bytes(peer_id);
1079
1080        let response =
1081            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1082
1083        match response {
1084            AuditResponse::Digests { digests, .. } => {
1085                assert_eq!(digests.len(), 2);
1086
1087                let expected_present =
1088                    compute_audit_digest(&nonce, &peer_id, &addr_present, content);
1089                assert_eq!(digests[0], expected_present);
1090                assert_eq!(
1091                    digests[1], ABSENT_KEY_DIGEST,
1092                    "absent key should be sentinel"
1093                );
1094            }
1095            AuditResponse::Bootstrapping { .. } => {
1096                panic!("expected Digests, got Bootstrapping");
1097            }
1098            AuditResponse::Rejected { .. } => {
1099                panic!("Unexpected Rejected response");
1100            }
1101        }
1102    }
1103
1104    // -- handle_audit_challenge: bootstrapping --------------------------------
1105
1106    #[tokio::test]
1107    async fn handle_challenge_bootstrapping_returns_bootstrapping_response() {
1108        let (storage, _temp) = create_test_storage().await;
1109
1110        let challenge = make_challenge(55, [0x00; 32], [0x01; 32], vec![[0x02; 32]]);
1111        let self_id = peer_id_from_bytes([0x01; 32]);
1112
1113        let response =
1114            handle_audit_challenge(&challenge, &storage, &self_id, true, TEST_STORED_CHUNKS).await;
1115
1116        match response {
1117            AuditResponse::Bootstrapping { challenge_id } => {
1118                assert_eq!(challenge_id, 55);
1119            }
1120            AuditResponse::Digests { .. } => {
1121                panic!("expected Bootstrapping, got Digests");
1122            }
1123            AuditResponse::Rejected { .. } => {
1124                panic!("Unexpected Rejected response");
1125            }
1126        }
1127    }
1128
1129    // -- handle_audit_challenge: empty key list -------------------------------
1130
1131    #[tokio::test]
1132    async fn handle_challenge_empty_keys_returns_empty_digests() {
1133        let (storage, _temp) = create_test_storage().await;
1134
1135        let challenge = make_challenge(100, [0x10; 32], [0x20; 32], vec![]);
1136        let self_id = peer_id_from_bytes([0x20; 32]);
1137
1138        let response =
1139            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1140
1141        match response {
1142            AuditResponse::Digests {
1143                challenge_id,
1144                digests,
1145            } => {
1146                assert_eq!(challenge_id, 100);
1147                assert!(
1148                    digests.is_empty(),
1149                    "empty key list should yield empty digests"
1150                );
1151            }
1152            AuditResponse::Bootstrapping { .. } => {
1153                panic!("expected Digests, got Bootstrapping");
1154            }
1155            AuditResponse::Rejected { .. } => {
1156                panic!("Unexpected Rejected response");
1157            }
1158        }
1159    }
1160
1161    // -- Digest verification: matching ----------------------------------------
1162
1163    #[test]
1164    fn digest_verification_matching() {
1165        let nonce = [0x01; 32];
1166        let peer_id = [0x02; 32];
1167        let key: XorName = [0x03; 32];
1168        let data = b"correct data";
1169
1170        let expected = compute_audit_digest(&nonce, &peer_id, &key, data);
1171        let recomputed = compute_audit_digest(&nonce, &peer_id, &key, data);
1172
1173        assert_eq!(
1174            expected, recomputed,
1175            "same inputs must produce identical digests"
1176        );
1177        assert_ne!(
1178            expected, ABSENT_KEY_DIGEST,
1179            "real digest must not be sentinel"
1180        );
1181    }
1182
1183    // -- Digest verification: mismatching -------------------------------------
1184
1185    #[test]
1186    fn digest_verification_mismatching_data() {
1187        let nonce = [0x01; 32];
1188        let peer_id = [0x02; 32];
1189        let key: XorName = [0x03; 32];
1190
1191        let digest_a = compute_audit_digest(&nonce, &peer_id, &key, b"data version A");
1192        let digest_b = compute_audit_digest(&nonce, &peer_id, &key, b"data version B");
1193
1194        assert_ne!(
1195            digest_a, digest_b,
1196            "different data must produce different digests"
1197        );
1198    }
1199
1200    #[test]
1201    fn digest_verification_mismatching_nonce() {
1202        let peer_id = [0x02; 32];
1203        let key: XorName = [0x03; 32];
1204        let data = b"same data";
1205
1206        let digest_a = compute_audit_digest(&[0x01; 32], &peer_id, &key, data);
1207        let digest_b = compute_audit_digest(&[0xFF; 32], &peer_id, &key, data);
1208
1209        assert_ne!(
1210            digest_a, digest_b,
1211            "different nonces must produce different digests"
1212        );
1213    }
1214
1215    #[test]
1216    fn digest_verification_mismatching_peer() {
1217        let nonce = [0x01; 32];
1218        let key: XorName = [0x03; 32];
1219        let data = b"same data";
1220
1221        let digest_a = compute_audit_digest(&nonce, &[0x02; 32], &key, data);
1222        let digest_b = compute_audit_digest(&nonce, &[0xFE; 32], &key, data);
1223
1224        assert_ne!(
1225            digest_a, digest_b,
1226            "different peers must produce different digests"
1227        );
1228    }
1229
1230    #[test]
1231    fn digest_verification_mismatching_key() {
1232        let nonce = [0x01; 32];
1233        let peer_id = [0x02; 32];
1234        let data = b"same data";
1235
1236        let digest_a = compute_audit_digest(&nonce, &peer_id, &[0x03; 32], data);
1237        let digest_b = compute_audit_digest(&nonce, &peer_id, &[0xFC; 32], data);
1238
1239        assert_ne!(
1240            digest_a, digest_b,
1241            "different keys must produce different digests"
1242        );
1243    }
1244
1245    // -- Absent sentinel is all zeros -----------------------------------------
1246
1247    #[test]
1248    fn absent_sentinel_is_all_zeros() {
1249        assert_eq!(ABSENT_KEY_DIGEST, [0u8; 32], "sentinel must be all zeros");
1250    }
1251
1252    // -- Bootstrapping skips digest computation even with stored keys ---------
1253
1254    #[tokio::test]
1255    async fn bootstrapping_skips_digest_computation() {
1256        let (storage, _temp) = create_test_storage().await;
1257
1258        let content = b"stored but bootstrapping";
1259        let addr = ChunkStore::compute_address(content);
1260        storage.put(&addr, content).await.expect("put");
1261
1262        let challenge = make_challenge(200, [0xCC; 32], [0xDD; 32], vec![addr]);
1263        let self_id = peer_id_from_bytes([0xDD; 32]);
1264
1265        let response =
1266            handle_audit_challenge(&challenge, &storage, &self_id, true, TEST_STORED_CHUNKS).await;
1267
1268        assert!(
1269            matches!(response, AuditResponse::Bootstrapping { challenge_id: 200 }),
1270            "bootstrapping node must not compute digests"
1271        );
1272    }
1273
1274    // -- Scenario 19/53: Partial failure with mixed responsibility ----------------
1275
1276    #[tokio::test]
1277    async fn scenario_19_partial_failure_mixed_responsibility() {
1278        // Three keys challenged: K1 matches, K2 mismatches, K3 absent.
1279        // After responsibility confirmation, only K2 is confirmed responsible.
1280        // AuditFailure emitted for {K2} only.
1281        // Test handle_audit_challenge with mixed results, then verify
1282        // the digest logic manually.
1283
1284        let (storage, _temp) = create_test_storage().await;
1285        let nonce = [0x42u8; 32];
1286        let peer_id = [0xAA; 32];
1287
1288        // Store K1 and K2, but NOT K3
1289        let content_k1 = b"key one data";
1290        let addr_k1 = ChunkStore::compute_address(content_k1);
1291        storage.put(&addr_k1, content_k1).await.unwrap();
1292
1293        let content_k2 = b"key two data";
1294        let addr_k2 = ChunkStore::compute_address(content_k2);
1295        storage.put(&addr_k2, content_k2).await.unwrap();
1296
1297        let addr_k3 = [0xFF; 32]; // Not stored
1298
1299        let challenge = AuditChallenge {
1300            challenge_id: 100,
1301            nonce,
1302            challenged_peer_id: peer_id,
1303            keys: vec![addr_k1, addr_k2, addr_k3],
1304        };
1305        let self_id = peer_id_from_bytes(peer_id);
1306
1307        let response =
1308            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1309
1310        match response {
1311            AuditResponse::Digests { digests, .. } => {
1312                assert_eq!(digests.len(), 3);
1313
1314                // K1 should have correct digest
1315                let expected_k1 = compute_audit_digest(&nonce, &peer_id, &addr_k1, content_k1);
1316                assert_eq!(digests[0], expected_k1);
1317
1318                // K2 should have correct digest
1319                let expected_k2 = compute_audit_digest(&nonce, &peer_id, &addr_k2, content_k2);
1320                assert_eq!(digests[1], expected_k2);
1321
1322                // K3 absent -> sentinel
1323                assert_eq!(digests[2], ABSENT_KEY_DIGEST);
1324            }
1325            AuditResponse::Bootstrapping { .. } => panic!("Expected Digests response"),
1326            AuditResponse::Rejected { .. } => panic!("Unexpected Rejected response"),
1327        }
1328    }
1329
1330    // -- Scenario 54: All digests pass -------------------------------------------
1331
1332    #[tokio::test]
1333    async fn scenario_54_all_digests_pass() {
1334        // All challenged keys present and digests match.
1335        // Multiple keys to strengthen coverage beyond existing two-key tests.
1336        let (storage, _temp) = create_test_storage().await;
1337        let nonce = [0x10; 32];
1338        let peer_id = [0x20; 32];
1339
1340        let c1 = b"chunk alpha";
1341        let c2 = b"chunk beta";
1342        let c3 = b"chunk gamma";
1343        let a1 = ChunkStore::compute_address(c1);
1344        let a2 = ChunkStore::compute_address(c2);
1345        let a3 = ChunkStore::compute_address(c3);
1346        storage.put(&a1, c1).await.unwrap();
1347        storage.put(&a2, c2).await.unwrap();
1348        storage.put(&a3, c3).await.unwrap();
1349
1350        let challenge = AuditChallenge {
1351            challenge_id: 200,
1352            nonce,
1353            challenged_peer_id: peer_id,
1354            keys: vec![a1, a2, a3],
1355        };
1356        let self_id = peer_id_from_bytes(peer_id);
1357
1358        let response =
1359            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1360        match response {
1361            AuditResponse::Digests { digests, .. } => {
1362                assert_eq!(digests.len(), 3);
1363                for (i, (addr, content)) in [(a1, &c1[..]), (a2, &c2[..]), (a3, &c3[..])]
1364                    .iter()
1365                    .enumerate()
1366                {
1367                    let expected = compute_audit_digest(&nonce, &peer_id, addr, content);
1368                    assert_eq!(digests[i], expected, "Key {i} digest should match");
1369                }
1370            }
1371            AuditResponse::Bootstrapping { .. } => panic!("Expected Digests"),
1372            AuditResponse::Rejected { .. } => panic!("Unexpected Rejected response"),
1373        }
1374    }
1375
1376    // -- A rotted local reference copy -------------------------------------------
1377
1378    /// The auditor's own copy is the reference a peer is judged against. A local
1379    /// copy that has rotted must not fail an honest peer, must not count as a
1380    /// verification either, and is taken out of service so replication repairs it.
1381    #[tokio::test]
1382    async fn a_rotted_local_copy_neither_fails_nor_passes_the_peer() {
1383        let temp_dir = TempDir::new().expect("temp dir");
1384        let storage = ChunkStore::new(ChunkStoreConfig {
1385            root_dir: temp_dir.path().to_path_buf(),
1386            ..ChunkStoreConfig::test_default()
1387        })
1388        .await
1389        .expect("storage");
1390        let nonce = [0x42; 32];
1391        let peer = PeerId::from_bytes([0x24; 32]);
1392        let rot = |key: &XorName| {
1393            let path = temp_dir
1394                .path()
1395                .join(CHUNKS_DIR_NAME)
1396                .join(format!("{:02x}", key.last().copied().unwrap_or(0)))
1397                .join(hex::encode(key));
1398            std::fs::write(path, b"rotted").expect("corrupt the file");
1399        };
1400
1401        let mut stored = Vec::new();
1402        for content in [
1403            &b"intact copy"[..],
1404            b"first rotted copy",
1405            b"second rotted copy",
1406        ] {
1407            let key = ChunkStore::compute_address(content);
1408            storage.put(&key, content).await.expect("put");
1409            stored.push((key, content.to_vec()));
1410        }
1411        let [(good, good_bytes), (lone, lone_bytes), (paired, paired_bytes)] = stored.as_slice()
1412        else {
1413            panic!("three chunks stored");
1414        };
1415        rot(lone);
1416        rot(paired);
1417        let honest = |key: &XorName, content: &[u8]| {
1418            compute_audit_digest(&nonce, peer.as_bytes(), key, content)
1419        };
1420
1421        // Only a rotted reference: nothing can be checked, so no pass either way.
1422        let nothing = compare_with_local_copies(
1423            &storage,
1424            &nonce,
1425            peer.as_bytes(),
1426            &[*lone],
1427            &[honest(lone, lone_bytes)],
1428        )
1429        .await;
1430        assert!(
1431            nothing.failed_keys.is_empty(),
1432            "an honest peer is not failed"
1433        );
1434        assert_eq!(nothing.verified, 0);
1435        assert!(matches!(
1436            unfailed_audit_verdict(&peer, 1, nothing.verified),
1437            AuditTickResult::Idle
1438        ));
1439        assert!(
1440            !storage.exists(lone).expect("exists"),
1441            "the rotted local copy is taken out of service"
1442        );
1443
1444        // A good and a rotted reference: the peer passes on what was checked.
1445        let partial = compare_with_local_copies(
1446            &storage,
1447            &nonce,
1448            peer.as_bytes(),
1449            &[*good, *paired],
1450            &[honest(good, good_bytes), honest(paired, paired_bytes)],
1451        )
1452        .await;
1453        assert!(
1454            partial.failed_keys.is_empty(),
1455            "an honest peer failed against a rotted reference: {:?}",
1456            partial.failed_keys
1457        );
1458        assert_eq!(partial.verified, 1);
1459        assert!(matches!(
1460            unfailed_audit_verdict(&peer, 2, partial.verified),
1461            AuditTickResult::Passed {
1462                keys_checked: 1,
1463                ..
1464            }
1465        ));
1466
1467        // A wrong digest against a good reference still fails, as before.
1468        let wrong =
1469            compare_with_local_copies(&storage, &nonce, peer.as_bytes(), &[*good], &[[0xAB; 32]])
1470                .await;
1471        assert_eq!(wrong.failed_keys.len(), 1);
1472        assert_eq!(wrong.verified, 0);
1473    }
1474
1475    // -- Scenario 55: Empty failure set means no evidence -------------------------
1476
1477    /// Scenario 55: Peer challenged on {K1, K2}. Both digests mismatch.
1478    /// Responsibility confirmation shows the peer is NOT responsible for
1479    /// either key. The confirmed failure set is empty — no `AuditFailure`
1480    /// evidence is emitted.
1481    ///
1482    /// Full `verify_digests` requires a live `P2PNode` for network lookups.
1483    /// This test exercises the deterministic sub-steps:
1484    ///   (1) Digest comparison identifies K1 and K2 as mismatches.
1485    ///   (2) Responsibility confirmation removes both keys.
1486    ///   (3) Empty confirmed failure set means no evidence.
1487    #[tokio::test]
1488    async fn scenario_55_no_confirmed_responsibility_no_evidence() {
1489        let (storage, _temp) = create_test_storage().await;
1490        let nonce = [0x55; 32];
1491        let peer_id = [0x55; 32];
1492
1493        // Store K1 and K2 on the challenger (for expected digest computation).
1494        let c1 = b"scenario 55 key one";
1495        let c2 = b"scenario 55 key two";
1496        let k1 = ChunkStore::compute_address(c1);
1497        let k2 = ChunkStore::compute_address(c2);
1498        storage.put(&k1, c1).await.expect("put k1");
1499        storage.put(&k2, c2).await.expect("put k2");
1500
1501        // Challenger computes expected digests.
1502        let expected_d1 = compute_audit_digest(&nonce, &peer_id, &k1, c1);
1503        let expected_d2 = compute_audit_digest(&nonce, &peer_id, &k2, c2);
1504
1505        // Simulate peer returning WRONG digests for both keys.
1506        let wrong_d1 = compute_audit_digest(&nonce, &peer_id, &k1, b"corrupted k1");
1507        let wrong_d2 = compute_audit_digest(&nonce, &peer_id, &k2, b"corrupted k2");
1508        assert_ne!(wrong_d1, expected_d1, "K1 digest should mismatch");
1509        assert_ne!(wrong_d2, expected_d2, "K2 digest should mismatch");
1510
1511        // Step 1: Identify failed keys via digest comparison.
1512        let keys = [k1, k2];
1513        let expected = [expected_d1, expected_d2];
1514        let received = [wrong_d1, wrong_d2];
1515
1516        let mut failed_keys = Vec::new();
1517        for i in 0..keys.len() {
1518            if received[i] != expected[i] {
1519                failed_keys.push(keys[i]);
1520            }
1521        }
1522        assert_eq!(
1523            failed_keys.len(),
1524            2,
1525            "Both keys should be identified as digest mismatches"
1526        );
1527
1528        // Step 2: Responsibility confirmation — peer is NOT responsible for
1529        // either key (simulated by filtering them all out).
1530        let confirmed_responsible_keys: Vec<XorName> = Vec::new();
1531        let confirmed_failures: Vec<XorName> = failed_keys
1532            .into_iter()
1533            .filter(|k| confirmed_responsible_keys.contains(k))
1534            .collect();
1535
1536        // Step 3: Empty confirmed failure set → no AuditFailure evidence.
1537        assert!(
1538            confirmed_failures.is_empty(),
1539            "With no confirmed responsibility, failure set must be empty — \
1540             no AuditFailure evidence should be emitted"
1541        );
1542
1543        // Verify that constructing evidence with empty keys results in a
1544        // no-penalty outcome (the caller checks is_empty before emitting).
1545        let peer = PeerId::from_bytes(peer_id);
1546        let evidence = FailureEvidence::AuditFailure {
1547            challenge_id: 5500,
1548            challenged_peer: peer,
1549            confirmed_failed_keys: confirmed_failures,
1550            summary: AuditFailureSummary::default(),
1551            reason: AuditFailureReason::DigestMismatch,
1552        };
1553        if let FailureEvidence::AuditFailure {
1554            confirmed_failed_keys,
1555            ..
1556        } = evidence
1557        {
1558            assert!(
1559                confirmed_failed_keys.is_empty(),
1560                "Evidence with empty failure set should not trigger a trust penalty"
1561            );
1562        }
1563    }
1564
1565    // -- Scenario 56: RepairOpportunity filters never-synced peers ----------------
1566
1567    #[test]
1568    fn scenario_56_repair_opportunity_filters_never_synced() {
1569        // PeerSyncRecord with last_sync=None should not pass
1570        // has_repair_opportunity().
1571
1572        let never_synced = PeerSyncRecord {
1573            last_sync: None,
1574            cycles_since_sync: 5,
1575        };
1576        assert!(!never_synced.has_repair_opportunity());
1577
1578        let synced_no_cycle = PeerSyncRecord {
1579            last_sync: Some(Instant::now()),
1580            cycles_since_sync: 0,
1581        };
1582        assert!(!synced_no_cycle.has_repair_opportunity());
1583
1584        let synced_with_cycle = PeerSyncRecord {
1585            last_sync: Some(Instant::now()),
1586            cycles_since_sync: 1,
1587        };
1588        assert!(synced_with_cycle.has_repair_opportunity());
1589    }
1590
1591    #[test]
1592    fn expired_bootstrap_claim_does_not_remove_peer_from_audit_eligibility() {
1593        let peer = peer_id_from_bytes([0x57; 32]);
1594        let mut sync_history = HashMap::new();
1595        sync_history.insert(
1596            peer,
1597            PeerSyncRecord {
1598                last_sync: Some(Instant::now()),
1599                cycles_since_sync: 1,
1600            },
1601        );
1602
1603        let mut bootstrap_claims = HashMap::new();
1604        let first_seen = Instant::now()
1605            .checked_sub(
1606                crate::replication::config::BOOTSTRAP_CLAIM_GRACE_PERIOD
1607                    + std::time::Duration::from_secs(1),
1608            )
1609            .unwrap_or_else(Instant::now);
1610        bootstrap_claims.insert(peer, first_seen);
1611
1612        let eligible = eligible_audit_peers(&sync_history);
1613
1614        assert!(bootstrap_claims.contains_key(&peer));
1615        assert!(
1616            eligible.contains(&peer),
1617            "continued bootstrap claims must remain auditable so past-grace abuse can be observed"
1618        );
1619    }
1620
1621    #[test]
1622    fn audit_failure_summary_counts_confirmed_absent_and_mismatch_keys() {
1623        let absent_key = [0xA1; 32];
1624        let mismatch_key = [0xB2; 32];
1625        let confirmed = vec![
1626            AuditKeyFailure::absent(absent_key),
1627            AuditKeyFailure::digest_mismatch(mismatch_key),
1628        ];
1629
1630        let summary = build_audit_failure_summary(5, &confirmed);
1631
1632        assert_eq!(summary.challenged_keys, 5);
1633        assert_eq!(summary.failed_keys, 2);
1634        assert_eq!(summary.absent_keys, 1);
1635        assert_eq!(summary.digest_mismatch_keys, 1);
1636    }
1637
1638    #[test]
1639    fn audit_failure_summary_leaves_unclassified_rejections_out_of_absent_mismatch_counts() {
1640        let rejected_key = [0xC3; 32];
1641        let confirmed = vec![AuditKeyFailure::unclassified(rejected_key)];
1642
1643        let summary = build_audit_failure_summary(3, &confirmed);
1644
1645        assert_eq!(summary.challenged_keys, 3);
1646        assert_eq!(summary.failed_keys, 1);
1647        assert_eq!(summary.absent_keys, 0);
1648        assert_eq!(summary.digest_mismatch_keys, 0);
1649    }
1650
1651    #[test]
1652    fn audit_digest_failure_reason_is_key_absent_when_all_confirmed_failures_are_absent() {
1653        let failures = vec![AuditKeyFailure::absent([0xD4; 32])];
1654
1655        assert_eq!(
1656            audit_digest_failure_reason(&failures),
1657            AuditFailureReason::KeyAbsent
1658        );
1659    }
1660
1661    #[test]
1662    fn audit_digest_failure_reason_is_digest_mismatch_for_mixed_failures() {
1663        let failures = vec![
1664            AuditKeyFailure::absent([0xD5; 32]),
1665            AuditKeyFailure::digest_mismatch([0xE6; 32]),
1666        ];
1667
1668        assert_eq!(
1669            audit_digest_failure_reason(&failures),
1670            AuditFailureReason::DigestMismatch
1671        );
1672    }
1673
1674    #[test]
1675    fn audit_key_filter_retains_stable_proofs_and_rejects_evicted_peers() {
1676        const HINT_EPOCH: u64 = 7;
1677        const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1678        const CHALLENGED_PEER_BYTE: u8 = 0xA1;
1679        const OTHER_PEER_BYTE: u8 = 0xA2;
1680        const NEW_PEER_BYTE: u8 = 0xA3;
1681        const MATURE_KEY_BYTE: u8 = 0xB1;
1682        const SAME_EPOCH_KEY_BYTE: u8 = 0xB2;
1683        const MISSING_PROOF_KEY_BYTE: u8 = 0xB3;
1684        const STABLE_CHURN_KEY_BYTE: u8 = 0xB4;
1685        const EVICTED_KEY_BYTE: u8 = 0xB5;
1686        const FRESH_HINT_KEY_BYTE: u8 = 0xB6;
1687        const XOR_NAME_LEN: usize = 32;
1688
1689        let challenged_peer = peer_id_from_bytes([CHALLENGED_PEER_BYTE; XOR_NAME_LEN]);
1690        let other_peer = peer_id_from_bytes([OTHER_PEER_BYTE; XOR_NAME_LEN]);
1691        let new_peer = peer_id_from_bytes([NEW_PEER_BYTE; XOR_NAME_LEN]);
1692        let mature_key = [MATURE_KEY_BYTE; XOR_NAME_LEN];
1693        let same_epoch_key = [SAME_EPOCH_KEY_BYTE; XOR_NAME_LEN];
1694        let missing_proof_key = [MISSING_PROOF_KEY_BYTE; XOR_NAME_LEN];
1695        let stable_churn_key = [STABLE_CHURN_KEY_BYTE; XOR_NAME_LEN];
1696        let evicted_key = [EVICTED_KEY_BYTE; XOR_NAME_LEN];
1697        let fresh_hint_key = [FRESH_HINT_KEY_BYTE; XOR_NAME_LEN];
1698        let close_group = HashSet::from([challenged_peer, other_peer]);
1699        let changed_close_group = HashSet::from([challenged_peer, new_peer]);
1700        let evicted_close_group = HashSet::from([other_peer, new_peer]);
1701        let mut repair_proofs = RepairProofs::new();
1702        let mature_hinted_at = Instant::now();
1703        let now = mature_hinted_at
1704            .checked_add(REPAIR_HINT_MIN_AGE)
1705            .unwrap_or(mature_hinted_at);
1706
1707        assert!(repair_proofs.record_replica_hint_sent_at(
1708            challenged_peer,
1709            mature_key,
1710            &close_group,
1711            HINT_EPOCH,
1712            mature_hinted_at,
1713        ));
1714        assert!(repair_proofs.record_replica_hint_sent_at(
1715            challenged_peer,
1716            same_epoch_key,
1717            &close_group,
1718            CURRENT_EPOCH,
1719            mature_hinted_at,
1720        ));
1721        assert!(repair_proofs.record_replica_hint_sent_at(
1722            challenged_peer,
1723            stable_churn_key,
1724            &close_group,
1725            HINT_EPOCH,
1726            mature_hinted_at,
1727        ));
1728        assert!(repair_proofs.record_replica_hint_sent_at(
1729            challenged_peer,
1730            evicted_key,
1731            &close_group,
1732            HINT_EPOCH,
1733            mature_hinted_at,
1734        ));
1735        assert!(repair_proofs.record_replica_hint_sent_at(
1736            challenged_peer,
1737            fresh_hint_key,
1738            &close_group,
1739            HINT_EPOCH,
1740            now,
1741        ));
1742
1743        let sampled_key_groups = vec![
1744            (mature_key, close_group.clone()),
1745            (same_epoch_key, close_group.clone()),
1746            (missing_proof_key, close_group.clone()),
1747            (stable_churn_key, changed_close_group),
1748            (evicted_key, evicted_close_group),
1749            (fresh_hint_key, close_group.clone()),
1750        ];
1751        let peer_keys = mature_audit_keys_for_peer(
1752            &challenged_peer,
1753            sampled_key_groups,
1754            &mut repair_proofs,
1755            CURRENT_EPOCH,
1756            now,
1757        );
1758
1759        assert_eq!(
1760            peer_keys,
1761            vec![mature_key, stable_churn_key],
1762            "mature proofs for stable close-group peers should become audit keys, while same-epoch, fresh, missing, and evicted-peer proofs should not"
1763        );
1764    }
1765
1766    // -- Audit response must match key count --------------------------------------
1767
1768    #[tokio::test]
1769    async fn audit_response_must_match_key_count() {
1770        // Section 15: "A response is invalid if it has fewer or more entries
1771        // than challenged keys."
1772        // Verify handle_audit_challenge always produces exactly N digests for
1773        // N keys, including edge cases.
1774
1775        let (storage, _temp) = create_test_storage().await;
1776        let nonce = [0x50; 32];
1777        let peer_id = [0x60; 32];
1778
1779        // Store a single chunk
1780        let content = b"single chunk";
1781        let addr = ChunkStore::compute_address(content);
1782        storage.put(&addr, content).await.unwrap();
1783
1784        // Challenge with 1 stored + 4 absent = 5 keys total
1785        let absent_keys: Vec<XorName> = (1..=4u8).map(|i| [i; 32]).collect();
1786        let mut keys = vec![addr];
1787        keys.extend_from_slice(&absent_keys);
1788
1789        let key_count = keys.len();
1790        let challenge = make_challenge(300, nonce, peer_id, keys);
1791        let self_id = peer_id_from_bytes(peer_id);
1792
1793        let response =
1794            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1795        match response {
1796            AuditResponse::Digests { digests, .. } => {
1797                assert_eq!(
1798                    digests.len(),
1799                    key_count,
1800                    "must produce exactly one digest per challenged key"
1801                );
1802            }
1803            AuditResponse::Bootstrapping { .. } => panic!("Expected Digests"),
1804            AuditResponse::Rejected { .. } => panic!("Unexpected Rejected response"),
1805        }
1806    }
1807
1808    // -- Audit digest uses full record bytes --------------------------------------
1809
1810    #[test]
1811    fn audit_digest_uses_full_record_bytes() {
1812        // Verify digest changes when record content changes.
1813        let nonce = [1u8; 32];
1814        let peer = [2u8; 32];
1815        let key = [3u8; 32];
1816
1817        let d1 = compute_audit_digest(&nonce, &peer, &key, b"data version 1");
1818        let d2 = compute_audit_digest(&nonce, &peer, &key, b"data version 2");
1819        assert_ne!(
1820            d1, d2,
1821            "Different record bytes must produce different digests"
1822        );
1823    }
1824
1825    // -- Scenario 29: Audit start gate ------------------------------------------
1826
1827    /// Scenario 29: `handle_audit_challenge` returns `Bootstrapping` when the
1828    /// node is still bootstrapping — audit digests are never computed, and no
1829    /// `AuditFailure` evidence is emitted by the caller.
1830    ///
1831    /// This is the responder-side gate.  The challenger-side gate is enforced
1832    /// by `audit_tick`'s `is_bootstrapping` guard (Invariant 19) and by
1833    /// `check_bootstrap_drained()` in the engine loop; this test confirms the
1834    /// complementary responder behavior.
1835    #[tokio::test]
1836    async fn scenario_29_audit_start_gate_during_bootstrap() {
1837        let (storage, _temp) = create_test_storage().await;
1838
1839        // Store data so there *would* be work to audit.
1840        let content = b"should not be audited during bootstrap";
1841        let addr = ChunkStore::compute_address(content);
1842        storage.put(&addr, content).await.expect("put");
1843
1844        let challenge = make_challenge(2900, [0x29; 32], [0x29; 32], vec![addr]);
1845        let self_id = peer_id_from_bytes([0x29; 32]);
1846
1847        // Responder is bootstrapping → Bootstrapping response, NOT Digests.
1848        let response =
1849            handle_audit_challenge(&challenge, &storage, &self_id, true, TEST_STORED_CHUNKS).await;
1850        assert!(
1851            matches!(
1852                response,
1853                AuditResponse::Bootstrapping { challenge_id: 2900 }
1854            ),
1855            "bootstrapping node must not compute digests — audit start gate"
1856        );
1857
1858        // Responder is NOT bootstrapping → normal Digests.
1859        let response =
1860            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1861        assert!(
1862            matches!(response, AuditResponse::Digests { .. }),
1863            "drained node should compute digests normally"
1864        );
1865    }
1866
1867    // -- Scenario 30: Audit peer selection from sampled keys --------------------
1868
1869    /// Scenario 30: Key sampling uses dynamic sqrt-based batch sizing and
1870    /// `RepairOpportunity` filtering excludes never-synced peers.
1871    ///
1872    /// Full `audit_tick` requires a live network.  This test verifies the two
1873    /// deterministic sub-steps the function relies on:
1874    ///   (a) `audit_sample_count` scales with `sqrt(total_keys)`.
1875    ///   (b) `PeerSyncRecord::has_repair_opportunity` gates peer eligibility.
1876    #[test]
1877    fn scenario_30_audit_peer_selection_from_sampled_keys() {
1878        // (a) Dynamic sample count scales with sqrt(total_keys).
1879        assert_eq!(
1880            ReplicationConfig::audit_sample_count(100),
1881            10,
1882            "sample count should scale with sqrt(total_keys)"
1883        );
1884
1885        assert_eq!(ReplicationConfig::audit_sample_count(3), 1, "sqrt(3) = 1");
1886
1887        assert_eq!(
1888            ReplicationConfig::audit_sample_count(10_000),
1889            100,
1890            "sqrt(10000) = 100"
1891        );
1892
1893        // (b) Peer eligibility via RepairOpportunity.
1894        // Never synced → not eligible.
1895        let never = PeerSyncRecord {
1896            last_sync: None,
1897            cycles_since_sync: 10,
1898        };
1899        assert!(!never.has_repair_opportunity());
1900
1901        // Synced but zero subsequent cycles → not eligible.
1902        let too_soon = PeerSyncRecord {
1903            last_sync: Some(Instant::now()),
1904            cycles_since_sync: 0,
1905        };
1906        assert!(!too_soon.has_repair_opportunity());
1907
1908        // Synced with ≥1 cycle → eligible.
1909        let eligible = PeerSyncRecord {
1910            last_sync: Some(Instant::now()),
1911            cycles_since_sync: 2,
1912        };
1913        assert!(eligible.has_repair_opportunity());
1914    }
1915
1916    // -- Scenario 32: Dynamic challenge size ------------------------------------
1917
1918    /// Scenario 32: Challenge key count equals `|PeerKeySet(challenged_peer)|`,
1919    /// which is dynamic per round.  If no eligible peer remains after filtering,
1920    /// the tick is idle.
1921    ///
1922    /// Verified via `handle_audit_challenge`: the response digest count always
1923    /// equals the number of keys in the challenge.
1924    #[tokio::test]
1925    async fn scenario_32_dynamic_challenge_size() {
1926        let (storage, _temp) = create_test_storage().await;
1927
1928        // Store varying numbers of chunks.
1929        let mut addrs = Vec::new();
1930        for i in 0u8..5 {
1931            let content = format!("dynamic challenge key {i}");
1932            let addr = ChunkStore::compute_address(content.as_bytes());
1933            storage.put(&addr, content.as_bytes()).await.expect("put");
1934            addrs.push(addr);
1935        }
1936
1937        let nonce = [0x32; 32];
1938        let peer_id = [0x32; 32];
1939        let self_id = peer_id_from_bytes(peer_id);
1940
1941        // Challenge with 1 key.
1942        let challenge1 = make_challenge(3201, nonce, peer_id, vec![addrs[0]]);
1943        let resp1 =
1944            handle_audit_challenge(&challenge1, &storage, &self_id, false, TEST_STORED_CHUNKS)
1945                .await;
1946        if let AuditResponse::Digests { digests, .. } = resp1 {
1947            assert_eq!(digests.len(), 1, "|PeerKeySet| = 1 → 1 digest");
1948        }
1949
1950        // Challenge with 3 keys.
1951        let challenge3 = make_challenge(3203, nonce, peer_id, addrs[0..3].to_vec());
1952        let resp3 =
1953            handle_audit_challenge(&challenge3, &storage, &self_id, false, TEST_STORED_CHUNKS)
1954                .await;
1955        if let AuditResponse::Digests { digests, .. } = resp3 {
1956            assert_eq!(digests.len(), 3, "|PeerKeySet| = 3 → 3 digests");
1957        }
1958
1959        // Challenge with all 5 keys.
1960        let challenge5 = make_challenge(3205, nonce, peer_id, addrs.clone());
1961        let resp5 =
1962            handle_audit_challenge(&challenge5, &storage, &self_id, false, TEST_STORED_CHUNKS)
1963                .await;
1964        if let AuditResponse::Digests { digests, .. } = resp5 {
1965            assert_eq!(digests.len(), 5, "|PeerKeySet| = 5 → 5 digests");
1966        }
1967
1968        // Challenge with 0 keys (idle equivalent — no work).
1969        let challenge0 = make_challenge(3200, nonce, peer_id, vec![]);
1970        let resp0 =
1971            handle_audit_challenge(&challenge0, &storage, &self_id, false, TEST_STORED_CHUNKS)
1972                .await;
1973        if let AuditResponse::Digests { digests, .. } = resp0 {
1974            assert!(digests.is_empty(), "|PeerKeySet| = 0 → 0 digests (idle)");
1975        }
1976    }
1977
1978    // -- Scenario 47: Bootstrap claim grace period (audit) ----------------------
1979
1980    /// Scenario 47: Challenged peer responds with bootstrapping claim during
1981    /// audit.  `handle_audit_challenge` returns `Bootstrapping`; caller records
1982    /// `BootstrapClaimFirstSeen`.  No `AuditFailure` evidence is emitted.
1983    #[tokio::test]
1984    async fn scenario_47_bootstrap_claim_grace_period_audit() {
1985        let (storage, _temp) = create_test_storage().await;
1986
1987        // Store data so there is an auditable key.
1988        let content = b"bootstrap grace test";
1989        let addr = ChunkStore::compute_address(content);
1990        storage.put(&addr, content).await.expect("put");
1991
1992        let challenge = make_challenge(4700, [0x47; 32], [0x47; 32], vec![addr]);
1993        let self_id = peer_id_from_bytes([0x47; 32]);
1994
1995        // Bootstrapping peer → Bootstrapping response (grace period start).
1996        let response =
1997            handle_audit_challenge(&challenge, &storage, &self_id, true, TEST_STORED_CHUNKS).await;
1998        let challenge_id = match response {
1999            AuditResponse::Bootstrapping { challenge_id } => challenge_id,
2000            AuditResponse::Digests { .. } => {
2001                panic!("Expected Bootstrapping response during grace period")
2002            }
2003            AuditResponse::Rejected { .. } => {
2004                panic!("Unexpected Rejected response")
2005            }
2006        };
2007        assert_eq!(challenge_id, 4700);
2008
2009        // Caller records BootstrapClaimFirstSeen — verify the types support it.
2010        let peer = PeerId::from_bytes([0x47; 32]);
2011        let mut state = NeighborSyncState::new_cycle(vec![peer]);
2012        let now = Instant::now();
2013        let observed = state.observe_bootstrap_claim(
2014            peer,
2015            now,
2016            crate::replication::config::BOOTSTRAP_CLAIM_GRACE_PERIOD,
2017        );
2018
2019        assert_eq!(
2020            observed,
2021            BootstrapClaimObservation::WithinGrace { first_seen: now }
2022        );
2023        assert!(
2024            state.bootstrap_claims.contains_key(&peer),
2025            "BootstrapClaimFirstSeen should be recorded after grace-period claim"
2026        );
2027        assert!(
2028            state.bootstrap_claim_history.contains_key(&peer),
2029            "Bootstrap claim history should remember that the grace window was used"
2030        );
2031    }
2032
2033    // -- Scenario 53: Audit partial per-key failure with mixed responsibility ---
2034
2035    /// Scenario 53: P challenged on {K1, K2, K3}.  K1 matches, K2 and K3
2036    /// mismatch.  Responsibility confirmation: P is responsible for K2 but
2037    /// not K3.  `AuditFailure` emitted for {K2} only.
2038    ///
2039    /// Full `verify_digests` + `handle_audit_failure` requires a `P2PNode` for
2040    /// network lookups.  This test verifies the conceptual steps:
2041    ///   (1) Digest comparison correctly identifies K2 and K3 as failures.
2042    ///   (2) `FailureEvidence::AuditFailure` carries only confirmed keys.
2043    #[tokio::test]
2044    async fn scenario_53_partial_failure_mixed_responsibility() {
2045        let (storage, _temp) = create_test_storage().await;
2046        let nonce = [0x53; 32];
2047        let peer_id = [0x53; 32];
2048
2049        // Store K1, K2, K3.
2050        let c1 = b"scenario 53 key one";
2051        let c2 = b"scenario 53 key two";
2052        let c3 = b"scenario 53 key three";
2053        let k1 = ChunkStore::compute_address(c1);
2054        let k2 = ChunkStore::compute_address(c2);
2055        let k3 = ChunkStore::compute_address(c3);
2056        storage.put(&k1, c1).await.expect("put k1");
2057        storage.put(&k2, c2).await.expect("put k2");
2058        storage.put(&k3, c3).await.expect("put k3");
2059
2060        // Correct digests from challenger's local store.
2061        let d1_expected = compute_audit_digest(&nonce, &peer_id, &k1, c1);
2062        let d2_expected = compute_audit_digest(&nonce, &peer_id, &k2, c2);
2063        let d3_expected = compute_audit_digest(&nonce, &peer_id, &k3, c3);
2064
2065        // Simulate peer response: K1 matches, K2 wrong data, K3 wrong data.
2066        let d2_wrong = compute_audit_digest(&nonce, &peer_id, &k2, b"tampered k2");
2067        let d3_wrong = compute_audit_digest(&nonce, &peer_id, &k3, b"tampered k3");
2068
2069        assert_eq!(d1_expected, d1_expected, "K1 should match");
2070        assert_ne!(d2_wrong, d2_expected, "K2 should mismatch");
2071        assert_ne!(d3_wrong, d3_expected, "K3 should mismatch");
2072
2073        // Step 1: Identify failed keys (digest comparison).
2074        let digests = [d1_expected, d2_wrong, d3_wrong];
2075        let keys = [k1, k2, k3];
2076        let contents: [&[u8]; 3] = [c1, c2, c3];
2077
2078        let mut failed_keys = Vec::new();
2079        for (i, key) in keys.iter().enumerate() {
2080            if digests[i] == ABSENT_KEY_DIGEST {
2081                failed_keys.push(*key);
2082                continue;
2083            }
2084            let expected = compute_audit_digest(&nonce, &peer_id, key, contents[i]);
2085            if digests[i] != expected {
2086                failed_keys.push(*key);
2087            }
2088        }
2089
2090        assert_eq!(failed_keys.len(), 2, "K2 and K3 should be in failure set");
2091        assert!(failed_keys.contains(&k2));
2092        assert!(failed_keys.contains(&k3));
2093        assert!(!failed_keys.contains(&k1), "K1 passed digest check");
2094
2095        // Step 2: Responsibility confirmation removes K3 (not responsible).
2096        // Simulate: P is in closest peers for K2 but not K3.
2097        let responsible_for_k2 = true;
2098        let responsible_for_k3 = false;
2099        let mut confirmed = Vec::new();
2100        for key in &failed_keys {
2101            let is_responsible = if *key == k2 {
2102                responsible_for_k2
2103            } else {
2104                responsible_for_k3
2105            };
2106            if is_responsible {
2107                confirmed.push(*key);
2108            }
2109        }
2110
2111        assert_eq!(confirmed, vec![k2], "Only K2 should be in confirmed set");
2112
2113        // Step 3: Construct evidence for confirmed failures only.
2114        let challenged_peer = PeerId::from_bytes(peer_id);
2115        let evidence = FailureEvidence::AuditFailure {
2116            challenge_id: 5300,
2117            challenged_peer,
2118            confirmed_failed_keys: confirmed,
2119            summary: AuditFailureSummary::default(),
2120            reason: AuditFailureReason::DigestMismatch,
2121        };
2122
2123        match evidence {
2124            FailureEvidence::AuditFailure {
2125                confirmed_failed_keys,
2126                ..
2127            } => {
2128                assert_eq!(
2129                    confirmed_failed_keys.len(),
2130                    1,
2131                    "Only K2 should generate evidence"
2132                );
2133                assert_eq!(confirmed_failed_keys[0], k2);
2134            }
2135            _ => panic!("Expected AuditFailure evidence"),
2136        }
2137    }
2138}