1use std::sync::atomic::{AtomicU64, Ordering};
7
8use serde::{Deserialize, Serialize};
9
10use crate::ant_protocol::XorName;
11
12pub use super::config::MAX_REPLICATION_MESSAGE_SIZE;
13
14pub const ABSENT_KEY_DIGEST: [u8; 32] = [0u8; 32];
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct ReplicationMessage {
30 pub request_id: u64,
32 pub body: ReplicationMessageBody,
34}
35
36impl ReplicationMessage {
37 pub fn encode(&self) -> Result<Vec<u8>, ReplicationProtocolError> {
44 let bytes = postcard::to_stdvec(self)
45 .map_err(|e| ReplicationProtocolError::SerializationFailed(e.to_string()))?;
46
47 if bytes.len() > MAX_REPLICATION_MESSAGE_SIZE {
48 return Err(ReplicationProtocolError::MessageTooLarge {
49 size: bytes.len(),
50 max_size: MAX_REPLICATION_MESSAGE_SIZE,
51 });
52 }
53
54 record_tx(&self.body, bytes.len());
57
58 Ok(bytes)
59 }
60
61 pub fn decode(data: &[u8]) -> Result<Self, ReplicationProtocolError> {
73 if data.len() > MAX_REPLICATION_MESSAGE_SIZE {
74 return Err(ReplicationProtocolError::MessageTooLarge {
75 size: data.len(),
76 max_size: MAX_REPLICATION_MESSAGE_SIZE,
77 });
78 }
79 let message: Self = postcard::from_bytes(data)
80 .map_err(|e| ReplicationProtocolError::DeserializationFailed(e.to_string()))?;
81
82 record_rx(&message.body, data.len());
85
86 Ok(message)
87 }
88}
89
90#[derive(Debug, Clone, Serialize, Deserialize)]
96pub enum ReplicationMessageBody {
97 FreshReplicationOffer(FreshReplicationOffer),
100 FreshReplicationResponse(FreshReplicationResponse),
102
103 PaidNotify(PaidNotify),
105
106 NeighborSyncRequest(NeighborSyncRequest),
109 NeighborSyncResponse(NeighborSyncResponse),
111
112 VerificationRequest(VerificationRequest),
115 VerificationResponse(VerificationResponse),
117
118 FetchRequest(FetchRequest),
121 FetchResponse(FetchResponse),
123
124 AuditChallenge(AuditChallenge),
128 AuditResponse(AuditResponse),
130
131 SubtreeAuditChallenge(SubtreeAuditChallenge),
134 SubtreeAuditResponse(SubtreeAuditResponse),
136 SubtreeByteChallenge(SubtreeByteChallenge),
138 SubtreeByteResponse(SubtreeByteResponse),
140
141 GetCommitmentByPin(GetCommitmentByPin),
151 GetCommitmentByPinResponse(GetCommitmentByPinResponse),
153}
154
155const N_REPLICATION_VARIANTS: usize = 17;
172
173static REPL_TX_BYTES: [AtomicU64; N_REPLICATION_VARIANTS] =
174 [const { AtomicU64::new(0) }; N_REPLICATION_VARIANTS];
175static REPL_TX_COUNT: [AtomicU64; N_REPLICATION_VARIANTS] =
176 [const { AtomicU64::new(0) }; N_REPLICATION_VARIANTS];
177static REPL_RX_BYTES: [AtomicU64; N_REPLICATION_VARIANTS] =
178 [const { AtomicU64::new(0) }; N_REPLICATION_VARIANTS];
179static REPL_RX_COUNT: [AtomicU64; N_REPLICATION_VARIANTS] =
180 [const { AtomicU64::new(0) }; N_REPLICATION_VARIANTS];
181
182impl ReplicationMessageBody {
183 pub(crate) fn variant_index(&self) -> usize {
188 match self {
189 Self::FreshReplicationOffer(_) => 0,
190 Self::FreshReplicationResponse(_) => 1,
191 Self::PaidNotify(_) => 2,
192 Self::NeighborSyncRequest(_) => 3,
193 Self::NeighborSyncResponse(_) => 4,
194 Self::VerificationRequest(_) => 5,
195 Self::VerificationResponse(_) => 6,
196 Self::FetchRequest(_) => 7,
197 Self::FetchResponse(_) => 8,
198 Self::AuditChallenge(_) => 9,
199 Self::AuditResponse(_) => 10,
200 Self::SubtreeAuditChallenge(_) => 11,
201 Self::SubtreeAuditResponse(_) => 12,
202 Self::SubtreeByteChallenge(_) => 13,
203 Self::SubtreeByteResponse(_) => 14,
204 Self::GetCommitmentByPin(_) => 15,
205 Self::GetCommitmentByPinResponse(_) => 16,
206 }
207 }
208}
209
210fn record_tx(body: &ReplicationMessageBody, bytes: usize) {
212 let i = body.variant_index();
213 REPL_TX_BYTES[i].fetch_add(bytes as u64, Ordering::Relaxed);
214 REPL_TX_COUNT[i].fetch_add(1, Ordering::Relaxed);
215}
216
217fn record_rx(body: &ReplicationMessageBody, bytes: usize) {
219 let i = body.variant_index();
220 REPL_RX_BYTES[i].fetch_add(bytes as u64, Ordering::Relaxed);
221 REPL_RX_COUNT[i].fetch_add(1, Ordering::Relaxed);
222}
223
224pub(crate) fn log_traffic_summary() {
237 let tb = |i: usize| REPL_TX_BYTES[i].load(Ordering::Relaxed);
240 let tc = |i: usize| REPL_TX_COUNT[i].load(Ordering::Relaxed);
241 let rb = |i: usize| REPL_RX_BYTES[i].load(Ordering::Relaxed);
242 let rc = |i: usize| REPL_RX_COUNT[i].load(Ordering::Relaxed);
243
244 crate::logging::info!(
245 target: "ant_node::replication::traffic",
246 group = 1,
247 fresh_offer_tx_bytes = tb(0), fresh_offer_tx_count = tc(0),
248 fresh_offer_rx_bytes = rb(0), fresh_offer_rx_count = rc(0),
249 fresh_response_tx_bytes = tb(1), fresh_response_tx_count = tc(1),
250 fresh_response_rx_bytes = rb(1), fresh_response_rx_count = rc(1),
251 paid_notify_tx_bytes = tb(2), paid_notify_tx_count = tc(2),
252 paid_notify_rx_bytes = rb(2), paid_notify_rx_count = rc(2),
253 neighbor_sync_request_tx_bytes = tb(3), neighbor_sync_request_tx_count = tc(3),
254 neighbor_sync_request_rx_bytes = rb(3), neighbor_sync_request_rx_count = rc(3),
255 neighbor_sync_response_tx_bytes = tb(4), neighbor_sync_response_tx_count = tc(4),
256 neighbor_sync_response_rx_bytes = rb(4), neighbor_sync_response_rx_count = rc(4),
257 verification_request_tx_bytes = tb(5), verification_request_tx_count = tc(5),
258 verification_request_rx_bytes = rb(5), verification_request_rx_count = rc(5),
259 "replication traffic summary (cumulative)"
260 );
261 crate::logging::info!(
262 target: "ant_node::replication::traffic",
263 group = 2,
264 verification_response_tx_bytes = tb(6), verification_response_tx_count = tc(6),
265 verification_response_rx_bytes = rb(6), verification_response_rx_count = rc(6),
266 fetch_request_tx_bytes = tb(7), fetch_request_tx_count = tc(7),
267 fetch_request_rx_bytes = rb(7), fetch_request_rx_count = rc(7),
268 fetch_response_tx_bytes = tb(8), fetch_response_tx_count = tc(8),
269 fetch_response_rx_bytes = rb(8), fetch_response_rx_count = rc(8),
270 audit_challenge_tx_bytes = tb(9), audit_challenge_tx_count = tc(9),
271 audit_challenge_rx_bytes = rb(9), audit_challenge_rx_count = rc(9),
272 audit_response_tx_bytes = tb(10), audit_response_tx_count = tc(10),
273 audit_response_rx_bytes = rb(10), audit_response_rx_count = rc(10),
274 subtree_audit_challenge_tx_bytes = tb(11), subtree_audit_challenge_tx_count = tc(11),
275 subtree_audit_challenge_rx_bytes = rb(11), subtree_audit_challenge_rx_count = rc(11),
276 "replication traffic summary (cumulative)"
277 );
278 crate::logging::info!(
279 target: "ant_node::replication::traffic",
280 group = 3,
281 subtree_audit_response_tx_bytes = tb(12), subtree_audit_response_tx_count = tc(12),
282 subtree_audit_response_rx_bytes = rb(12), subtree_audit_response_rx_count = rc(12),
283 subtree_byte_challenge_tx_bytes = tb(13), subtree_byte_challenge_tx_count = tc(13),
284 subtree_byte_challenge_rx_bytes = rb(13), subtree_byte_challenge_rx_count = rc(13),
285 subtree_byte_response_tx_bytes = tb(14), subtree_byte_response_tx_count = tc(14),
286 subtree_byte_response_rx_bytes = rb(14), subtree_byte_response_rx_count = rc(14),
287 get_commitment_by_pin_tx_bytes = tb(15), get_commitment_by_pin_tx_count = tc(15),
288 get_commitment_by_pin_rx_bytes = rb(15), get_commitment_by_pin_rx_count = rc(15),
289 get_commitment_by_pin_response_tx_bytes = tb(16),
290 get_commitment_by_pin_response_tx_count = tc(16),
291 get_commitment_by_pin_response_rx_bytes = rb(16),
292 get_commitment_by_pin_response_rx_count = rc(16),
293 "replication traffic summary (cumulative)"
294 );
295}
296
297#[derive(Debug, Clone, Serialize, Deserialize)]
305pub struct FreshReplicationOffer {
306 pub key: XorName,
308 pub data: Vec<u8>,
310 pub proof_of_payment: Vec<u8>,
312}
313
314#[derive(Debug, Clone, Serialize, Deserialize)]
316pub enum FreshReplicationResponse {
317 Accepted {
319 key: XorName,
321 },
322 Rejected {
324 key: XorName,
326 reason: String,
328 },
329}
330
331#[derive(Debug, Clone, Serialize, Deserialize)]
336pub struct PaidNotify {
337 pub key: XorName,
339 pub proof_of_payment: Vec<u8>,
341}
342
343#[derive(Debug, Clone, Serialize, Deserialize)]
351pub struct NeighborSyncRequest {
352 pub replica_hints: Vec<XorName>,
354 pub paid_hints: Vec<XorName>,
356 pub bootstrapping: bool,
358 #[serde(default)]
365 pub commitment: Option<crate::replication::commitment::StorageCommitment>,
366}
367
368#[derive(Debug, Clone, Serialize, Deserialize)]
370pub struct NeighborSyncResponse {
371 pub replica_hints: Vec<XorName>,
373 pub paid_hints: Vec<XorName>,
375 pub bootstrapping: bool,
377 pub rejected_keys: Vec<XorName>,
379 #[serde(default)]
382 pub commitment: Option<crate::replication::commitment::StorageCommitment>,
383}
384
385#[derive(Debug, Clone, Serialize, Deserialize)]
395pub struct VerificationRequest {
396 pub keys: Vec<XorName>,
398 pub paid_list_check_indices: Vec<u32>,
401}
402
403#[derive(Debug, Clone, Serialize, Deserialize)]
405pub struct KeyVerificationResult {
406 pub key: XorName,
408 pub present: bool,
410 pub paid: Option<bool>,
416}
417
418#[derive(Debug, Clone, Serialize, Deserialize)]
420pub struct VerificationResponse {
421 pub results: Vec<KeyVerificationResult>,
423}
424
425#[derive(Debug, Clone, Serialize, Deserialize)]
431pub struct FetchRequest {
432 pub key: XorName,
434}
435
436#[derive(Debug, Clone, Serialize, Deserialize)]
438pub enum FetchResponse {
439 Success {
441 key: XorName,
443 data: Vec<u8>,
445 },
446 NotFound {
448 key: XorName,
450 },
451 Error {
453 key: XorName,
455 reason: String,
457 },
458}
459
460#[derive(Debug, Clone, Serialize, Deserialize)]
472pub struct GetCommitmentByPin {
473 pub pin: [u8; 32],
475}
476
477#[derive(Debug, Clone, Serialize, Deserialize)]
479pub enum GetCommitmentByPinResponse {
480 Found {
482 commitment: crate::replication::commitment::StorageCommitment,
485 },
486 NotRetained {
490 pin: [u8; 32],
492 },
493}
494
495#[derive(Debug, Clone, Serialize, Deserialize)]
508pub struct AuditChallenge {
509 pub challenge_id: u64,
511 pub nonce: [u8; 32],
513 pub challenged_peer_id: [u8; 32],
515 pub keys: Vec<XorName>,
517}
518
519#[derive(Debug, Clone, Serialize, Deserialize)]
521pub enum AuditResponse {
522 Digests {
527 challenge_id: u64,
529 digests: Vec<[u8; 32]>,
531 },
532 Bootstrapping {
534 challenge_id: u64,
536 },
537 Rejected {
542 challenge_id: u64,
544 reason: String,
546 },
547}
548
549#[derive(Debug, Clone, Serialize, Deserialize)]
561pub struct SubtreeAuditChallenge {
562 pub challenge_id: u64,
564 pub nonce: [u8; 32],
567 pub challenged_peer_id: [u8; 32],
569 pub expected_commitment_hash: [u8; 32],
573}
574
575#[derive(Debug, Clone, Serialize, Deserialize)]
577pub enum SubtreeAuditResponse {
578 Proof {
597 challenge_id: u64,
599 commitment: crate::replication::commitment::StorageCommitment,
601 proof: crate::replication::subtree::SubtreeProof,
603 },
604 Bootstrapping {
606 challenge_id: u64,
608 },
609 Rejected {
612 challenge_id: u64,
614 kind: RejectKind,
616 reason: String,
618 },
619}
620
621#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
640pub enum RejectKind {
641 UnknownCommitment,
645 Transient,
649 Protocol,
652}
653
654#[derive(Debug, Clone, Serialize, Deserialize)]
671pub struct SubtreeByteChallenge {
672 pub challenge_id: u64,
675 pub nonce: [u8; 32],
678 pub challenged_peer_id: [u8; 32],
680 pub expected_commitment_hash: [u8; 32],
683 pub keys: Vec<XorName>,
687}
688
689#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
691pub enum SubtreeByteItem {
692 Present {
694 key: XorName,
696 bytes: Vec<u8>,
698 },
699 Absent {
705 key: XorName,
707 },
708}
709
710#[derive(Debug, Clone, Serialize, Deserialize)]
719pub enum SubtreeByteResponse {
720 Items {
722 challenge_id: u64,
724 items: Vec<SubtreeByteItem>,
726 },
727 Bootstrapping {
729 challenge_id: u64,
731 },
732 Rejected {
737 challenge_id: u64,
739 kind: RejectKind,
741 reason: String,
743 },
744}
745
746#[must_use]
756pub fn compute_audit_digest(
757 nonce: &[u8; 32],
758 challenged_peer_id: &[u8; 32],
759 key: &XorName,
760 record_bytes: &[u8],
761) -> [u8; 32] {
762 let mut hasher = blake3::Hasher::new();
763 hasher.update(nonce);
764 hasher.update(challenged_peer_id);
765 hasher.update(key);
766 hasher.update(record_bytes);
767 *hasher.finalize().as_bytes()
768}
769
770#[derive(Debug, Clone)]
776pub enum ReplicationProtocolError {
777 SerializationFailed(String),
779 DeserializationFailed(String),
781 MessageTooLarge {
783 size: usize,
785 max_size: usize,
787 },
788}
789
790impl std::fmt::Display for ReplicationProtocolError {
791 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
792 match self {
793 Self::SerializationFailed(msg) => {
794 write!(f, "replication serialization failed: {msg}")
795 }
796 Self::DeserializationFailed(msg) => {
797 write!(f, "replication deserialization failed: {msg}")
798 }
799 Self::MessageTooLarge { size, max_size } => {
800 write!(
801 f,
802 "replication message size {size} exceeds maximum {max_size}"
803 )
804 }
805 }
806 }
807}
808
809impl std::error::Error for ReplicationProtocolError {}
810
811#[cfg(test)]
816#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
817mod tests {
818 use super::*;
819
820 #[test]
823 fn max_batch_worst_case_byte_response_fits_wire_cap() {
824 let items: Vec<SubtreeByteItem> = (0..crate::replication::config::MAX_BYTE_CHALLENGE_KEYS)
829 .map(|i| SubtreeByteItem::Present {
830 key: [u8::try_from(i).unwrap_or(u8::MAX); 32],
831 bytes: vec![0xAB; crate::ant_protocol::MAX_CHUNK_SIZE],
832 })
833 .collect();
834 let msg = ReplicationMessage {
835 request_id: 7,
836 body: ReplicationMessageBody::SubtreeByteResponse(SubtreeByteResponse::Items {
837 challenge_id: 7,
838 items,
839 }),
840 };
841 let encoded = msg
842 .encode()
843 .expect("worst-case max-batch byte response must fit the wire cap");
844 assert!(encoded.len() <= MAX_REPLICATION_MESSAGE_SIZE);
845 }
846
847 #[test]
850 fn fresh_replication_offer_roundtrip() {
851 let msg = ReplicationMessage {
852 request_id: 1,
853 body: ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
854 key: [0xAA; 32],
855 data: vec![1, 2, 3, 4, 5],
856 proof_of_payment: vec![10, 20, 30],
857 }),
858 };
859 let encoded = msg.encode().expect("encode should succeed");
860 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
861
862 assert_eq!(decoded.request_id, 1);
863 if let ReplicationMessageBody::FreshReplicationOffer(offer) = decoded.body {
864 assert_eq!(offer.key, [0xAA; 32]);
865 assert_eq!(offer.data, vec![1, 2, 3, 4, 5]);
866 assert_eq!(offer.proof_of_payment, vec![10, 20, 30]);
867 } else {
868 panic!("expected FreshReplicationOffer");
869 }
870 }
871
872 #[test]
873 fn fresh_replication_response_accepted_roundtrip() {
874 let msg = ReplicationMessage {
875 request_id: 2,
876 body: ReplicationMessageBody::FreshReplicationResponse(
877 FreshReplicationResponse::Accepted { key: [0xBB; 32] },
878 ),
879 };
880 let encoded = msg.encode().expect("encode should succeed");
881 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
882
883 assert_eq!(decoded.request_id, 2);
884 if let ReplicationMessageBody::FreshReplicationResponse(
885 FreshReplicationResponse::Accepted { key },
886 ) = decoded.body
887 {
888 assert_eq!(key, [0xBB; 32]);
889 } else {
890 panic!("expected FreshReplicationResponse::Accepted");
891 }
892 }
893
894 #[test]
895 fn fresh_replication_response_rejected_roundtrip() {
896 let msg = ReplicationMessage {
897 request_id: 3,
898 body: ReplicationMessageBody::FreshReplicationResponse(
899 FreshReplicationResponse::Rejected {
900 key: [0xCC; 32],
901 reason: "out of range".to_string(),
902 },
903 ),
904 };
905 let encoded = msg.encode().expect("encode should succeed");
906 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
907
908 assert_eq!(decoded.request_id, 3);
909 if let ReplicationMessageBody::FreshReplicationResponse(
910 FreshReplicationResponse::Rejected { key, reason },
911 ) = decoded.body
912 {
913 assert_eq!(key, [0xCC; 32]);
914 assert_eq!(reason, "out of range");
915 } else {
916 panic!("expected FreshReplicationResponse::Rejected");
917 }
918 }
919
920 #[test]
923 fn paid_notify_roundtrip() {
924 let msg = ReplicationMessage {
925 request_id: 4,
926 body: ReplicationMessageBody::PaidNotify(PaidNotify {
927 key: [0xDD; 32],
928 proof_of_payment: vec![99, 100],
929 }),
930 };
931 let encoded = msg.encode().expect("encode should succeed");
932 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
933
934 assert_eq!(decoded.request_id, 4);
935 if let ReplicationMessageBody::PaidNotify(notify) = decoded.body {
936 assert_eq!(notify.key, [0xDD; 32]);
937 assert_eq!(notify.proof_of_payment, vec![99, 100]);
938 } else {
939 panic!("expected PaidNotify");
940 }
941 }
942
943 #[test]
959 fn old_decoder_tolerates_new_neighbor_sync_request() {
960 use serde::Deserialize;
961 #[derive(Deserialize)]
962 struct OldNeighborSyncRequest {
963 #[allow(dead_code)]
964 pub replica_hints: Vec<XorName>,
965 #[allow(dead_code)]
966 pub paid_hints: Vec<XorName>,
967 #[allow(dead_code)]
968 pub bootstrapping: bool,
969 }
970
971 let new_req = NeighborSyncRequest {
972 replica_hints: vec![[0x01; 32], [0x02; 32]],
973 paid_hints: vec![[0x03; 32]],
974 bootstrapping: true,
975 commitment: None,
976 };
977 let encoded = postcard::to_stdvec(&new_req).expect("encode");
978 let old_decoded: OldNeighborSyncRequest =
979 postcard::from_bytes(&encoded).expect("old decoder accepts");
980 assert_eq!(old_decoded.replica_hints.len(), 2);
983 assert_eq!(old_decoded.paid_hints.len(), 1);
984 assert!(old_decoded.bootstrapping);
985 }
986
987 #[test]
989 fn old_decoder_tolerates_new_neighbor_sync_response() {
990 use serde::Deserialize;
991 #[derive(Deserialize)]
992 struct OldNeighborSyncResponse {
993 #[allow(dead_code)]
994 pub replica_hints: Vec<XorName>,
995 #[allow(dead_code)]
996 pub paid_hints: Vec<XorName>,
997 #[allow(dead_code)]
998 pub bootstrapping: bool,
999 #[allow(dead_code)]
1000 pub rejected_keys: Vec<XorName>,
1001 }
1002
1003 let new_resp = NeighborSyncResponse {
1004 replica_hints: vec![[0x04; 32]],
1005 paid_hints: vec![],
1006 bootstrapping: false,
1007 rejected_keys: vec![[0x05; 32]],
1008 commitment: None,
1009 };
1010 let encoded = postcard::to_stdvec(&new_resp).expect("encode");
1011 let old_decoded: OldNeighborSyncResponse =
1012 postcard::from_bytes(&encoded).expect("old decoder accepts");
1013 assert_eq!(old_decoded.replica_hints.len(), 1);
1014 assert_eq!(old_decoded.rejected_keys.len(), 1);
1015 }
1016
1017 #[test]
1021 fn new_peer_roundtrips_with_commitment_some() {
1022 use crate::replication::commitment::{sign_commitment, StorageCommitment};
1023 use saorsa_pqc::api::sig::ml_dsa_65;
1024
1025 let (pk, sk) = ml_dsa_65().generate_keypair().expect("keygen");
1026 let root = [0x7Fu8; 32];
1027 let sender = [0xCCu8; 32];
1028 let pk_bytes = pk.to_bytes();
1029 let sig = sign_commitment(&sk, &root, 3, &sender, &pk_bytes).expect("sign");
1030 let commitment = StorageCommitment {
1031 root,
1032 key_count: 3,
1033 sender_peer_id: sender,
1034 sender_public_key: pk_bytes,
1035 signature: sig,
1036 };
1037
1038 let req = NeighborSyncRequest {
1039 replica_hints: vec![[0x01; 32]],
1040 paid_hints: vec![],
1041 bootstrapping: false,
1042 commitment: Some(commitment.clone()),
1043 };
1044 let encoded = postcard::to_stdvec(&req).expect("encode");
1045 let decoded: NeighborSyncRequest = postcard::from_bytes(&encoded).expect("new decoder");
1046 assert_eq!(decoded.commitment, Some(commitment));
1047 }
1048
1049 #[test]
1050 fn neighbor_sync_request_roundtrip() {
1051 let msg = ReplicationMessage {
1052 request_id: 5,
1053 body: ReplicationMessageBody::NeighborSyncRequest(NeighborSyncRequest {
1054 replica_hints: vec![[0x01; 32], [0x02; 32]],
1055 paid_hints: vec![[0x03; 32]],
1056 bootstrapping: true,
1057 commitment: None,
1058 }),
1059 };
1060 let encoded = msg.encode().expect("encode should succeed");
1061 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1062
1063 assert_eq!(decoded.request_id, 5);
1064 if let ReplicationMessageBody::NeighborSyncRequest(req) = decoded.body {
1065 assert_eq!(req.replica_hints.len(), 2);
1066 assert_eq!(req.paid_hints.len(), 1);
1067 assert!(req.bootstrapping);
1068 } else {
1069 panic!("expected NeighborSyncRequest");
1070 }
1071 }
1072
1073 #[test]
1074 fn neighbor_sync_response_roundtrip() {
1075 let msg = ReplicationMessage {
1076 request_id: 6,
1077 body: ReplicationMessageBody::NeighborSyncResponse(NeighborSyncResponse {
1078 replica_hints: vec![[0x04; 32]],
1079 paid_hints: vec![],
1080 bootstrapping: false,
1081 rejected_keys: vec![[0x05; 32], [0x06; 32]],
1082 commitment: None,
1083 }),
1084 };
1085 let encoded = msg.encode().expect("encode should succeed");
1086 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1087
1088 assert_eq!(decoded.request_id, 6);
1089 if let ReplicationMessageBody::NeighborSyncResponse(resp) = decoded.body {
1090 assert_eq!(resp.replica_hints.len(), 1);
1091 assert!(resp.paid_hints.is_empty());
1092 assert!(!resp.bootstrapping);
1093 assert_eq!(resp.rejected_keys.len(), 2);
1094 } else {
1095 panic!("expected NeighborSyncResponse");
1096 }
1097 }
1098
1099 #[test]
1102 fn verification_request_roundtrip() {
1103 let msg = ReplicationMessage {
1104 request_id: 7,
1105 body: ReplicationMessageBody::VerificationRequest(VerificationRequest {
1106 keys: vec![[0x10; 32], [0x20; 32], [0x30; 32]],
1107 paid_list_check_indices: vec![0, 2],
1108 }),
1109 };
1110 let encoded = msg.encode().expect("encode should succeed");
1111 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1112
1113 assert_eq!(decoded.request_id, 7);
1114 if let ReplicationMessageBody::VerificationRequest(req) = decoded.body {
1115 assert_eq!(req.keys.len(), 3);
1116 assert_eq!(req.paid_list_check_indices, vec![0, 2]);
1117 } else {
1118 panic!("expected VerificationRequest");
1119 }
1120 }
1121
1122 #[test]
1123 fn verification_response_roundtrip() {
1124 let results = vec![
1125 KeyVerificationResult {
1126 key: [0x10; 32],
1127 present: true,
1128 paid: Some(true),
1129 },
1130 KeyVerificationResult {
1131 key: [0x20; 32],
1132 present: false,
1133 paid: None,
1134 },
1135 KeyVerificationResult {
1136 key: [0x30; 32],
1137 present: true,
1138 paid: Some(false),
1139 },
1140 ];
1141 let msg = ReplicationMessage {
1142 request_id: 8,
1143 body: ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
1144 };
1145 let encoded = msg.encode().expect("encode should succeed");
1146 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1147
1148 assert_eq!(decoded.request_id, 8);
1149 if let ReplicationMessageBody::VerificationResponse(resp) = decoded.body {
1150 assert_eq!(resp.results.len(), 3);
1151 assert!(resp.results[0].present);
1152 assert_eq!(resp.results[0].paid, Some(true));
1153 assert!(!resp.results[1].present);
1154 assert_eq!(resp.results[1].paid, None);
1155 assert!(resp.results[2].present);
1156 assert_eq!(resp.results[2].paid, Some(false));
1157 } else {
1158 panic!("expected VerificationResponse");
1159 }
1160 }
1161
1162 #[test]
1165 fn fetch_request_roundtrip() {
1166 let msg = ReplicationMessage {
1167 request_id: 9,
1168 body: ReplicationMessageBody::FetchRequest(FetchRequest { key: [0x40; 32] }),
1169 };
1170 let encoded = msg.encode().expect("encode should succeed");
1171 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1172
1173 assert_eq!(decoded.request_id, 9);
1174 if let ReplicationMessageBody::FetchRequest(req) = decoded.body {
1175 assert_eq!(req.key, [0x40; 32]);
1176 } else {
1177 panic!("expected FetchRequest");
1178 }
1179 }
1180
1181 #[test]
1182 fn fetch_response_success_roundtrip() {
1183 let msg = ReplicationMessage {
1184 request_id: 10,
1185 body: ReplicationMessageBody::FetchResponse(FetchResponse::Success {
1186 key: [0x50; 32],
1187 data: vec![7, 8, 9],
1188 }),
1189 };
1190 let encoded = msg.encode().expect("encode should succeed");
1191 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1192
1193 assert_eq!(decoded.request_id, 10);
1194 if let ReplicationMessageBody::FetchResponse(FetchResponse::Success { key, data }) =
1195 decoded.body
1196 {
1197 assert_eq!(key, [0x50; 32]);
1198 assert_eq!(data, vec![7, 8, 9]);
1199 } else {
1200 panic!("expected FetchResponse::Success");
1201 }
1202 }
1203
1204 #[test]
1205 fn fetch_response_not_found_roundtrip() {
1206 let msg = ReplicationMessage {
1207 request_id: 11,
1208 body: ReplicationMessageBody::FetchResponse(FetchResponse::NotFound {
1209 key: [0x60; 32],
1210 }),
1211 };
1212 let encoded = msg.encode().expect("encode should succeed");
1213 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1214
1215 assert_eq!(decoded.request_id, 11);
1216 if let ReplicationMessageBody::FetchResponse(FetchResponse::NotFound { key }) = decoded.body
1217 {
1218 assert_eq!(key, [0x60; 32]);
1219 } else {
1220 panic!("expected FetchResponse::NotFound");
1221 }
1222 }
1223
1224 #[test]
1225 fn fetch_response_error_roundtrip() {
1226 let msg = ReplicationMessage {
1227 request_id: 12,
1228 body: ReplicationMessageBody::FetchResponse(FetchResponse::Error {
1229 key: [0x70; 32],
1230 reason: "disk full".to_string(),
1231 }),
1232 };
1233 let encoded = msg.encode().expect("encode should succeed");
1234 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1235
1236 assert_eq!(decoded.request_id, 12);
1237 if let ReplicationMessageBody::FetchResponse(FetchResponse::Error { key, reason }) =
1238 decoded.body
1239 {
1240 assert_eq!(key, [0x70; 32]);
1241 assert_eq!(reason, "disk full");
1242 } else {
1243 panic!("expected FetchResponse::Error");
1244 }
1245 }
1246
1247 #[test]
1250 fn audit_challenge_roundtrip() {
1251 let msg = ReplicationMessage {
1252 request_id: 13,
1253 body: ReplicationMessageBody::AuditChallenge(AuditChallenge {
1254 challenge_id: 999,
1255 nonce: [0xAB; 32],
1256 challenged_peer_id: [0xCD; 32],
1257 keys: vec![[0x01; 32], [0x02; 32]],
1258 }),
1259 };
1260 let encoded = msg.encode().expect("encode should succeed");
1261 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1262
1263 assert_eq!(decoded.request_id, 13);
1264 if let ReplicationMessageBody::AuditChallenge(challenge) = decoded.body {
1265 assert_eq!(challenge.challenge_id, 999);
1266 assert_eq!(challenge.nonce, [0xAB; 32]);
1267 assert_eq!(challenge.challenged_peer_id, [0xCD; 32]);
1268 assert_eq!(challenge.keys.len(), 2);
1269 } else {
1270 panic!("expected AuditChallenge");
1271 }
1272 }
1273
1274 #[test]
1275 fn audit_response_digests_roundtrip() {
1276 let digests = vec![[0x11; 32], ABSENT_KEY_DIGEST];
1277 let msg = ReplicationMessage {
1278 request_id: 14,
1279 body: ReplicationMessageBody::AuditResponse(AuditResponse::Digests {
1280 challenge_id: 999,
1281 digests: digests.clone(),
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, 14);
1288 if let ReplicationMessageBody::AuditResponse(AuditResponse::Digests {
1289 challenge_id,
1290 digests: decoded_digests,
1291 }) = decoded.body
1292 {
1293 assert_eq!(challenge_id, 999);
1294 assert_eq!(decoded_digests, digests);
1295 } else {
1296 panic!("expected AuditResponse::Digests");
1297 }
1298 }
1299
1300 #[test]
1301 fn audit_response_bootstrapping_roundtrip() {
1302 let msg = ReplicationMessage {
1303 request_id: 15,
1304 body: ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping {
1305 challenge_id: 42,
1306 }),
1307 };
1308 let encoded = msg.encode().expect("encode should succeed");
1309 let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1310
1311 assert_eq!(decoded.request_id, 15);
1312 if let ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping {
1313 challenge_id,
1314 }) = decoded.body
1315 {
1316 assert_eq!(challenge_id, 42);
1317 } else {
1318 panic!("expected AuditResponse::Bootstrapping");
1319 }
1320 }
1321
1322 #[test]
1325 fn decode_rejects_oversized_payload() {
1326 let oversized = vec![0u8; MAX_REPLICATION_MESSAGE_SIZE + 1];
1327 let result = ReplicationMessage::decode(&oversized);
1328 assert!(result.is_err());
1329 let err = result.unwrap_err();
1330 assert!(
1331 matches!(err, ReplicationProtocolError::MessageTooLarge { .. }),
1332 "expected MessageTooLarge, got {err:?}"
1333 );
1334 }
1335
1336 #[test]
1337 fn encode_rejects_oversized_message() {
1338 let msg = ReplicationMessage {
1340 request_id: 0,
1341 body: ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
1342 key: [0; 32],
1343 data: vec![0xFF; MAX_REPLICATION_MESSAGE_SIZE],
1344 proof_of_payment: vec![],
1345 }),
1346 };
1347 let result = msg.encode();
1348 assert!(result.is_err());
1349 let err = result.unwrap_err();
1350 assert!(
1351 matches!(err, ReplicationProtocolError::MessageTooLarge { .. }),
1352 "expected MessageTooLarge, got {err:?}"
1353 );
1354 }
1355
1356 #[test]
1359 fn decode_rejects_invalid_data() {
1360 let invalid = vec![0xFF, 0xFF, 0xFF];
1361 let result = ReplicationMessage::decode(&invalid);
1362 assert!(result.is_err());
1363 let err = result.unwrap_err();
1364 assert!(
1365 matches!(err, ReplicationProtocolError::DeserializationFailed(_)),
1366 "expected DeserializationFailed, got {err:?}"
1367 );
1368 }
1369
1370 #[test]
1373 fn audit_digest_is_deterministic() {
1374 let nonce = [0x01; 32];
1375 let peer_id = [0x02; 32];
1376 let key: XorName = [0x03; 32];
1377 let record_bytes = b"hello world";
1378
1379 let digest_a = compute_audit_digest(&nonce, &peer_id, &key, record_bytes);
1380 let digest_b = compute_audit_digest(&nonce, &peer_id, &key, record_bytes);
1381
1382 assert_eq!(digest_a, digest_b, "same inputs must produce same digest");
1383 }
1384
1385 #[test]
1386 fn audit_digest_differs_with_different_nonce() {
1387 let peer_id = [0x02; 32];
1388 let key: XorName = [0x03; 32];
1389 let record_bytes = b"hello world";
1390
1391 let digest_a = compute_audit_digest(&[0x01; 32], &peer_id, &key, record_bytes);
1392 let digest_b = compute_audit_digest(&[0xFF; 32], &peer_id, &key, record_bytes);
1393
1394 assert_ne!(
1395 digest_a, digest_b,
1396 "different nonces must produce different digests"
1397 );
1398 }
1399
1400 #[test]
1401 fn audit_digest_differs_with_different_data() {
1402 let nonce = [0x01; 32];
1403 let peer_id = [0x02; 32];
1404 let key: XorName = [0x03; 32];
1405
1406 let digest_a = compute_audit_digest(&nonce, &peer_id, &key, b"data-A");
1407 let digest_b = compute_audit_digest(&nonce, &peer_id, &key, b"data-B");
1408
1409 assert_ne!(
1410 digest_a, digest_b,
1411 "different data must produce different digests"
1412 );
1413 }
1414
1415 #[test]
1416 fn audit_digest_differs_with_different_peer() {
1417 let nonce = [0x01; 32];
1418 let key: XorName = [0x03; 32];
1419 let record_bytes = b"hello";
1420
1421 let digest_a = compute_audit_digest(&nonce, &[0x02; 32], &key, record_bytes);
1422 let digest_b = compute_audit_digest(&nonce, &[0xFF; 32], &key, record_bytes);
1423
1424 assert_ne!(
1425 digest_a, digest_b,
1426 "different peer IDs must produce different digests"
1427 );
1428 }
1429
1430 #[test]
1431 fn audit_digest_differs_with_different_key() {
1432 let nonce = [0x01; 32];
1433 let peer_id = [0x02; 32];
1434 let record_bytes = b"hello";
1435
1436 let digest_a = compute_audit_digest(&nonce, &peer_id, &[0x03; 32], record_bytes);
1437 let digest_b = compute_audit_digest(&nonce, &peer_id, &[0xFF; 32], record_bytes);
1438
1439 assert_ne!(
1440 digest_a, digest_b,
1441 "different keys must produce different digests"
1442 );
1443 }
1444
1445 #[test]
1448 fn absent_key_digest_is_all_zeros() {
1449 assert_eq!(ABSENT_KEY_DIGEST, [0u8; 32]);
1450 }
1451
1452 #[test]
1453 fn real_digest_differs_from_absent_sentinel() {
1454 let nonce = [0x01; 32];
1455 let peer_id = [0x02; 32];
1456 let key: XorName = [0x03; 32];
1457 let record_bytes = b"non-empty data";
1458
1459 let digest = compute_audit_digest(&nonce, &peer_id, &key, record_bytes);
1460 assert_ne!(
1461 digest, ABSENT_KEY_DIGEST,
1462 "a real digest should not collide with the all-zeros sentinel"
1463 );
1464 }
1465
1466 #[test]
1469 fn error_display_serialization_failed() {
1470 let err = ReplicationProtocolError::SerializationFailed("boom".to_string());
1471 assert_eq!(err.to_string(), "replication serialization failed: boom");
1472 }
1473
1474 #[test]
1475 fn error_display_deserialization_failed() {
1476 let err = ReplicationProtocolError::DeserializationFailed("bad data".to_string());
1477 assert_eq!(
1478 err.to_string(),
1479 "replication deserialization failed: bad data"
1480 );
1481 }
1482
1483 #[test]
1484 fn error_display_message_too_large() {
1485 let err = ReplicationProtocolError::MessageTooLarge {
1486 size: 20_000_000,
1487 max_size: MAX_REPLICATION_MESSAGE_SIZE,
1488 };
1489 let display = err.to_string();
1490 assert!(display.contains("20000000"));
1491 assert!(display.contains(&MAX_REPLICATION_MESSAGE_SIZE.to_string()));
1492 }
1493}