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::file_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            max_map_size: 0,
958            disk_reserve: 0,
959            ..ChunkStoreConfig::test_default()
960        };
961        let storage = ChunkStore::new(config).await.expect("create storage");
962        (storage, temp_dir)
963    }
964
965    /// Build a challenge with the given parameters.
966    fn make_challenge(
967        challenge_id: u64,
968        nonce: [u8; 32],
969        peer_id: [u8; 32],
970        keys: Vec<XorName>,
971    ) -> AuditChallenge {
972        AuditChallenge {
973            challenge_id,
974            nonce,
975            challenged_peer_id: peer_id,
976            keys,
977        }
978    }
979
980    /// Build a `PeerId` matching the raw bytes used in a challenge.
981    fn peer_id_from_bytes(bytes: [u8; 32]) -> PeerId {
982        PeerId::from_bytes(bytes)
983    }
984
985    // -- handle_audit_challenge: present keys ---------------------------------
986
987    #[tokio::test]
988    async fn handle_challenge_present_keys_returns_correct_digests() {
989        let (storage, _temp) = create_test_storage().await;
990
991        // Store two chunks.
992        let content_a = b"chunk alpha";
993        let addr_a = ChunkStore::compute_address(content_a);
994        storage.put(&addr_a, content_a).await.expect("put a");
995
996        let content_b = b"chunk beta";
997        let addr_b = ChunkStore::compute_address(content_b);
998        storage.put(&addr_b, content_b).await.expect("put b");
999
1000        let nonce = [0xAA; 32];
1001        let peer_id = [0xBB; 32];
1002        let challenge = make_challenge(42, nonce, peer_id, vec![addr_a, addr_b]);
1003        let self_id = peer_id_from_bytes(peer_id);
1004
1005        let response =
1006            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1007
1008        match response {
1009            AuditResponse::Digests {
1010                challenge_id,
1011                digests,
1012            } => {
1013                assert_eq!(challenge_id, 42);
1014                assert_eq!(digests.len(), 2);
1015
1016                let expected_a = compute_audit_digest(&nonce, &peer_id, &addr_a, content_a);
1017                let expected_b = compute_audit_digest(&nonce, &peer_id, &addr_b, content_b);
1018                assert_eq!(digests[0], expected_a);
1019                assert_eq!(digests[1], expected_b);
1020            }
1021            AuditResponse::Bootstrapping { .. } => {
1022                panic!("expected Digests, got Bootstrapping");
1023            }
1024            AuditResponse::Rejected { .. } => {
1025                panic!("Unexpected Rejected response");
1026            }
1027        }
1028    }
1029
1030    // -- handle_audit_challenge: absent keys ----------------------------------
1031
1032    #[tokio::test]
1033    async fn handle_challenge_absent_keys_returns_sentinel() {
1034        let (storage, _temp) = create_test_storage().await;
1035
1036        let absent_key = [0xFF; 32];
1037        let nonce = [0x11; 32];
1038        let peer_id = [0x22; 32];
1039        let challenge = make_challenge(99, nonce, peer_id, vec![absent_key]);
1040        let self_id = peer_id_from_bytes(peer_id);
1041
1042        let response =
1043            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1044
1045        match response {
1046            AuditResponse::Digests {
1047                challenge_id,
1048                digests,
1049            } => {
1050                assert_eq!(challenge_id, 99);
1051                assert_eq!(digests.len(), 1);
1052                assert_eq!(
1053                    digests[0], ABSENT_KEY_DIGEST,
1054                    "absent key should produce sentinel digest"
1055                );
1056            }
1057            AuditResponse::Bootstrapping { .. } => {
1058                panic!("expected Digests, got Bootstrapping");
1059            }
1060            AuditResponse::Rejected { .. } => {
1061                panic!("Unexpected Rejected response");
1062            }
1063        }
1064    }
1065
1066    // -- handle_audit_challenge: mixed present and absent ---------------------
1067
1068    #[tokio::test]
1069    async fn handle_challenge_mixed_present_and_absent() {
1070        let (storage, _temp) = create_test_storage().await;
1071
1072        let content = b"present chunk";
1073        let addr_present = ChunkStore::compute_address(content);
1074        storage.put(&addr_present, content).await.expect("put");
1075
1076        let addr_absent = [0xDE; 32];
1077        let nonce = [0x33; 32];
1078        let peer_id = [0x44; 32];
1079        let challenge = make_challenge(7, nonce, peer_id, vec![addr_present, addr_absent]);
1080        let self_id = peer_id_from_bytes(peer_id);
1081
1082        let response =
1083            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1084
1085        match response {
1086            AuditResponse::Digests { digests, .. } => {
1087                assert_eq!(digests.len(), 2);
1088
1089                let expected_present =
1090                    compute_audit_digest(&nonce, &peer_id, &addr_present, content);
1091                assert_eq!(digests[0], expected_present);
1092                assert_eq!(
1093                    digests[1], ABSENT_KEY_DIGEST,
1094                    "absent key should be sentinel"
1095                );
1096            }
1097            AuditResponse::Bootstrapping { .. } => {
1098                panic!("expected Digests, got Bootstrapping");
1099            }
1100            AuditResponse::Rejected { .. } => {
1101                panic!("Unexpected Rejected response");
1102            }
1103        }
1104    }
1105
1106    // -- handle_audit_challenge: bootstrapping --------------------------------
1107
1108    #[tokio::test]
1109    async fn handle_challenge_bootstrapping_returns_bootstrapping_response() {
1110        let (storage, _temp) = create_test_storage().await;
1111
1112        let challenge = make_challenge(55, [0x00; 32], [0x01; 32], vec![[0x02; 32]]);
1113        let self_id = peer_id_from_bytes([0x01; 32]);
1114
1115        let response =
1116            handle_audit_challenge(&challenge, &storage, &self_id, true, TEST_STORED_CHUNKS).await;
1117
1118        match response {
1119            AuditResponse::Bootstrapping { challenge_id } => {
1120                assert_eq!(challenge_id, 55);
1121            }
1122            AuditResponse::Digests { .. } => {
1123                panic!("expected Bootstrapping, got Digests");
1124            }
1125            AuditResponse::Rejected { .. } => {
1126                panic!("Unexpected Rejected response");
1127            }
1128        }
1129    }
1130
1131    // -- handle_audit_challenge: empty key list -------------------------------
1132
1133    #[tokio::test]
1134    async fn handle_challenge_empty_keys_returns_empty_digests() {
1135        let (storage, _temp) = create_test_storage().await;
1136
1137        let challenge = make_challenge(100, [0x10; 32], [0x20; 32], vec![]);
1138        let self_id = peer_id_from_bytes([0x20; 32]);
1139
1140        let response =
1141            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1142
1143        match response {
1144            AuditResponse::Digests {
1145                challenge_id,
1146                digests,
1147            } => {
1148                assert_eq!(challenge_id, 100);
1149                assert!(
1150                    digests.is_empty(),
1151                    "empty key list should yield empty digests"
1152                );
1153            }
1154            AuditResponse::Bootstrapping { .. } => {
1155                panic!("expected Digests, got Bootstrapping");
1156            }
1157            AuditResponse::Rejected { .. } => {
1158                panic!("Unexpected Rejected response");
1159            }
1160        }
1161    }
1162
1163    // -- Digest verification: matching ----------------------------------------
1164
1165    #[test]
1166    fn digest_verification_matching() {
1167        let nonce = [0x01; 32];
1168        let peer_id = [0x02; 32];
1169        let key: XorName = [0x03; 32];
1170        let data = b"correct data";
1171
1172        let expected = compute_audit_digest(&nonce, &peer_id, &key, data);
1173        let recomputed = compute_audit_digest(&nonce, &peer_id, &key, data);
1174
1175        assert_eq!(
1176            expected, recomputed,
1177            "same inputs must produce identical digests"
1178        );
1179        assert_ne!(
1180            expected, ABSENT_KEY_DIGEST,
1181            "real digest must not be sentinel"
1182        );
1183    }
1184
1185    // -- Digest verification: mismatching -------------------------------------
1186
1187    #[test]
1188    fn digest_verification_mismatching_data() {
1189        let nonce = [0x01; 32];
1190        let peer_id = [0x02; 32];
1191        let key: XorName = [0x03; 32];
1192
1193        let digest_a = compute_audit_digest(&nonce, &peer_id, &key, b"data version A");
1194        let digest_b = compute_audit_digest(&nonce, &peer_id, &key, b"data version B");
1195
1196        assert_ne!(
1197            digest_a, digest_b,
1198            "different data must produce different digests"
1199        );
1200    }
1201
1202    #[test]
1203    fn digest_verification_mismatching_nonce() {
1204        let peer_id = [0x02; 32];
1205        let key: XorName = [0x03; 32];
1206        let data = b"same data";
1207
1208        let digest_a = compute_audit_digest(&[0x01; 32], &peer_id, &key, data);
1209        let digest_b = compute_audit_digest(&[0xFF; 32], &peer_id, &key, data);
1210
1211        assert_ne!(
1212            digest_a, digest_b,
1213            "different nonces must produce different digests"
1214        );
1215    }
1216
1217    #[test]
1218    fn digest_verification_mismatching_peer() {
1219        let nonce = [0x01; 32];
1220        let key: XorName = [0x03; 32];
1221        let data = b"same data";
1222
1223        let digest_a = compute_audit_digest(&nonce, &[0x02; 32], &key, data);
1224        let digest_b = compute_audit_digest(&nonce, &[0xFE; 32], &key, data);
1225
1226        assert_ne!(
1227            digest_a, digest_b,
1228            "different peers must produce different digests"
1229        );
1230    }
1231
1232    #[test]
1233    fn digest_verification_mismatching_key() {
1234        let nonce = [0x01; 32];
1235        let peer_id = [0x02; 32];
1236        let data = b"same data";
1237
1238        let digest_a = compute_audit_digest(&nonce, &peer_id, &[0x03; 32], data);
1239        let digest_b = compute_audit_digest(&nonce, &peer_id, &[0xFC; 32], data);
1240
1241        assert_ne!(
1242            digest_a, digest_b,
1243            "different keys must produce different digests"
1244        );
1245    }
1246
1247    // -- Absent sentinel is all zeros -----------------------------------------
1248
1249    #[test]
1250    fn absent_sentinel_is_all_zeros() {
1251        assert_eq!(ABSENT_KEY_DIGEST, [0u8; 32], "sentinel must be all zeros");
1252    }
1253
1254    // -- Bootstrapping skips digest computation even with stored keys ---------
1255
1256    #[tokio::test]
1257    async fn bootstrapping_skips_digest_computation() {
1258        let (storage, _temp) = create_test_storage().await;
1259
1260        let content = b"stored but bootstrapping";
1261        let addr = ChunkStore::compute_address(content);
1262        storage.put(&addr, content).await.expect("put");
1263
1264        let challenge = make_challenge(200, [0xCC; 32], [0xDD; 32], vec![addr]);
1265        let self_id = peer_id_from_bytes([0xDD; 32]);
1266
1267        let response =
1268            handle_audit_challenge(&challenge, &storage, &self_id, true, TEST_STORED_CHUNKS).await;
1269
1270        assert!(
1271            matches!(response, AuditResponse::Bootstrapping { challenge_id: 200 }),
1272            "bootstrapping node must not compute digests"
1273        );
1274    }
1275
1276    // -- Scenario 19/53: Partial failure with mixed responsibility ----------------
1277
1278    #[tokio::test]
1279    async fn scenario_19_partial_failure_mixed_responsibility() {
1280        // Three keys challenged: K1 matches, K2 mismatches, K3 absent.
1281        // After responsibility confirmation, only K2 is confirmed responsible.
1282        // AuditFailure emitted for {K2} only.
1283        // Test handle_audit_challenge with mixed results, then verify
1284        // the digest logic manually.
1285
1286        let (storage, _temp) = create_test_storage().await;
1287        let nonce = [0x42u8; 32];
1288        let peer_id = [0xAA; 32];
1289
1290        // Store K1 and K2, but NOT K3
1291        let content_k1 = b"key one data";
1292        let addr_k1 = ChunkStore::compute_address(content_k1);
1293        storage.put(&addr_k1, content_k1).await.unwrap();
1294
1295        let content_k2 = b"key two data";
1296        let addr_k2 = ChunkStore::compute_address(content_k2);
1297        storage.put(&addr_k2, content_k2).await.unwrap();
1298
1299        let addr_k3 = [0xFF; 32]; // Not stored
1300
1301        let challenge = AuditChallenge {
1302            challenge_id: 100,
1303            nonce,
1304            challenged_peer_id: peer_id,
1305            keys: vec![addr_k1, addr_k2, addr_k3],
1306        };
1307        let self_id = peer_id_from_bytes(peer_id);
1308
1309        let response =
1310            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1311
1312        match response {
1313            AuditResponse::Digests { digests, .. } => {
1314                assert_eq!(digests.len(), 3);
1315
1316                // K1 should have correct digest
1317                let expected_k1 = compute_audit_digest(&nonce, &peer_id, &addr_k1, content_k1);
1318                assert_eq!(digests[0], expected_k1);
1319
1320                // K2 should have correct digest
1321                let expected_k2 = compute_audit_digest(&nonce, &peer_id, &addr_k2, content_k2);
1322                assert_eq!(digests[1], expected_k2);
1323
1324                // K3 absent -> sentinel
1325                assert_eq!(digests[2], ABSENT_KEY_DIGEST);
1326            }
1327            AuditResponse::Bootstrapping { .. } => panic!("Expected Digests response"),
1328            AuditResponse::Rejected { .. } => panic!("Unexpected Rejected response"),
1329        }
1330    }
1331
1332    // -- Scenario 54: All digests pass -------------------------------------------
1333
1334    #[tokio::test]
1335    async fn scenario_54_all_digests_pass() {
1336        // All challenged keys present and digests match.
1337        // Multiple keys to strengthen coverage beyond existing two-key tests.
1338        let (storage, _temp) = create_test_storage().await;
1339        let nonce = [0x10; 32];
1340        let peer_id = [0x20; 32];
1341
1342        let c1 = b"chunk alpha";
1343        let c2 = b"chunk beta";
1344        let c3 = b"chunk gamma";
1345        let a1 = ChunkStore::compute_address(c1);
1346        let a2 = ChunkStore::compute_address(c2);
1347        let a3 = ChunkStore::compute_address(c3);
1348        storage.put(&a1, c1).await.unwrap();
1349        storage.put(&a2, c2).await.unwrap();
1350        storage.put(&a3, c3).await.unwrap();
1351
1352        let challenge = AuditChallenge {
1353            challenge_id: 200,
1354            nonce,
1355            challenged_peer_id: peer_id,
1356            keys: vec![a1, a2, a3],
1357        };
1358        let self_id = peer_id_from_bytes(peer_id);
1359
1360        let response =
1361            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1362        match response {
1363            AuditResponse::Digests { digests, .. } => {
1364                assert_eq!(digests.len(), 3);
1365                for (i, (addr, content)) in [(a1, &c1[..]), (a2, &c2[..]), (a3, &c3[..])]
1366                    .iter()
1367                    .enumerate()
1368                {
1369                    let expected = compute_audit_digest(&nonce, &peer_id, addr, content);
1370                    assert_eq!(digests[i], expected, "Key {i} digest should match");
1371                }
1372            }
1373            AuditResponse::Bootstrapping { .. } => panic!("Expected Digests"),
1374            AuditResponse::Rejected { .. } => panic!("Unexpected Rejected response"),
1375        }
1376    }
1377
1378    // -- A rotted local reference copy -------------------------------------------
1379
1380    /// The auditor's own copy is the reference a peer is judged against. A local
1381    /// copy that has rotted must not fail an honest peer, must not count as a
1382    /// verification either, and is taken out of service so replication repairs it.
1383    #[tokio::test]
1384    async fn a_rotted_local_copy_neither_fails_nor_passes_the_peer() {
1385        let temp_dir = TempDir::new().expect("temp dir");
1386        let storage = ChunkStore::new(ChunkStoreConfig {
1387            root_dir: temp_dir.path().to_path_buf(),
1388            ..ChunkStoreConfig::test_default()
1389        })
1390        .await
1391        .expect("storage");
1392        let nonce = [0x42; 32];
1393        let peer = PeerId::from_bytes([0x24; 32]);
1394        let rot = |key: &XorName| {
1395            let path = temp_dir
1396                .path()
1397                .join(CHUNKS_DIR_NAME)
1398                .join(format!("{:02x}", key.last().copied().unwrap_or(0)))
1399                .join(hex::encode(key));
1400            std::fs::write(path, b"rotted").expect("corrupt the file");
1401        };
1402
1403        let mut stored = Vec::new();
1404        for content in [
1405            &b"intact copy"[..],
1406            b"first rotted copy",
1407            b"second rotted copy",
1408        ] {
1409            let key = ChunkStore::compute_address(content);
1410            storage.put(&key, content).await.expect("put");
1411            stored.push((key, content.to_vec()));
1412        }
1413        let [(good, good_bytes), (lone, lone_bytes), (paired, paired_bytes)] = stored.as_slice()
1414        else {
1415            panic!("three chunks stored");
1416        };
1417        rot(lone);
1418        rot(paired);
1419        let honest = |key: &XorName, content: &[u8]| {
1420            compute_audit_digest(&nonce, peer.as_bytes(), key, content)
1421        };
1422
1423        // Only a rotted reference: nothing can be checked, so no pass either way.
1424        let nothing = compare_with_local_copies(
1425            &storage,
1426            &nonce,
1427            peer.as_bytes(),
1428            &[*lone],
1429            &[honest(lone, lone_bytes)],
1430        )
1431        .await;
1432        assert!(
1433            nothing.failed_keys.is_empty(),
1434            "an honest peer is not failed"
1435        );
1436        assert_eq!(nothing.verified, 0);
1437        assert!(matches!(
1438            unfailed_audit_verdict(&peer, 1, nothing.verified),
1439            AuditTickResult::Idle
1440        ));
1441        assert!(
1442            !storage.exists(lone).expect("exists"),
1443            "the rotted local copy is taken out of service"
1444        );
1445
1446        // A good and a rotted reference: the peer passes on what was checked.
1447        let partial = compare_with_local_copies(
1448            &storage,
1449            &nonce,
1450            peer.as_bytes(),
1451            &[*good, *paired],
1452            &[honest(good, good_bytes), honest(paired, paired_bytes)],
1453        )
1454        .await;
1455        assert!(
1456            partial.failed_keys.is_empty(),
1457            "an honest peer failed against a rotted reference: {:?}",
1458            partial.failed_keys
1459        );
1460        assert_eq!(partial.verified, 1);
1461        assert!(matches!(
1462            unfailed_audit_verdict(&peer, 2, partial.verified),
1463            AuditTickResult::Passed {
1464                keys_checked: 1,
1465                ..
1466            }
1467        ));
1468
1469        // A wrong digest against a good reference still fails, as before.
1470        let wrong =
1471            compare_with_local_copies(&storage, &nonce, peer.as_bytes(), &[*good], &[[0xAB; 32]])
1472                .await;
1473        assert_eq!(wrong.failed_keys.len(), 1);
1474        assert_eq!(wrong.verified, 0);
1475    }
1476
1477    // -- Scenario 55: Empty failure set means no evidence -------------------------
1478
1479    /// Scenario 55: Peer challenged on {K1, K2}. Both digests mismatch.
1480    /// Responsibility confirmation shows the peer is NOT responsible for
1481    /// either key. The confirmed failure set is empty — no `AuditFailure`
1482    /// evidence is emitted.
1483    ///
1484    /// Full `verify_digests` requires a live `P2PNode` for network lookups.
1485    /// This test exercises the deterministic sub-steps:
1486    ///   (1) Digest comparison identifies K1 and K2 as mismatches.
1487    ///   (2) Responsibility confirmation removes both keys.
1488    ///   (3) Empty confirmed failure set means no evidence.
1489    #[tokio::test]
1490    async fn scenario_55_no_confirmed_responsibility_no_evidence() {
1491        let (storage, _temp) = create_test_storage().await;
1492        let nonce = [0x55; 32];
1493        let peer_id = [0x55; 32];
1494
1495        // Store K1 and K2 on the challenger (for expected digest computation).
1496        let c1 = b"scenario 55 key one";
1497        let c2 = b"scenario 55 key two";
1498        let k1 = ChunkStore::compute_address(c1);
1499        let k2 = ChunkStore::compute_address(c2);
1500        storage.put(&k1, c1).await.expect("put k1");
1501        storage.put(&k2, c2).await.expect("put k2");
1502
1503        // Challenger computes expected digests.
1504        let expected_d1 = compute_audit_digest(&nonce, &peer_id, &k1, c1);
1505        let expected_d2 = compute_audit_digest(&nonce, &peer_id, &k2, c2);
1506
1507        // Simulate peer returning WRONG digests for both keys.
1508        let wrong_d1 = compute_audit_digest(&nonce, &peer_id, &k1, b"corrupted k1");
1509        let wrong_d2 = compute_audit_digest(&nonce, &peer_id, &k2, b"corrupted k2");
1510        assert_ne!(wrong_d1, expected_d1, "K1 digest should mismatch");
1511        assert_ne!(wrong_d2, expected_d2, "K2 digest should mismatch");
1512
1513        // Step 1: Identify failed keys via digest comparison.
1514        let keys = [k1, k2];
1515        let expected = [expected_d1, expected_d2];
1516        let received = [wrong_d1, wrong_d2];
1517
1518        let mut failed_keys = Vec::new();
1519        for i in 0..keys.len() {
1520            if received[i] != expected[i] {
1521                failed_keys.push(keys[i]);
1522            }
1523        }
1524        assert_eq!(
1525            failed_keys.len(),
1526            2,
1527            "Both keys should be identified as digest mismatches"
1528        );
1529
1530        // Step 2: Responsibility confirmation — peer is NOT responsible for
1531        // either key (simulated by filtering them all out).
1532        let confirmed_responsible_keys: Vec<XorName> = Vec::new();
1533        let confirmed_failures: Vec<XorName> = failed_keys
1534            .into_iter()
1535            .filter(|k| confirmed_responsible_keys.contains(k))
1536            .collect();
1537
1538        // Step 3: Empty confirmed failure set → no AuditFailure evidence.
1539        assert!(
1540            confirmed_failures.is_empty(),
1541            "With no confirmed responsibility, failure set must be empty — \
1542             no AuditFailure evidence should be emitted"
1543        );
1544
1545        // Verify that constructing evidence with empty keys results in a
1546        // no-penalty outcome (the caller checks is_empty before emitting).
1547        let peer = PeerId::from_bytes(peer_id);
1548        let evidence = FailureEvidence::AuditFailure {
1549            challenge_id: 5500,
1550            challenged_peer: peer,
1551            confirmed_failed_keys: confirmed_failures,
1552            summary: AuditFailureSummary::default(),
1553            reason: AuditFailureReason::DigestMismatch,
1554        };
1555        if let FailureEvidence::AuditFailure {
1556            confirmed_failed_keys,
1557            ..
1558        } = evidence
1559        {
1560            assert!(
1561                confirmed_failed_keys.is_empty(),
1562                "Evidence with empty failure set should not trigger a trust penalty"
1563            );
1564        }
1565    }
1566
1567    // -- Scenario 56: RepairOpportunity filters never-synced peers ----------------
1568
1569    #[test]
1570    fn scenario_56_repair_opportunity_filters_never_synced() {
1571        // PeerSyncRecord with last_sync=None should not pass
1572        // has_repair_opportunity().
1573
1574        let never_synced = PeerSyncRecord {
1575            last_sync: None,
1576            cycles_since_sync: 5,
1577        };
1578        assert!(!never_synced.has_repair_opportunity());
1579
1580        let synced_no_cycle = PeerSyncRecord {
1581            last_sync: Some(Instant::now()),
1582            cycles_since_sync: 0,
1583        };
1584        assert!(!synced_no_cycle.has_repair_opportunity());
1585
1586        let synced_with_cycle = PeerSyncRecord {
1587            last_sync: Some(Instant::now()),
1588            cycles_since_sync: 1,
1589        };
1590        assert!(synced_with_cycle.has_repair_opportunity());
1591    }
1592
1593    #[test]
1594    fn expired_bootstrap_claim_does_not_remove_peer_from_audit_eligibility() {
1595        let peer = peer_id_from_bytes([0x57; 32]);
1596        let mut sync_history = HashMap::new();
1597        sync_history.insert(
1598            peer,
1599            PeerSyncRecord {
1600                last_sync: Some(Instant::now()),
1601                cycles_since_sync: 1,
1602            },
1603        );
1604
1605        let mut bootstrap_claims = HashMap::new();
1606        let first_seen = Instant::now()
1607            .checked_sub(
1608                crate::replication::config::BOOTSTRAP_CLAIM_GRACE_PERIOD
1609                    + std::time::Duration::from_secs(1),
1610            )
1611            .unwrap_or_else(Instant::now);
1612        bootstrap_claims.insert(peer, first_seen);
1613
1614        let eligible = eligible_audit_peers(&sync_history);
1615
1616        assert!(bootstrap_claims.contains_key(&peer));
1617        assert!(
1618            eligible.contains(&peer),
1619            "continued bootstrap claims must remain auditable so past-grace abuse can be observed"
1620        );
1621    }
1622
1623    #[test]
1624    fn audit_failure_summary_counts_confirmed_absent_and_mismatch_keys() {
1625        let absent_key = [0xA1; 32];
1626        let mismatch_key = [0xB2; 32];
1627        let confirmed = vec![
1628            AuditKeyFailure::absent(absent_key),
1629            AuditKeyFailure::digest_mismatch(mismatch_key),
1630        ];
1631
1632        let summary = build_audit_failure_summary(5, &confirmed);
1633
1634        assert_eq!(summary.challenged_keys, 5);
1635        assert_eq!(summary.failed_keys, 2);
1636        assert_eq!(summary.absent_keys, 1);
1637        assert_eq!(summary.digest_mismatch_keys, 1);
1638    }
1639
1640    #[test]
1641    fn audit_failure_summary_leaves_unclassified_rejections_out_of_absent_mismatch_counts() {
1642        let rejected_key = [0xC3; 32];
1643        let confirmed = vec![AuditKeyFailure::unclassified(rejected_key)];
1644
1645        let summary = build_audit_failure_summary(3, &confirmed);
1646
1647        assert_eq!(summary.challenged_keys, 3);
1648        assert_eq!(summary.failed_keys, 1);
1649        assert_eq!(summary.absent_keys, 0);
1650        assert_eq!(summary.digest_mismatch_keys, 0);
1651    }
1652
1653    #[test]
1654    fn audit_digest_failure_reason_is_key_absent_when_all_confirmed_failures_are_absent() {
1655        let failures = vec![AuditKeyFailure::absent([0xD4; 32])];
1656
1657        assert_eq!(
1658            audit_digest_failure_reason(&failures),
1659            AuditFailureReason::KeyAbsent
1660        );
1661    }
1662
1663    #[test]
1664    fn audit_digest_failure_reason_is_digest_mismatch_for_mixed_failures() {
1665        let failures = vec![
1666            AuditKeyFailure::absent([0xD5; 32]),
1667            AuditKeyFailure::digest_mismatch([0xE6; 32]),
1668        ];
1669
1670        assert_eq!(
1671            audit_digest_failure_reason(&failures),
1672            AuditFailureReason::DigestMismatch
1673        );
1674    }
1675
1676    #[test]
1677    fn audit_key_filter_retains_stable_proofs_and_rejects_evicted_peers() {
1678        const HINT_EPOCH: u64 = 7;
1679        const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1680        const CHALLENGED_PEER_BYTE: u8 = 0xA1;
1681        const OTHER_PEER_BYTE: u8 = 0xA2;
1682        const NEW_PEER_BYTE: u8 = 0xA3;
1683        const MATURE_KEY_BYTE: u8 = 0xB1;
1684        const SAME_EPOCH_KEY_BYTE: u8 = 0xB2;
1685        const MISSING_PROOF_KEY_BYTE: u8 = 0xB3;
1686        const STABLE_CHURN_KEY_BYTE: u8 = 0xB4;
1687        const EVICTED_KEY_BYTE: u8 = 0xB5;
1688        const FRESH_HINT_KEY_BYTE: u8 = 0xB6;
1689        const XOR_NAME_LEN: usize = 32;
1690
1691        let challenged_peer = peer_id_from_bytes([CHALLENGED_PEER_BYTE; XOR_NAME_LEN]);
1692        let other_peer = peer_id_from_bytes([OTHER_PEER_BYTE; XOR_NAME_LEN]);
1693        let new_peer = peer_id_from_bytes([NEW_PEER_BYTE; XOR_NAME_LEN]);
1694        let mature_key = [MATURE_KEY_BYTE; XOR_NAME_LEN];
1695        let same_epoch_key = [SAME_EPOCH_KEY_BYTE; XOR_NAME_LEN];
1696        let missing_proof_key = [MISSING_PROOF_KEY_BYTE; XOR_NAME_LEN];
1697        let stable_churn_key = [STABLE_CHURN_KEY_BYTE; XOR_NAME_LEN];
1698        let evicted_key = [EVICTED_KEY_BYTE; XOR_NAME_LEN];
1699        let fresh_hint_key = [FRESH_HINT_KEY_BYTE; XOR_NAME_LEN];
1700        let close_group = HashSet::from([challenged_peer, other_peer]);
1701        let changed_close_group = HashSet::from([challenged_peer, new_peer]);
1702        let evicted_close_group = HashSet::from([other_peer, new_peer]);
1703        let mut repair_proofs = RepairProofs::new();
1704        let mature_hinted_at = Instant::now();
1705        let now = mature_hinted_at
1706            .checked_add(REPAIR_HINT_MIN_AGE)
1707            .unwrap_or(mature_hinted_at);
1708
1709        assert!(repair_proofs.record_replica_hint_sent_at(
1710            challenged_peer,
1711            mature_key,
1712            &close_group,
1713            HINT_EPOCH,
1714            mature_hinted_at,
1715        ));
1716        assert!(repair_proofs.record_replica_hint_sent_at(
1717            challenged_peer,
1718            same_epoch_key,
1719            &close_group,
1720            CURRENT_EPOCH,
1721            mature_hinted_at,
1722        ));
1723        assert!(repair_proofs.record_replica_hint_sent_at(
1724            challenged_peer,
1725            stable_churn_key,
1726            &close_group,
1727            HINT_EPOCH,
1728            mature_hinted_at,
1729        ));
1730        assert!(repair_proofs.record_replica_hint_sent_at(
1731            challenged_peer,
1732            evicted_key,
1733            &close_group,
1734            HINT_EPOCH,
1735            mature_hinted_at,
1736        ));
1737        assert!(repair_proofs.record_replica_hint_sent_at(
1738            challenged_peer,
1739            fresh_hint_key,
1740            &close_group,
1741            HINT_EPOCH,
1742            now,
1743        ));
1744
1745        let sampled_key_groups = vec![
1746            (mature_key, close_group.clone()),
1747            (same_epoch_key, close_group.clone()),
1748            (missing_proof_key, close_group.clone()),
1749            (stable_churn_key, changed_close_group),
1750            (evicted_key, evicted_close_group),
1751            (fresh_hint_key, close_group.clone()),
1752        ];
1753        let peer_keys = mature_audit_keys_for_peer(
1754            &challenged_peer,
1755            sampled_key_groups,
1756            &mut repair_proofs,
1757            CURRENT_EPOCH,
1758            now,
1759        );
1760
1761        assert_eq!(
1762            peer_keys,
1763            vec![mature_key, stable_churn_key],
1764            "mature proofs for stable close-group peers should become audit keys, while same-epoch, fresh, missing, and evicted-peer proofs should not"
1765        );
1766    }
1767
1768    // -- Audit response must match key count --------------------------------------
1769
1770    #[tokio::test]
1771    async fn audit_response_must_match_key_count() {
1772        // Section 15: "A response is invalid if it has fewer or more entries
1773        // than challenged keys."
1774        // Verify handle_audit_challenge always produces exactly N digests for
1775        // N keys, including edge cases.
1776
1777        let (storage, _temp) = create_test_storage().await;
1778        let nonce = [0x50; 32];
1779        let peer_id = [0x60; 32];
1780
1781        // Store a single chunk
1782        let content = b"single chunk";
1783        let addr = ChunkStore::compute_address(content);
1784        storage.put(&addr, content).await.unwrap();
1785
1786        // Challenge with 1 stored + 4 absent = 5 keys total
1787        let absent_keys: Vec<XorName> = (1..=4u8).map(|i| [i; 32]).collect();
1788        let mut keys = vec![addr];
1789        keys.extend_from_slice(&absent_keys);
1790
1791        let key_count = keys.len();
1792        let challenge = make_challenge(300, nonce, peer_id, keys);
1793        let self_id = peer_id_from_bytes(peer_id);
1794
1795        let response =
1796            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1797        match response {
1798            AuditResponse::Digests { digests, .. } => {
1799                assert_eq!(
1800                    digests.len(),
1801                    key_count,
1802                    "must produce exactly one digest per challenged key"
1803                );
1804            }
1805            AuditResponse::Bootstrapping { .. } => panic!("Expected Digests"),
1806            AuditResponse::Rejected { .. } => panic!("Unexpected Rejected response"),
1807        }
1808    }
1809
1810    // -- Audit digest uses full record bytes --------------------------------------
1811
1812    #[test]
1813    fn audit_digest_uses_full_record_bytes() {
1814        // Verify digest changes when record content changes.
1815        let nonce = [1u8; 32];
1816        let peer = [2u8; 32];
1817        let key = [3u8; 32];
1818
1819        let d1 = compute_audit_digest(&nonce, &peer, &key, b"data version 1");
1820        let d2 = compute_audit_digest(&nonce, &peer, &key, b"data version 2");
1821        assert_ne!(
1822            d1, d2,
1823            "Different record bytes must produce different digests"
1824        );
1825    }
1826
1827    // -- Scenario 29: Audit start gate ------------------------------------------
1828
1829    /// Scenario 29: `handle_audit_challenge` returns `Bootstrapping` when the
1830    /// node is still bootstrapping — audit digests are never computed, and no
1831    /// `AuditFailure` evidence is emitted by the caller.
1832    ///
1833    /// This is the responder-side gate.  The challenger-side gate is enforced
1834    /// by `audit_tick`'s `is_bootstrapping` guard (Invariant 19) and by
1835    /// `check_bootstrap_drained()` in the engine loop; this test confirms the
1836    /// complementary responder behavior.
1837    #[tokio::test]
1838    async fn scenario_29_audit_start_gate_during_bootstrap() {
1839        let (storage, _temp) = create_test_storage().await;
1840
1841        // Store data so there *would* be work to audit.
1842        let content = b"should not be audited during bootstrap";
1843        let addr = ChunkStore::compute_address(content);
1844        storage.put(&addr, content).await.expect("put");
1845
1846        let challenge = make_challenge(2900, [0x29; 32], [0x29; 32], vec![addr]);
1847        let self_id = peer_id_from_bytes([0x29; 32]);
1848
1849        // Responder is bootstrapping → Bootstrapping response, NOT Digests.
1850        let response =
1851            handle_audit_challenge(&challenge, &storage, &self_id, true, TEST_STORED_CHUNKS).await;
1852        assert!(
1853            matches!(
1854                response,
1855                AuditResponse::Bootstrapping { challenge_id: 2900 }
1856            ),
1857            "bootstrapping node must not compute digests — audit start gate"
1858        );
1859
1860        // Responder is NOT bootstrapping → normal Digests.
1861        let response =
1862            handle_audit_challenge(&challenge, &storage, &self_id, false, TEST_STORED_CHUNKS).await;
1863        assert!(
1864            matches!(response, AuditResponse::Digests { .. }),
1865            "drained node should compute digests normally"
1866        );
1867    }
1868
1869    // -- Scenario 30: Audit peer selection from sampled keys --------------------
1870
1871    /// Scenario 30: Key sampling uses dynamic sqrt-based batch sizing and
1872    /// `RepairOpportunity` filtering excludes never-synced peers.
1873    ///
1874    /// Full `audit_tick` requires a live network.  This test verifies the two
1875    /// deterministic sub-steps the function relies on:
1876    ///   (a) `audit_sample_count` scales with `sqrt(total_keys)`.
1877    ///   (b) `PeerSyncRecord::has_repair_opportunity` gates peer eligibility.
1878    #[test]
1879    fn scenario_30_audit_peer_selection_from_sampled_keys() {
1880        // (a) Dynamic sample count scales with sqrt(total_keys).
1881        assert_eq!(
1882            ReplicationConfig::audit_sample_count(100),
1883            10,
1884            "sample count should scale with sqrt(total_keys)"
1885        );
1886
1887        assert_eq!(ReplicationConfig::audit_sample_count(3), 1, "sqrt(3) = 1");
1888
1889        assert_eq!(
1890            ReplicationConfig::audit_sample_count(10_000),
1891            100,
1892            "sqrt(10000) = 100"
1893        );
1894
1895        // (b) Peer eligibility via RepairOpportunity.
1896        // Never synced → not eligible.
1897        let never = PeerSyncRecord {
1898            last_sync: None,
1899            cycles_since_sync: 10,
1900        };
1901        assert!(!never.has_repair_opportunity());
1902
1903        // Synced but zero subsequent cycles → not eligible.
1904        let too_soon = PeerSyncRecord {
1905            last_sync: Some(Instant::now()),
1906            cycles_since_sync: 0,
1907        };
1908        assert!(!too_soon.has_repair_opportunity());
1909
1910        // Synced with ≥1 cycle → eligible.
1911        let eligible = PeerSyncRecord {
1912            last_sync: Some(Instant::now()),
1913            cycles_since_sync: 2,
1914        };
1915        assert!(eligible.has_repair_opportunity());
1916    }
1917
1918    // -- Scenario 32: Dynamic challenge size ------------------------------------
1919
1920    /// Scenario 32: Challenge key count equals `|PeerKeySet(challenged_peer)|`,
1921    /// which is dynamic per round.  If no eligible peer remains after filtering,
1922    /// the tick is idle.
1923    ///
1924    /// Verified via `handle_audit_challenge`: the response digest count always
1925    /// equals the number of keys in the challenge.
1926    #[tokio::test]
1927    async fn scenario_32_dynamic_challenge_size() {
1928        let (storage, _temp) = create_test_storage().await;
1929
1930        // Store varying numbers of chunks.
1931        let mut addrs = Vec::new();
1932        for i in 0u8..5 {
1933            let content = format!("dynamic challenge key {i}");
1934            let addr = ChunkStore::compute_address(content.as_bytes());
1935            storage.put(&addr, content.as_bytes()).await.expect("put");
1936            addrs.push(addr);
1937        }
1938
1939        let nonce = [0x32; 32];
1940        let peer_id = [0x32; 32];
1941        let self_id = peer_id_from_bytes(peer_id);
1942
1943        // Challenge with 1 key.
1944        let challenge1 = make_challenge(3201, nonce, peer_id, vec![addrs[0]]);
1945        let resp1 =
1946            handle_audit_challenge(&challenge1, &storage, &self_id, false, TEST_STORED_CHUNKS)
1947                .await;
1948        if let AuditResponse::Digests { digests, .. } = resp1 {
1949            assert_eq!(digests.len(), 1, "|PeerKeySet| = 1 → 1 digest");
1950        }
1951
1952        // Challenge with 3 keys.
1953        let challenge3 = make_challenge(3203, nonce, peer_id, addrs[0..3].to_vec());
1954        let resp3 =
1955            handle_audit_challenge(&challenge3, &storage, &self_id, false, TEST_STORED_CHUNKS)
1956                .await;
1957        if let AuditResponse::Digests { digests, .. } = resp3 {
1958            assert_eq!(digests.len(), 3, "|PeerKeySet| = 3 → 3 digests");
1959        }
1960
1961        // Challenge with all 5 keys.
1962        let challenge5 = make_challenge(3205, nonce, peer_id, addrs.clone());
1963        let resp5 =
1964            handle_audit_challenge(&challenge5, &storage, &self_id, false, TEST_STORED_CHUNKS)
1965                .await;
1966        if let AuditResponse::Digests { digests, .. } = resp5 {
1967            assert_eq!(digests.len(), 5, "|PeerKeySet| = 5 → 5 digests");
1968        }
1969
1970        // Challenge with 0 keys (idle equivalent — no work).
1971        let challenge0 = make_challenge(3200, nonce, peer_id, vec![]);
1972        let resp0 =
1973            handle_audit_challenge(&challenge0, &storage, &self_id, false, TEST_STORED_CHUNKS)
1974                .await;
1975        if let AuditResponse::Digests { digests, .. } = resp0 {
1976            assert!(digests.is_empty(), "|PeerKeySet| = 0 → 0 digests (idle)");
1977        }
1978    }
1979
1980    // -- Scenario 47: Bootstrap claim grace period (audit) ----------------------
1981
1982    /// Scenario 47: Challenged peer responds with bootstrapping claim during
1983    /// audit.  `handle_audit_challenge` returns `Bootstrapping`; caller records
1984    /// `BootstrapClaimFirstSeen`.  No `AuditFailure` evidence is emitted.
1985    #[tokio::test]
1986    async fn scenario_47_bootstrap_claim_grace_period_audit() {
1987        let (storage, _temp) = create_test_storage().await;
1988
1989        // Store data so there is an auditable key.
1990        let content = b"bootstrap grace test";
1991        let addr = ChunkStore::compute_address(content);
1992        storage.put(&addr, content).await.expect("put");
1993
1994        let challenge = make_challenge(4700, [0x47; 32], [0x47; 32], vec![addr]);
1995        let self_id = peer_id_from_bytes([0x47; 32]);
1996
1997        // Bootstrapping peer → Bootstrapping response (grace period start).
1998        let response =
1999            handle_audit_challenge(&challenge, &storage, &self_id, true, TEST_STORED_CHUNKS).await;
2000        let challenge_id = match response {
2001            AuditResponse::Bootstrapping { challenge_id } => challenge_id,
2002            AuditResponse::Digests { .. } => {
2003                panic!("Expected Bootstrapping response during grace period")
2004            }
2005            AuditResponse::Rejected { .. } => {
2006                panic!("Unexpected Rejected response")
2007            }
2008        };
2009        assert_eq!(challenge_id, 4700);
2010
2011        // Caller records BootstrapClaimFirstSeen — verify the types support it.
2012        let peer = PeerId::from_bytes([0x47; 32]);
2013        let mut state = NeighborSyncState::new_cycle(vec![peer]);
2014        let now = Instant::now();
2015        let observed = state.observe_bootstrap_claim(
2016            peer,
2017            now,
2018            crate::replication::config::BOOTSTRAP_CLAIM_GRACE_PERIOD,
2019        );
2020
2021        assert_eq!(
2022            observed,
2023            BootstrapClaimObservation::WithinGrace { first_seen: now }
2024        );
2025        assert!(
2026            state.bootstrap_claims.contains_key(&peer),
2027            "BootstrapClaimFirstSeen should be recorded after grace-period claim"
2028        );
2029        assert!(
2030            state.bootstrap_claim_history.contains_key(&peer),
2031            "Bootstrap claim history should remember that the grace window was used"
2032        );
2033    }
2034
2035    // -- Scenario 53: Audit partial per-key failure with mixed responsibility ---
2036
2037    /// Scenario 53: P challenged on {K1, K2, K3}.  K1 matches, K2 and K3
2038    /// mismatch.  Responsibility confirmation: P is responsible for K2 but
2039    /// not K3.  `AuditFailure` emitted for {K2} only.
2040    ///
2041    /// Full `verify_digests` + `handle_audit_failure` requires a `P2PNode` for
2042    /// network lookups.  This test verifies the conceptual steps:
2043    ///   (1) Digest comparison correctly identifies K2 and K3 as failures.
2044    ///   (2) `FailureEvidence::AuditFailure` carries only confirmed keys.
2045    #[tokio::test]
2046    async fn scenario_53_partial_failure_mixed_responsibility() {
2047        let (storage, _temp) = create_test_storage().await;
2048        let nonce = [0x53; 32];
2049        let peer_id = [0x53; 32];
2050
2051        // Store K1, K2, K3.
2052        let c1 = b"scenario 53 key one";
2053        let c2 = b"scenario 53 key two";
2054        let c3 = b"scenario 53 key three";
2055        let k1 = ChunkStore::compute_address(c1);
2056        let k2 = ChunkStore::compute_address(c2);
2057        let k3 = ChunkStore::compute_address(c3);
2058        storage.put(&k1, c1).await.expect("put k1");
2059        storage.put(&k2, c2).await.expect("put k2");
2060        storage.put(&k3, c3).await.expect("put k3");
2061
2062        // Correct digests from challenger's local store.
2063        let d1_expected = compute_audit_digest(&nonce, &peer_id, &k1, c1);
2064        let d2_expected = compute_audit_digest(&nonce, &peer_id, &k2, c2);
2065        let d3_expected = compute_audit_digest(&nonce, &peer_id, &k3, c3);
2066
2067        // Simulate peer response: K1 matches, K2 wrong data, K3 wrong data.
2068        let d2_wrong = compute_audit_digest(&nonce, &peer_id, &k2, b"tampered k2");
2069        let d3_wrong = compute_audit_digest(&nonce, &peer_id, &k3, b"tampered k3");
2070
2071        assert_eq!(d1_expected, d1_expected, "K1 should match");
2072        assert_ne!(d2_wrong, d2_expected, "K2 should mismatch");
2073        assert_ne!(d3_wrong, d3_expected, "K3 should mismatch");
2074
2075        // Step 1: Identify failed keys (digest comparison).
2076        let digests = [d1_expected, d2_wrong, d3_wrong];
2077        let keys = [k1, k2, k3];
2078        let contents: [&[u8]; 3] = [c1, c2, c3];
2079
2080        let mut failed_keys = Vec::new();
2081        for (i, key) in keys.iter().enumerate() {
2082            if digests[i] == ABSENT_KEY_DIGEST {
2083                failed_keys.push(*key);
2084                continue;
2085            }
2086            let expected = compute_audit_digest(&nonce, &peer_id, key, contents[i]);
2087            if digests[i] != expected {
2088                failed_keys.push(*key);
2089            }
2090        }
2091
2092        assert_eq!(failed_keys.len(), 2, "K2 and K3 should be in failure set");
2093        assert!(failed_keys.contains(&k2));
2094        assert!(failed_keys.contains(&k3));
2095        assert!(!failed_keys.contains(&k1), "K1 passed digest check");
2096
2097        // Step 2: Responsibility confirmation removes K3 (not responsible).
2098        // Simulate: P is in closest peers for K2 but not K3.
2099        let responsible_for_k2 = true;
2100        let responsible_for_k3 = false;
2101        let mut confirmed = Vec::new();
2102        for key in &failed_keys {
2103            let is_responsible = if *key == k2 {
2104                responsible_for_k2
2105            } else {
2106                responsible_for_k3
2107            };
2108            if is_responsible {
2109                confirmed.push(*key);
2110            }
2111        }
2112
2113        assert_eq!(confirmed, vec![k2], "Only K2 should be in confirmed set");
2114
2115        // Step 3: Construct evidence for confirmed failures only.
2116        let challenged_peer = PeerId::from_bytes(peer_id);
2117        let evidence = FailureEvidence::AuditFailure {
2118            challenge_id: 5300,
2119            challenged_peer,
2120            confirmed_failed_keys: confirmed,
2121            summary: AuditFailureSummary::default(),
2122            reason: AuditFailureReason::DigestMismatch,
2123        };
2124
2125        match evidence {
2126            FailureEvidence::AuditFailure {
2127                confirmed_failed_keys,
2128                ..
2129            } => {
2130                assert_eq!(
2131                    confirmed_failed_keys.len(),
2132                    1,
2133                    "Only K2 should generate evidence"
2134                );
2135                assert_eq!(confirmed_failed_keys[0], k2);
2136            }
2137            _ => panic!("Expected AuditFailure evidence"),
2138        }
2139    }
2140}