1use std::sync::atomic::{AtomicU64, Ordering};
7
8use parking_lot::RwLock;
9use saorsa_core::identity::PeerId;
10use serde::{Deserialize, Serialize};
11
12use crate::ant_protocol::XorName;
13
14pub use super::config::MAX_REPLICATION_MESSAGE_SIZE;
15
16pub const ABSENT_KEY_DIGEST: [u8; 32] = [0u8; 32];
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct ReplicationMessage {
32 pub request_id: u64,
34 pub body: ReplicationMessageBody,
36}
37
38impl ReplicationMessage {
39 pub fn encode(&self) -> Result<Vec<u8>, ReplicationProtocolError> {
46 let bytes = postcard::to_stdvec(self)
47 .map_err(|e| ReplicationProtocolError::SerializationFailed(e.to_string()))?;
48
49 if bytes.len() > MAX_REPLICATION_MESSAGE_SIZE {
50 return Err(ReplicationProtocolError::MessageTooLarge {
51 size: bytes.len(),
52 max_size: MAX_REPLICATION_MESSAGE_SIZE,
53 });
54 }
55
56 record_tx(&self.body, bytes.len());
59
60 Ok(bytes)
61 }
62
63 pub fn decode(data: &[u8]) -> Result<Self, ReplicationProtocolError> {
75 if data.len() > MAX_REPLICATION_MESSAGE_SIZE {
76 return Err(ReplicationProtocolError::MessageTooLarge {
77 size: data.len(),
78 max_size: MAX_REPLICATION_MESSAGE_SIZE,
79 });
80 }
81 let message: Self = postcard::from_bytes(data)
82 .map_err(|e| ReplicationProtocolError::DeserializationFailed(e.to_string()))?;
83
84 record_rx(&message.body, data.len());
87
88 Ok(message)
89 }
90}
91
92#[derive(Debug, Clone, Serialize, Deserialize)]
98pub enum ReplicationMessageBody {
99 FreshReplicationOffer(FreshReplicationOffer),
102 FreshReplicationResponse(FreshReplicationResponse),
104
105 PaidNotify(PaidNotify),
107
108 NeighborSyncRequest(NeighborSyncRequest),
111 NeighborSyncResponse(NeighborSyncResponse),
113
114 VerificationRequest(VerificationRequest),
117 VerificationResponse(VerificationResponse),
119
120 FetchRequest(FetchRequest),
123 FetchResponse(FetchResponse),
125
126 AuditChallenge(AuditChallenge),
130 AuditResponse(AuditResponse),
132
133 SubtreeAuditChallenge(SubtreeAuditChallenge),
136 SubtreeAuditResponse(SubtreeAuditResponse),
138 SubtreeByteChallenge(SubtreeByteChallenge),
140 SubtreeByteResponse(SubtreeByteResponse),
142
143 GetCommitmentByPin(GetCommitmentByPin),
153 GetCommitmentByPinResponse(GetCommitmentByPinResponse),
155}
156
157const N_REPLICATION_VARIANTS: usize = 17;
174
175static REPL_TX_BYTES: [AtomicU64; N_REPLICATION_VARIANTS] =
176 [const { AtomicU64::new(0) }; N_REPLICATION_VARIANTS];
177static REPL_TX_COUNT: [AtomicU64; N_REPLICATION_VARIANTS] =
178 [const { AtomicU64::new(0) }; N_REPLICATION_VARIANTS];
179static REPL_RX_BYTES: [AtomicU64; N_REPLICATION_VARIANTS] =
180 [const { AtomicU64::new(0) }; N_REPLICATION_VARIANTS];
181static REPL_RX_COUNT: [AtomicU64; N_REPLICATION_VARIANTS] =
182 [const { AtomicU64::new(0) }; N_REPLICATION_VARIANTS];
183
184impl ReplicationMessageBody {
185 pub(crate) fn variant_index(&self) -> usize {
190 match self {
191 Self::FreshReplicationOffer(_) => 0,
192 Self::FreshReplicationResponse(_) => 1,
193 Self::PaidNotify(_) => 2,
194 Self::NeighborSyncRequest(_) => 3,
195 Self::NeighborSyncResponse(_) => 4,
196 Self::VerificationRequest(_) => 5,
197 Self::VerificationResponse(_) => 6,
198 Self::FetchRequest(_) => 7,
199 Self::FetchResponse(_) => 8,
200 Self::AuditChallenge(_) => 9,
201 Self::AuditResponse(_) => 10,
202 Self::SubtreeAuditChallenge(_) => 11,
203 Self::SubtreeAuditResponse(_) => 12,
204 Self::SubtreeByteChallenge(_) => 13,
205 Self::SubtreeByteResponse(_) => 14,
206 Self::GetCommitmentByPin(_) => 15,
207 Self::GetCommitmentByPinResponse(_) => 16,
208 }
209 }
210}
211
212fn record_tx(body: &ReplicationMessageBody, bytes: usize) {
214 let i = body.variant_index();
215 REPL_TX_BYTES[i].fetch_add(bytes as u64, Ordering::Relaxed);
216 REPL_TX_COUNT[i].fetch_add(1, Ordering::Relaxed);
217}
218
219fn record_rx(body: &ReplicationMessageBody, bytes: usize) {
221 let i = body.variant_index();
222 REPL_RX_BYTES[i].fetch_add(bytes as u64, Ordering::Relaxed);
223 REPL_RX_COUNT[i].fetch_add(1, Ordering::Relaxed);
224}
225
226pub(crate) fn log_traffic_summary() {
239 let tb = |i: usize| REPL_TX_BYTES[i].load(Ordering::Relaxed);
242 let tc = |i: usize| REPL_TX_COUNT[i].load(Ordering::Relaxed);
243 let rb = |i: usize| REPL_RX_BYTES[i].load(Ordering::Relaxed);
244 let rc = |i: usize| REPL_RX_COUNT[i].load(Ordering::Relaxed);
245
246 crate::logging::info!(
247 target: "ant_node::replication::traffic",
248 group = 1,
249 fresh_offer_tx_bytes = tb(0), fresh_offer_tx_count = tc(0),
250 fresh_offer_rx_bytes = rb(0), fresh_offer_rx_count = rc(0),
251 fresh_response_tx_bytes = tb(1), fresh_response_tx_count = tc(1),
252 fresh_response_rx_bytes = rb(1), fresh_response_rx_count = rc(1),
253 paid_notify_tx_bytes = tb(2), paid_notify_tx_count = tc(2),
254 paid_notify_rx_bytes = rb(2), paid_notify_rx_count = rc(2),
255 neighbor_sync_request_tx_bytes = tb(3), neighbor_sync_request_tx_count = tc(3),
256 neighbor_sync_request_rx_bytes = rb(3), neighbor_sync_request_rx_count = rc(3),
257 neighbor_sync_response_tx_bytes = tb(4), neighbor_sync_response_tx_count = tc(4),
258 neighbor_sync_response_rx_bytes = rb(4), neighbor_sync_response_rx_count = rc(4),
259 verification_request_tx_bytes = tb(5), verification_request_tx_count = tc(5),
260 verification_request_rx_bytes = rb(5), verification_request_rx_count = rc(5),
261 "replication traffic summary (cumulative)"
262 );
263 crate::logging::info!(
264 target: "ant_node::replication::traffic",
265 group = 2,
266 verification_response_tx_bytes = tb(6), verification_response_tx_count = tc(6),
267 verification_response_rx_bytes = rb(6), verification_response_rx_count = rc(6),
268 fetch_request_tx_bytes = tb(7), fetch_request_tx_count = tc(7),
269 fetch_request_rx_bytes = rb(7), fetch_request_rx_count = rc(7),
270 fetch_response_tx_bytes = tb(8), fetch_response_tx_count = tc(8),
271 fetch_response_rx_bytes = rb(8), fetch_response_rx_count = rc(8),
272 audit_challenge_tx_bytes = tb(9), audit_challenge_tx_count = tc(9),
273 audit_challenge_rx_bytes = rb(9), audit_challenge_rx_count = rc(9),
274 audit_response_tx_bytes = tb(10), audit_response_tx_count = tc(10),
275 audit_response_rx_bytes = rb(10), audit_response_rx_count = rc(10),
276 subtree_audit_challenge_tx_bytes = tb(11), subtree_audit_challenge_tx_count = tc(11),
277 subtree_audit_challenge_rx_bytes = rb(11), subtree_audit_challenge_rx_count = rc(11),
278 "replication traffic summary (cumulative)"
279 );
280 crate::logging::info!(
281 target: "ant_node::replication::traffic",
282 group = 3,
283 subtree_audit_response_tx_bytes = tb(12), subtree_audit_response_tx_count = tc(12),
284 subtree_audit_response_rx_bytes = rb(12), subtree_audit_response_rx_count = rc(12),
285 subtree_byte_challenge_tx_bytes = tb(13), subtree_byte_challenge_tx_count = tc(13),
286 subtree_byte_challenge_rx_bytes = rb(13), subtree_byte_challenge_rx_count = rc(13),
287 subtree_byte_response_tx_bytes = tb(14), subtree_byte_response_tx_count = tc(14),
288 subtree_byte_response_rx_bytes = rb(14), subtree_byte_response_rx_count = rc(14),
289 get_commitment_by_pin_tx_bytes = tb(15), get_commitment_by_pin_tx_count = tc(15),
290 get_commitment_by_pin_rx_bytes = rb(15), get_commitment_by_pin_rx_count = rc(15),
291 get_commitment_by_pin_response_tx_bytes = tb(16),
292 get_commitment_by_pin_response_tx_count = tc(16),
293 get_commitment_by_pin_response_rx_bytes = rb(16),
294 get_commitment_by_pin_response_rx_count = rc(16),
295 "replication traffic summary (cumulative)"
296 );
297}
298
299const SERVED_SHARDS: usize = 16;
327
328const SERVED_SHARD_CAP: usize = 16;
330
331struct PeerServeStats {
333 bytes: AtomicU64,
334 count: AtomicU64,
335}
336
337struct ServedShard {
343 entries: RwLock<Vec<(PeerId, PeerServeStats)>>,
344}
345
346impl ServedShard {
347 const fn new() -> Self {
348 Self {
349 entries: RwLock::new(Vec::new()),
350 }
351 }
352}
353
354static SERVED_PEERS: [ServedShard; SERVED_SHARDS] = [const { ServedShard::new() }; SERVED_SHARDS];
355
356static SERVED_EVICTIONS: AtomicU64 = AtomicU64::new(0);
359
360fn served_shard_index(peer: &PeerId) -> usize {
363 (peer.to_bytes()[0] as usize) & (SERVED_SHARDS - 1)
364}
365
366pub(crate) fn record_served(peer: &PeerId, bytes: usize) {
374 let shard = &SERVED_PEERS[served_shard_index(peer)];
375 let bytes = bytes as u64;
376
377 {
379 let guard = shard.entries.read();
380 if let Some((_, stats)) = guard.iter().find(|(p, _)| p == peer) {
381 stats.bytes.fetch_add(bytes, Ordering::Relaxed);
382 stats.count.fetch_add(1, Ordering::Relaxed);
383 return;
384 }
385 }
386
387 let mut guard = shard.entries.write();
390 if let Some((_, stats)) = guard.iter().find(|(p, _)| p == peer) {
391 stats.bytes.fetch_add(bytes, Ordering::Relaxed);
392 stats.count.fetch_add(1, Ordering::Relaxed);
393 return;
394 }
395 if guard.len() >= SERVED_SHARD_CAP {
396 if let Some((min_idx, _)) = guard
399 .iter()
400 .enumerate()
401 .min_by_key(|(_, (_, s))| s.bytes.load(Ordering::Relaxed))
402 {
403 guard.swap_remove(min_idx);
404 SERVED_EVICTIONS.fetch_add(1, Ordering::Relaxed);
405 }
406 }
407 guard.push((
408 *peer,
409 PeerServeStats {
410 bytes: AtomicU64::new(bytes),
411 count: AtomicU64::new(1),
412 },
413 ));
414}
415
416pub(crate) fn log_served_peers_summary() {
427 let mut all: Vec<(PeerId, u64, u64)> = Vec::new();
431 for shard in &SERVED_PEERS {
432 let guard = shard.entries.read();
433 for (peer, stats) in guard.iter() {
434 all.push((
435 *peer,
436 stats.bytes.load(Ordering::Relaxed),
437 stats.count.load(Ordering::Relaxed),
438 ));
439 }
440 }
441 let tracked_peers = all.len() as u64;
442 let evictions = SERVED_EVICTIONS.load(Ordering::Relaxed);
443
444 all.sort_unstable_by_key(|(_, bytes, _)| std::cmp::Reverse(*bytes));
446
447 let id = |n: usize| all.get(n).map(|(p, _, _)| p.to_hex()).unwrap_or_default();
450 let by = |n: usize| all.get(n).map_or(0, |(_, b, _)| *b);
451 let ct = |n: usize| all.get(n).map_or(0, |(_, _, c)| *c);
452
453 crate::logging::info!(
454 target: "ant_node::replication::traffic",
455 peer_1_id = %id(0), peer_1_bytes = by(0), peer_1_count = ct(0),
456 peer_2_id = %id(1), peer_2_bytes = by(1), peer_2_count = ct(1),
457 peer_3_id = %id(2), peer_3_bytes = by(2), peer_3_count = ct(2),
458 peer_4_id = %id(3), peer_4_bytes = by(3), peer_4_count = ct(3),
459 peer_5_id = %id(4), peer_5_bytes = by(4), peer_5_count = ct(4),
460 peer_6_id = %id(5), peer_6_bytes = by(5), peer_6_count = ct(5),
461 peer_7_id = %id(6), peer_7_bytes = by(6), peer_7_count = ct(6),
462 peer_8_id = %id(7), peer_8_bytes = by(7), peer_8_count = ct(7),
463 peer_9_id = %id(8), peer_9_bytes = by(8), peer_9_count = ct(8),
464 peer_10_id = %id(9), peer_10_bytes = by(9), peer_10_count = ct(9),
465 tracked_peers = tracked_peers,
466 evictions = evictions,
467 "replication served-peers summary (cumulative)"
468 );
469}
470
471#[derive(Debug, Clone, Serialize, Deserialize)]
479pub struct FreshReplicationOffer {
480 pub key: XorName,
482 pub data: Vec<u8>,
484 pub proof_of_payment: Vec<u8>,
486}
487
488#[derive(Debug, Clone, Serialize, Deserialize)]
490pub enum FreshReplicationResponse {
491 Accepted {
493 key: XorName,
495 },
496 Rejected {
498 key: XorName,
500 reason: String,
502 },
503}
504
505#[derive(Debug, Clone, Serialize, Deserialize)]
510pub struct PaidNotify {
511 pub key: XorName,
513 pub proof_of_payment: Vec<u8>,
515}
516
517#[derive(Debug, Clone, Serialize, Deserialize)]
525pub struct NeighborSyncRequest {
526 pub replica_hints: Vec<XorName>,
528 pub paid_hints: Vec<XorName>,
530 pub bootstrapping: bool,
532 #[serde(default)]
539 pub commitment: Option<crate::replication::commitment::StorageCommitment>,
540}
541
542#[derive(Debug, Clone, Serialize, Deserialize)]
544pub struct NeighborSyncResponse {
545 pub replica_hints: Vec<XorName>,
547 pub paid_hints: Vec<XorName>,
549 pub bootstrapping: bool,
551 pub rejected_keys: Vec<XorName>,
553 #[serde(default)]
556 pub commitment: Option<crate::replication::commitment::StorageCommitment>,
557}
558
559#[derive(Debug, Clone, Serialize, Deserialize)]
569pub struct VerificationRequest {
570 pub keys: Vec<XorName>,
572 pub paid_list_check_indices: Vec<u32>,
575}
576
577#[derive(Debug, Clone, Serialize, Deserialize)]
579pub struct KeyVerificationResult {
580 pub key: XorName,
582 pub present: bool,
584 pub paid: Option<bool>,
590}
591
592#[derive(Debug, Clone, Serialize, Deserialize)]
594pub struct VerificationResponse {
595 pub results: Vec<KeyVerificationResult>,
597}
598
599#[derive(Debug, Clone, Serialize, Deserialize)]
605pub struct FetchRequest {
606 pub key: XorName,
608}
609
610#[derive(Debug, Clone, Serialize, Deserialize)]
612pub enum FetchResponse {
613 Success {
615 key: XorName,
617 data: Vec<u8>,
619 },
620 NotFound {
622 key: XorName,
624 },
625 Error {
627 key: XorName,
629 reason: String,
631 },
632}
633
634#[derive(Debug, Clone, Serialize, Deserialize)]
646pub struct GetCommitmentByPin {
647 pub pin: [u8; 32],
649}
650
651#[derive(Debug, Clone, Serialize, Deserialize)]
653pub enum GetCommitmentByPinResponse {
654 Found {
656 commitment: crate::replication::commitment::StorageCommitment,
659 },
660 NotRetained {
664 pin: [u8; 32],
666 },
667}
668
669#[derive(Debug, Clone, Serialize, Deserialize)]
682pub struct AuditChallenge {
683 pub challenge_id: u64,
685 pub nonce: [u8; 32],
687 pub challenged_peer_id: [u8; 32],
689 pub keys: Vec<XorName>,
691}
692
693#[derive(Debug, Clone, Serialize, Deserialize)]
695pub enum AuditResponse {
696 Digests {
701 challenge_id: u64,
703 digests: Vec<[u8; 32]>,
705 },
706 Bootstrapping {
708 challenge_id: u64,
710 },
711 Rejected {
716 challenge_id: u64,
718 reason: String,
720 },
721}
722
723#[derive(Debug, Clone, Serialize, Deserialize)]
735pub struct SubtreeAuditChallenge {
736 pub challenge_id: u64,
738 pub nonce: [u8; 32],
741 pub challenged_peer_id: [u8; 32],
743 pub expected_commitment_hash: [u8; 32],
747}
748
749#[derive(Debug, Clone, Serialize, Deserialize)]
751pub enum SubtreeAuditResponse {
752 Proof {
771 challenge_id: u64,
773 commitment: crate::replication::commitment::StorageCommitment,
775 proof: crate::replication::subtree::SubtreeProof,
777 },
778 Bootstrapping {
780 challenge_id: u64,
782 },
783 Rejected {
786 challenge_id: u64,
788 kind: RejectKind,
790 reason: String,
792 },
793}
794
795#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
814pub enum RejectKind {
815 UnknownCommitment,
819 Transient,
823 Protocol,
826}
827
828#[derive(Debug, Clone, Serialize, Deserialize)]
845pub struct SubtreeByteChallenge {
846 pub challenge_id: u64,
849 pub nonce: [u8; 32],
852 pub challenged_peer_id: [u8; 32],
854 pub expected_commitment_hash: [u8; 32],
857 pub keys: Vec<XorName>,
861}
862
863#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
865pub enum SubtreeByteItem {
866 Present {
868 key: XorName,
870 bytes: Vec<u8>,
872 },
873 Absent {
879 key: XorName,
881 },
882}
883
884#[derive(Debug, Clone, Serialize, Deserialize)]
893pub enum SubtreeByteResponse {
894 Items {
896 challenge_id: u64,
898 items: Vec<SubtreeByteItem>,
900 },
901 Bootstrapping {
903 challenge_id: u64,
905 },
906 Rejected {
911 challenge_id: u64,
913 kind: RejectKind,
915 reason: String,
917 },
918}
919
920#[must_use]
930pub fn compute_audit_digest(
931 nonce: &[u8; 32],
932 challenged_peer_id: &[u8; 32],
933 key: &XorName,
934 record_bytes: &[u8],
935) -> [u8; 32] {
936 let mut hasher = blake3::Hasher::new();
937 hasher.update(nonce);
938 hasher.update(challenged_peer_id);
939 hasher.update(key);
940 hasher.update(record_bytes);
941 *hasher.finalize().as_bytes()
942}
943
944#[derive(Debug, Clone)]
950pub enum ReplicationProtocolError {
951 SerializationFailed(String),
953 DeserializationFailed(String),
955 MessageTooLarge {
957 size: usize,
959 max_size: usize,
961 },
962}
963
964impl std::fmt::Display for ReplicationProtocolError {
965 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
966 match self {
967 Self::SerializationFailed(msg) => {
968 write!(f, "replication serialization failed: {msg}")
969 }
970 Self::DeserializationFailed(msg) => {
971 write!(f, "replication deserialization failed: {msg}")
972 }
973 Self::MessageTooLarge { size, max_size } => {
974 write!(
975 f,
976 "replication message size {size} exceeds maximum {max_size}"
977 )
978 }
979 }
980 }
981}
982
983impl std::error::Error for ReplicationProtocolError {}
984
985#[cfg(test)]
990#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
991mod tests {
992 use super::*;
993
994 #[test]
997 fn max_batch_worst_case_byte_response_fits_wire_cap() {
998 let items: Vec<SubtreeByteItem> = (0..crate::replication::config::MAX_BYTE_CHALLENGE_KEYS)
1003 .map(|i| SubtreeByteItem::Present {
1004 key: [u8::try_from(i).unwrap_or(u8::MAX); 32],
1005 bytes: vec![0xAB; crate::ant_protocol::MAX_CHUNK_SIZE],
1006 })
1007 .collect();
1008 let msg = ReplicationMessage {
1009 request_id: 7,
1010 body: ReplicationMessageBody::SubtreeByteResponse(SubtreeByteResponse::Items {
1011 challenge_id: 7,
1012 items,
1013 }),
1014 };
1015 let encoded = msg
1016 .encode()
1017 .expect("worst-case max-batch byte response must fit the wire cap");
1018 assert!(encoded.len() <= MAX_REPLICATION_MESSAGE_SIZE);
1019 }
1020
1021 #[test]
1024 fn fresh_replication_offer_roundtrip() {
1025 let msg = ReplicationMessage {
1026 request_id: 1,
1027 body: ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
1028 key: [0xAA; 32],
1029 data: vec![1, 2, 3, 4, 5],
1030 proof_of_payment: vec![10, 20, 30],
1031 }),
1032 };
1033 let encoded = msg.encode().expect("encode should succeed");
1034 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1035
1036 assert_eq!(decoded.request_id, 1);
1037 if let ReplicationMessageBody::FreshReplicationOffer(offer) = decoded.body {
1038 assert_eq!(offer.key, [0xAA; 32]);
1039 assert_eq!(offer.data, vec![1, 2, 3, 4, 5]);
1040 assert_eq!(offer.proof_of_payment, vec![10, 20, 30]);
1041 } else {
1042 panic!("expected FreshReplicationOffer");
1043 }
1044 }
1045
1046 #[test]
1047 fn fresh_replication_response_accepted_roundtrip() {
1048 let msg = ReplicationMessage {
1049 request_id: 2,
1050 body: ReplicationMessageBody::FreshReplicationResponse(
1051 FreshReplicationResponse::Accepted { key: [0xBB; 32] },
1052 ),
1053 };
1054 let encoded = msg.encode().expect("encode should succeed");
1055 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1056
1057 assert_eq!(decoded.request_id, 2);
1058 if let ReplicationMessageBody::FreshReplicationResponse(
1059 FreshReplicationResponse::Accepted { key },
1060 ) = decoded.body
1061 {
1062 assert_eq!(key, [0xBB; 32]);
1063 } else {
1064 panic!("expected FreshReplicationResponse::Accepted");
1065 }
1066 }
1067
1068 #[test]
1069 fn fresh_replication_response_rejected_roundtrip() {
1070 let msg = ReplicationMessage {
1071 request_id: 3,
1072 body: ReplicationMessageBody::FreshReplicationResponse(
1073 FreshReplicationResponse::Rejected {
1074 key: [0xCC; 32],
1075 reason: "out of range".to_string(),
1076 },
1077 ),
1078 };
1079 let encoded = msg.encode().expect("encode should succeed");
1080 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1081
1082 assert_eq!(decoded.request_id, 3);
1083 if let ReplicationMessageBody::FreshReplicationResponse(
1084 FreshReplicationResponse::Rejected { key, reason },
1085 ) = decoded.body
1086 {
1087 assert_eq!(key, [0xCC; 32]);
1088 assert_eq!(reason, "out of range");
1089 } else {
1090 panic!("expected FreshReplicationResponse::Rejected");
1091 }
1092 }
1093
1094 #[test]
1097 fn paid_notify_roundtrip() {
1098 let msg = ReplicationMessage {
1099 request_id: 4,
1100 body: ReplicationMessageBody::PaidNotify(PaidNotify {
1101 key: [0xDD; 32],
1102 proof_of_payment: vec![99, 100],
1103 }),
1104 };
1105 let encoded = msg.encode().expect("encode should succeed");
1106 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1107
1108 assert_eq!(decoded.request_id, 4);
1109 if let ReplicationMessageBody::PaidNotify(notify) = decoded.body {
1110 assert_eq!(notify.key, [0xDD; 32]);
1111 assert_eq!(notify.proof_of_payment, vec![99, 100]);
1112 } else {
1113 panic!("expected PaidNotify");
1114 }
1115 }
1116
1117 #[test]
1133 fn old_decoder_tolerates_new_neighbor_sync_request() {
1134 use serde::Deserialize;
1135 #[derive(Deserialize)]
1136 struct OldNeighborSyncRequest {
1137 #[allow(dead_code)]
1138 pub replica_hints: Vec<XorName>,
1139 #[allow(dead_code)]
1140 pub paid_hints: Vec<XorName>,
1141 #[allow(dead_code)]
1142 pub bootstrapping: bool,
1143 }
1144
1145 let new_req = NeighborSyncRequest {
1146 replica_hints: vec![[0x01; 32], [0x02; 32]],
1147 paid_hints: vec![[0x03; 32]],
1148 bootstrapping: true,
1149 commitment: None,
1150 };
1151 let encoded = postcard::to_stdvec(&new_req).expect("encode");
1152 let old_decoded: OldNeighborSyncRequest =
1153 postcard::from_bytes(&encoded).expect("old decoder accepts");
1154 assert_eq!(old_decoded.replica_hints.len(), 2);
1157 assert_eq!(old_decoded.paid_hints.len(), 1);
1158 assert!(old_decoded.bootstrapping);
1159 }
1160
1161 #[test]
1163 fn old_decoder_tolerates_new_neighbor_sync_response() {
1164 use serde::Deserialize;
1165 #[derive(Deserialize)]
1166 struct OldNeighborSyncResponse {
1167 #[allow(dead_code)]
1168 pub replica_hints: Vec<XorName>,
1169 #[allow(dead_code)]
1170 pub paid_hints: Vec<XorName>,
1171 #[allow(dead_code)]
1172 pub bootstrapping: bool,
1173 #[allow(dead_code)]
1174 pub rejected_keys: Vec<XorName>,
1175 }
1176
1177 let new_resp = NeighborSyncResponse {
1178 replica_hints: vec![[0x04; 32]],
1179 paid_hints: vec![],
1180 bootstrapping: false,
1181 rejected_keys: vec![[0x05; 32]],
1182 commitment: None,
1183 };
1184 let encoded = postcard::to_stdvec(&new_resp).expect("encode");
1185 let old_decoded: OldNeighborSyncResponse =
1186 postcard::from_bytes(&encoded).expect("old decoder accepts");
1187 assert_eq!(old_decoded.replica_hints.len(), 1);
1188 assert_eq!(old_decoded.rejected_keys.len(), 1);
1189 }
1190
1191 #[test]
1195 fn new_peer_roundtrips_with_commitment_some() {
1196 use crate::replication::commitment::{sign_commitment, StorageCommitment};
1197 use saorsa_pqc::api::sig::ml_dsa_65;
1198
1199 let (pk, sk) = ml_dsa_65().generate_keypair().expect("keygen");
1200 let root = [0x7Fu8; 32];
1201 let sender = [0xCCu8; 32];
1202 let pk_bytes = pk.to_bytes();
1203 let sig = sign_commitment(&sk, &root, 3, &sender, &pk_bytes).expect("sign");
1204 let commitment = StorageCommitment {
1205 root,
1206 key_count: 3,
1207 sender_peer_id: sender,
1208 sender_public_key: pk_bytes,
1209 signature: sig,
1210 };
1211
1212 let req = NeighborSyncRequest {
1213 replica_hints: vec![[0x01; 32]],
1214 paid_hints: vec![],
1215 bootstrapping: false,
1216 commitment: Some(commitment.clone()),
1217 };
1218 let encoded = postcard::to_stdvec(&req).expect("encode");
1219 let decoded: NeighborSyncRequest = postcard::from_bytes(&encoded).expect("new decoder");
1220 assert_eq!(decoded.commitment, Some(commitment));
1221 }
1222
1223 #[test]
1224 fn neighbor_sync_request_roundtrip() {
1225 let msg = ReplicationMessage {
1226 request_id: 5,
1227 body: ReplicationMessageBody::NeighborSyncRequest(NeighborSyncRequest {
1228 replica_hints: vec![[0x01; 32], [0x02; 32]],
1229 paid_hints: vec![[0x03; 32]],
1230 bootstrapping: true,
1231 commitment: None,
1232 }),
1233 };
1234 let encoded = msg.encode().expect("encode should succeed");
1235 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1236
1237 assert_eq!(decoded.request_id, 5);
1238 if let ReplicationMessageBody::NeighborSyncRequest(req) = decoded.body {
1239 assert_eq!(req.replica_hints.len(), 2);
1240 assert_eq!(req.paid_hints.len(), 1);
1241 assert!(req.bootstrapping);
1242 } else {
1243 panic!("expected NeighborSyncRequest");
1244 }
1245 }
1246
1247 #[test]
1248 fn neighbor_sync_response_roundtrip() {
1249 let msg = ReplicationMessage {
1250 request_id: 6,
1251 body: ReplicationMessageBody::NeighborSyncResponse(NeighborSyncResponse {
1252 replica_hints: vec![[0x04; 32]],
1253 paid_hints: vec![],
1254 bootstrapping: false,
1255 rejected_keys: vec![[0x05; 32], [0x06; 32]],
1256 commitment: None,
1257 }),
1258 };
1259 let encoded = msg.encode().expect("encode should succeed");
1260 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1261
1262 assert_eq!(decoded.request_id, 6);
1263 if let ReplicationMessageBody::NeighborSyncResponse(resp) = decoded.body {
1264 assert_eq!(resp.replica_hints.len(), 1);
1265 assert!(resp.paid_hints.is_empty());
1266 assert!(!resp.bootstrapping);
1267 assert_eq!(resp.rejected_keys.len(), 2);
1268 } else {
1269 panic!("expected NeighborSyncResponse");
1270 }
1271 }
1272
1273 #[test]
1276 fn verification_request_roundtrip() {
1277 let msg = ReplicationMessage {
1278 request_id: 7,
1279 body: ReplicationMessageBody::VerificationRequest(VerificationRequest {
1280 keys: vec![[0x10; 32], [0x20; 32], [0x30; 32]],
1281 paid_list_check_indices: vec![0, 2],
1282 }),
1283 };
1284 let encoded = msg.encode().expect("encode should succeed");
1285 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1286
1287 assert_eq!(decoded.request_id, 7);
1288 if let ReplicationMessageBody::VerificationRequest(req) = decoded.body {
1289 assert_eq!(req.keys.len(), 3);
1290 assert_eq!(req.paid_list_check_indices, vec![0, 2]);
1291 } else {
1292 panic!("expected VerificationRequest");
1293 }
1294 }
1295
1296 #[test]
1297 fn verification_response_roundtrip() {
1298 let results = vec![
1299 KeyVerificationResult {
1300 key: [0x10; 32],
1301 present: true,
1302 paid: Some(true),
1303 },
1304 KeyVerificationResult {
1305 key: [0x20; 32],
1306 present: false,
1307 paid: None,
1308 },
1309 KeyVerificationResult {
1310 key: [0x30; 32],
1311 present: true,
1312 paid: Some(false),
1313 },
1314 ];
1315 let msg = ReplicationMessage {
1316 request_id: 8,
1317 body: ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
1318 };
1319 let encoded = msg.encode().expect("encode should succeed");
1320 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1321
1322 assert_eq!(decoded.request_id, 8);
1323 if let ReplicationMessageBody::VerificationResponse(resp) = decoded.body {
1324 assert_eq!(resp.results.len(), 3);
1325 assert!(resp.results[0].present);
1326 assert_eq!(resp.results[0].paid, Some(true));
1327 assert!(!resp.results[1].present);
1328 assert_eq!(resp.results[1].paid, None);
1329 assert!(resp.results[2].present);
1330 assert_eq!(resp.results[2].paid, Some(false));
1331 } else {
1332 panic!("expected VerificationResponse");
1333 }
1334 }
1335
1336 #[test]
1339 fn fetch_request_roundtrip() {
1340 let msg = ReplicationMessage {
1341 request_id: 9,
1342 body: ReplicationMessageBody::FetchRequest(FetchRequest { key: [0x40; 32] }),
1343 };
1344 let encoded = msg.encode().expect("encode should succeed");
1345 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1346
1347 assert_eq!(decoded.request_id, 9);
1348 if let ReplicationMessageBody::FetchRequest(req) = decoded.body {
1349 assert_eq!(req.key, [0x40; 32]);
1350 } else {
1351 panic!("expected FetchRequest");
1352 }
1353 }
1354
1355 #[test]
1356 fn fetch_response_success_roundtrip() {
1357 let msg = ReplicationMessage {
1358 request_id: 10,
1359 body: ReplicationMessageBody::FetchResponse(FetchResponse::Success {
1360 key: [0x50; 32],
1361 data: vec![7, 8, 9],
1362 }),
1363 };
1364 let encoded = msg.encode().expect("encode should succeed");
1365 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1366
1367 assert_eq!(decoded.request_id, 10);
1368 if let ReplicationMessageBody::FetchResponse(FetchResponse::Success { key, data }) =
1369 decoded.body
1370 {
1371 assert_eq!(key, [0x50; 32]);
1372 assert_eq!(data, vec![7, 8, 9]);
1373 } else {
1374 panic!("expected FetchResponse::Success");
1375 }
1376 }
1377
1378 #[test]
1379 fn fetch_response_not_found_roundtrip() {
1380 let msg = ReplicationMessage {
1381 request_id: 11,
1382 body: ReplicationMessageBody::FetchResponse(FetchResponse::NotFound {
1383 key: [0x60; 32],
1384 }),
1385 };
1386 let encoded = msg.encode().expect("encode should succeed");
1387 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1388
1389 assert_eq!(decoded.request_id, 11);
1390 if let ReplicationMessageBody::FetchResponse(FetchResponse::NotFound { key }) = decoded.body
1391 {
1392 assert_eq!(key, [0x60; 32]);
1393 } else {
1394 panic!("expected FetchResponse::NotFound");
1395 }
1396 }
1397
1398 #[test]
1399 fn fetch_response_error_roundtrip() {
1400 let msg = ReplicationMessage {
1401 request_id: 12,
1402 body: ReplicationMessageBody::FetchResponse(FetchResponse::Error {
1403 key: [0x70; 32],
1404 reason: "disk full".to_string(),
1405 }),
1406 };
1407 let encoded = msg.encode().expect("encode should succeed");
1408 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1409
1410 assert_eq!(decoded.request_id, 12);
1411 if let ReplicationMessageBody::FetchResponse(FetchResponse::Error { key, reason }) =
1412 decoded.body
1413 {
1414 assert_eq!(key, [0x70; 32]);
1415 assert_eq!(reason, "disk full");
1416 } else {
1417 panic!("expected FetchResponse::Error");
1418 }
1419 }
1420
1421 #[test]
1424 fn audit_challenge_roundtrip() {
1425 let msg = ReplicationMessage {
1426 request_id: 13,
1427 body: ReplicationMessageBody::AuditChallenge(AuditChallenge {
1428 challenge_id: 999,
1429 nonce: [0xAB; 32],
1430 challenged_peer_id: [0xCD; 32],
1431 keys: vec![[0x01; 32], [0x02; 32]],
1432 }),
1433 };
1434 let encoded = msg.encode().expect("encode should succeed");
1435 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1436
1437 assert_eq!(decoded.request_id, 13);
1438 if let ReplicationMessageBody::AuditChallenge(challenge) = decoded.body {
1439 assert_eq!(challenge.challenge_id, 999);
1440 assert_eq!(challenge.nonce, [0xAB; 32]);
1441 assert_eq!(challenge.challenged_peer_id, [0xCD; 32]);
1442 assert_eq!(challenge.keys.len(), 2);
1443 } else {
1444 panic!("expected AuditChallenge");
1445 }
1446 }
1447
1448 #[test]
1449 fn audit_response_digests_roundtrip() {
1450 let digests = vec![[0x11; 32], ABSENT_KEY_DIGEST];
1451 let msg = ReplicationMessage {
1452 request_id: 14,
1453 body: ReplicationMessageBody::AuditResponse(AuditResponse::Digests {
1454 challenge_id: 999,
1455 digests: digests.clone(),
1456 }),
1457 };
1458 let encoded = msg.encode().expect("encode should succeed");
1459 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1460
1461 assert_eq!(decoded.request_id, 14);
1462 if let ReplicationMessageBody::AuditResponse(AuditResponse::Digests {
1463 challenge_id,
1464 digests: decoded_digests,
1465 }) = decoded.body
1466 {
1467 assert_eq!(challenge_id, 999);
1468 assert_eq!(decoded_digests, digests);
1469 } else {
1470 panic!("expected AuditResponse::Digests");
1471 }
1472 }
1473
1474 #[test]
1475 fn audit_response_bootstrapping_roundtrip() {
1476 let msg = ReplicationMessage {
1477 request_id: 15,
1478 body: ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping {
1479 challenge_id: 42,
1480 }),
1481 };
1482 let encoded = msg.encode().expect("encode should succeed");
1483 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1484
1485 assert_eq!(decoded.request_id, 15);
1486 if let ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping {
1487 challenge_id,
1488 }) = decoded.body
1489 {
1490 assert_eq!(challenge_id, 42);
1491 } else {
1492 panic!("expected AuditResponse::Bootstrapping");
1493 }
1494 }
1495
1496 #[test]
1499 fn decode_rejects_oversized_payload() {
1500 let oversized = vec![0u8; MAX_REPLICATION_MESSAGE_SIZE + 1];
1501 let result = ReplicationMessage::decode(&oversized);
1502 assert!(result.is_err());
1503 let err = result.unwrap_err();
1504 assert!(
1505 matches!(err, ReplicationProtocolError::MessageTooLarge { .. }),
1506 "expected MessageTooLarge, got {err:?}"
1507 );
1508 }
1509
1510 #[test]
1511 fn encode_rejects_oversized_message() {
1512 let msg = ReplicationMessage {
1514 request_id: 0,
1515 body: ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
1516 key: [0; 32],
1517 data: vec![0xFF; MAX_REPLICATION_MESSAGE_SIZE],
1518 proof_of_payment: vec![],
1519 }),
1520 };
1521 let result = msg.encode();
1522 assert!(result.is_err());
1523 let err = result.unwrap_err();
1524 assert!(
1525 matches!(err, ReplicationProtocolError::MessageTooLarge { .. }),
1526 "expected MessageTooLarge, got {err:?}"
1527 );
1528 }
1529
1530 #[test]
1533 fn decode_rejects_invalid_data() {
1534 let invalid = vec![0xFF, 0xFF, 0xFF];
1535 let result = ReplicationMessage::decode(&invalid);
1536 assert!(result.is_err());
1537 let err = result.unwrap_err();
1538 assert!(
1539 matches!(err, ReplicationProtocolError::DeserializationFailed(_)),
1540 "expected DeserializationFailed, got {err:?}"
1541 );
1542 }
1543
1544 #[test]
1547 fn audit_digest_is_deterministic() {
1548 let nonce = [0x01; 32];
1549 let peer_id = [0x02; 32];
1550 let key: XorName = [0x03; 32];
1551 let record_bytes = b"hello world";
1552
1553 let digest_a = compute_audit_digest(&nonce, &peer_id, &key, record_bytes);
1554 let digest_b = compute_audit_digest(&nonce, &peer_id, &key, record_bytes);
1555
1556 assert_eq!(digest_a, digest_b, "same inputs must produce same digest");
1557 }
1558
1559 #[test]
1560 fn audit_digest_differs_with_different_nonce() {
1561 let peer_id = [0x02; 32];
1562 let key: XorName = [0x03; 32];
1563 let record_bytes = b"hello world";
1564
1565 let digest_a = compute_audit_digest(&[0x01; 32], &peer_id, &key, record_bytes);
1566 let digest_b = compute_audit_digest(&[0xFF; 32], &peer_id, &key, record_bytes);
1567
1568 assert_ne!(
1569 digest_a, digest_b,
1570 "different nonces must produce different digests"
1571 );
1572 }
1573
1574 #[test]
1575 fn audit_digest_differs_with_different_data() {
1576 let nonce = [0x01; 32];
1577 let peer_id = [0x02; 32];
1578 let key: XorName = [0x03; 32];
1579
1580 let digest_a = compute_audit_digest(&nonce, &peer_id, &key, b"data-A");
1581 let digest_b = compute_audit_digest(&nonce, &peer_id, &key, b"data-B");
1582
1583 assert_ne!(
1584 digest_a, digest_b,
1585 "different data must produce different digests"
1586 );
1587 }
1588
1589 #[test]
1590 fn audit_digest_differs_with_different_peer() {
1591 let nonce = [0x01; 32];
1592 let key: XorName = [0x03; 32];
1593 let record_bytes = b"hello";
1594
1595 let digest_a = compute_audit_digest(&nonce, &[0x02; 32], &key, record_bytes);
1596 let digest_b = compute_audit_digest(&nonce, &[0xFF; 32], &key, record_bytes);
1597
1598 assert_ne!(
1599 digest_a, digest_b,
1600 "different peer IDs must produce different digests"
1601 );
1602 }
1603
1604 #[test]
1605 fn audit_digest_differs_with_different_key() {
1606 let nonce = [0x01; 32];
1607 let peer_id = [0x02; 32];
1608 let record_bytes = b"hello";
1609
1610 let digest_a = compute_audit_digest(&nonce, &peer_id, &[0x03; 32], record_bytes);
1611 let digest_b = compute_audit_digest(&nonce, &peer_id, &[0xFF; 32], record_bytes);
1612
1613 assert_ne!(
1614 digest_a, digest_b,
1615 "different keys must produce different digests"
1616 );
1617 }
1618
1619 #[test]
1622 fn absent_key_digest_is_all_zeros() {
1623 assert_eq!(ABSENT_KEY_DIGEST, [0u8; 32]);
1624 }
1625
1626 #[test]
1627 fn real_digest_differs_from_absent_sentinel() {
1628 let nonce = [0x01; 32];
1629 let peer_id = [0x02; 32];
1630 let key: XorName = [0x03; 32];
1631 let record_bytes = b"non-empty data";
1632
1633 let digest = compute_audit_digest(&nonce, &peer_id, &key, record_bytes);
1634 assert_ne!(
1635 digest, ABSENT_KEY_DIGEST,
1636 "a real digest should not collide with the all-zeros sentinel"
1637 );
1638 }
1639
1640 #[test]
1643 fn error_display_serialization_failed() {
1644 let err = ReplicationProtocolError::SerializationFailed("boom".to_string());
1645 assert_eq!(err.to_string(), "replication serialization failed: boom");
1646 }
1647
1648 #[test]
1649 fn error_display_deserialization_failed() {
1650 let err = ReplicationProtocolError::DeserializationFailed("bad data".to_string());
1651 assert_eq!(
1652 err.to_string(),
1653 "replication deserialization failed: bad data"
1654 );
1655 }
1656
1657 #[test]
1658 fn error_display_message_too_large() {
1659 let err = ReplicationProtocolError::MessageTooLarge {
1660 size: 20_000_000,
1661 max_size: MAX_REPLICATION_MESSAGE_SIZE,
1662 };
1663 let display = err.to_string();
1664 assert!(display.contains("20000000"));
1665 assert!(display.contains(&MAX_REPLICATION_MESSAGE_SIZE.to_string()));
1666 }
1667}