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 pub prune_cursor: usize,
636}
637
638impl NeighborSyncState {
639 #[must_use]
641 pub fn new_cycle(close_neighbors: Vec<PeerId>) -> Self {
642 Self {
643 priority_order: VecDeque::new(),
644 order: close_neighbors,
645 cursor: 0,
646 last_sync_times: HashMap::new(),
647 bootstrap_claims: HashMap::new(),
648 bootstrap_claim_history: HashMap::new(),
649 prune_cursor: 0,
650 }
651 }
652
653 #[must_use]
660 pub fn observe_bootstrap_claim(
661 &mut self,
662 peer: PeerId,
663 now: Instant,
664 grace_period: Duration,
665 ) -> BootstrapClaimObservation {
666 if let Some(first_seen) = self.bootstrap_claims.get(&peer).copied() {
667 if now.duration_since(first_seen) > grace_period {
668 BootstrapClaimObservation::PastGrace { first_seen }
669 } else {
670 BootstrapClaimObservation::WithinGrace { first_seen }
671 }
672 } else if let Some(first_seen) = self.bootstrap_claim_history.get(&peer).copied() {
673 BootstrapClaimObservation::Repeated { first_seen }
674 } else {
675 self.bootstrap_claims.insert(peer, now);
676 self.bootstrap_claim_history.insert(peer, now);
677 BootstrapClaimObservation::WithinGrace { first_seen: now }
678 }
679 }
680
681 pub fn clear_active_bootstrap_claim(&mut self, peer: &PeerId) -> bool {
683 self.bootstrap_claims.remove(peer).is_some()
684 }
685
686 pub fn queue_priority_peers<I>(&mut self, peers: I) -> usize
691 where
692 I: IntoIterator<Item = PeerId>,
693 {
694 let mut queued = 0;
695 for peer in peers {
696 if self.priority_order.contains(&peer) {
697 continue;
698 }
699 self.priority_order.push_back(peer);
700 queued += 1;
701 }
702 queued
703 }
704
705 pub fn retain_sync_peers(&mut self, close_peers: &HashSet<PeerId>) -> usize {
710 let old_priority_len = self.priority_order.len();
711 self.priority_order
712 .retain(|peer| close_peers.contains(peer));
713
714 let old_order_len = self.order.len();
715 let old_cursor = self.cursor;
716 let mut retained_before_cursor = 0;
717 let mut retained_order = Vec::with_capacity(old_order_len);
718 for (idx, peer) in self.order.drain(..).enumerate() {
719 if close_peers.contains(&peer) {
720 if idx < old_cursor {
721 retained_before_cursor += 1;
722 }
723 retained_order.push(peer);
724 }
725 }
726
727 self.order = retained_order;
728 self.cursor = retained_before_cursor;
729
730 (old_priority_len - self.priority_order.len()) + (old_order_len - self.order.len())
731 }
732
733 pub fn remove_peer(&mut self, peer: &PeerId) -> bool {
735 let old_priority_len = self.priority_order.len();
736 self.priority_order.retain(|queued| queued != peer);
737
738 let old_order_len = self.order.len();
739 if let Some(pos) = self.order.iter().position(|queued| queued == peer) {
740 self.order.remove(pos);
741 if pos < self.cursor {
742 self.cursor = self.cursor.saturating_sub(1);
743 }
744 }
745
746 old_priority_len != self.priority_order.len() || old_order_len != self.order.len()
747 }
748
749 #[must_use]
751 pub fn is_cycle_complete(&self) -> bool {
752 self.priority_order.is_empty() && self.cursor >= self.order.len()
753 }
754
755 #[must_use]
762 pub fn has_priority_peers(&self) -> bool {
763 !self.priority_order.is_empty()
764 }
765}
766
767#[derive(Debug)]
773pub struct BootstrapState {
774 pub drained: bool,
776 pub pending_peer_requests: usize,
778 pub pending_keys: HashSet<XorName>,
781 pub capacity_rejected_sources: HashMap<PeerId, Instant>,
822}
823
824impl BootstrapState {
825 #[must_use]
827 pub fn new() -> Self {
828 Self {
829 drained: false,
830 pending_peer_requests: 0,
831 pending_keys: HashSet::new(),
832 capacity_rejected_sources: HashMap::new(),
833 }
834 }
835
836 pub fn note_capacity_rejected(&mut self, source: PeerId, now: Instant) -> bool {
847 let first = !self.capacity_rejected_sources.contains_key(&source);
848 self.capacity_rejected_sources.entry(source).or_insert(now);
849 first
850 }
851
852 #[must_use]
859 pub fn is_drained(&self) -> bool {
860 self.drained
861 }
862
863 pub fn remove_key(&mut self, key: &XorName) {
869 self.pending_keys.remove(key);
870 }
871}
872
873impl Default for BootstrapState {
874 fn default() -> Self {
875 Self::new()
876 }
877}
878
879#[cfg(test)]
884mod tests {
885 use super::*;
886
887 fn peer_id_from_byte(b: u8) -> PeerId {
889 let mut bytes = [0u8; 32];
890 bytes[0] = b;
891 PeerId::from_bytes(bytes)
892 }
893
894 fn mature_hint_times() -> (Instant, Instant) {
895 let hinted_at = Instant::now();
896 let now = hinted_at
897 .checked_add(REPAIR_HINT_MIN_AGE)
898 .unwrap_or(hinted_at);
899 (hinted_at, now)
900 }
901
902 #[test]
905 fn fetch_order_nearest_key_has_highest_priority() {
906 let near = FetchOrder {
907 key: [1u8; 32],
908 distance: [
909 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,
910 0, 0, 0, 0,
911 ],
912 };
913
914 let far = FetchOrder {
915 key: [2u8; 32],
916 distance: [
917 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,
918 0, 0, 0, 0, 0,
919 ],
920 };
921
922 assert!(near > far, "nearer candidate should compare greater");
925
926 let mut heap = std::collections::BinaryHeap::new();
927 heap.push(far);
928 heap.push(near);
929
930 assert_eq!(heap.len(), 2, "heap should contain both candidates");
931
932 let first = heap.pop();
933 assert!(first.is_some(), "first pop should succeed");
934 assert_eq!(
935 first.map(|c| c.key),
936 Some(near.key),
937 "nearest key should pop first"
938 );
939
940 let second = heap.pop();
941 assert!(second.is_some(), "second pop should succeed");
942 assert_eq!(
943 second.map(|c| c.key),
944 Some(far.key),
945 "farthest key should pop second"
946 );
947 }
948
949 #[test]
950 fn fetch_order_same_distance_and_key_is_equal() {
951 let a = FetchOrder {
952 key: [1u8; 32],
953 distance: [5u8; 32],
954 };
955
956 let b = FetchOrder {
957 key: [1u8; 32],
958 distance: [5u8; 32],
959 };
960
961 assert_eq!(
962 a.cmp(&b),
963 Ordering::Equal,
964 "same distance + same key should yield Equal"
965 );
966 assert_eq!(a, b, "PartialEq must agree with Ord");
967 }
968
969 #[test]
970 fn fetch_order_same_distance_different_key_is_deterministic() {
971 let a = FetchOrder {
972 key: [1u8; 32],
973 distance: [5u8; 32],
974 };
975
976 let b = FetchOrder {
977 key: [2u8; 32],
978 distance: [5u8; 32],
979 };
980
981 assert_ne!(
982 a.cmp(&b),
983 Ordering::Equal,
984 "same distance + different key must not be Equal"
985 );
986 assert_ne!(a, b, "PartialEq must agree with Ord");
987 }
988
989 #[test]
992 fn peer_sync_record_no_sync_yet() {
993 let record = PeerSyncRecord {
994 last_sync: None,
995 cycles_since_sync: 0,
996 };
997 assert!(
998 !record.has_repair_opportunity(),
999 "never-synced peer has no repair opportunity"
1000 );
1001 }
1002
1003 #[test]
1004 fn peer_sync_record_synced_but_no_cycle() {
1005 let record = PeerSyncRecord {
1006 last_sync: Some(Instant::now()),
1007 cycles_since_sync: 0,
1008 };
1009 assert!(
1010 !record.has_repair_opportunity(),
1011 "synced peer with zero subsequent cycles has no repair opportunity"
1012 );
1013 }
1014
1015 #[test]
1016 fn peer_sync_record_synced_with_cycle() {
1017 let record = PeerSyncRecord {
1018 last_sync: Some(Instant::now()),
1019 cycles_since_sync: 1,
1020 };
1021 assert!(
1022 record.has_repair_opportunity(),
1023 "synced peer with >= 1 cycle should have repair opportunity"
1024 );
1025 }
1026
1027 #[test]
1028 fn peer_sync_record_no_sync_many_cycles() {
1029 let record = PeerSyncRecord {
1030 last_sync: None,
1031 cycles_since_sync: 10,
1032 };
1033 assert!(
1034 !record.has_repair_opportunity(),
1035 "never-synced peer has no repair opportunity regardless of cycle count"
1036 );
1037 }
1038
1039 #[test]
1042 fn repair_proofs_record_sent_hint_for_close_peer() {
1043 const HINT_EPOCH: u64 = 7;
1044 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1045
1046 let key = [0xA1; 32];
1047 let peer = peer_id_from_byte(1);
1048 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1049 let mut proofs = RepairProofs::new();
1050 let (hinted_at, now) = mature_hint_times();
1051
1052 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1053
1054 assert!(
1055 proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1056 "old sent hint should make key auditable for that peer"
1057 );
1058 }
1059
1060 #[test]
1061 fn repair_proofs_reject_peer_outside_current_close_group() {
1062 const HINT_EPOCH: u64 = 7;
1063 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1064
1065 let key = [0xA2; 32];
1066 let peer = peer_id_from_byte(1);
1067 let close_peers = HashSet::from([peer_id_from_byte(2), peer_id_from_byte(3)]);
1068 let mut proofs = RepairProofs::new();
1069 let (hinted_at, now) = mature_hint_times();
1070
1071 assert!(!proofs.record_replica_hint_sent_at(
1072 peer,
1073 key,
1074 &close_peers,
1075 HINT_EPOCH,
1076 hinted_at,
1077 ));
1078
1079 assert!(
1080 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1081 "peers outside current close group must not get repair proof"
1082 );
1083 }
1084
1085 #[test]
1086 fn repair_proofs_require_later_epoch() {
1087 const HINT_EPOCH: u64 = 7;
1088 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1089
1090 let key = [0xA3; 32];
1091 let peer = peer_id_from_byte(1);
1092 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1093 let mut proofs = RepairProofs::new();
1094 let (hinted_at, now) = mature_hint_times();
1095
1096 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1097
1098 assert!(
1099 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, HINT_EPOCH, now),
1100 "same-cycle proof should not be audit-eligible"
1101 );
1102 assert!(
1103 proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1104 "old proof should mature after a later local sync-cycle epoch"
1105 );
1106 }
1107
1108 #[test]
1109 fn repair_proofs_require_min_hint_age() {
1110 const HINT_EPOCH: u64 = 7;
1111 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1112
1113 let key = [0xA8; 32];
1114 let peer = peer_id_from_byte(1);
1115 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1116 let mut proofs = RepairProofs::new();
1117 let hinted_at = Instant::now();
1118
1119 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at));
1120
1121 assert!(
1122 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, hinted_at),
1123 "fresh repair hints should not be audit-eligible"
1124 );
1125 assert!(
1126 proofs.has_mature_replica_hint(
1127 &peer,
1128 &key,
1129 &close_peers,
1130 CURRENT_EPOCH,
1131 hinted_at
1132 .checked_add(REPAIR_HINT_MIN_AGE)
1133 .unwrap_or(hinted_at),
1134 ),
1135 "repair hints should mature once they are at least the minimum age"
1136 );
1137 }
1138
1139 #[test]
1140 fn repair_proofs_repeated_hint_does_not_reset_maturity() {
1141 const HINT_EPOCH: u64 = 7;
1142 const REPEATED_HINT_EPOCH: u64 = HINT_EPOCH + 1;
1143
1144 let key = [0xA5; 32];
1145 let peer = peer_id_from_byte(1);
1146 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1147 let mut proofs = RepairProofs::new();
1148 let (hinted_at, now) = mature_hint_times();
1149
1150 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1151 assert!(
1152 !proofs.record_replica_hint_sent_at(peer, key, &close_peers, REPEATED_HINT_EPOCH, now),
1153 "duplicate hint in the same close group should keep existing proof"
1154 );
1155 assert!(
1156 proofs.has_mature_replica_hint(&peer, &key, &close_peers, REPEATED_HINT_EPOCH, now),
1157 "duplicate hint must not reset an already mature proof"
1158 );
1159 }
1160
1161 #[test]
1162 fn repair_proofs_retain_stable_peers_on_close_group_change() {
1163 const HINT_EPOCH: u64 = 7;
1164 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1165
1166 let key = [0xA7; 32];
1167 let stable_peer = peer_id_from_byte(1);
1168 let departing_peer = peer_id_from_byte(2);
1169 let retained_peer = peer_id_from_byte(3);
1170 let new_peer = peer_id_from_byte(4);
1171 let old_group = HashSet::from([stable_peer, departing_peer, retained_peer]);
1172 let changed_group = HashSet::from([stable_peer, retained_peer, new_peer]);
1173 let mut proofs = RepairProofs::new();
1174 let (hinted_at, now) = mature_hint_times();
1175
1176 assert!(proofs.record_replica_hint_sent_at(
1177 stable_peer,
1178 key,
1179 &old_group,
1180 HINT_EPOCH,
1181 hinted_at,
1182 ));
1183 assert!(proofs.record_replica_hint_sent_at(
1184 departing_peer,
1185 key,
1186 &old_group,
1187 HINT_EPOCH,
1188 hinted_at,
1189 ));
1190
1191 assert!(
1192 proofs.has_mature_replica_hint(&stable_peer, &key, &changed_group, CURRENT_EPOCH, now),
1193 "stable peers should keep mature repair proofs across unrelated close-group churn"
1194 );
1195 assert!(
1196 !proofs.has_mature_replica_hint(
1197 &departing_peer,
1198 &key,
1199 &changed_group,
1200 CURRENT_EPOCH,
1201 now,
1202 ),
1203 "peers that left the close group should lose repair proofs"
1204 );
1205 assert!(
1206 !proofs.has_mature_replica_hint(&new_peer, &key, &changed_group, CURRENT_EPOCH, now),
1207 "new close-group peers need their own repair hint before auditing"
1208 );
1209 }
1210
1211 #[test]
1212 fn repair_proofs_evicted_peer_reentry_requires_fresh_hint() {
1213 const FIRST_HINT_EPOCH: u64 = 7;
1214 const SECOND_HINT_EPOCH: u64 = FIRST_HINT_EPOCH + 1;
1215 const CURRENT_EPOCH: u64 = SECOND_HINT_EPOCH + 1;
1216
1217 let key = [0xA3; 32];
1218 let returning_peer = peer_id_from_byte(1);
1219 let new_peer = peer_id_from_byte(4);
1220 let old_group = HashSet::from([returning_peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1221 let changed_group = HashSet::from([new_peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1222 let mut proofs = RepairProofs::new();
1223 let (hinted_at, now) = mature_hint_times();
1224
1225 assert!(proofs.record_replica_hint_sent_at(
1226 returning_peer,
1227 key,
1228 &old_group,
1229 FIRST_HINT_EPOCH,
1230 hinted_at,
1231 ));
1232
1233 assert!(
1234 !proofs.has_mature_replica_hint(
1235 &new_peer,
1236 &key,
1237 &changed_group,
1238 SECOND_HINT_EPOCH,
1239 now
1240 ),
1241 "new close-group peer should not inherit another peer's repair proof"
1242 );
1243 assert!(
1244 !proofs.has_mature_replica_hint(&returning_peer, &key, &old_group, CURRENT_EPOCH, now),
1245 "a peer that re-enters must receive a fresh repair hint"
1246 );
1247
1248 assert!(proofs.record_replica_hint_sent_at(
1249 returning_peer,
1250 key,
1251 &old_group,
1252 SECOND_HINT_EPOCH,
1253 hinted_at,
1254 ));
1255 assert!(
1256 proofs.has_mature_replica_hint(&returning_peer, &key, &old_group, CURRENT_EPOCH, now),
1257 "fresh repair hint after re-entry should be eligible once mature"
1258 );
1259 }
1260
1261 #[test]
1262 fn repair_proofs_remove_peer_requires_fresh_hint_after_reentry() {
1263 const FIRST_HINT_EPOCH: u64 = 7;
1264 const SECOND_HINT_EPOCH: u64 = FIRST_HINT_EPOCH + 1;
1265 const CURRENT_EPOCH: u64 = SECOND_HINT_EPOCH + 1;
1266
1267 let key = [0xA6; 32];
1268 let peer = peer_id_from_byte(1);
1269 let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1270 let mut proofs = RepairProofs::new();
1271 let (hinted_at, now) = mature_hint_times();
1272
1273 assert!(proofs.record_replica_hint_sent_at(
1274 peer,
1275 key,
1276 &close_peers,
1277 FIRST_HINT_EPOCH,
1278 hinted_at,
1279 ));
1280 proofs.remove_peer(&peer);
1281
1282 assert!(
1283 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1284 "routing-table removal should clear proof even if peer re-enters same close group"
1285 );
1286
1287 assert!(proofs.record_replica_hint_sent_at(
1288 peer,
1289 key,
1290 &close_peers,
1291 SECOND_HINT_EPOCH,
1292 hinted_at,
1293 ));
1294 assert!(
1295 proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1296 "fresh hint after re-entry should become eligible after a later epoch"
1297 );
1298 }
1299
1300 #[test]
1301 fn repair_proofs_remove_key_clears_all_peer_entries() {
1302 const HINT_EPOCH: u64 = 7;
1303 const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1304
1305 let key = [0xA4; 32];
1306 let peer = peer_id_from_byte(1);
1307 let close_peers = HashSet::from([peer]);
1308 let mut proofs = RepairProofs::new();
1309 let (hinted_at, now) = mature_hint_times();
1310
1311 assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1312 proofs.remove_key(&key);
1313
1314 assert!(
1315 !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1316 "deleted local key should not retain repair proof entries"
1317 );
1318 }
1319
1320 #[test]
1323 fn neighbor_sync_empty_cycle_is_immediately_complete() {
1324 let state = NeighborSyncState::new_cycle(vec![]);
1325 assert!(
1326 state.is_cycle_complete(),
1327 "empty neighbor list means cycle is complete"
1328 );
1329 }
1330
1331 #[test]
1332 fn neighbor_sync_new_cycle_not_complete() {
1333 let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
1334 let state = NeighborSyncState::new_cycle(peers);
1335 assert!(
1336 !state.is_cycle_complete(),
1337 "fresh cycle with peers should not be complete"
1338 );
1339 }
1340
1341 #[test]
1342 fn neighbor_sync_cycle_completes_when_cursor_reaches_end() {
1343 let peers = vec![
1344 peer_id_from_byte(1),
1345 peer_id_from_byte(2),
1346 peer_id_from_byte(3),
1347 ];
1348 let mut state = NeighborSyncState::new_cycle(peers);
1349
1350 state.cursor = 2;
1352 assert!(
1353 !state.is_cycle_complete(),
1354 "cursor at len-1 should not be complete"
1355 );
1356
1357 state.cursor = 3;
1358 assert!(
1359 state.is_cycle_complete(),
1360 "cursor at len should be complete"
1361 );
1362 }
1363
1364 #[test]
1365 fn neighbor_sync_cursor_past_end_is_still_complete() {
1366 let peers = vec![peer_id_from_byte(1)];
1367 let mut state = NeighborSyncState::new_cycle(peers);
1368 state.cursor = 5;
1369 assert!(
1370 state.is_cycle_complete(),
1371 "cursor past end should still report complete"
1372 );
1373 }
1374
1375 #[test]
1376 fn neighbor_sync_priority_queue_blocks_cycle_completion() {
1377 let peer = peer_id_from_byte(2);
1378 let mut state = NeighborSyncState::new_cycle(Vec::new());
1379
1380 assert!(state.is_cycle_complete());
1381 assert_eq!(state.queue_priority_peers([peer]), 1);
1382 assert!(
1383 !state.is_cycle_complete(),
1384 "pending priority peers must sync before the cycle completes"
1385 );
1386 }
1387
1388 #[test]
1389 fn neighbor_sync_priority_queue_deduplicates_peers() {
1390 let peer = peer_id_from_byte(3);
1391 let mut state = NeighborSyncState::new_cycle(Vec::new());
1392
1393 assert_eq!(state.queue_priority_peers([peer, peer]), 1);
1394 assert_eq!(state.priority_order.len(), 1);
1395 }
1396
1397 #[test]
1398 fn neighbor_sync_has_priority_peers_tracks_queue_and_drain() {
1399 let first = peer_id_from_byte(6);
1405 let second = peer_id_from_byte(7);
1406 let mut state = NeighborSyncState::new_cycle(Vec::new());
1407 assert!(!state.has_priority_peers());
1408
1409 assert_eq!(state.queue_priority_peers([first, second]), 2);
1410 assert!(state.has_priority_peers());
1411
1412 assert!(state.remove_peer(&first));
1413 assert!(state.has_priority_peers(), "one entrant still pending");
1414
1415 assert!(state.remove_peer(&second));
1416 assert!(
1417 !state.has_priority_peers(),
1418 "drained queue must let the loop park"
1419 );
1420 }
1421
1422 #[test]
1423 fn neighbor_sync_remove_peer_clears_order_and_priority_queue() {
1424 let peer = peer_id_from_byte(4);
1425 let retained = peer_id_from_byte(5);
1426 let mut state = NeighborSyncState::new_cycle(vec![peer, retained]);
1427 assert_eq!(state.queue_priority_peers([peer]), 1);
1428 state.cursor = 1;
1429
1430 assert!(state.remove_peer(&peer));
1431
1432 assert!(!state.order.contains(&peer));
1433 assert!(!state.priority_order.contains(&peer));
1434 assert_eq!(state.order, vec![retained]);
1435 assert_eq!(state.cursor, 0);
1436 }
1437
1438 #[test]
1439 fn neighbor_sync_retain_sync_peers_prunes_only_departed_peers() {
1440 let already_scanned = peer_id_from_byte(1);
1441 let stable_scanned = peer_id_from_byte(2);
1442 let departed_priority = peer_id_from_byte(3);
1443 let stable_unscanned = peer_id_from_byte(4);
1444 let stable_priority = peer_id_from_byte(5);
1445 let mut state = NeighborSyncState::new_cycle(vec![
1446 already_scanned,
1447 stable_scanned,
1448 departed_priority,
1449 stable_unscanned,
1450 ]);
1451 assert_eq!(
1452 state.queue_priority_peers([departed_priority, stable_priority]),
1453 2
1454 );
1455 state.cursor = 2;
1456 let close_peers = HashSet::from([stable_scanned, stable_unscanned, stable_priority]);
1457
1458 let removed = state.retain_sync_peers(&close_peers);
1459
1460 assert_eq!(removed, 3);
1461 assert_eq!(state.order, vec![stable_scanned, stable_unscanned]);
1462 assert_eq!(
1463 state.priority_order.iter().copied().collect::<Vec<_>>(),
1464 vec![stable_priority]
1465 );
1466 assert_eq!(
1467 state.cursor, 1,
1468 "stable peer scanned before churn must not be selected again"
1469 );
1470 }
1471
1472 #[test]
1473 fn bootstrap_claim_history_prevents_second_grace_window() {
1474 let peer = peer_id_from_byte(9);
1475 let mut state = NeighborSyncState::new_cycle(vec![peer]);
1476 let first_seen = Instant::now();
1477 let grace = Duration::from_mins(1);
1478
1479 assert_eq!(
1480 state.observe_bootstrap_claim(peer, first_seen, grace),
1481 BootstrapClaimObservation::WithinGrace { first_seen }
1482 );
1483 assert!(state.clear_active_bootstrap_claim(&peer));
1484 assert!(!state.bootstrap_claims.contains_key(&peer));
1485 assert!(state.bootstrap_claim_history.contains_key(&peer));
1486
1487 assert_eq!(
1488 state.observe_bootstrap_claim(peer, first_seen + Duration::from_secs(1), grace),
1489 BootstrapClaimObservation::Repeated { first_seen }
1490 );
1491 assert!(
1492 !state.bootstrap_claims.contains_key(&peer),
1493 "repeated claims must not recreate an active grace window"
1494 );
1495 assert_eq!(
1496 state.observe_bootstrap_claim(peer, first_seen + Duration::from_secs(2), grace),
1497 BootstrapClaimObservation::Repeated { first_seen }
1498 );
1499 }
1500
1501 #[test]
1502 fn bootstrap_claim_active_window_reports_past_grace() {
1503 let peer = peer_id_from_byte(10);
1504 let mut state = NeighborSyncState::new_cycle(vec![peer]);
1505 let first_seen = Instant::now();
1506 let grace = Duration::from_mins(1);
1507
1508 let _ = state.observe_bootstrap_claim(peer, first_seen, grace);
1509
1510 assert_eq!(
1511 state.observe_bootstrap_claim(peer, first_seen + grace + Duration::from_secs(1), grace),
1512 BootstrapClaimObservation::PastGrace { first_seen }
1513 );
1514 }
1515
1516 #[test]
1519 fn bootstrap_state_initial_not_drained() {
1520 let state = BootstrapState::new();
1523 assert!(
1524 !state.is_drained(),
1525 "initial state must not be drained before bootstrap begins"
1526 );
1527 }
1528
1529 #[test]
1530 fn bootstrap_state_pending_requests_block_drain() {
1531 let mut state = BootstrapState::new();
1532 state.pending_peer_requests = 3;
1533 assert!(
1534 !state.is_drained(),
1535 "pending peer requests should block drain"
1536 );
1537 }
1538
1539 #[test]
1540 fn bootstrap_state_pending_keys_block_drain() {
1541 let mut state = BootstrapState::new();
1542 state.pending_keys.insert([42u8; 32]);
1543 assert!(!state.is_drained(), "pending keys should block drain");
1544 }
1545
1546 #[test]
1547 fn bootstrap_state_explicit_drained_overrides() {
1548 let mut state = BootstrapState::new();
1549 state.pending_peer_requests = 5;
1550 state.pending_keys.insert([99u8; 32]);
1551 state.drained = true;
1552 assert!(
1553 state.is_drained(),
1554 "explicit drained flag should override pending counts"
1555 );
1556 }
1557
1558 #[test]
1559 fn bootstrap_state_requires_explicit_drain() {
1560 let mut state = BootstrapState::new();
1561 state.pending_peer_requests = 2;
1562 state.pending_keys.insert([1u8; 32]);
1563
1564 state.pending_peer_requests = 0;
1566 state.pending_keys.clear();
1567
1568 assert!(
1569 !state.is_drained(),
1570 "clearing counters alone must not drain — requires check_bootstrap_drained"
1571 );
1572
1573 state.drained = true;
1575 assert!(state.is_drained(), "explicit flag should drain");
1576 }
1577
1578 #[test]
1579 fn bootstrap_state_default_matches_new() {
1580 let from_new = BootstrapState::new();
1581 let from_default = BootstrapState::default();
1582
1583 assert_eq!(from_new.drained, from_default.drained);
1584 assert_eq!(
1585 from_new.pending_peer_requests,
1586 from_default.pending_peer_requests
1587 );
1588 assert_eq!(from_new.pending_keys, from_default.pending_keys);
1589 }
1590
1591 #[test]
1596 fn bootstrap_drain_requires_empty_pending_keys() {
1597 let key_a: XorName = [0xA0; 32];
1598 let key_b: XorName = [0xB0; 32];
1599 let key_c: XorName = [0xC0; 32];
1600
1601 let mut state = BootstrapState::new();
1602 state.pending_peer_requests = 0; state.pending_keys = std::iter::once(key_a)
1604 .chain(std::iter::once(key_b))
1605 .chain(std::iter::once(key_c))
1606 .collect();
1607
1608 assert!(
1609 !state.is_drained(),
1610 "should NOT be drained while pending_keys still has entries"
1611 );
1612
1613 state.pending_keys.remove(&key_a);
1615 assert!(!state.is_drained(), "still not drained with 2 pending keys");
1616
1617 state.pending_keys.remove(&key_b);
1618 assert!(!state.is_drained(), "still not drained with 1 pending key");
1619
1620 state.pending_keys.remove(&key_c);
1621 assert!(
1622 !state.is_drained(),
1623 "removing all keys is necessary but not sufficient — needs explicit drain"
1624 );
1625
1626 state.drained = true;
1628 assert!(state.is_drained(), "explicit drain flag should finalize");
1629 }
1630
1631 #[test]
1634 fn verification_state_terminal_variants() {
1635 let terminal_states = [
1636 VerificationState::QuorumAbandoned,
1637 VerificationState::FetchAbandoned,
1638 VerificationState::Stored,
1639 VerificationState::Idle,
1640 ];
1641
1642 for (i, a) in terminal_states.iter().enumerate() {
1644 for (j, b) in terminal_states.iter().enumerate() {
1645 if i != j {
1646 assert_ne!(
1647 a, b,
1648 "terminal states at indices {i} and {j} must be distinct"
1649 );
1650 }
1651 }
1652 }
1653
1654 let non_terminal_states = [
1656 VerificationState::OfferReceived,
1657 VerificationState::PendingVerify,
1658 VerificationState::QuorumVerified,
1659 VerificationState::PaidListVerified,
1660 VerificationState::QueuedForFetch,
1661 VerificationState::Fetching,
1662 VerificationState::FetchRetryable,
1663 VerificationState::QuorumFailed,
1664 VerificationState::QuorumInconclusive,
1665 ];
1666
1667 for terminal in &terminal_states {
1668 for non_terminal in &non_terminal_states {
1669 assert_ne!(
1670 terminal, non_terminal,
1671 "terminal state {terminal:?} must not equal non-terminal state {non_terminal:?}"
1672 );
1673 }
1674 }
1675 }
1676
1677 #[test]
1680 fn repair_opportunity_requires_both_sync_and_cycle() {
1681 let synced_no_cycle = PeerSyncRecord {
1683 last_sync: Some(
1684 Instant::now()
1685 .checked_sub(std::time::Duration::from_secs(2))
1686 .unwrap_or_else(Instant::now),
1687 ),
1688 cycles_since_sync: 0,
1689 };
1690 assert!(
1691 !synced_no_cycle.has_repair_opportunity(),
1692 "synced with zero subsequent cycles should NOT have repair opportunity"
1693 );
1694
1695 let never_synced = PeerSyncRecord {
1697 last_sync: None,
1698 cycles_since_sync: 5,
1699 };
1700 assert!(
1701 !never_synced.has_repair_opportunity(),
1702 "never-synced peer should NOT have repair opportunity regardless of cycles"
1703 );
1704
1705 let ready = PeerSyncRecord {
1707 last_sync: Some(
1708 Instant::now()
1709 .checked_sub(std::time::Duration::from_secs(5))
1710 .unwrap_or_else(Instant::now),
1711 ),
1712 cycles_since_sync: 1,
1713 };
1714 assert!(
1715 ready.has_repair_opportunity(),
1716 "synced peer with >= 1 cycle SHOULD have repair opportunity"
1717 );
1718 }
1719}