Skip to main content

ant_node/replication/
possession.rs

1//! Delayed possession verification for fresh replication (ADR-0003).
2//!
3//! After a node fresh-replicates a chunk, every close-group peer responsible
4//! for it is checked 5-15 minutes later for actual possession. The check is a
5//! single-key cryptographic
6//! [`AuditChallenge`]: the probed
7//! peer must return `BLAKE3(nonce ‖ peer_id ‖ key ‖ bytes)` computed over the
8//! chunk it claims to hold. It cannot produce that digest without the bytes, so
9//! — unlike a self-reported presence flag — a peer cannot escape the check by
10//! falsely asserting possession. A peer that holds the chunk earns nothing —
11//! storing what it was paid to store is the baseline expectation, not
12//! meritorious; a peer that returns the absent sentinel, or a digest that does
13//! not match the checker's canonical copy (cryptographic proof it lacks the
14//! bytes), is penalised at `AuditChallenge` severity. Delivery of the original
15//! push is irrelevant: a peer the push never reached is still checked and
16//! penalised if it lacks the chunk.
17//!
18//! A peer unreachable at check time is penalised immediately at audit severity,
19//! matching the responsible-chunk `AuditChallenge` path. A matching bootstrap
20//! claim uses the shared bootstrap-claim grace/abuse tracker; peer-side
21//! malformed, rejected, or mismatched responses are audit failures.
22
23use std::sync::Arc;
24use std::time::{Duration, Instant};
25
26use rand::Rng;
27use saorsa_core::identity::PeerId;
28use saorsa_core::{P2PNode, TrustEvent};
29use tokio::sync::RwLock;
30use tokio_util::sync::CancellationToken;
31
32use crate::ant_protocol::XorName;
33use crate::logging::{debug, info, warn};
34use crate::replication::audit_coordinator::AuditChallengeCoordinator;
35use crate::replication::audit_metrics::{self, AuditFailureClass, AuditType};
36use crate::replication::config::{
37    ReplicationConfig, AUDIT_FAILURE_TRUST_WEIGHT, REPLICATION_PROTOCOL_ID,
38};
39use crate::replication::protocol::{
40    compute_audit_digest, AuditChallenge, AuditResponse, ReplicationMessage,
41    ReplicationMessageBody, ABSENT_KEY_DIGEST,
42};
43use crate::replication::types::{BootstrapClaimObservation, NeighborSyncState};
44use crate::storage::LmdbStorage;
45
46use super::REPLICATION_TRUST_WEIGHT;
47
48/// A possession probe challenges exactly one key, so the per-probe response
49/// budget is the audit-response timeout sized for a single chunk.
50const POSSESSION_PROBE_KEY_COUNT: usize = 1;
51
52pub(crate) fn possession_probe_response_timeout(config: &ReplicationConfig) -> Duration {
53    config.audit_response_timeout(POSSESSION_PROBE_KEY_COUNT)
54}
55
56/// A scheduled possession check for one freshly-replicated chunk.
57pub struct PossessionCheckEvent {
58    /// Content-address of the chunk.
59    pub key: XorName,
60    /// Close-group peers responsible for holding it (excludes self).
61    pub peers: Vec<PeerId>,
62}
63
64/// Verdict of cryptographically probing a single peer for possession of a chunk.
65#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
66enum ProbeOutcome {
67    /// Peer returned a digest proving it holds the chunk's bytes.
68    Present,
69    /// Peer failed the audit challenge: absent sentinel, digest mismatch,
70    /// rejection, mismatched challenge ID, wrong digest count, or malformed reply.
71    Failed(PossessionFailureReason),
72    /// No response. Penalised immediately at audit-failure severity; the class
73    /// is node-local observability only.
74    NoResponse(AuditFailureClass),
75    /// Peer returned a matching bootstrap claim. Graced only through the shared
76    /// bootstrap-claim tracker.
77    BootstrapClaim,
78    /// The probe could not be sent locally. Graced: no penalty.
79    Inconclusive,
80}
81
82/// Exact reason a responsive peer failed a possession proof check.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84enum PossessionFailureReason {
85    ResponseDecode,
86    UnexpectedResponseType,
87    DigestChallengeIdMismatch,
88    DigestCountMismatch,
89    AbsentKey,
90    DigestMismatch,
91    BootstrapChallengeIdMismatch,
92    Rejected,
93}
94
95#[cfg(any(feature = "logging", test))]
96impl PossessionFailureReason {
97    const fn as_str(self) -> &'static str {
98        match self {
99            Self::ResponseDecode => "response_decode",
100            Self::UnexpectedResponseType => "unexpected_response_type",
101            Self::DigestChallengeIdMismatch => "digest_challenge_id_mismatch",
102            Self::DigestCountMismatch => "digest_count_mismatch",
103            Self::AbsentKey => "absent_key",
104            Self::DigestMismatch => "digest_mismatch",
105            Self::BootstrapChallengeIdMismatch => "bootstrap_challenge_id_mismatch",
106            Self::Rejected => "rejected",
107        }
108    }
109}
110
111/// Pick a randomised delay in `[min, max]` to wait before a possession check
112/// runs. The bounds come from `ReplicationConfig` (defaulting to
113/// `POSSESSION_CHECK_DELAY_MIN`/`MAX`) so tests can shorten them.
114#[must_use]
115pub fn random_delay(min: Duration, max: Duration) -> Duration {
116    let to_millis = |d: Duration| u64::try_from(d.as_millis()).unwrap_or(u64::MAX);
117    let min_ms = to_millis(min);
118    let max_ms = to_millis(max);
119    if min_ms >= max_ms {
120        return min;
121    }
122    Duration::from_millis(rand::thread_rng().gen_range(min_ms..=max_ms))
123}
124
125/// Run the possession check for one chunk against every responsible peer.
126///
127/// Recomputes the expected audit digest from the checker's own canonical copy
128/// of `key`, so the check is meaningful only while the checker still holds the
129/// chunk — which it does immediately after accepting and fresh-replicating a
130/// PUT. If the checker no longer holds it (e.g. pruned), the check is moot and
131/// is skipped without penalising anyone.
132///
133/// A peer that fails to prove possession, including by timeout, is penalised at
134/// `AuditChallenge` severity immediately. A responsive peer is left unrewarded.
135#[allow(clippy::too_many_arguments)]
136pub(crate) async fn run_possession_check(
137    key: XorName,
138    peers: Vec<PeerId>,
139    p2p_node: &Arc<P2PNode>,
140    storage: &Arc<LmdbStorage>,
141    config: &ReplicationConfig,
142    sync_state: &Arc<RwLock<NeighborSyncState>>,
143    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
144    shutdown: &CancellationToken,
145) {
146    let key_hex = hex::encode(key);
147
148    // Read our canonical copy once: the audit digest is recomputed from these
149    // bytes for every peer (hoisted out of the per-peer loop). If we no longer
150    // hold the chunk we cannot verify any peer's proof, and we are no longer a
151    // responsible checker for it — skip without penalising anyone.
152    let local_bytes = match storage.get_raw(&key).await {
153        Ok(Some(bytes)) => bytes,
154        Ok(None) => {
155            debug!("Possession check: checker no longer holds {key_hex}; skipping");
156            return;
157        }
158        Err(e) => {
159            warn!("Possession check: failed to read local {key_hex}: {e}; skipping");
160            return;
161        }
162    };
163
164    // Single-key probe budget, matched to the audit response timeout's
165    // bandwidth-calibrated deadline (tight enough that a relay that must refetch
166    // the bytes blows it, generous for an honest local-disk read).
167    let probe_timeout = possession_probe_response_timeout(config);
168
169    for peer in peers {
170        if shutdown.is_cancelled() {
171            return;
172        }
173        match probe_once(
174            &key,
175            &local_bytes,
176            &peer,
177            p2p_node,
178            audit_challenge_coordinator,
179            probe_timeout,
180        )
181        .await
182        {
183            ProbeOutcome::Present => {
184                debug!("Possession check: {peer} proved possession of {key_hex}");
185                clear_possession_bootstrap_claim(&peer, sync_state).await;
186            }
187            ProbeOutcome::Failed(reason) => {
188                clear_possession_bootstrap_claim(&peer, sync_state).await;
189                report_possession_confirmed_failure(&peer, &key_hex, reason, p2p_node).await;
190            }
191            ProbeOutcome::NoResponse(class) => {
192                audit_metrics::record_audit_no_response(AuditType::Possession, class);
193                report_possession_audit_failure(&peer, &key_hex, class, p2p_node).await;
194            }
195            ProbeOutcome::BootstrapClaim => {
196                handle_possession_bootstrap_claim(&peer, &key_hex, p2p_node, config, sync_state)
197                    .await;
198            }
199            ProbeOutcome::Inconclusive => {
200                debug!(
201                    "Possession check: inconclusive probe of {peer} for {key_hex}; not penalised"
202                );
203            }
204        }
205    }
206}
207
208async fn clear_possession_bootstrap_claim(
209    peer: &PeerId,
210    sync_state: &Arc<RwLock<NeighborSyncState>>,
211) {
212    sync_state.write().await.clear_active_bootstrap_claim(peer);
213}
214
215async fn report_possession_confirmed_failure(
216    peer: &PeerId,
217    key_hex: &str,
218    failure_reason: PossessionFailureReason,
219    p2p_node: &Arc<P2PNode>,
220) {
221    warn!(
222        audit_type = AuditType::Possession.as_str(),
223        audit_failure_class = "confirmed",
224        possession_failure_reason = failure_reason.as_str(),
225        peer = %peer,
226        key = %key_hex,
227        trust_weight = AUDIT_FAILURE_TRUST_WEIGHT,
228        "Possession check: {peer} failed to prove possession for {key_hex} ({}); recorded at audit severity",
229        failure_reason.as_str()
230    );
231    crate::replication::config::penalise_unheld_close_group_chunk(
232        p2p_node,
233        peer,
234        AuditType::Possession.as_str(),
235        AUDIT_FAILURE_TRUST_WEIGHT,
236    )
237    .await;
238}
239
240async fn report_possession_audit_failure(
241    peer: &PeerId,
242    key_hex: &str,
243    failure_class: AuditFailureClass,
244    p2p_node: &Arc<P2PNode>,
245) {
246    warn!(
247        audit_type = AuditType::Possession.as_str(),
248        audit_failure_class = failure_class.as_str(),
249        peer = %peer,
250        key = %key_hex,
251        trust_weight = AUDIT_FAILURE_TRUST_WEIGHT,
252        "Possession check: {peer} {} for {key_hex}; recorded at audit severity",
253        failure_class.as_str()
254    );
255    crate::replication::config::penalise_unheld_close_group_chunk(
256        p2p_node,
257        peer,
258        AuditType::Possession.as_str(),
259        AUDIT_FAILURE_TRUST_WEIGHT,
260    )
261    .await;
262}
263
264async fn handle_possession_bootstrap_claim(
265    peer: &PeerId,
266    key_hex: &str,
267    p2p_node: &Arc<P2PNode>,
268    config: &ReplicationConfig,
269    sync_state: &Arc<RwLock<NeighborSyncState>>,
270) {
271    let (now, observation) = {
272        let now = Instant::now();
273        let mut state = sync_state.write().await;
274        (
275            now,
276            state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period),
277        )
278    };
279
280    match observation {
281        BootstrapClaimObservation::WithinGrace { .. } => {
282            debug!(
283                "Possession check: peer {peer} claims bootstrapping for {key_hex} \
284                 (within grace period)"
285            );
286        }
287        BootstrapClaimObservation::PastGrace { first_seen } => {
288            warn!(
289                "Possession check: peer {peer} claiming bootstrap for {key_hex} past grace period \
290                 ({:?} > {:?}), reporting abuse",
291                now.duration_since(first_seen),
292                config.bootstrap_claim_grace_period,
293            );
294            p2p_node
295                .report_trust_event(
296                    peer,
297                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
298                )
299                .await;
300        }
301        BootstrapClaimObservation::Repeated { first_seen } => {
302            warn!(
303                "Possession check: peer {peer} repeated bootstrap claim for {key_hex} after \
304                 previously stopping; first claim was {:?} ago, reporting abuse",
305                now.duration_since(first_seen),
306            );
307            p2p_node
308                .report_trust_event(
309                    peer,
310                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
311                )
312                .await;
313        }
314    }
315}
316
317/// Send one single-key cryptographic [`AuditChallenge`] and interpret the
318/// response. The peer proves possession by returning
319/// `compute_audit_digest(nonce, peer, key, bytes)`; absence is proven by the
320/// [`ABSENT_KEY_DIGEST`] sentinel or any digest that does not match the
321/// checker's canonical copy. A transport failure / deadline is a `Timeout`; a
322/// matching bootstrap response is a `BootstrapClaim`; a local encode failure is
323/// `Inconclusive`; peer-side malformed, rejected, or mismatched replies are
324/// `Failed`.
325#[allow(clippy::too_many_lines)]
326async fn probe_once(
327    key: &XorName,
328    local_bytes: &[u8],
329    peer: &PeerId,
330    p2p_node: &Arc<P2PNode>,
331    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
332    probe_timeout: Duration,
333) -> ProbeOutcome {
334    // Fresh nonce per probe so a stored digest cannot be replayed, and bind the
335    // challenge to this peer's identity so it cannot relay another node's proof.
336    let (nonce, challenge_id) = {
337        let mut rng = rand::thread_rng();
338        let nonce: [u8; 32] = rng.gen();
339        let challenge_id: u64 = rng.gen();
340        (nonce, challenge_id)
341    };
342    let challenge = AuditChallenge {
343        challenge_id,
344        nonce,
345        challenged_peer_id: *peer.as_bytes(),
346        keys: vec![*key],
347    };
348    let msg = ReplicationMessage {
349        request_id: challenge_id,
350        body: ReplicationMessageBody::AuditChallenge(challenge),
351    };
352    let Ok(encoded) = msg.encode() else {
353        warn!(
354            "Failed to encode possession challenge for {}",
355            hex::encode(key)
356        );
357        return ProbeOutcome::Inconclusive;
358    };
359
360    let Some(_slot) = audit_challenge_coordinator.acquire(*peer).await else {
361        warn!("Failed to acquire possession audit coordinator slot for {peer}");
362        return ProbeOutcome::Inconclusive;
363    };
364    info!(
365        target: "ant_node::replication::audit_requester",
366        event = "started",
367        audit_origin = AuditType::Possession.as_str(),
368        audit_round = "digest",
369        challenged_peer = %peer,
370        challenge_id,
371        work_items = 1,
372        timeout_ms = probe_timeout.as_millis(),
373        "Outbound audit request started"
374    );
375    let request_started = Instant::now();
376    let response = match p2p_node
377        .send_request(peer, REPLICATION_PROTOCOL_ID, encoded, probe_timeout)
378        .await
379    {
380        Ok(response) => {
381            info!(
382                target: "ant_node::replication::audit_requester",
383                event = "completed",
384                audit_origin = AuditType::Possession.as_str(),
385                audit_round = "digest",
386                challenged_peer = %peer,
387                challenge_id,
388                work_items = 1,
389                elapsed_ms = request_started.elapsed().as_millis(),
390                outcome = "response",
391                "Outbound audit request completed"
392            );
393            response
394        }
395        Err(e) => {
396            let error = e.to_string();
397            let (send_error_class, audit_failure_class) =
398                audit_metrics::classify_audit_send_error(&error);
399            warn!(
400                target: "ant_node::replication::audit_requester",
401                event = "completed",
402                audit_origin = AuditType::Possession.as_str(),
403                audit_round = "digest",
404                challenged_peer = %peer,
405                challenge_id,
406                work_items = 1,
407                elapsed_ms = request_started.elapsed().as_millis(),
408                outcome = "no_response",
409                audit_type = AuditType::Possession.as_str(),
410                audit_failure_class = audit_failure_class.as_str(),
411                send_error_class,
412                "Possession probe to {peer} got no response: {e}"
413            );
414            return ProbeOutcome::NoResponse(audit_failure_class);
415        }
416    };
417
418    let decoded = match ReplicationMessage::decode(&response.data) {
419        Ok(decoded) => decoded,
420        Err(e) => {
421            debug!("Failed to decode possession response from {peer}: {e}");
422            return ProbeOutcome::Failed(PossessionFailureReason::ResponseDecode);
423        }
424    };
425
426    let ReplicationMessageBody::AuditResponse(resp) = decoded.body else {
427        debug!("Unexpected possession response type from {peer}");
428        return ProbeOutcome::Failed(PossessionFailureReason::UnexpectedResponseType);
429    };
430
431    interpret_audit_response(
432        key,
433        local_bytes,
434        peer.as_bytes(),
435        &nonce,
436        challenge_id,
437        resp,
438    )
439}
440
441/// Classify an [`AuditResponse`] into a possession verdict. Pure (no I/O): the
442/// digest is verified against `local_bytes`, the checker's canonical copy.
443fn interpret_audit_response(
444    key: &XorName,
445    local_bytes: &[u8],
446    challenged_peer_id: &[u8; 32],
447    nonce: &[u8; 32],
448    challenge_id: u64,
449    response: AuditResponse,
450) -> ProbeOutcome {
451    match response {
452        AuditResponse::Digests {
453            challenge_id: resp_id,
454            digests,
455        } => {
456            if resp_id != challenge_id {
457                return ProbeOutcome::Failed(PossessionFailureReason::DigestChallengeIdMismatch);
458            }
459            if digests.len() != 1 {
460                return ProbeOutcome::Failed(PossessionFailureReason::DigestCountMismatch);
461            }
462            let received = digests[0];
463            if received == ABSENT_KEY_DIGEST {
464                return ProbeOutcome::Failed(PossessionFailureReason::AbsentKey);
465            }
466            let expected = compute_audit_digest(nonce, challenged_peer_id, key, local_bytes);
467            if received == expected {
468                ProbeOutcome::Present
469            } else {
470                // A non-sentinel digest that does not match our canonical bytes
471                // proves the peer cannot reproduce the content — treat as absent
472                // (matches the audit's DigestMismatch handling).
473                ProbeOutcome::Failed(PossessionFailureReason::DigestMismatch)
474            }
475        }
476        AuditResponse::Bootstrapping {
477            challenge_id: resp_id,
478        } => {
479            if resp_id == challenge_id {
480                ProbeOutcome::BootstrapClaim
481            } else {
482                ProbeOutcome::Failed(PossessionFailureReason::BootstrapChallengeIdMismatch)
483            }
484        }
485        AuditResponse::Rejected { .. } => ProbeOutcome::Failed(PossessionFailureReason::Rejected),
486    }
487}
488
489#[cfg(test)]
490mod tests {
491    use super::*;
492    use crate::replication::config::{POSSESSION_CHECK_DELAY_MAX, POSSESSION_CHECK_DELAY_MIN};
493
494    const PEER_ID: [u8; 32] = [0x42; 32];
495    const NONCE: [u8; 32] = [0x7a; 32];
496    const CHALLENGE_ID: u64 = 0xDEAD_BEEF;
497    const KEY: XorName = [0x11; 32];
498    const BYTES: &[u8] = b"possession-check payload";
499
500    fn digests_response(challenge_id: u64, digests: Vec<[u8; 32]>) -> AuditResponse {
501        AuditResponse::Digests {
502            challenge_id,
503            digests,
504        }
505    }
506
507    #[test]
508    fn possession_failure_reasons_have_stable_log_labels() {
509        let cases = [
510            (PossessionFailureReason::ResponseDecode, "response_decode"),
511            (
512                PossessionFailureReason::UnexpectedResponseType,
513                "unexpected_response_type",
514            ),
515            (
516                PossessionFailureReason::DigestChallengeIdMismatch,
517                "digest_challenge_id_mismatch",
518            ),
519            (
520                PossessionFailureReason::DigestCountMismatch,
521                "digest_count_mismatch",
522            ),
523            (PossessionFailureReason::AbsentKey, "absent_key"),
524            (PossessionFailureReason::DigestMismatch, "digest_mismatch"),
525            (
526                PossessionFailureReason::BootstrapChallengeIdMismatch,
527                "bootstrap_challenge_id_mismatch",
528            ),
529            (PossessionFailureReason::Rejected, "rejected"),
530        ];
531
532        for (reason, expected) in cases {
533            assert_eq!(reason.as_str(), expected);
534        }
535    }
536
537    #[test]
538    fn random_delay_is_within_bounds() {
539        for _ in 0..100 {
540            let d = random_delay(POSSESSION_CHECK_DELAY_MIN, POSSESSION_CHECK_DELAY_MAX);
541            assert!(d >= POSSESSION_CHECK_DELAY_MIN);
542            assert!(d <= POSSESSION_CHECK_DELAY_MAX);
543        }
544    }
545
546    #[test]
547    fn matching_digest_is_present() {
548        let valid = compute_audit_digest(&NONCE, &PEER_ID, &KEY, BYTES);
549        let verdict = interpret_audit_response(
550            &KEY,
551            BYTES,
552            &PEER_ID,
553            &NONCE,
554            CHALLENGE_ID,
555            digests_response(CHALLENGE_ID, vec![valid]),
556        );
557        assert_eq!(verdict, ProbeOutcome::Present);
558    }
559
560    #[test]
561    fn absent_sentinel_is_failed() {
562        let verdict = interpret_audit_response(
563            &KEY,
564            BYTES,
565            &PEER_ID,
566            &NONCE,
567            CHALLENGE_ID,
568            digests_response(CHALLENGE_ID, vec![ABSENT_KEY_DIGEST]),
569        );
570        assert_eq!(
571            verdict,
572            ProbeOutcome::Failed(PossessionFailureReason::AbsentKey)
573        );
574    }
575
576    #[test]
577    fn forged_digest_is_failed() {
578        // A peer that lacks the bytes cannot compute the right digest; whatever
579        // non-sentinel value it sends must not match our canonical copy.
580        let forged = [0x99; 32];
581        let valid = compute_audit_digest(&NONCE, &PEER_ID, &KEY, BYTES);
582        assert_ne!(forged, valid, "test fixture must use a wrong digest");
583        let verdict = interpret_audit_response(
584            &KEY,
585            BYTES,
586            &PEER_ID,
587            &NONCE,
588            CHALLENGE_ID,
589            digests_response(CHALLENGE_ID, vec![forged]),
590        );
591        assert_eq!(
592            verdict,
593            ProbeOutcome::Failed(PossessionFailureReason::DigestMismatch)
594        );
595    }
596
597    #[test]
598    fn mismatched_challenge_id_is_failed() {
599        let valid = compute_audit_digest(&NONCE, &PEER_ID, &KEY, BYTES);
600        let verdict = interpret_audit_response(
601            &KEY,
602            BYTES,
603            &PEER_ID,
604            &NONCE,
605            CHALLENGE_ID,
606            digests_response(CHALLENGE_ID.wrapping_add(1), vec![valid]),
607        );
608        assert_eq!(
609            verdict,
610            ProbeOutcome::Failed(PossessionFailureReason::DigestChallengeIdMismatch)
611        );
612    }
613
614    #[test]
615    fn wrong_arity_is_failed() {
616        let valid = compute_audit_digest(&NONCE, &PEER_ID, &KEY, BYTES);
617        let verdict = interpret_audit_response(
618            &KEY,
619            BYTES,
620            &PEER_ID,
621            &NONCE,
622            CHALLENGE_ID,
623            digests_response(CHALLENGE_ID, vec![valid, ABSENT_KEY_DIGEST]),
624        );
625        assert_eq!(
626            verdict,
627            ProbeOutcome::Failed(PossessionFailureReason::DigestCountMismatch)
628        );
629    }
630
631    #[test]
632    fn bootstrapping_is_bootstrap_claim() {
633        let verdict = interpret_audit_response(
634            &KEY,
635            BYTES,
636            &PEER_ID,
637            &NONCE,
638            CHALLENGE_ID,
639            AuditResponse::Bootstrapping {
640                challenge_id: CHALLENGE_ID,
641            },
642        );
643        assert_eq!(verdict, ProbeOutcome::BootstrapClaim);
644    }
645
646    #[test]
647    fn bootstrapping_with_wrong_challenge_id_is_failed() {
648        let verdict = interpret_audit_response(
649            &KEY,
650            BYTES,
651            &PEER_ID,
652            &NONCE,
653            CHALLENGE_ID,
654            AuditResponse::Bootstrapping {
655                challenge_id: CHALLENGE_ID.wrapping_add(1),
656            },
657        );
658        assert_eq!(
659            verdict,
660            ProbeOutcome::Failed(PossessionFailureReason::BootstrapChallengeIdMismatch)
661        );
662    }
663
664    #[tokio::test]
665    async fn possession_success_clears_active_bootstrap_claim_but_keeps_history() {
666        let peer = PeerId::from_bytes(PEER_ID);
667        let sync_state = Arc::new(RwLock::new(NeighborSyncState::new_cycle(Vec::new())));
668        {
669            let mut state = sync_state.write().await;
670            let now = Instant::now();
671            state.bootstrap_claims.insert(peer, now);
672            state.bootstrap_claim_history.insert(peer, now);
673        }
674
675        clear_possession_bootstrap_claim(&peer, &sync_state).await;
676
677        let state = sync_state.read().await;
678        assert!(!state.bootstrap_claims.contains_key(&peer));
679        assert!(state.bootstrap_claim_history.contains_key(&peer));
680    }
681
682    #[test]
683    fn rejected_is_failed() {
684        let verdict = interpret_audit_response(
685            &KEY,
686            BYTES,
687            &PEER_ID,
688            &NONCE,
689            CHALLENGE_ID,
690            AuditResponse::Rejected {
691                challenge_id: CHALLENGE_ID,
692                reason: "nope".to_string(),
693            },
694        );
695        assert_eq!(
696            verdict,
697            ProbeOutcome::Failed(PossessionFailureReason::Rejected)
698        );
699    }
700}