Skip to main content

ant_node/replication/
protocol.rs

1//! Wire protocol messages for the replication subsystem.
2//!
3//! All messages use postcard serialization for compact, fast encoding.
4//! Peer IDs are transmitted as raw `[u8; 32]` byte arrays.
5
6use 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
14/// Sentinel digest value indicating the challenged key is absent from storage.
15///
16/// Used in [`AuditResponse::Digests`] for keys the peer does not hold.
17pub const ABSENT_KEY_DIGEST: [u8; 32] = [0u8; 32];
18
19// ---------------------------------------------------------------------------
20// Top-level envelope
21// ---------------------------------------------------------------------------
22
23/// Top-level replication message envelope.
24///
25/// Every replication wire message carries a sender-assigned `request_id` so
26/// that the receiver can correlate responses without relying on transport-layer
27/// ordering.
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct ReplicationMessage {
30    /// Sender-assigned request ID for correlation.
31    pub request_id: u64,
32    /// The message body.
33    pub body: ReplicationMessageBody,
34}
35
36impl ReplicationMessage {
37    /// Encode the message to bytes using postcard.
38    ///
39    /// # Errors
40    ///
41    /// Returns [`ReplicationProtocolError::SerializationFailed`] if postcard
42    /// serialization fails.
43    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        // V2-623: cumulative per-variant tx accounting. Every replication send
55        // funnels through here, so this is the single tx choke point.
56        record_tx(&self.body, bytes.len());
57
58        Ok(bytes)
59    }
60
61    /// Decode a message from bytes using postcard.
62    ///
63    /// Rejects payloads larger than [`MAX_REPLICATION_MESSAGE_SIZE`] before
64    /// attempting deserialization.
65    ///
66    /// # Errors
67    ///
68    /// Returns [`ReplicationProtocolError::MessageTooLarge`] if the input
69    /// exceeds the size limit, or
70    /// [`ReplicationProtocolError::DeserializationFailed`] if postcard cannot
71    /// parse the data.
72    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        // V2-623: cumulative per-variant rx accounting. Every replication
83        // receive funnels through here, so this is the single rx choke point.
84        record_rx(&message.body, data.len());
85
86        Ok(message)
87    }
88}
89
90// ---------------------------------------------------------------------------
91// Message body enum
92// ---------------------------------------------------------------------------
93
94/// All replication protocol message types.
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub enum ReplicationMessageBody {
97    // === Fresh Replication (Section 6.1) ===
98    /// Fresh replication offer with `PoP` (sent to close group members).
99    FreshReplicationOffer(FreshReplicationOffer),
100    /// Response to a fresh replication offer.
101    FreshReplicationResponse(FreshReplicationResponse),
102
103    /// Paid-list notification with `PoP` (sent to `PaidCloseGroup` members).
104    PaidNotify(PaidNotify),
105
106    // === Neighbor Sync (Section 6.2) ===
107    /// Neighbor sync hint exchange (bidirectional).
108    NeighborSyncRequest(NeighborSyncRequest),
109    /// Response to neighbor sync with own hints.
110    NeighborSyncResponse(NeighborSyncResponse),
111
112    // === Verification (Section 9) ===
113    /// Batched verification request (presence + paid-list queries).
114    VerificationRequest(VerificationRequest),
115    /// Response to verification request with per-key evidence.
116    VerificationResponse(VerificationResponse),
117
118    // === Fetch (record retrieval) ===
119    /// Request to fetch a record by key.
120    FetchRequest(FetchRequest),
121    /// Response with the record data.
122    FetchResponse(FetchResponse),
123
124    // === Responsible-chunk audit (per-key digests) ===
125    /// Per-key audit challenge: used by the responsible-chunk audit and the
126    /// prune-confirmation path.
127    AuditChallenge(AuditChallenge),
128    /// Response to a per-key audit challenge.
129    AuditResponse(AuditResponse),
130
131    // === Storage-bound subtree audit (ADR-0002) ===
132    /// Gossip-triggered contiguous-subtree storage audit challenge (round 1).
133    SubtreeAuditChallenge(SubtreeAuditChallenge),
134    /// Response to a contiguous-subtree storage audit challenge (round 1).
135    SubtreeAuditResponse(SubtreeAuditResponse),
136    /// Surprise byte challenge for the spot-checked leaves (round 2).
137    SubtreeByteChallenge(SubtreeByteChallenge),
138    /// Response carrying the requested chunks' original bytes (round 2).
139    SubtreeByteResponse(SubtreeByteResponse),
140
141    // === Commitment fetch by pin (ADR-0004) ===
142    // APPENDED at the end so postcard variant discriminants of all the
143    // pre-existing variants are unchanged — old nodes keep decoding every
144    // message they already understood; only these two new indices are unknown
145    // to them (and they never receive them, since old nodes never send the
146    // matching request).
147    /// Fetch a retained commitment by its pin (ADR-0004): used to resolve a
148    /// quote's `commitment_pin` when the sidecar is absent and the gossip cache
149    /// has no fresh copy.
150    GetCommitmentByPin(GetCommitmentByPin),
151    /// Response to [`Self::GetCommitmentByPin`].
152    GetCommitmentByPinResponse(GetCommitmentByPinResponse),
153}
154
155// ---------------------------------------------------------------------------
156// Cumulative per-variant traffic accounting (V2-623)
157// ---------------------------------------------------------------------------
158//
159// Process-global relaxed-atomic counter table, indexed by variant. The
160// encode/decode choke points bump these on every replication tx/rx; a periodic
161// task in the replication engine emits them as `replication traffic summary
162// (cumulative)` INFO lines. Values are monotonic since process start — rates
163// are computed as deltas at query time, so a dropped/delayed log line cannot
164// corrupt the data.
165//
166// A process-global static (rather than engine-owned state) is used because the
167// encode/decode call sites are free functions scattered across the replication
168// modules that do not carry any shared engine handle.
169
170/// Number of [`ReplicationMessageBody`] variants (the counter-table width).
171const 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    /// Stable counter-table index for this variant.
184    ///
185    /// Matches declaration order. The last two variants were deliberately
186    /// appended (see the enum comment) so this order is postcard-stable.
187    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
210/// Record an encoded (tx) replication message against its variant.
211fn 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
217/// Record a decoded (rx) replication message against its variant.
218fn 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
224/// Emit the cumulative per-variant replication traffic as INFO summary lines
225/// (V2-623), target `ant_node::replication::traffic`.
226///
227/// The fields are flat snake-case keys (`<stem>_tx_bytes`, `<stem>_rx_count`,
228/// …) so the telegraf→Elasticsearch pipeline lifts each into a first-class
229/// `tail.*` field and the acceptance query (`max` per field per hour → delta)
230/// yields per-variant MB/h directly.
231///
232/// 17 variants × 4 fields = 68 flat keys. `tracing` caps an event at 32 fields,
233/// so the keys are split across three lines that share the same `target` and
234/// message and are distinguished by a `group` field — telegraf still lifts
235/// every key into its own ES field, so the split is transparent at query time.
236pub(crate) fn log_traffic_summary() {
237    // Relaxed loads — a slightly skewed read across counters is fine because
238    // rates are computed as deltas over many intervals at query time.
239    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// ---------------------------------------------------------------------------
298// Fresh Replication Messages
299// ---------------------------------------------------------------------------
300
301/// Fresh replication offer (includes record + `PoP`).
302///
303/// Sent to close-group members when a node receives a new chunk via client PUT.
304#[derive(Debug, Clone, Serialize, Deserialize)]
305pub struct FreshReplicationOffer {
306    /// The record key.
307    pub key: XorName,
308    /// The record data.
309    pub data: Vec<u8>,
310    /// Proof of Payment (required, validated by receiver).
311    pub proof_of_payment: Vec<u8>,
312}
313
314/// Response to a fresh replication offer.
315#[derive(Debug, Clone, Serialize, Deserialize)]
316pub enum FreshReplicationResponse {
317    /// Record accepted and stored.
318    Accepted {
319        /// The accepted record key.
320        key: XorName,
321    },
322    /// Record rejected (with reason).
323    Rejected {
324        /// The rejected record key.
325        key: XorName,
326        /// Human-readable rejection reason.
327        reason: String,
328    },
329}
330
331/// Paid-list notification carrying key + `PoP` (Section 7.3).
332///
333/// Sent to `PaidCloseGroup` members so they record the key in their
334/// `PaidForList` without needing to hold the record data.
335#[derive(Debug, Clone, Serialize, Deserialize)]
336pub struct PaidNotify {
337    /// The record key.
338    pub key: XorName,
339    /// Proof of Payment for receiver-side verification.
340    pub proof_of_payment: Vec<u8>,
341}
342
343// ---------------------------------------------------------------------------
344// Neighbor Sync Messages
345// ---------------------------------------------------------------------------
346
347/// Neighbor sync request carrying hint sets (Section 6.2).
348///
349/// Exchanged between close neighbors to detect and repair missing replicas.
350#[derive(Debug, Clone, Serialize, Deserialize)]
351pub struct NeighborSyncRequest {
352    /// Keys sender believes receiver should hold (replica hints).
353    pub replica_hints: Vec<XorName>,
354    /// Keys sender believes receiver should track in `PaidForList` (paid hints).
355    pub paid_hints: Vec<XorName>,
356    /// Whether sender is currently bootstrapping.
357    pub bootstrapping: bool,
358    /// Sender's signed storage commitment (optional, see
359    /// [`crate::replication::commitment`]). `None` from old peers; from
360    /// new peers this carries the Merkle-root commitment over the
361    /// sender's claimed keys. Receivers that recognize it store it as
362    /// the per-peer "last known commitment" used to pin commitment-bound
363    /// audits.
364    #[serde(default)]
365    pub commitment: Option<crate::replication::commitment::StorageCommitment>,
366}
367
368/// Neighbor sync response carrying own hint sets.
369#[derive(Debug, Clone, Serialize, Deserialize)]
370pub struct NeighborSyncResponse {
371    /// Keys receiver believes sender should hold (replica hints).
372    pub replica_hints: Vec<XorName>,
373    /// Keys receiver believes sender should track in `PaidForList` (paid hints).
374    pub paid_hints: Vec<XorName>,
375    /// Whether receiver is currently bootstrapping.
376    pub bootstrapping: bool,
377    /// Keys that receiver rejected (optional feedback to sender).
378    pub rejected_keys: Vec<XorName>,
379    /// Receiver's signed storage commitment (optional, see
380    /// [`NeighborSyncRequest::commitment`]).
381    #[serde(default)]
382    pub commitment: Option<crate::replication::commitment::StorageCommitment>,
383}
384
385// ---------------------------------------------------------------------------
386// Verification Messages
387// ---------------------------------------------------------------------------
388
389/// Batched verification request for multiple keys (Section 9).
390///
391/// Sent to peers in `VerifyTargets` (union of `QuorumTargets` and
392/// `PaidTargets`). Each peer returns per-key presence and optionally
393/// paid-list status.
394#[derive(Debug, Clone, Serialize, Deserialize)]
395pub struct VerificationRequest {
396    /// Keys to verify (batched).
397    pub keys: Vec<XorName>,
398    /// Which keys need paid-list status in addition to presence.
399    /// Each value is an index into the `keys` vector.
400    pub paid_list_check_indices: Vec<u32>,
401}
402
403/// Per-key verification result from a peer.
404#[derive(Debug, Clone, Serialize, Deserialize)]
405pub struct KeyVerificationResult {
406    /// The key being verified.
407    pub key: XorName,
408    /// Whether this peer holds the record.
409    pub present: bool,
410    /// Paid-list status (only set if peer was asked for paid-list check).
411    ///
412    /// - `Some(true)` -- key is in peer's `PaidForList`.
413    /// - `Some(false)` -- key is NOT in peer's `PaidForList`.
414    /// - `None` -- paid-list check was not requested for this key.
415    pub paid: Option<bool>,
416}
417
418/// Batched verification response with per-key results.
419#[derive(Debug, Clone, Serialize, Deserialize)]
420pub struct VerificationResponse {
421    /// Per-key results (one per requested key, in request order).
422    pub results: Vec<KeyVerificationResult>,
423}
424
425// ---------------------------------------------------------------------------
426// Fetch Messages
427// ---------------------------------------------------------------------------
428
429/// Request to fetch a specific record by key.
430#[derive(Debug, Clone, Serialize, Deserialize)]
431pub struct FetchRequest {
432    /// The key of the record to fetch.
433    pub key: XorName,
434}
435
436/// Response to a fetch request.
437#[derive(Debug, Clone, Serialize, Deserialize)]
438pub enum FetchResponse {
439    /// Record found and returned.
440    Success {
441        /// The record key.
442        key: XorName,
443        /// The record data.
444        data: Vec<u8>,
445    },
446    /// Record not found on this peer.
447    NotFound {
448        /// The requested key.
449        key: XorName,
450    },
451    /// Error during fetch.
452    Error {
453        /// The requested key.
454        key: XorName,
455        /// Human-readable error description.
456        reason: String,
457    },
458}
459
460// ---------------------------------------------------------------------------
461// Commitment fetch by pin (ADR-0004)
462// ---------------------------------------------------------------------------
463
464/// Request a retained commitment by its pin (commitment hash).
465///
466/// ADR-0004: a storer cross-checking a quote whose `commitment_pin` it does not
467/// already hold (no sidecar, no fresh gossip copy) fetches the signed
468/// commitment so it can verify the binding and route the commitment into audit.
469/// The responder answers only from its retained set, so this never forces a
470/// node to reconstruct or re-sign anything.
471#[derive(Debug, Clone, Serialize, Deserialize)]
472pub struct GetCommitmentByPin {
473    /// The commitment hash (pin) being resolved.
474    pub pin: [u8; 32],
475}
476
477/// Response to [`GetCommitmentByPin`].
478#[derive(Debug, Clone, Serialize, Deserialize)]
479pub enum GetCommitmentByPinResponse {
480    /// The pin resolved to a retained, signed commitment.
481    Found {
482        /// The signed commitment matching the requested pin. The fetcher
483        /// re-verifies its signature and peer binding before trusting it.
484        commitment: crate::replication::commitment::StorageCommitment,
485    },
486    /// The pin is not among the responder's retained commitments (rotated/aged
487    /// out, or never held). ADR-0004 treats this as graced, never confirmed:
488    /// an unanswerable pin is indistinguishable from an honest crash-restart.
489    NotRetained {
490        /// Echo of the requested pin, for matching.
491        pin: [u8; 32],
492    },
493}
494
495// ---------------------------------------------------------------------------
496// Audit Messages
497// ---------------------------------------------------------------------------
498
499/// Per-key audit challenge.
500///
501/// The challenger picks a random nonce and a set of keys the challenged peer
502/// should hold, then sends this challenge. The challenged peer proves storage
503/// by returning per-key BLAKE3 digests. Used by the responsible-chunk audit
504/// (audit #2: a node samples keys a close peer should hold) and by the
505/// prune-confirmation path (a node checks a peer still holds a key before
506/// pruning its own copy).
507#[derive(Debug, Clone, Serialize, Deserialize)]
508pub struct AuditChallenge {
509    /// Unique challenge identifier.
510    pub challenge_id: u64,
511    /// Random nonce for digest computation.
512    pub nonce: [u8; 32],
513    /// Challenged peer ID (included in digest computation).
514    pub challenged_peer_id: [u8; 32],
515    /// Ordered list of keys to prove storage of.
516    pub keys: Vec<XorName>,
517}
518
519/// Response to a per-key audit challenge.
520#[derive(Debug, Clone, Serialize, Deserialize)]
521pub enum AuditResponse {
522    /// Per-key digests proving storage.
523    ///
524    /// `digests[i]` corresponds to `challenge.keys[i]`.
525    /// An [`ABSENT_KEY_DIGEST`] sentinel signals key absence.
526    Digests {
527        /// The challenge this response answers.
528        challenge_id: u64,
529        /// One 32-byte digest per challenged key, in challenge order.
530        digests: Vec<[u8; 32]>,
531    },
532    /// Peer is still bootstrapping (not ready for audit).
533    Bootstrapping {
534        /// The challenge this response answers.
535        challenge_id: u64,
536    },
537    /// Challenge rejected (wrong target peer or too many keys).
538    ///
539    /// Distinct from empty `Digests` so the challenger can distinguish a
540    /// legitimate rejection from misbehavior.
541    Rejected {
542        /// The challenge this response answers.
543        challenge_id: u64,
544        /// Human-readable rejection reason.
545        reason: String,
546    },
547}
548
549/// Gossip-triggered contiguous-subtree storage audit challenge (ADR-0002).
550///
551/// The auditor pins the commitment a peer just gossiped and sends a fresh
552/// random nonce. The nonce alone deterministically selects one contiguous
553/// subtree of the peer's committed Merkle tree (see
554/// [`crate::replication::subtree::select_subtree_path`]); the auditor does
555/// **not** name keys. The responder must reply with a
556/// [`SubtreeAuditResponse::Proof`] for that selected subtree against the pinned
557/// commitment, or a [`SubtreeAuditResponse::Rejected`] if it genuinely cannot
558/// (for a recently gossiped pinned commitment a rejection is a confirmed
559/// failure, since the responder retains its last two gossiped commitments).
560#[derive(Debug, Clone, Serialize, Deserialize)]
561pub struct SubtreeAuditChallenge {
562    /// Unique challenge identifier.
563    pub challenge_id: u64,
564    /// Random nonce. Selects the subtree AND freshens each leaf's possession
565    /// hash, so a stored answer cannot be replayed.
566    pub nonce: [u8; 32],
567    /// Challenged peer ID. Bound into each leaf's possession hash.
568    pub challenged_peer_id: [u8; 32],
569    /// The auditor's pin: the [`crate::replication::commitment::commitment_hash`]
570    /// of the commitment the peer just gossiped. The response's commitment must
571    /// hash to exactly this value.
572    pub expected_commitment_hash: [u8; 32],
573}
574
575/// Response to a contiguous-subtree storage audit challenge (ADR-0002).
576#[derive(Debug, Clone, Serialize, Deserialize)]
577pub enum SubtreeAuditResponse {
578    /// The single-contiguous-subtree proof.
579    ///
580    /// Carries the responder's signed commitment (so the auditor re-derives
581    /// `key_count` and confirms the pin and signature) and the
582    /// nonce-selected subtree expanded to its leaves plus the sibling
583    /// cut-hashes on the path to the root. This is **round 1** of the
584    /// two-round audit. The auditor:
585    ///   1. confirms `commitment_hash(commitment) == expected_commitment_hash`
586    ///      and the signature is valid;
587    ///   2. re-derives the selected subtree from `(nonce, key_count)`, rebuilds
588    ///      the root from the proof, and requires it to equal the commitment
589    ///      root (structure).
590    ///
591    /// The leaves carry only hashes (`bytes_hash`, `nonced_hash`), so this round
592    /// proves the tree SHAPE is committed — not that the bytes are still held.
593    /// Real possession is proven in **round 2**: the auditor picks a few of the
594    /// just-verified leaves and sends a [`SubtreeByteChallenge`] requesting their
595    /// original chunk bytes FROM the responder (see that type).
596    Proof {
597        /// The challenge this response answers.
598        challenge_id: u64,
599        /// The signed commitment whose root the proof is against.
600        commitment: crate::replication::commitment::StorageCommitment,
601        /// The nonce-selected contiguous subtree proof.
602        proof: crate::replication::subtree::SubtreeProof,
603    },
604    /// Peer is still bootstrapping (not ready for audit).
605    Bootstrapping {
606        /// The challenge this response answers.
607        challenge_id: u64,
608    },
609    /// Challenge rejected. `kind` drives the auditor's accounting (confirmed vs
610    /// graced); `reason` is the human-readable detail for logs.
611    Rejected {
612        /// The challenge this response answers.
613        challenge_id: u64,
614        /// Machine-readable rejection class (accounting).
615        kind: RejectKind,
616        /// Human-readable rejection reason.
617        reason: String,
618    },
619}
620
621/// Why a responder rejected an audit challenge, in a form the auditor can act
622/// on without string-matching.
623///
624/// ADR-0004 Amendment 1: audit **grace is removed**. Answerability is now
625/// restart-durable (the responder persists and reloads its commitment retention)
626/// and the auditor only pins roots inside the answerability window, so an honest
627/// node can always answer a pin it could be challenged on. The auditor therefore
628/// grades a responsive rejection purely by kind, with no grace:
629/// - `UnknownCommitment` / `Protocol` → **confirmed failure**: repudiating a
630///   pinned root the node published (and may have been paid for), or an explicit
631///   protocol fault.
632/// - `Transient` → routed to the **non-response/timeout lane** (no trust penalty,
633///   but the holder credit for the pinned commitment IS revoked). The responder
634///   retries reads before emitting `Transient`, so one that still reaches the
635///   auditor means the node could not serve data it committed to. A
636///   `Transient`-spammer thus gains no positive standing; deterministically
637///   distinguishing malicious from genuine transient IO network-wide is the
638///   out-of-scope distributed non-response problem.
639#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
640pub enum RejectKind {
641    /// The responder does not retain the pinned commitment. With restart-durable
642    /// retention and in-window auditing this is provable repudiation of a root
643    /// the node published → CONFIRMED failure.
644    UnknownCommitment,
645    /// A transient, recoverable local condition (e.g. a storage read error),
646    /// emitted only after the responder's read retries failed. Routed to the
647    /// timeout lane (holder credit revoked, no trust penalty).
648    Transient,
649    /// Any other rejection (wrong target peer, no commitment state, malformed
650    /// proof plan, oversized byte challenge, …). CONFIRMED failure.
651    Protocol,
652}
653
654/// Round 2 of the storage audit (ADR-0002): the **surprise byte challenge**.
655///
656/// After the auditor has structurally verified a [`SubtreeAuditResponse::Proof`]
657/// it picks a small sample of that subtree's just-proven leaves with FRESH
658/// randomness (chosen now, after the proof is committed — NOT derived from the
659/// round-1 nonce, so the responder could not have predicted it at proof-build
660/// time) and asks the responder to return the ORIGINAL chunk bytes for exactly
661/// those keys. The auditor then checks each returned chunk against the committed
662/// leaf:
663///   - `BLAKE3(bytes) == leaf.bytes_hash` (the chunk's content address), AND
664///   - `compute_audit_digest(nonce, peer, key, bytes) == leaf.nonced_hash`.
665///
666/// This makes possession non-delegable to the auditor: the auditor needs to
667/// hold NONE of the responder's chunks. A responder that committed to a chunk it
668/// no longer holds cannot fabricate bytes that hash to the committed address (a
669/// preimage break), so it is caught regardless of who audits it.
670#[derive(Debug, Clone, Serialize, Deserialize)]
671pub struct SubtreeByteChallenge {
672    /// The same `challenge_id` as the round-1 [`SubtreeAuditChallenge`], so the
673    /// responder/auditor correlate the two rounds.
674    pub challenge_id: u64,
675    /// The same nonce as round 1 — needed for the freshness (`nonced_hash`)
676    /// check and to bind these bytes to this audit.
677    pub nonce: [u8; 32],
678    /// The challenged peer ID (bound into each leaf's possession hash).
679    pub challenged_peer_id: [u8; 32],
680    /// The pinned commitment hash from round 1, so the responder resolves the
681    /// SAME tree it just proved and serves bytes only for keys it committed to.
682    pub expected_commitment_hash: [u8; 32],
683    /// The exact keys whose original bytes the responder must return. These are
684    /// the auditor's freshly-randomised spot-check sample of the round-1 subtree
685    /// (chosen after the proof was received; not nonce-derived).
686    pub keys: Vec<XorName>,
687}
688
689/// One requested chunk in a [`SubtreeByteResponse`].
690#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
691pub enum SubtreeByteItem {
692    /// The responder holds this committed key and returns its original bytes.
693    Present {
694        /// The requested key.
695        key: XorName,
696        /// The original chunk bytes (the auditor re-hashes to verify).
697        bytes: Vec<u8>,
698    },
699    /// The responder committed to this key but cannot serve its bytes. This is a
700    /// PROVABLE cheat (it published a commitment over a chunk it does not hold),
701    /// so the auditor counts it as a confirmed failure — NOT a graced timeout.
702    /// Distinguishing this explicit signal from silence is what separates a
703    /// deleter (instant fail) from a dropped packet (timeout).
704    Absent {
705        /// The committed key the responder could not serve.
706        key: XorName,
707    },
708}
709
710/// Response to a [`SubtreeByteChallenge`] (round 2). One item per requested key,
711/// in the requested order.
712///
713/// Sizing rule: a challenge carries at most
714/// [`MAX_BYTE_CHALLENGE_KEYS`](super::config::MAX_BYTE_CHALLENGE_KEYS) keys —
715/// the auditor batches its sample, the responder rejects larger requests — so
716/// the WORST-CASE `Items` response (every chunk at `MAX_CHUNK_SIZE`) always
717/// encodes under [`MAX_REPLICATION_MESSAGE_SIZE`].
718#[derive(Debug, Clone, Serialize, Deserialize)]
719pub enum SubtreeByteResponse {
720    /// The responder's per-key answers (bytes or an explicit absent signal).
721    Items {
722        /// The challenge this response answers.
723        challenge_id: u64,
724        /// One entry per requested key.
725        items: Vec<SubtreeByteItem>,
726    },
727    /// Peer is still bootstrapping (should not happen mid-audit, but handled).
728    Bootstrapping {
729        /// The challenge this response answers.
730        challenge_id: u64,
731    },
732    /// The responder rejects the byte challenge outright. `kind` drives the
733    /// auditor's accounting (ADR-0004 A1: grace removed): [`RejectKind::Transient`]
734    /// routes to the timeout lane (no trust penalty, holder credit revoked); every
735    /// other kind is a confirmed failure, like round 1.
736    Rejected {
737        /// The challenge this response answers.
738        challenge_id: u64,
739        /// Machine-readable rejection class (accounting).
740        kind: RejectKind,
741        /// Human-readable rejection reason.
742        reason: String,
743    },
744}
745
746// ---------------------------------------------------------------------------
747// Audit digest helper
748// ---------------------------------------------------------------------------
749
750/// Compute `AuditKeyDigest(K_i) = BLAKE3(nonce || challenged_peer_id || K_i || record_bytes_i)`.
751///
752/// Returns the 32-byte BLAKE3 digest binding the nonce, peer identity, key,
753/// and record content together so a peer cannot forge proofs without holding
754/// the actual data.
755#[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// ---------------------------------------------------------------------------
771// Error type
772// ---------------------------------------------------------------------------
773
774/// Errors from replication protocol encode/decode operations.
775#[derive(Debug, Clone)]
776pub enum ReplicationProtocolError {
777    /// Postcard serialization failed.
778    SerializationFailed(String),
779    /// Postcard deserialization failed.
780    DeserializationFailed(String),
781    /// Wire message exceeds the maximum allowed size.
782    MessageTooLarge {
783        /// Actual size of the message in bytes.
784        size: usize,
785        /// Maximum allowed size.
786        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// ---------------------------------------------------------------------------
812// Tests
813// ---------------------------------------------------------------------------
814
815#[cfg(test)]
816#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
817mod tests {
818    use super::*;
819
820    // === Round-2 byte response sizing ===
821
822    #[test]
823    fn max_batch_worst_case_byte_response_fits_wire_cap() {
824        // The auditor batches its round-2 sample to MAX_BYTE_CHALLENGE_KEYS per
825        // challenge precisely so this worst case — every requested chunk at
826        // MAX_CHUNK_SIZE — still encodes. If this fails, honest responders
827        // would hit encode errors and fail otherwise valid byte challenges.
828        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    // === Fresh Replication roundtrip ===
848
849    #[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    // === PaidNotify roundtrip ===
921
922    #[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    // === Neighbor Sync roundtrips ===
944
945    // -- backwards compat across the wire-type extension --------------------
946
947    /// Backwards-compat: an old peer that has the v0 layout of
948    /// `NeighborSyncRequest` (no `commitment` field) can still decode a
949    /// message encoded by a new peer that emits `commitment: None`. This
950    /// is the realistic mixed-version case during rollout: new peers
951    /// gossip with the field; old peers must not crash.
952    ///
953    /// The check works because postcard's [`from_bytes`] is lenient on
954    /// trailing bytes — the old decoder reads what it knows about and
955    /// stops, the new fields are silently ignored. This test pins that
956    /// invariant so any future codec/library swap that breaks it is
957    /// caught immediately.
958    #[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        // Field-by-field check would fail if old peer misaligned on the
981        // length prefix — passing decode is the structural check.
982        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    /// Same property for `NeighborSyncResponse`.
988    #[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    /// Roundtrip: a new peer can decode its own message including the
1018    /// commitment field. Catches accidental serde annotation breakage
1019    /// (e.g. forgetting `#[serde(default)]` on the new field).
1020    #[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    // === Verification roundtrips ===
1100
1101    #[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    // === Fetch roundtrips ===
1163
1164    #[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    // === Audit roundtrips ===
1248
1249    #[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    // === Oversized message rejection ===
1323
1324    #[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        // Build a message whose serialized form exceeds the limit.
1339        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    // === Invalid data rejection ===
1357
1358    #[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    // === Audit digest computation ===
1371
1372    #[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    // === Absent key digest sentinel ===
1446
1447    #[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    // === Error Display ===
1467
1468    #[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}