1use std::cmp::Ordering;
8use std::collections::{HashMap, HashSet, VecDeque};
9use std::time::{Duration, Instant};
10
11use serde::{Deserialize, Serialize};
12
13use crate::ant_protocol::XorName;
14use crate::replication::config::REPAIR_HINT_MIN_AGE;
15use saorsa_core::identity::PeerId;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum VerificationState {
28 OfferReceived,
30 PendingVerify,
32 QuorumVerified,
35 PaidListVerified,
38 QueuedForFetch,
40 Fetching,
42 Stored,
44 FetchRetryable,
46 FetchAbandoned,
48 QuorumFailed,
51 QuorumInconclusive,
53 QuorumAbandoned,
55 Idle,
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
66pub enum HintPipeline {
67 Replica,
69 PaidOnly,
72}
73
74#[derive(Debug, Clone)]
83pub struct VerificationEntry {
84 pub state: VerificationState,
86 pub verified_sources: Vec<PeerId>,
89 pub tried_sources: HashSet<PeerId>,
91 pub created_at: Instant,
93 pub next_verify_at: Instant,
96 pub hint_sources: HashSet<PeerId>,
99 pub replica_hint_sources: HashSet<PeerId>,
102 pub unresolved_retries: u32,
116 pub no_holder_reported: bool,
128}
129
130impl VerificationEntry {
131 #[must_use]
147 pub fn pipeline(&self) -> HintPipeline {
148 if self.replica_hint_sources.is_empty() {
149 HintPipeline::PaidOnly
150 } else {
151 HintPipeline::Replica
152 }
153 }
154}
155
156#[derive(Debug, Clone, Copy)]
173pub struct FetchOrder {
174 pub key: XorName,
176 pub distance: XorName,
178}
179
180impl Eq for FetchOrder {}
181
182impl PartialEq for FetchOrder {
183 fn eq(&self, other: &Self) -> bool {
184 self.distance == other.distance && self.key == other.key
185 }
186}
187
188impl Ord for FetchOrder {
189 fn cmp(&self, other: &Self) -> Ordering {
190 other
193 .distance
194 .cmp(&self.distance)
195 .then_with(|| self.key.cmp(&other.key))
196 }
197}
198
199impl PartialOrd for FetchOrder {
200 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
201 Some(self.cmp(other))
202 }
203}
204
205#[derive(Debug, Clone)]
212pub struct FetchPayload {
213 pub sources: Vec<PeerId>,
215 pub retry_verification: Option<VerificationEntry>,
218}
219
220#[derive(Debug, Clone)]
223pub struct FetchCandidate {
224 pub key: XorName,
226 pub distance: XorName,
228 pub sources: Vec<PeerId>,
230 pub retry_verification: Option<VerificationEntry>,
233}
234
235#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
241pub enum PresenceEvidence {
242 Present,
244 Absent,
246 Unresolved,
248}
249
250#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
252pub enum PaidListEvidence {
253 Confirmed,
255 NotFound,
257 Unresolved,
259}
260
261#[derive(Debug, Clone)]
264pub struct KeyVerificationEvidence {
265 pub presence: HashMap<PeerId, PresenceEvidence>,
267 pub paid_list: HashMap<PeerId, PaidListEvidence>,
269}
270
271#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
278pub struct AuditFailureSummary {
279 pub challenged_keys: usize,
281 pub failed_keys: usize,
283 pub absent_keys: usize,
285 pub digest_mismatch_keys: usize,
288}
289
290#[derive(Debug, Clone)]
292pub enum FailureEvidence {
293 ReplicationFailure {
295 peer: PeerId,
297 key: XorName,
299 },
300 AuditFailure {
302 challenge_id: u64,
304 challenged_peer: PeerId,
306 confirmed_failed_keys: Vec<XorName>,
308 summary: AuditFailureSummary,
310 reason: AuditFailureReason,
312 },
313 BootstrapClaimAbuse {
315 peer: PeerId,
317 first_seen: Instant,
319 },
320 QuoteCommitmentMismatch {
329 peer: PeerId,
331 pinned_commitment: [u8; 32],
334 quoted_key_count: u32,
336 committed_key_count: u32,
338 quote_artifact: Vec<u8>,
345 commitment: Box<crate::replication::commitment::StorageCommitment>,
351 },
352}
353
354#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
356pub enum AuditFailureReason {
357 Timeout,
359 MalformedResponse,
361 DigestMismatch,
363 KeyAbsent,
365 Rejected,
367}
368
369#[derive(Debug, Clone)]
375pub struct PeerSyncRecord {
376 pub last_sync: Option<Instant>,
378 pub cycles_since_sync: u32,
381}
382
383impl PeerSyncRecord {
384 #[must_use]
387 pub fn has_repair_opportunity(&self) -> bool {
388 self.last_sync.is_some() && self.cycles_since_sync >= 1
389 }
390}
391
392#[derive(Debug, Clone)]
398struct RepairProof {
399 hinted_at_epoch: u64,
401 hinted_at: Instant,
403}
404
405#[derive(Debug, Clone)]
408struct RepairProofEntry {
409 close_peers: HashSet<PeerId>,
411 peer_proofs: HashMap<PeerId, RepairProof>,
413}
414
415impl RepairProofEntry {
416 fn new(close_peers: HashSet<PeerId>) -> Self {
417 Self {
418 close_peers,
419 peer_proofs: HashMap::new(),
420 }
421 }
422}
423
424#[derive(Debug, Clone, Default)]
430pub struct RepairProofs {
431 proofs_by_key: HashMap<XorName, RepairProofEntry>,
433}
434
435impl RepairProofs {
436 #[must_use]
438 pub fn new() -> Self {
439 Self::default()
440 }
441
442 pub fn record_replica_hint_sent(
450 &mut self,
451 peer: PeerId,
452 key: XorName,
453 current_close_peers: &HashSet<PeerId>,
454 hinted_at_epoch: u64,
455 ) -> bool {
456 self.insert_replica_hint_sent(
457 peer,
458 key,
459 current_close_peers,
460 hinted_at_epoch,
461 Instant::now(),
462 )
463 }
464
465 #[cfg(any(test, feature = "test-utils"))]
472 pub fn record_replica_hint_sent_at(
473 &mut self,
474 peer: PeerId,
475 key: XorName,
476 current_close_peers: &HashSet<PeerId>,
477 hinted_at_epoch: u64,
478 hinted_at: Instant,
479 ) -> bool {
480 self.insert_replica_hint_sent(peer, key, current_close_peers, hinted_at_epoch, hinted_at)
481 }
482
483 fn insert_replica_hint_sent(
484 &mut self,
485 peer: PeerId,
486 key: XorName,
487 current_close_peers: &HashSet<PeerId>,
488 hinted_at_epoch: u64,
489 hinted_at: Instant,
490 ) -> bool {
491 self.reconcile_key_close_group(&key, current_close_peers);
492
493 if !current_close_peers.contains(&peer) {
494 return false;
495 }
496
497 let entry = self
498 .proofs_by_key
499 .entry(key)
500 .or_insert_with(|| RepairProofEntry::new(current_close_peers.clone()));
501
502 if entry.peer_proofs.contains_key(&peer) {
503 return false;
504 }
505
506 entry.peer_proofs.insert(
507 peer,
508 RepairProof {
509 hinted_at_epoch,
510 hinted_at,
511 },
512 );
513 true
514 }
515
516 pub fn has_mature_replica_hint(
523 &mut self,
524 peer: &PeerId,
525 key: &XorName,
526 current_close_peers: &HashSet<PeerId>,
527 current_epoch: u64,
528 now: Instant,
529 ) -> bool {
530 self.reconcile_key_close_group(key, current_close_peers);
531
532 self.proofs_by_key
533 .get(key)
534 .and_then(|entry| entry.peer_proofs.get(peer))
535 .is_some_and(|proof| {
536 proof.hinted_at_epoch < current_epoch
537 && now.saturating_duration_since(proof.hinted_at) >= REPAIR_HINT_MIN_AGE
538 })
539 }
540
541 pub fn remove_key(&mut self, key: &XorName) {
543 self.proofs_by_key.remove(key);
544 }
545
546 pub fn remove_peer(&mut self, peer: &PeerId) {
548 self.proofs_by_key.retain(|_, entry| {
549 entry.peer_proofs.remove(peer);
550 !entry.peer_proofs.is_empty()
551 });
552 }
553
554 fn reconcile_key_close_group(&mut self, key: &XorName, current_close_peers: &HashSet<PeerId>) {
555 let should_remove = if let Some(entry) = self.proofs_by_key.get_mut(key) {
556 if entry.close_peers == *current_close_peers {
557 return;
558 }
559
560 entry.close_peers.clone_from(current_close_peers);
561 entry
562 .peer_proofs
563 .retain(|peer, _| current_close_peers.contains(peer));
564 entry.peer_proofs.is_empty()
565 } else {
566 false
567 };
568
569 if should_remove {
570 self.proofs_by_key.remove(key);
571 }
572 }
573}
574
575#[derive(Debug, Clone, Copy, PartialEq, Eq)]
581pub enum BootstrapClaimObservation {
582 WithinGrace {
584 first_seen: Instant,
586 },
587 PastGrace {
589 first_seen: Instant,
591 },
592 Repeated {
594 first_seen: Instant,
596 },
597}
598
599#[derive(Debug)]
605pub struct NeighborSyncState {
606 pub priority_order: VecDeque<PeerId>,
613 pub order: Vec<PeerId>,
615 pub cursor: usize,
617 pub last_sync_times: HashMap<PeerId, Instant>,
619 pub bootstrap_claims: HashMap<PeerId, Instant>,
625 pub bootstrap_claim_history: HashMap<PeerId, Instant>,
633}
634
635impl NeighborSyncState {
636 #[must_use]
638 pub fn new_cycle(close_neighbors: Vec<PeerId>) -> Self {
639 Self {
640 priority_order: VecDeque::new(),
641 order: close_neighbors,
642 cursor: 0,
643 last_sync_times: HashMap::new(),
644 bootstrap_claims: HashMap::new(),
645 bootstrap_claim_history: HashMap::new(),
646 }
647 }
648
649 #[must_use]
656 pub fn observe_bootstrap_claim(
657 &mut self,
658 peer: PeerId,
659 now: Instant,
660 grace_period: Duration,
661 ) -> BootstrapClaimObservation {
662 if let Some(first_seen) = self.bootstrap_claims.get(&peer).copied() {
663 if now.duration_since(first_seen) > grace_period {
664 BootstrapClaimObservation::PastGrace { first_seen }
665 } else {
666 BootstrapClaimObservation::WithinGrace { first_seen }
667 }
668 } else if let Some(first_seen) = self.bootstrap_claim_history.get(&peer).copied() {
669 BootstrapClaimObservation::Repeated { first_seen }
670 } else {
671 self.bootstrap_claims.insert(peer, now);
672 self.bootstrap_claim_history.insert(peer, now);
673 BootstrapClaimObservation::WithinGrace { first_seen: now }
674 }
675 }
676
677 pub fn clear_active_bootstrap_claim(&mut self, peer: &PeerId) -> bool {
679 self.bootstrap_claims.remove(peer).is_some()
680 }
681
682 pub fn queue_priority_peers<I>(&mut self, peers: I) -> usize
687 where
688 I: IntoIterator<Item = PeerId>,
689 {
690 let mut queued = 0;
691 for peer in peers {
692 if self.priority_order.contains(&peer) {
693 continue;
694 }
695 self.priority_order.push_back(peer);
696 queued += 1;
697 }
698 queued
699 }
700
701 pub fn retain_sync_peers(&mut self, close_peers: &HashSet<PeerId>) -> usize {
706 let old_priority_len = self.priority_order.len();
707 self.priority_order
708 .retain(|peer| close_peers.contains(peer));
709
710 let old_order_len = self.order.len();
711 let old_cursor = self.cursor;
712 let mut retained_before_cursor = 0;
713 let mut retained_order = Vec::with_capacity(old_order_len);
714 for (idx, peer) in self.order.drain(..).enumerate() {
715 if close_peers.contains(&peer) {
716 if idx < old_cursor {
717 retained_before_cursor += 1;
718 }
719 retained_order.push(peer);
720 }
721 }
722
723 self.order = retained_order;
724 self.cursor = retained_before_cursor;
725
726 (old_priority_len - self.priority_order.len()) + (old_order_len - self.order.len())
727 }
728
729 pub fn remove_peer(&mut self, peer: &PeerId) -> bool {
731 let old_priority_len = self.priority_order.len();
732 self.priority_order.retain(|queued| queued != peer);
733
734 let old_order_len = self.order.len();
735 if let Some(pos) = self.order.iter().position(|queued| queued == peer) {
736 self.order.remove(pos);
737 if pos < self.cursor {
738 self.cursor = self.cursor.saturating_sub(1);
739 }
740 }
741
742 old_priority_len != self.priority_order.len() || old_order_len != self.order.len()
743 }
744
745 #[must_use]
747 pub fn is_cycle_complete(&self) -> bool {
748 self.priority_order.is_empty() && self.cursor >= self.order.len()
749 }
750
751 #[must_use]
758 pub fn has_priority_peers(&self) -> bool {
759 !self.priority_order.is_empty()
760 }
761}
762
763#[derive(Debug)]
769pub struct BootstrapState {
770 pub drained: bool,
772 pub pending_peer_requests: usize,
774 pub pending_keys: HashSet<XorName>,
777 pub capacity_rejected_sources: HashMap<PeerId, Instant>,
818}
819
820impl BootstrapState {
821 #[must_use]
823 pub fn new() -> Self {
824 Self {
825 drained: false,
826 pending_peer_requests: 0,
827 pending_keys: HashSet::new(),
828 capacity_rejected_sources: HashMap::new(),
829 }
830 }
831
832 pub fn note_capacity_rejected(&mut self, source: PeerId, now: Instant) -> bool {
843 let first = !self.capacity_rejected_sources.contains_key(&source);
844 self.capacity_rejected_sources.entry(source).or_insert(now);
845 first
846 }
847
848 #[must_use]
855 pub fn is_drained(&self) -> bool {
856 self.drained
857 }
858
859 pub fn remove_key(&mut self, key: &XorName) {
865 self.pending_keys.remove(key);
866 }
867}
868
869impl Default for BootstrapState {
870 fn default() -> Self {
871 Self::new()
872 }
873}
874
875#[cfg(test)]
880mod tests {
881 use super::*;
882
883 fn peer_id_from_byte(b: u8) -> PeerId {
885 let mut bytes = [0u8; 32];
886 bytes[0] = b;
887 PeerId::from_bytes(bytes)
888 }
889
890 fn mature_hint_times() -> (Instant, Instant) {
891 let hinted_at = Instant::now();
892 let now = hinted_at
893 .checked_add(REPAIR_HINT_MIN_AGE)
894 .unwrap_or(hinted_at);
895 (hinted_at, now)
896 }
897
898 #[test]
901 fn fetch_order_nearest_key_has_highest_priority() {
902 let near = FetchOrder {
903 key: [1u8; 32],
904 distance: [
905 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
906 0, 0, 0, 0,
907 ],
908 };
909
910 let far = FetchOrder {
911 key: [2u8; 32],
912 distance: [
913 0xFF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
914 0, 0, 0, 0, 0,
915 ],
916 };
917
918 assert!(near > far, "nearer candidate should compare greater");
921
922 let mut heap = std::collections::BinaryHeap::new();
923 heap.push(far);
924 heap.push(near);
925
926 assert_eq!(heap.len(), 2, "heap should contain both candidates");
927
928 let first = heap.pop();
929 assert!(first.is_some(), "first pop should succeed");
930 assert_eq!(
931 first.map(|c| c.key),
932 Some(near.key),
933 "nearest key should pop first"
934 );
935
936 let second = heap.pop();
937 assert!(second.is_some(), "second pop should succeed");
938 assert_eq!(
939 second.map(|c| c.key),
940 Some(far.key),
941 "farthest key should pop second"
942 );
943 }
944
945 #[test]
946 fn fetch_order_same_distance_and_key_is_equal() {
947 let a = FetchOrder {
948 key: [1u8; 32],
949 distance: [5u8; 32],
950 };
951
952 let b = FetchOrder {
953 key: [1u8; 32],
954 distance: [5u8; 32],
955 };
956
957 assert_eq!(
958 a.cmp(&b),
959 Ordering::Equal,
960 "same distance + same key should yield Equal"
961 );
962 assert_eq!(a, b, "PartialEq must agree with Ord");
963 }
964
965 #[test]
966 fn fetch_order_same_distance_different_key_is_deterministic() {
967 let a = FetchOrder {
968 key: [1u8; 32],
969 distance: [5u8; 32],
970 };
971
972 let b = FetchOrder {
973 key: [2u8; 32],
974 distance: [5u8; 32],
975 };
976
977 assert_ne!(
978 a.cmp(&b),
979 Ordering::Equal,
980 "same distance + different key must not be Equal"
981 );
982 assert_ne!(a, b, "PartialEq must agree with Ord");
983 }
984
985 #[test]
988 fn peer_sync_record_no_sync_yet() {
989 let record = PeerSyncRecord {
990 last_sync: None,
991 cycles_since_sync: 0,
992 };
993 assert!(
994 !record.has_repair_opportunity(),
995 "never-synced peer has no repair opportunity"
996 );
997 }
998
999 #[test]
1000 fn peer_sync_record_synced_but_no_cycle() {
1001 let record = PeerSyncRecord {
1002 last_sync: Some(Instant::now()),
1003 cycles_since_sync: 0,
1004 };
1005 assert!(
1006 !record.has_repair_opportunity(),
1007 "synced peer with zero subsequent cycles has no repair opportunity"
1008 );
1009 }
1010
1011 #[test]
1012 fn peer_sync_record_synced_with_cycle() {
1013 let record = PeerSyncRecord {
1014 last_sync: Some(Instant::now()),
1015 cycles_since_sync: 1,
1016 };
1017 assert!(
1018 record.has_repair_opportunity(),
1019 "synced peer with >= 1 cycle should have repair opportunity"
1020 );
1021 }
1022
1023 #[test]
1024 fn peer_sync_record_no_sync_many_cycles() {
1025 let record = PeerSyncRecord {
1026 last_sync: None,
1027 cycles_since_sync: 10,
1028 };
1029 assert!(
1030 !record.has_repair_opportunity(),
1031 "never-synced peer has no repair opportunity regardless of cycle count"
1032 );
1033 }
1034
1035 #[test]
1038 fn repair_proofs_record_sent_hint_for_close_peer() {
1039 const HINT_EPOCH: u64 = 7;
1040 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1041
1042 let key = [0xA1; 32];
1043 let peer = peer_id_from_byte(1);
1044 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1045 let mut proofs = RepairProofs::new();
1046 let (hinted_at, now) = mature_hint_times();
1047
1048 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1049
1050 assert!(
1051 proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1052 "old sent hint should make key auditable for that peer"
1053 );
1054 }
1055
1056 #[test]
1057 fn repair_proofs_reject_peer_outside_current_close_group() {
1058 const HINT_EPOCH: u64 = 7;
1059 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1060
1061 let key = [0xA2; 32];
1062 let peer = peer_id_from_byte(1);
1063 let close_peers = HashSet::from([peer_id_from_byte(2), peer_id_from_byte(3)]);
1064 let mut proofs = RepairProofs::new();
1065 let (hinted_at, now) = mature_hint_times();
1066
1067 assert!(!proofs.record_replica_hint_sent_at(
1068 peer,
1069 key,
1070 &close_peers,
1071 HINT_EPOCH,
1072 hinted_at,
1073 ));
1074
1075 assert!(
1076 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1077 "peers outside current close group must not get repair proof"
1078 );
1079 }
1080
1081 #[test]
1082 fn repair_proofs_require_later_epoch() {
1083 const HINT_EPOCH: u64 = 7;
1084 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1085
1086 let key = [0xA3; 32];
1087 let peer = peer_id_from_byte(1);
1088 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1089 let mut proofs = RepairProofs::new();
1090 let (hinted_at, now) = mature_hint_times();
1091
1092 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1093
1094 assert!(
1095 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, HINT_EPOCH, now),
1096 "same-cycle proof should not be audit-eligible"
1097 );
1098 assert!(
1099 proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1100 "old proof should mature after a later local sync-cycle epoch"
1101 );
1102 }
1103
1104 #[test]
1105 fn repair_proofs_require_min_hint_age() {
1106 const HINT_EPOCH: u64 = 7;
1107 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1108
1109 let key = [0xA8; 32];
1110 let peer = peer_id_from_byte(1);
1111 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1112 let mut proofs = RepairProofs::new();
1113 let hinted_at = Instant::now();
1114
1115 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at));
1116
1117 assert!(
1118 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, hinted_at),
1119 "fresh repair hints should not be audit-eligible"
1120 );
1121 assert!(
1122 proofs.has_mature_replica_hint(
1123 &peer,
1124 &key,
1125 &close_peers,
1126 CURRENT_EPOCH,
1127 hinted_at
1128 .checked_add(REPAIR_HINT_MIN_AGE)
1129 .unwrap_or(hinted_at),
1130 ),
1131 "repair hints should mature once they are at least the minimum age"
1132 );
1133 }
1134
1135 #[test]
1136 fn repair_proofs_repeated_hint_does_not_reset_maturity() {
1137 const HINT_EPOCH: u64 = 7;
1138 const REPEATED_HINT_EPOCH: u64 = HINT_EPOCH + 1;
1139
1140 let key = [0xA5; 32];
1141 let peer = peer_id_from_byte(1);
1142 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1143 let mut proofs = RepairProofs::new();
1144 let (hinted_at, now) = mature_hint_times();
1145
1146 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1147 assert!(
1148 !proofs.record_replica_hint_sent_at(peer, key, &close_peers, REPEATED_HINT_EPOCH, now),
1149 "duplicate hint in the same close group should keep existing proof"
1150 );
1151 assert!(
1152 proofs.has_mature_replica_hint(&peer, &key, &close_peers, REPEATED_HINT_EPOCH, now),
1153 "duplicate hint must not reset an already mature proof"
1154 );
1155 }
1156
1157 #[test]
1158 fn repair_proofs_retain_stable_peers_on_close_group_change() {
1159 const HINT_EPOCH: u64 = 7;
1160 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1161
1162 let key = [0xA7; 32];
1163 let stable_peer = peer_id_from_byte(1);
1164 let departing_peer = peer_id_from_byte(2);
1165 let retained_peer = peer_id_from_byte(3);
1166 let new_peer = peer_id_from_byte(4);
1167 let old_group = HashSet::from([stable_peer, departing_peer, retained_peer]);
1168 let changed_group = HashSet::from([stable_peer, retained_peer, new_peer]);
1169 let mut proofs = RepairProofs::new();
1170 let (hinted_at, now) = mature_hint_times();
1171
1172 assert!(proofs.record_replica_hint_sent_at(
1173 stable_peer,
1174 key,
1175 &old_group,
1176 HINT_EPOCH,
1177 hinted_at,
1178 ));
1179 assert!(proofs.record_replica_hint_sent_at(
1180 departing_peer,
1181 key,
1182 &old_group,
1183 HINT_EPOCH,
1184 hinted_at,
1185 ));
1186
1187 assert!(
1188 proofs.has_mature_replica_hint(&stable_peer, &key, &changed_group, CURRENT_EPOCH, now),
1189 "stable peers should keep mature repair proofs across unrelated close-group churn"
1190 );
1191 assert!(
1192 !proofs.has_mature_replica_hint(
1193 &departing_peer,
1194 &key,
1195 &changed_group,
1196 CURRENT_EPOCH,
1197 now,
1198 ),
1199 "peers that left the close group should lose repair proofs"
1200 );
1201 assert!(
1202 !proofs.has_mature_replica_hint(&new_peer, &key, &changed_group, CURRENT_EPOCH, now),
1203 "new close-group peers need their own repair hint before auditing"
1204 );
1205 }
1206
1207 #[test]
1208 fn repair_proofs_evicted_peer_reentry_requires_fresh_hint() {
1209 const FIRST_HINT_EPOCH: u64 = 7;
1210 const SECOND_HINT_EPOCH: u64 = FIRST_HINT_EPOCH + 1;
1211 const CURRENT_EPOCH: u64 = SECOND_HINT_EPOCH + 1;
1212
1213 let key = [0xA3; 32];
1214 let returning_peer = peer_id_from_byte(1);
1215 let new_peer = peer_id_from_byte(4);
1216 let old_group = HashSet::from([returning_peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1217 let changed_group = HashSet::from([new_peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1218 let mut proofs = RepairProofs::new();
1219 let (hinted_at, now) = mature_hint_times();
1220
1221 assert!(proofs.record_replica_hint_sent_at(
1222 returning_peer,
1223 key,
1224 &old_group,
1225 FIRST_HINT_EPOCH,
1226 hinted_at,
1227 ));
1228
1229 assert!(
1230 !proofs.has_mature_replica_hint(
1231 &new_peer,
1232 &key,
1233 &changed_group,
1234 SECOND_HINT_EPOCH,
1235 now
1236 ),
1237 "new close-group peer should not inherit another peer's repair proof"
1238 );
1239 assert!(
1240 !proofs.has_mature_replica_hint(&returning_peer, &key, &old_group, CURRENT_EPOCH, now),
1241 "a peer that re-enters must receive a fresh repair hint"
1242 );
1243
1244 assert!(proofs.record_replica_hint_sent_at(
1245 returning_peer,
1246 key,
1247 &old_group,
1248 SECOND_HINT_EPOCH,
1249 hinted_at,
1250 ));
1251 assert!(
1252 proofs.has_mature_replica_hint(&returning_peer, &key, &old_group, CURRENT_EPOCH, now),
1253 "fresh repair hint after re-entry should be eligible once mature"
1254 );
1255 }
1256
1257 #[test]
1258 fn repair_proofs_remove_peer_requires_fresh_hint_after_reentry() {
1259 const FIRST_HINT_EPOCH: u64 = 7;
1260 const SECOND_HINT_EPOCH: u64 = FIRST_HINT_EPOCH + 1;
1261 const CURRENT_EPOCH: u64 = SECOND_HINT_EPOCH + 1;
1262
1263 let key = [0xA6; 32];
1264 let peer = peer_id_from_byte(1);
1265 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1266 let mut proofs = RepairProofs::new();
1267 let (hinted_at, now) = mature_hint_times();
1268
1269 assert!(proofs.record_replica_hint_sent_at(
1270 peer,
1271 key,
1272 &close_peers,
1273 FIRST_HINT_EPOCH,
1274 hinted_at,
1275 ));
1276 proofs.remove_peer(&peer);
1277
1278 assert!(
1279 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1280 "routing-table removal should clear proof even if peer re-enters same close group"
1281 );
1282
1283 assert!(proofs.record_replica_hint_sent_at(
1284 peer,
1285 key,
1286 &close_peers,
1287 SECOND_HINT_EPOCH,
1288 hinted_at,
1289 ));
1290 assert!(
1291 proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1292 "fresh hint after re-entry should become eligible after a later epoch"
1293 );
1294 }
1295
1296 #[test]
1297 fn repair_proofs_remove_key_clears_all_peer_entries() {
1298 const HINT_EPOCH: u64 = 7;
1299 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1300
1301 let key = [0xA4; 32];
1302 let peer = peer_id_from_byte(1);
1303 let close_peers = HashSet::from([peer]);
1304 let mut proofs = RepairProofs::new();
1305 let (hinted_at, now) = mature_hint_times();
1306
1307 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1308 proofs.remove_key(&key);
1309
1310 assert!(
1311 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1312 "deleted local key should not retain repair proof entries"
1313 );
1314 }
1315
1316 #[test]
1319 fn neighbor_sync_empty_cycle_is_immediately_complete() {
1320 let state = NeighborSyncState::new_cycle(vec![]);
1321 assert!(
1322 state.is_cycle_complete(),
1323 "empty neighbor list means cycle is complete"
1324 );
1325 }
1326
1327 #[test]
1328 fn neighbor_sync_new_cycle_not_complete() {
1329 let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
1330 let state = NeighborSyncState::new_cycle(peers);
1331 assert!(
1332 !state.is_cycle_complete(),
1333 "fresh cycle with peers should not be complete"
1334 );
1335 }
1336
1337 #[test]
1338 fn neighbor_sync_cycle_completes_when_cursor_reaches_end() {
1339 let peers = vec![
1340 peer_id_from_byte(1),
1341 peer_id_from_byte(2),
1342 peer_id_from_byte(3),
1343 ];
1344 let mut state = NeighborSyncState::new_cycle(peers);
1345
1346 state.cursor = 2;
1348 assert!(
1349 !state.is_cycle_complete(),
1350 "cursor at len-1 should not be complete"
1351 );
1352
1353 state.cursor = 3;
1354 assert!(
1355 state.is_cycle_complete(),
1356 "cursor at len should be complete"
1357 );
1358 }
1359
1360 #[test]
1361 fn neighbor_sync_cursor_past_end_is_still_complete() {
1362 let peers = vec![peer_id_from_byte(1)];
1363 let mut state = NeighborSyncState::new_cycle(peers);
1364 state.cursor = 5;
1365 assert!(
1366 state.is_cycle_complete(),
1367 "cursor past end should still report complete"
1368 );
1369 }
1370
1371 #[test]
1372 fn neighbor_sync_priority_queue_blocks_cycle_completion() {
1373 let peer = peer_id_from_byte(2);
1374 let mut state = NeighborSyncState::new_cycle(Vec::new());
1375
1376 assert!(state.is_cycle_complete());
1377 assert_eq!(state.queue_priority_peers([peer]), 1);
1378 assert!(
1379 !state.is_cycle_complete(),
1380 "pending priority peers must sync before the cycle completes"
1381 );
1382 }
1383
1384 #[test]
1385 fn neighbor_sync_priority_queue_deduplicates_peers() {
1386 let peer = peer_id_from_byte(3);
1387 let mut state = NeighborSyncState::new_cycle(Vec::new());
1388
1389 assert_eq!(state.queue_priority_peers([peer, peer]), 1);
1390 assert_eq!(state.priority_order.len(), 1);
1391 }
1392
1393 #[test]
1394 fn neighbor_sync_has_priority_peers_tracks_queue_and_drain() {
1395 let first = peer_id_from_byte(6);
1401 let second = peer_id_from_byte(7);
1402 let mut state = NeighborSyncState::new_cycle(Vec::new());
1403 assert!(!state.has_priority_peers());
1404
1405 assert_eq!(state.queue_priority_peers([first, second]), 2);
1406 assert!(state.has_priority_peers());
1407
1408 assert!(state.remove_peer(&first));
1409 assert!(state.has_priority_peers(), "one entrant still pending");
1410
1411 assert!(state.remove_peer(&second));
1412 assert!(
1413 !state.has_priority_peers(),
1414 "drained queue must let the loop park"
1415 );
1416 }
1417
1418 #[test]
1419 fn neighbor_sync_remove_peer_clears_order_and_priority_queue() {
1420 let peer = peer_id_from_byte(4);
1421 let retained = peer_id_from_byte(5);
1422 let mut state = NeighborSyncState::new_cycle(vec![peer, retained]);
1423 assert_eq!(state.queue_priority_peers([peer]), 1);
1424 state.cursor = 1;
1425
1426 assert!(state.remove_peer(&peer));
1427
1428 assert!(!state.order.contains(&peer));
1429 assert!(!state.priority_order.contains(&peer));
1430 assert_eq!(state.order, vec![retained]);
1431 assert_eq!(state.cursor, 0);
1432 }
1433
1434 #[test]
1435 fn neighbor_sync_retain_sync_peers_prunes_only_departed_peers() {
1436 let already_scanned = peer_id_from_byte(1);
1437 let stable_scanned = peer_id_from_byte(2);
1438 let departed_priority = peer_id_from_byte(3);
1439 let stable_unscanned = peer_id_from_byte(4);
1440 let stable_priority = peer_id_from_byte(5);
1441 let mut state = NeighborSyncState::new_cycle(vec![
1442 already_scanned,
1443 stable_scanned,
1444 departed_priority,
1445 stable_unscanned,
1446 ]);
1447 assert_eq!(
1448 state.queue_priority_peers([departed_priority, stable_priority]),
1449 2
1450 );
1451 state.cursor = 2;
1452 let close_peers = HashSet::from([stable_scanned, stable_unscanned, stable_priority]);
1453
1454 let removed = state.retain_sync_peers(&close_peers);
1455
1456 assert_eq!(removed, 3);
1457 assert_eq!(state.order, vec![stable_scanned, stable_unscanned]);
1458 assert_eq!(
1459 state.priority_order.iter().copied().collect::<Vec<_>>(),
1460 vec![stable_priority]
1461 );
1462 assert_eq!(
1463 state.cursor, 1,
1464 "stable peer scanned before churn must not be selected again"
1465 );
1466 }
1467
1468 #[test]
1469 fn bootstrap_claim_history_prevents_second_grace_window() {
1470 let peer = peer_id_from_byte(9);
1471 let mut state = NeighborSyncState::new_cycle(vec![peer]);
1472 let first_seen = Instant::now();
1473 let grace = Duration::from_mins(1);
1474
1475 assert_eq!(
1476 state.observe_bootstrap_claim(peer, first_seen, grace),
1477 BootstrapClaimObservation::WithinGrace { first_seen }
1478 );
1479 assert!(state.clear_active_bootstrap_claim(&peer));
1480 assert!(!state.bootstrap_claims.contains_key(&peer));
1481 assert!(state.bootstrap_claim_history.contains_key(&peer));
1482
1483 assert_eq!(
1484 state.observe_bootstrap_claim(peer, first_seen + Duration::from_secs(1), grace),
1485 BootstrapClaimObservation::Repeated { first_seen }
1486 );
1487 assert!(
1488 !state.bootstrap_claims.contains_key(&peer),
1489 "repeated claims must not recreate an active grace window"
1490 );
1491 assert_eq!(
1492 state.observe_bootstrap_claim(peer, first_seen + Duration::from_secs(2), grace),
1493 BootstrapClaimObservation::Repeated { first_seen }
1494 );
1495 }
1496
1497 #[test]
1498 fn bootstrap_claim_active_window_reports_past_grace() {
1499 let peer = peer_id_from_byte(10);
1500 let mut state = NeighborSyncState::new_cycle(vec![peer]);
1501 let first_seen = Instant::now();
1502 let grace = Duration::from_mins(1);
1503
1504 let _ = state.observe_bootstrap_claim(peer, first_seen, grace);
1505
1506 assert_eq!(
1507 state.observe_bootstrap_claim(peer, first_seen + grace + Duration::from_secs(1), grace),
1508 BootstrapClaimObservation::PastGrace { first_seen }
1509 );
1510 }
1511
1512 #[test]
1515 fn bootstrap_state_initial_not_drained() {
1516 let state = BootstrapState::new();
1519 assert!(
1520 !state.is_drained(),
1521 "initial state must not be drained before bootstrap begins"
1522 );
1523 }
1524
1525 #[test]
1526 fn bootstrap_state_pending_requests_block_drain() {
1527 let mut state = BootstrapState::new();
1528 state.pending_peer_requests = 3;
1529 assert!(
1530 !state.is_drained(),
1531 "pending peer requests should block drain"
1532 );
1533 }
1534
1535 #[test]
1536 fn bootstrap_state_pending_keys_block_drain() {
1537 let mut state = BootstrapState::new();
1538 state.pending_keys.insert([42u8; 32]);
1539 assert!(!state.is_drained(), "pending keys should block drain");
1540 }
1541
1542 #[test]
1543 fn bootstrap_state_explicit_drained_overrides() {
1544 let mut state = BootstrapState::new();
1545 state.pending_peer_requests = 5;
1546 state.pending_keys.insert([99u8; 32]);
1547 state.drained = true;
1548 assert!(
1549 state.is_drained(),
1550 "explicit drained flag should override pending counts"
1551 );
1552 }
1553
1554 #[test]
1555 fn bootstrap_state_requires_explicit_drain() {
1556 let mut state = BootstrapState::new();
1557 state.pending_peer_requests = 2;
1558 state.pending_keys.insert([1u8; 32]);
1559
1560 state.pending_peer_requests = 0;
1562 state.pending_keys.clear();
1563
1564 assert!(
1565 !state.is_drained(),
1566 "clearing counters alone must not drain — requires check_bootstrap_drained"
1567 );
1568
1569 state.drained = true;
1571 assert!(state.is_drained(), "explicit flag should drain");
1572 }
1573
1574 #[test]
1575 fn bootstrap_state_default_matches_new() {
1576 let from_new = BootstrapState::new();
1577 let from_default = BootstrapState::default();
1578
1579 assert_eq!(from_new.drained, from_default.drained);
1580 assert_eq!(
1581 from_new.pending_peer_requests,
1582 from_default.pending_peer_requests
1583 );
1584 assert_eq!(from_new.pending_keys, from_default.pending_keys);
1585 }
1586
1587 #[test]
1592 fn bootstrap_drain_requires_empty_pending_keys() {
1593 let key_a: XorName = [0xA0; 32];
1594 let key_b: XorName = [0xB0; 32];
1595 let key_c: XorName = [0xC0; 32];
1596
1597 let mut state = BootstrapState::new();
1598 state.pending_peer_requests = 0; state.pending_keys = std::iter::once(key_a)
1600 .chain(std::iter::once(key_b))
1601 .chain(std::iter::once(key_c))
1602 .collect();
1603
1604 assert!(
1605 !state.is_drained(),
1606 "should NOT be drained while pending_keys still has entries"
1607 );
1608
1609 state.pending_keys.remove(&key_a);
1611 assert!(!state.is_drained(), "still not drained with 2 pending keys");
1612
1613 state.pending_keys.remove(&key_b);
1614 assert!(!state.is_drained(), "still not drained with 1 pending key");
1615
1616 state.pending_keys.remove(&key_c);
1617 assert!(
1618 !state.is_drained(),
1619 "removing all keys is necessary but not sufficient — needs explicit drain"
1620 );
1621
1622 state.drained = true;
1624 assert!(state.is_drained(), "explicit drain flag should finalize");
1625 }
1626
1627 #[test]
1630 fn verification_state_terminal_variants() {
1631 let terminal_states = [
1632 VerificationState::QuorumAbandoned,
1633 VerificationState::FetchAbandoned,
1634 VerificationState::Stored,
1635 VerificationState::Idle,
1636 ];
1637
1638 for (i, a) in terminal_states.iter().enumerate() {
1640 for (j, b) in terminal_states.iter().enumerate() {
1641 if i != j {
1642 assert_ne!(
1643 a, b,
1644 "terminal states at indices {i} and {j} must be distinct"
1645 );
1646 }
1647 }
1648 }
1649
1650 let non_terminal_states = [
1652 VerificationState::OfferReceived,
1653 VerificationState::PendingVerify,
1654 VerificationState::QuorumVerified,
1655 VerificationState::PaidListVerified,
1656 VerificationState::QueuedForFetch,
1657 VerificationState::Fetching,
1658 VerificationState::FetchRetryable,
1659 VerificationState::QuorumFailed,
1660 VerificationState::QuorumInconclusive,
1661 ];
1662
1663 for terminal in &terminal_states {
1664 for non_terminal in &non_terminal_states {
1665 assert_ne!(
1666 terminal, non_terminal,
1667 "terminal state {terminal:?} must not equal non-terminal state {non_terminal:?}"
1668 );
1669 }
1670 }
1671 }
1672
1673 #[test]
1676 fn repair_opportunity_requires_both_sync_and_cycle() {
1677 let synced_no_cycle = PeerSyncRecord {
1679 last_sync: Some(
1680 Instant::now()
1681 .checked_sub(std::time::Duration::from_secs(2))
1682 .unwrap_or_else(Instant::now),
1683 ),
1684 cycles_since_sync: 0,
1685 };
1686 assert!(
1687 !synced_no_cycle.has_repair_opportunity(),
1688 "synced with zero subsequent cycles should NOT have repair opportunity"
1689 );
1690
1691 let never_synced = PeerSyncRecord {
1693 last_sync: None,
1694 cycles_since_sync: 5,
1695 };
1696 assert!(
1697 !never_synced.has_repair_opportunity(),
1698 "never-synced peer should NOT have repair opportunity regardless of cycles"
1699 );
1700
1701 let ready = PeerSyncRecord {
1703 last_sync: Some(
1704 Instant::now()
1705 .checked_sub(std::time::Duration::from_secs(5))
1706 .unwrap_or_else(Instant::now),
1707 ),
1708 cycles_since_sync: 1,
1709 };
1710 assert!(
1711 ready.has_repair_opportunity(),
1712 "synced peer with >= 1 cycle SHOULD have repair opportunity"
1713 );
1714 }
1715}