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