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} ({}); penalising at audit severity",
229        failure_reason.as_str()
230    );
231    p2p_node
232        .report_trust_event(
233            peer,
234            TrustEvent::ApplicationFailure(AUDIT_FAILURE_TRUST_WEIGHT),
235        )
236        .await;
237}
238
239async fn report_possession_audit_failure(
240    peer: &PeerId,
241    key_hex: &str,
242    failure_class: AuditFailureClass,
243    p2p_node: &Arc<P2PNode>,
244) {
245    warn!(
246        audit_type = AuditType::Possession.as_str(),
247        audit_failure_class = failure_class.as_str(),
248        peer = %peer,
249        key = %key_hex,
250        trust_weight = AUDIT_FAILURE_TRUST_WEIGHT,
251        "Possession check: {peer} {} for {key_hex}; penalising at audit severity",
252        failure_class.as_str()
253    );
254    p2p_node
255        .report_trust_event(
256            peer,
257            TrustEvent::ApplicationFailure(AUDIT_FAILURE_TRUST_WEIGHT),
258        )
259        .await;
260}
261
262async fn handle_possession_bootstrap_claim(
263    peer: &PeerId,
264    key_hex: &str,
265    p2p_node: &Arc<P2PNode>,
266    config: &ReplicationConfig,
267    sync_state: &Arc<RwLock<NeighborSyncState>>,
268) {
269    let (now, observation) = {
270        let now = Instant::now();
271        let mut state = sync_state.write().await;
272        (
273            now,
274            state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period),
275        )
276    };
277
278    match observation {
279        BootstrapClaimObservation::WithinGrace { .. } => {
280            debug!(
281                "Possession check: peer {peer} claims bootstrapping for {key_hex} \
282                 (within grace period)"
283            );
284        }
285        BootstrapClaimObservation::PastGrace { first_seen } => {
286            warn!(
287                "Possession check: peer {peer} claiming bootstrap for {key_hex} past grace period \
288                 ({:?} > {:?}), reporting abuse",
289                now.duration_since(first_seen),
290                config.bootstrap_claim_grace_period,
291            );
292            p2p_node
293                .report_trust_event(
294                    peer,
295                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
296                )
297                .await;
298        }
299        BootstrapClaimObservation::Repeated { first_seen } => {
300            warn!(
301                "Possession check: peer {peer} repeated bootstrap claim for {key_hex} after \
302                 previously stopping; first claim was {:?} ago, reporting abuse",
303                now.duration_since(first_seen),
304            );
305            p2p_node
306                .report_trust_event(
307                    peer,
308                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
309                )
310                .await;
311        }
312    }
313}
314
315/// Send one single-key cryptographic [`AuditChallenge`] and interpret the
316/// response. The peer proves possession by returning
317/// `compute_audit_digest(nonce, peer, key, bytes)`; absence is proven by the
318/// [`ABSENT_KEY_DIGEST`] sentinel or any digest that does not match the
319/// checker's canonical copy. A transport failure / deadline is a `Timeout`; a
320/// matching bootstrap response is a `BootstrapClaim`; a local encode failure is
321/// `Inconclusive`; peer-side malformed, rejected, or mismatched replies are
322/// `Failed`.
323#[allow(clippy::too_many_lines)]
324async fn probe_once(
325    key: &XorName,
326    local_bytes: &[u8],
327    peer: &PeerId,
328    p2p_node: &Arc<P2PNode>,
329    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
330    probe_timeout: Duration,
331) -> ProbeOutcome {
332    // Fresh nonce per probe so a stored digest cannot be replayed, and bind the
333    // challenge to this peer's identity so it cannot relay another node's proof.
334    let (nonce, challenge_id) = {
335        let mut rng = rand::thread_rng();
336        let nonce: [u8; 32] = rng.gen();
337        let challenge_id: u64 = rng.gen();
338        (nonce, challenge_id)
339    };
340    let challenge = AuditChallenge {
341        challenge_id,
342        nonce,
343        challenged_peer_id: *peer.as_bytes(),
344        keys: vec![*key],
345    };
346    let msg = ReplicationMessage {
347        request_id: challenge_id,
348        body: ReplicationMessageBody::AuditChallenge(challenge),
349    };
350    let Ok(encoded) = msg.encode() else {
351        warn!(
352            "Failed to encode possession challenge for {}",
353            hex::encode(key)
354        );
355        return ProbeOutcome::Inconclusive;
356    };
357
358    let Some(_slot) = audit_challenge_coordinator.acquire(*peer).await else {
359        warn!("Failed to acquire possession audit coordinator slot for {peer}");
360        return ProbeOutcome::Inconclusive;
361    };
362    info!(
363        target: "ant_node::replication::audit_requester",
364        event = "started",
365        audit_origin = AuditType::Possession.as_str(),
366        audit_round = "digest",
367        challenged_peer = %peer,
368        challenge_id,
369        work_items = 1,
370        timeout_ms = probe_timeout.as_millis(),
371        "Outbound audit request started"
372    );
373    let request_started = Instant::now();
374    let response = match p2p_node
375        .send_request(peer, REPLICATION_PROTOCOL_ID, encoded, probe_timeout)
376        .await
377    {
378        Ok(response) => {
379            info!(
380                target: "ant_node::replication::audit_requester",
381                event = "completed",
382                audit_origin = AuditType::Possession.as_str(),
383                audit_round = "digest",
384                challenged_peer = %peer,
385                challenge_id,
386                work_items = 1,
387                elapsed_ms = request_started.elapsed().as_millis(),
388                outcome = "response",
389                "Outbound audit request completed"
390            );
391            response
392        }
393        Err(e) => {
394            let error = e.to_string();
395            let (send_error_class, audit_failure_class) =
396                audit_metrics::classify_audit_send_error(&error);
397            warn!(
398                target: "ant_node::replication::audit_requester",
399                event = "completed",
400                audit_origin = AuditType::Possession.as_str(),
401                audit_round = "digest",
402                challenged_peer = %peer,
403                challenge_id,
404                work_items = 1,
405                elapsed_ms = request_started.elapsed().as_millis(),
406                outcome = "no_response",
407                audit_type = AuditType::Possession.as_str(),
408                audit_failure_class = audit_failure_class.as_str(),
409                send_error_class,
410                "Possession probe to {peer} got no response: {e}"
411            );
412            return ProbeOutcome::NoResponse(audit_failure_class);
413        }
414    };
415
416    let decoded = match ReplicationMessage::decode(&response.data) {
417        Ok(decoded) => decoded,
418        Err(e) => {
419            debug!("Failed to decode possession response from {peer}: {e}");
420            return ProbeOutcome::Failed(PossessionFailureReason::ResponseDecode);
421        }
422    };
423
424    let ReplicationMessageBody::AuditResponse(resp) = decoded.body else {
425        debug!("Unexpected possession response type from {peer}");
426        return ProbeOutcome::Failed(PossessionFailureReason::UnexpectedResponseType);
427    };
428
429    interpret_audit_response(
430        key,
431        local_bytes,
432        peer.as_bytes(),
433        &nonce,
434        challenge_id,
435        resp,
436    )
437}
438
439/// Classify an [`AuditResponse`] into a possession verdict. Pure (no I/O): the
440/// digest is verified against `local_bytes`, the checker's canonical copy.
441fn interpret_audit_response(
442    key: &XorName,
443    local_bytes: &[u8],
444    challenged_peer_id: &[u8; 32],
445    nonce: &[u8; 32],
446    challenge_id: u64,
447    response: AuditResponse,
448) -> ProbeOutcome {
449    match response {
450        AuditResponse::Digests {
451            challenge_id: resp_id,
452            digests,
453        } => {
454            if resp_id != challenge_id {
455                return ProbeOutcome::Failed(PossessionFailureReason::DigestChallengeIdMismatch);
456            }
457            if digests.len() != 1 {
458                return ProbeOutcome::Failed(PossessionFailureReason::DigestCountMismatch);
459            }
460            let received = digests[0];
461            if received == ABSENT_KEY_DIGEST {
462                return ProbeOutcome::Failed(PossessionFailureReason::AbsentKey);
463            }
464            let expected = compute_audit_digest(nonce, challenged_peer_id, key, local_bytes);
465            if received == expected {
466                ProbeOutcome::Present
467            } else {
468                // A non-sentinel digest that does not match our canonical bytes
469                // proves the peer cannot reproduce the content — treat as absent
470                // (matches the audit's DigestMismatch handling).
471                ProbeOutcome::Failed(PossessionFailureReason::DigestMismatch)
472            }
473        }
474        AuditResponse::Bootstrapping {
475            challenge_id: resp_id,
476        } => {
477            if resp_id == challenge_id {
478                ProbeOutcome::BootstrapClaim
479            } else {
480                ProbeOutcome::Failed(PossessionFailureReason::BootstrapChallengeIdMismatch)
481            }
482        }
483        AuditResponse::Rejected { .. } => ProbeOutcome::Failed(PossessionFailureReason::Rejected),
484    }
485}
486
487#[cfg(test)]
488mod tests {
489    use super::*;
490    use crate::replication::config::{POSSESSION_CHECK_DELAY_MAX, POSSESSION_CHECK_DELAY_MIN};
491
492    const PEER_ID: [u8; 32] = [0x42; 32];
493    const NONCE: [u8; 32] = [0x7a; 32];
494    const CHALLENGE_ID: u64 = 0xDEAD_BEEF;
495    const KEY: XorName = [0x11; 32];
496    const BYTES: &[u8] = b"possession-check payload";
497
498    fn digests_response(challenge_id: u64, digests: Vec<[u8; 32]>) -> AuditResponse {
499        AuditResponse::Digests {
500            challenge_id,
501            digests,
502        }
503    }
504
505    #[test]
506    fn possession_failure_reasons_have_stable_log_labels() {
507        let cases = [
508            (PossessionFailureReason::ResponseDecode, "response_decode"),
509            (
510                PossessionFailureReason::UnexpectedResponseType,
511                "unexpected_response_type",
512            ),
513            (
514                PossessionFailureReason::DigestChallengeIdMismatch,
515                "digest_challenge_id_mismatch",
516            ),
517            (
518                PossessionFailureReason::DigestCountMismatch,
519                "digest_count_mismatch",
520            ),
521            (PossessionFailureReason::AbsentKey, "absent_key"),
522            (PossessionFailureReason::DigestMismatch, "digest_mismatch"),
523            (
524                PossessionFailureReason::BootstrapChallengeIdMismatch,
525                "bootstrap_challenge_id_mismatch",
526            ),
527            (PossessionFailureReason::Rejected, "rejected"),
528        ];
529
530        for (reason, expected) in cases {
531            assert_eq!(reason.as_str(), expected);
532        }
533    }
534
535    #[test]
536    fn random_delay_is_within_bounds() {
537        for _ in 0..100 {
538            let d = random_delay(POSSESSION_CHECK_DELAY_MIN, POSSESSION_CHECK_DELAY_MAX);
539            assert!(d >= POSSESSION_CHECK_DELAY_MIN);
540            assert!(d <= POSSESSION_CHECK_DELAY_MAX);
541        }
542    }
543
544    #[test]
545    fn matching_digest_is_present() {
546        let valid = compute_audit_digest(&NONCE, &PEER_ID, &KEY, BYTES);
547        let verdict = interpret_audit_response(
548            &KEY,
549            BYTES,
550            &PEER_ID,
551            &NONCE,
552            CHALLENGE_ID,
553            digests_response(CHALLENGE_ID, vec![valid]),
554        );
555        assert_eq!(verdict, ProbeOutcome::Present);
556    }
557
558    #[test]
559    fn absent_sentinel_is_failed() {
560        let verdict = interpret_audit_response(
561            &KEY,
562            BYTES,
563            &PEER_ID,
564            &NONCE,
565            CHALLENGE_ID,
566            digests_response(CHALLENGE_ID, vec![ABSENT_KEY_DIGEST]),
567        );
568        assert_eq!(
569            verdict,
570            ProbeOutcome::Failed(PossessionFailureReason::AbsentKey)
571        );
572    }
573
574    #[test]
575    fn forged_digest_is_failed() {
576        // A peer that lacks the bytes cannot compute the right digest; whatever
577        // non-sentinel value it sends must not match our canonical copy.
578        let forged = [0x99; 32];
579        let valid = compute_audit_digest(&NONCE, &PEER_ID, &KEY, BYTES);
580        assert_ne!(forged, valid, "test fixture must use a wrong digest");
581        let verdict = interpret_audit_response(
582            &KEY,
583            BYTES,
584            &PEER_ID,
585            &NONCE,
586            CHALLENGE_ID,
587            digests_response(CHALLENGE_ID, vec![forged]),
588        );
589        assert_eq!(
590            verdict,
591            ProbeOutcome::Failed(PossessionFailureReason::DigestMismatch)
592        );
593    }
594
595    #[test]
596    fn mismatched_challenge_id_is_failed() {
597        let valid = compute_audit_digest(&NONCE, &PEER_ID, &KEY, BYTES);
598        let verdict = interpret_audit_response(
599            &KEY,
600            BYTES,
601            &PEER_ID,
602            &NONCE,
603            CHALLENGE_ID,
604            digests_response(CHALLENGE_ID.wrapping_add(1), vec![valid]),
605        );
606        assert_eq!(
607            verdict,
608            ProbeOutcome::Failed(PossessionFailureReason::DigestChallengeIdMismatch)
609        );
610    }
611
612    #[test]
613    fn wrong_arity_is_failed() {
614        let valid = compute_audit_digest(&NONCE, &PEER_ID, &KEY, BYTES);
615        let verdict = interpret_audit_response(
616            &KEY,
617            BYTES,
618            &PEER_ID,
619            &NONCE,
620            CHALLENGE_ID,
621            digests_response(CHALLENGE_ID, vec![valid, ABSENT_KEY_DIGEST]),
622        );
623        assert_eq!(
624            verdict,
625            ProbeOutcome::Failed(PossessionFailureReason::DigestCountMismatch)
626        );
627    }
628
629    #[test]
630    fn bootstrapping_is_bootstrap_claim() {
631        let verdict = interpret_audit_response(
632            &KEY,
633            BYTES,
634            &PEER_ID,
635            &NONCE,
636            CHALLENGE_ID,
637            AuditResponse::Bootstrapping {
638                challenge_id: CHALLENGE_ID,
639            },
640        );
641        assert_eq!(verdict, ProbeOutcome::BootstrapClaim);
642    }
643
644    #[test]
645    fn bootstrapping_with_wrong_challenge_id_is_failed() {
646        let verdict = interpret_audit_response(
647            &KEY,
648            BYTES,
649            &PEER_ID,
650            &NONCE,
651            CHALLENGE_ID,
652            AuditResponse::Bootstrapping {
653                challenge_id: CHALLENGE_ID.wrapping_add(1),
654            },
655        );
656        assert_eq!(
657            verdict,
658            ProbeOutcome::Failed(PossessionFailureReason::BootstrapChallengeIdMismatch)
659        );
660    }
661
662    #[tokio::test]
663    async fn possession_success_clears_active_bootstrap_claim_but_keeps_history() {
664        let peer = PeerId::from_bytes(PEER_ID);
665        let sync_state = Arc::new(RwLock::new(NeighborSyncState::new_cycle(Vec::new())));
666        {
667            let mut state = sync_state.write().await;
668            let now = Instant::now();
669            state.bootstrap_claims.insert(peer, now);
670            state.bootstrap_claim_history.insert(peer, now);
671        }
672
673        clear_possession_bootstrap_claim(&peer, &sync_state).await;
674
675        let state = sync_state.read().await;
676        assert!(!state.bootstrap_claims.contains_key(&peer));
677        assert!(state.bootstrap_claim_history.contains_key(&peer));
678    }
679
680    #[test]
681    fn rejected_is_failed() {
682        let verdict = interpret_audit_response(
683            &KEY,
684            BYTES,
685            &PEER_ID,
686            &NONCE,
687            CHALLENGE_ID,
688            AuditResponse::Rejected {
689                challenge_id: CHALLENGE_ID,
690                reason: "nope".to_string(),
691            },
692        );
693        assert_eq!(
694            verdict,
695            ProbeOutcome::Failed(PossessionFailureReason::Rejected)
696        );
697    }
698}