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 parking_lot::RwLock;
9use saorsa_core::identity::PeerId;
10use serde::{Deserialize, Serialize};
11
12use crate::ant_protocol::XorName;
13
14pub use super::config::MAX_REPLICATION_MESSAGE_SIZE;
15
16/// Sentinel digest value indicating the challenged key is absent from storage.
17///
18/// Used in [`AuditResponse::Digests`] for keys the peer does not hold.
19pub const ABSENT_KEY_DIGEST: [u8; 32] = [0u8; 32];
20
21// ---------------------------------------------------------------------------
22// Top-level envelope
23// ---------------------------------------------------------------------------
24
25/// Top-level replication message envelope.
26///
27/// Every replication wire message carries a sender-assigned `request_id` so
28/// that the receiver can correlate responses without relying on transport-layer
29/// ordering.
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct ReplicationMessage {
32    /// Sender-assigned request ID for correlation.
33    pub request_id: u64,
34    /// The message body.
35    pub body: ReplicationMessageBody,
36}
37
38impl ReplicationMessage {
39    /// Encode the message to bytes using postcard.
40    ///
41    /// # Errors
42    ///
43    /// Returns [`ReplicationProtocolError::SerializationFailed`] if postcard
44    /// serialization fails.
45    pub fn encode(&self) -> Result<Vec<u8>, ReplicationProtocolError> {
46        let bytes = postcard::to_stdvec(self)
47            .map_err(|e| ReplicationProtocolError::SerializationFailed(e.to_string()))?;
48
49        if bytes.len() > MAX_REPLICATION_MESSAGE_SIZE {
50            return Err(ReplicationProtocolError::MessageTooLarge {
51                size: bytes.len(),
52                max_size: MAX_REPLICATION_MESSAGE_SIZE,
53            });
54        }
55
56        // V2-623: cumulative per-variant tx accounting. Every replication send
57        // funnels through here, so this is the single tx choke point.
58        record_tx(&self.body, bytes.len());
59
60        Ok(bytes)
61    }
62
63    /// Decode a message from bytes using postcard.
64    ///
65    /// Rejects payloads larger than [`MAX_REPLICATION_MESSAGE_SIZE`] before
66    /// attempting deserialization.
67    ///
68    /// # Errors
69    ///
70    /// Returns [`ReplicationProtocolError::MessageTooLarge`] if the input
71    /// exceeds the size limit, or
72    /// [`ReplicationProtocolError::DeserializationFailed`] if postcard cannot
73    /// parse the data.
74    pub fn decode(data: &[u8]) -> Result<Self, ReplicationProtocolError> {
75        if data.len() > MAX_REPLICATION_MESSAGE_SIZE {
76            return Err(ReplicationProtocolError::MessageTooLarge {
77                size: data.len(),
78                max_size: MAX_REPLICATION_MESSAGE_SIZE,
79            });
80        }
81        let message: Self = postcard::from_bytes(data)
82            .map_err(|e| ReplicationProtocolError::DeserializationFailed(e.to_string()))?;
83
84        // V2-623: cumulative per-variant rx accounting. Every replication
85        // receive funnels through here, so this is the single rx choke point.
86        record_rx(&message.body, data.len());
87
88        Ok(message)
89    }
90}
91
92// ---------------------------------------------------------------------------
93// Message body enum
94// ---------------------------------------------------------------------------
95
96/// All replication protocol message types.
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub enum ReplicationMessageBody {
99    // === Fresh Replication (Section 6.1) ===
100    /// Fresh replication offer with `PoP` (sent to close group members).
101    FreshReplicationOffer(FreshReplicationOffer),
102    /// Response to a fresh replication offer.
103    FreshReplicationResponse(FreshReplicationResponse),
104
105    /// Paid-list notification with `PoP` (sent to `PaidCloseGroup` members).
106    PaidNotify(PaidNotify),
107
108    // === Neighbor Sync (Section 6.2) ===
109    /// Neighbor sync hint exchange (bidirectional).
110    NeighborSyncRequest(NeighborSyncRequest),
111    /// Response to neighbor sync with own hints.
112    NeighborSyncResponse(NeighborSyncResponse),
113
114    // === Verification (Section 9) ===
115    /// Batched verification request (presence + paid-list queries).
116    VerificationRequest(VerificationRequest),
117    /// Response to verification request with per-key evidence.
118    VerificationResponse(VerificationResponse),
119
120    // === Fetch (record retrieval) ===
121    /// Request to fetch a record by key.
122    FetchRequest(FetchRequest),
123    /// Response with the record data.
124    FetchResponse(FetchResponse),
125
126    // === Responsible-chunk audit (per-key digests) ===
127    /// Per-key audit challenge: used by the responsible-chunk audit and the
128    /// prune-confirmation path.
129    AuditChallenge(AuditChallenge),
130    /// Response to a per-key audit challenge.
131    AuditResponse(AuditResponse),
132
133    // === Storage-bound subtree audit (ADR-0002) ===
134    /// Gossip-triggered contiguous-subtree storage audit challenge (round 1).
135    SubtreeAuditChallenge(SubtreeAuditChallenge),
136    /// Response to a contiguous-subtree storage audit challenge (round 1).
137    SubtreeAuditResponse(SubtreeAuditResponse),
138    /// Surprise byte challenge for the spot-checked leaves (round 2).
139    SubtreeByteChallenge(SubtreeByteChallenge),
140    /// Response carrying the requested chunks' original bytes (round 2).
141    SubtreeByteResponse(SubtreeByteResponse),
142
143    // === Commitment fetch by pin (ADR-0004) ===
144    // APPENDED at the end so postcard variant discriminants of all the
145    // pre-existing variants are unchanged — old nodes keep decoding every
146    // message they already understood; only these two new indices are unknown
147    // to them (and they never receive them, since old nodes never send the
148    // matching request).
149    /// Fetch a retained commitment by its pin (ADR-0004): used to resolve a
150    /// quote's `commitment_pin` when the sidecar is absent and the gossip cache
151    /// has no fresh copy.
152    GetCommitmentByPin(GetCommitmentByPin),
153    /// Response to [`Self::GetCommitmentByPin`].
154    GetCommitmentByPinResponse(GetCommitmentByPinResponse),
155}
156
157// ---------------------------------------------------------------------------
158// Cumulative per-variant traffic accounting (V2-623)
159// ---------------------------------------------------------------------------
160//
161// Process-global relaxed-atomic counter table, indexed by variant. The
162// encode/decode choke points bump these on every replication tx/rx; a periodic
163// task in the replication engine emits them as `replication traffic summary
164// (cumulative)` INFO lines. Values are monotonic since process start — rates
165// are computed as deltas at query time, so a dropped/delayed log line cannot
166// corrupt the data.
167//
168// A process-global static (rather than engine-owned state) is used because the
169// encode/decode call sites are free functions scattered across the replication
170// modules that do not carry any shared engine handle.
171
172/// Number of [`ReplicationMessageBody`] variants (the counter-table width).
173const N_REPLICATION_VARIANTS: usize = 17;
174
175static REPL_TX_BYTES: [AtomicU64; N_REPLICATION_VARIANTS] =
176    [const { AtomicU64::new(0) }; N_REPLICATION_VARIANTS];
177static REPL_TX_COUNT: [AtomicU64; N_REPLICATION_VARIANTS] =
178    [const { AtomicU64::new(0) }; N_REPLICATION_VARIANTS];
179static REPL_RX_BYTES: [AtomicU64; N_REPLICATION_VARIANTS] =
180    [const { AtomicU64::new(0) }; N_REPLICATION_VARIANTS];
181static REPL_RX_COUNT: [AtomicU64; N_REPLICATION_VARIANTS] =
182    [const { AtomicU64::new(0) }; N_REPLICATION_VARIANTS];
183
184impl ReplicationMessageBody {
185    /// Stable counter-table index for this variant.
186    ///
187    /// Matches declaration order. The last two variants were deliberately
188    /// appended (see the enum comment) so this order is postcard-stable.
189    pub(crate) fn variant_index(&self) -> usize {
190        match self {
191            Self::FreshReplicationOffer(_) => 0,
192            Self::FreshReplicationResponse(_) => 1,
193            Self::PaidNotify(_) => 2,
194            Self::NeighborSyncRequest(_) => 3,
195            Self::NeighborSyncResponse(_) => 4,
196            Self::VerificationRequest(_) => 5,
197            Self::VerificationResponse(_) => 6,
198            Self::FetchRequest(_) => 7,
199            Self::FetchResponse(_) => 8,
200            Self::AuditChallenge(_) => 9,
201            Self::AuditResponse(_) => 10,
202            Self::SubtreeAuditChallenge(_) => 11,
203            Self::SubtreeAuditResponse(_) => 12,
204            Self::SubtreeByteChallenge(_) => 13,
205            Self::SubtreeByteResponse(_) => 14,
206            Self::GetCommitmentByPin(_) => 15,
207            Self::GetCommitmentByPinResponse(_) => 16,
208        }
209    }
210}
211
212/// Record an encoded (tx) replication message against its variant.
213fn record_tx(body: &ReplicationMessageBody, bytes: usize) {
214    let i = body.variant_index();
215    REPL_TX_BYTES[i].fetch_add(bytes as u64, Ordering::Relaxed);
216    REPL_TX_COUNT[i].fetch_add(1, Ordering::Relaxed);
217}
218
219/// Record a decoded (rx) replication message against its variant.
220fn record_rx(body: &ReplicationMessageBody, bytes: usize) {
221    let i = body.variant_index();
222    REPL_RX_BYTES[i].fetch_add(bytes as u64, Ordering::Relaxed);
223    REPL_RX_COUNT[i].fetch_add(1, Ordering::Relaxed);
224}
225
226/// Emit the cumulative per-variant replication traffic as INFO summary lines
227/// (V2-623), target `ant_node::replication::traffic`.
228///
229/// The fields are flat snake-case keys (`<stem>_tx_bytes`, `<stem>_rx_count`,
230/// …) so the telegraf→Elasticsearch pipeline lifts each into a first-class
231/// `tail.*` field and the acceptance query (`max` per field per hour → delta)
232/// yields per-variant MB/h directly.
233///
234/// 17 variants × 4 fields = 68 flat keys. `tracing` caps an event at 32 fields,
235/// so the keys are split across three lines that share the same `target` and
236/// message and are distinguished by a `group` field — telegraf still lifts
237/// every key into its own ES field, so the split is transparent at query time.
238pub(crate) fn log_traffic_summary() {
239    // Relaxed loads — a slightly skewed read across counters is fine because
240    // rates are computed as deltas over many intervals at query time.
241    let tb = |i: usize| REPL_TX_BYTES[i].load(Ordering::Relaxed);
242    let tc = |i: usize| REPL_TX_COUNT[i].load(Ordering::Relaxed);
243    let rb = |i: usize| REPL_RX_BYTES[i].load(Ordering::Relaxed);
244    let rc = |i: usize| REPL_RX_COUNT[i].load(Ordering::Relaxed);
245
246    crate::logging::info!(
247        target: "ant_node::replication::traffic",
248        group = 1,
249        fresh_offer_tx_bytes = tb(0), fresh_offer_tx_count = tc(0),
250        fresh_offer_rx_bytes = rb(0), fresh_offer_rx_count = rc(0),
251        fresh_response_tx_bytes = tb(1), fresh_response_tx_count = tc(1),
252        fresh_response_rx_bytes = rb(1), fresh_response_rx_count = rc(1),
253        paid_notify_tx_bytes = tb(2), paid_notify_tx_count = tc(2),
254        paid_notify_rx_bytes = rb(2), paid_notify_rx_count = rc(2),
255        neighbor_sync_request_tx_bytes = tb(3), neighbor_sync_request_tx_count = tc(3),
256        neighbor_sync_request_rx_bytes = rb(3), neighbor_sync_request_rx_count = rc(3),
257        neighbor_sync_response_tx_bytes = tb(4), neighbor_sync_response_tx_count = tc(4),
258        neighbor_sync_response_rx_bytes = rb(4), neighbor_sync_response_rx_count = rc(4),
259        verification_request_tx_bytes = tb(5), verification_request_tx_count = tc(5),
260        verification_request_rx_bytes = rb(5), verification_request_rx_count = rc(5),
261        "replication traffic summary (cumulative)"
262    );
263    crate::logging::info!(
264        target: "ant_node::replication::traffic",
265        group = 2,
266        verification_response_tx_bytes = tb(6), verification_response_tx_count = tc(6),
267        verification_response_rx_bytes = rb(6), verification_response_rx_count = rc(6),
268        fetch_request_tx_bytes = tb(7), fetch_request_tx_count = tc(7),
269        fetch_request_rx_bytes = rb(7), fetch_request_rx_count = rc(7),
270        fetch_response_tx_bytes = tb(8), fetch_response_tx_count = tc(8),
271        fetch_response_rx_bytes = rb(8), fetch_response_rx_count = rc(8),
272        audit_challenge_tx_bytes = tb(9), audit_challenge_tx_count = tc(9),
273        audit_challenge_rx_bytes = rb(9), audit_challenge_rx_count = rc(9),
274        audit_response_tx_bytes = tb(10), audit_response_tx_count = tc(10),
275        audit_response_rx_bytes = rb(10), audit_response_rx_count = rc(10),
276        subtree_audit_challenge_tx_bytes = tb(11), subtree_audit_challenge_tx_count = tc(11),
277        subtree_audit_challenge_rx_bytes = rb(11), subtree_audit_challenge_rx_count = rc(11),
278        "replication traffic summary (cumulative)"
279    );
280    crate::logging::info!(
281        target: "ant_node::replication::traffic",
282        group = 3,
283        subtree_audit_response_tx_bytes = tb(12), subtree_audit_response_tx_count = tc(12),
284        subtree_audit_response_rx_bytes = rb(12), subtree_audit_response_rx_count = rc(12),
285        subtree_byte_challenge_tx_bytes = tb(13), subtree_byte_challenge_tx_count = tc(13),
286        subtree_byte_challenge_rx_bytes = rb(13), subtree_byte_challenge_rx_count = rc(13),
287        subtree_byte_response_tx_bytes = tb(14), subtree_byte_response_tx_count = tc(14),
288        subtree_byte_response_rx_bytes = rb(14), subtree_byte_response_rx_count = rc(14),
289        get_commitment_by_pin_tx_bytes = tb(15), get_commitment_by_pin_tx_count = tc(15),
290        get_commitment_by_pin_rx_bytes = rb(15), get_commitment_by_pin_rx_count = rc(15),
291        get_commitment_by_pin_response_tx_bytes = tb(16),
292        get_commitment_by_pin_response_tx_count = tc(16),
293        get_commitment_by_pin_response_rx_bytes = rb(16),
294        get_commitment_by_pin_response_rx_count = rc(16),
295        "replication traffic summary (cumulative)"
296    );
297}
298
299// ---------------------------------------------------------------------------
300// Per-peer served-bytes accounting (V2-684)
301// ---------------------------------------------------------------------------
302//
303// Follow-up to V2-623: the per-variant table above says how many bytes each
304// message type served, but not WHICH peers pulled them. This adds per-peer
305// attribution for the heavy serve paths (`FetchResponse`, `SubtreeByteResponse`,
306// `NeighborSyncResponse` — ~99% of served bytes), emitted as a top-10-by-bytes
307// INFO line on the same cadence and target as `log_traffic_summary`.
308//
309// Design (mirrors V2-623's process-global-static choice for the same reason —
310// the serve choke point is a free function with no engine handle):
311//
312//   * A bounded, sharded table caps memory at `SERVED_SHARDS * SERVED_SHARD_CAP`
313//     peers total.
314//   * The serve hot path takes only a shared read lock on one shard plus two
315//     relaxed `fetch_add`s when the peer is already tracked — no global lock per
316//     response. A previously-unseen peer takes a one-shard write lock (rare).
317//   * Per-shard eviction of the smallest-bytes entry when a shard is full. The
318//     peers that matter are the largest accumulators and are never the minimum,
319//     so they cannot be evicted by transient noise.
320//   * Values are cumulative/monotonic since process start, so a dropped or
321//     delayed log line cannot corrupt query-time deltas.
322
323/// Number of shards in the served-peers table. Peers are assigned by the low
324/// nibble of their first ID byte; peer IDs are hash-random (BLAKE3), so the
325/// distribution across shards is uniform. Must be a power of two.
326const SERVED_SHARDS: usize = 16;
327
328/// Max peers tracked per shard. `SERVED_SHARDS * SERVED_SHARD_CAP` = 256 total.
329const SERVED_SHARD_CAP: usize = 16;
330
331/// Cumulative served counters for a single peer.
332struct PeerServeStats {
333    bytes: AtomicU64,
334    count: AtomicU64,
335}
336
337/// One shard of the served-peers table: a small, cap-bounded list of
338/// `(peer, counters)`. A `Vec` linear-scanned over at most `SERVED_SHARD_CAP`
339/// entries is cheaper than hashing and — unlike `HashMap` — is
340/// const-constructible, so the whole table is a plain `static` with no lazy
341/// initialisation.
342struct ServedShard {
343    entries: RwLock<Vec<(PeerId, PeerServeStats)>>,
344}
345
346impl ServedShard {
347    const fn new() -> Self {
348        Self {
349            entries: RwLock::new(Vec::new()),
350        }
351    }
352}
353
354static SERVED_PEERS: [ServedShard; SERVED_SHARDS] = [const { ServedShard::new() }; SERVED_SHARDS];
355
356/// Cumulative count of peers evicted from the table (bounded-map pressure
357/// indicator; emitted as `evictions`).
358static SERVED_EVICTIONS: AtomicU64 = AtomicU64::new(0);
359
360/// Shard index for a peer: the low `log2(SERVED_SHARDS)` bits of the first ID
361/// byte.
362fn served_shard_index(peer: &PeerId) -> usize {
363    (peer.to_bytes()[0] as usize) & (SERVED_SHARDS - 1)
364}
365
366/// Record `bytes` served to `peer` (V2-684), called from the replication serve
367/// choke point for the heavy response variants.
368///
369/// Fast path (peer already tracked): a shared read lock on one shard plus two
370/// relaxed `fetch_add`s. Slow path (new peer): a one-shard write lock that
371/// inserts the peer and, if the shard is at capacity, first evicts its
372/// smallest-bytes entry.
373pub(crate) fn record_served(peer: &PeerId, bytes: usize) {
374    let shard = &SERVED_PEERS[served_shard_index(peer)];
375    let bytes = bytes as u64;
376
377    // Fast path: peer already present — no structural change, shared lock only.
378    {
379        let guard = shard.entries.read();
380        if let Some((_, stats)) = guard.iter().find(|(p, _)| p == peer) {
381            stats.bytes.fetch_add(bytes, Ordering::Relaxed);
382            stats.count.fetch_add(1, Ordering::Relaxed);
383            return;
384        }
385    }
386
387    // Slow path: insert the new peer. Re-check under the write lock in case a
388    // racing writer added it between our read and write.
389    let mut guard = shard.entries.write();
390    if let Some((_, stats)) = guard.iter().find(|(p, _)| p == peer) {
391        stats.bytes.fetch_add(bytes, Ordering::Relaxed);
392        stats.count.fetch_add(1, Ordering::Relaxed);
393        return;
394    }
395    if guard.len() >= SERVED_SHARD_CAP {
396        // Evict the smallest-bytes entry; the peers we care about are the
397        // largest accumulators and are never the per-shard minimum.
398        if let Some((min_idx, _)) = guard
399            .iter()
400            .enumerate()
401            .min_by_key(|(_, (_, s))| s.bytes.load(Ordering::Relaxed))
402        {
403            guard.swap_remove(min_idx);
404            SERVED_EVICTIONS.fetch_add(1, Ordering::Relaxed);
405        }
406    }
407    guard.push((
408        *peer,
409        PeerServeStats {
410            bytes: AtomicU64::new(bytes),
411            count: AtomicU64::new(1),
412        },
413    ));
414}
415
416/// Emit the cumulative top-K per-peer served-bytes summary (V2-684) as one INFO
417/// line, target `ant_node::replication::traffic`, on the same cadence as
418/// [`log_traffic_summary`].
419///
420/// The top 10 peers × 3 fields + `tracked_peers` + `evictions` = 32 fields,
421/// exactly the `tracing` per-event field cap, so it fits on one line. Peer IDs
422/// are full hex ([`PeerId::to_hex`]), matching the `claiming bootstrap` /
423/// `per-source pending cap` log lines so the two can be joined in Elasticsearch.
424/// Empty slots (fewer than 10 tracked peers) emit an empty id and zero counters
425/// to keep the ES field schema stable.
426pub(crate) fn log_served_peers_summary() {
427    // Snapshot every shard, then rank. Reads are relaxed and short-lived; a
428    // slightly skewed snapshot is fine because values are cumulative and
429    // compared as deltas at query time.
430    let mut all: Vec<(PeerId, u64, u64)> = Vec::new();
431    for shard in &SERVED_PEERS {
432        let guard = shard.entries.read();
433        for (peer, stats) in guard.iter() {
434            all.push((
435                *peer,
436                stats.bytes.load(Ordering::Relaxed),
437                stats.count.load(Ordering::Relaxed),
438            ));
439        }
440    }
441    let tracked_peers = all.len() as u64;
442    let evictions = SERVED_EVICTIONS.load(Ordering::Relaxed);
443
444    // Top-K by bytes served, descending.
445    all.sort_unstable_by_key(|(_, bytes, _)| std::cmp::Reverse(*bytes));
446
447    // Fixed slots keep the emitted field set stable regardless of how many peers
448    // are currently tracked.
449    let id = |n: usize| all.get(n).map(|(p, _, _)| p.to_hex()).unwrap_or_default();
450    let by = |n: usize| all.get(n).map_or(0, |(_, b, _)| *b);
451    let ct = |n: usize| all.get(n).map_or(0, |(_, _, c)| *c);
452
453    crate::logging::info!(
454        target: "ant_node::replication::traffic",
455        peer_1_id = %id(0), peer_1_bytes = by(0), peer_1_count = ct(0),
456        peer_2_id = %id(1), peer_2_bytes = by(1), peer_2_count = ct(1),
457        peer_3_id = %id(2), peer_3_bytes = by(2), peer_3_count = ct(2),
458        peer_4_id = %id(3), peer_4_bytes = by(3), peer_4_count = ct(3),
459        peer_5_id = %id(4), peer_5_bytes = by(4), peer_5_count = ct(4),
460        peer_6_id = %id(5), peer_6_bytes = by(5), peer_6_count = ct(5),
461        peer_7_id = %id(6), peer_7_bytes = by(6), peer_7_count = ct(6),
462        peer_8_id = %id(7), peer_8_bytes = by(7), peer_8_count = ct(7),
463        peer_9_id = %id(8), peer_9_bytes = by(8), peer_9_count = ct(8),
464        peer_10_id = %id(9), peer_10_bytes = by(9), peer_10_count = ct(9),
465        tracked_peers = tracked_peers,
466        evictions = evictions,
467        "replication served-peers summary (cumulative)"
468    );
469}
470
471// ---------------------------------------------------------------------------
472// Fresh Replication Messages
473// ---------------------------------------------------------------------------
474
475/// Fresh replication offer (includes record + `PoP`).
476///
477/// Sent to close-group members when a node receives a new chunk via client PUT.
478#[derive(Debug, Clone, Serialize, Deserialize)]
479pub struct FreshReplicationOffer {
480    /// The record key.
481    pub key: XorName,
482    /// The record data.
483    pub data: Vec<u8>,
484    /// Proof of Payment (required, validated by receiver).
485    pub proof_of_payment: Vec<u8>,
486}
487
488/// Response to a fresh replication offer.
489#[derive(Debug, Clone, Serialize, Deserialize)]
490pub enum FreshReplicationResponse {
491    /// Record accepted and stored.
492    Accepted {
493        /// The accepted record key.
494        key: XorName,
495    },
496    /// Record rejected (with reason).
497    Rejected {
498        /// The rejected record key.
499        key: XorName,
500        /// Human-readable rejection reason.
501        reason: String,
502    },
503}
504
505/// Paid-list notification carrying key + `PoP` (Section 7.3).
506///
507/// Sent to `PaidCloseGroup` members so they record the key in their
508/// `PaidForList` without needing to hold the record data.
509#[derive(Debug, Clone, Serialize, Deserialize)]
510pub struct PaidNotify {
511    /// The record key.
512    pub key: XorName,
513    /// Proof of Payment for receiver-side verification.
514    pub proof_of_payment: Vec<u8>,
515}
516
517// ---------------------------------------------------------------------------
518// Neighbor Sync Messages
519// ---------------------------------------------------------------------------
520
521/// Neighbor sync request carrying hint sets (Section 6.2).
522///
523/// Exchanged between close neighbors to detect and repair missing replicas.
524#[derive(Debug, Clone, Serialize, Deserialize)]
525pub struct NeighborSyncRequest {
526    /// Keys sender believes receiver should hold (replica hints).
527    pub replica_hints: Vec<XorName>,
528    /// Keys sender believes receiver should track in `PaidForList` (paid hints).
529    pub paid_hints: Vec<XorName>,
530    /// Whether sender is currently bootstrapping.
531    pub bootstrapping: bool,
532    /// Sender's signed storage commitment (optional, see
533    /// [`crate::replication::commitment`]). `None` from old peers; from
534    /// new peers this carries the Merkle-root commitment over the
535    /// sender's claimed keys. Receivers that recognize it store it as
536    /// the per-peer "last known commitment" used to pin commitment-bound
537    /// audits.
538    #[serde(default)]
539    pub commitment: Option<crate::replication::commitment::StorageCommitment>,
540}
541
542/// Neighbor sync response carrying own hint sets.
543#[derive(Debug, Clone, Serialize, Deserialize)]
544pub struct NeighborSyncResponse {
545    /// Keys receiver believes sender should hold (replica hints).
546    pub replica_hints: Vec<XorName>,
547    /// Keys receiver believes sender should track in `PaidForList` (paid hints).
548    pub paid_hints: Vec<XorName>,
549    /// Whether receiver is currently bootstrapping.
550    pub bootstrapping: bool,
551    /// Keys that receiver rejected (optional feedback to sender).
552    pub rejected_keys: Vec<XorName>,
553    /// Receiver's signed storage commitment (optional, see
554    /// [`NeighborSyncRequest::commitment`]).
555    #[serde(default)]
556    pub commitment: Option<crate::replication::commitment::StorageCommitment>,
557}
558
559// ---------------------------------------------------------------------------
560// Verification Messages
561// ---------------------------------------------------------------------------
562
563/// Batched verification request for multiple keys (Section 9).
564///
565/// Sent to peers in `VerifyTargets` (union of `QuorumTargets` and
566/// `PaidTargets`). Each peer returns per-key presence and optionally
567/// paid-list status.
568#[derive(Debug, Clone, Serialize, Deserialize)]
569pub struct VerificationRequest {
570    /// Keys to verify (batched).
571    pub keys: Vec<XorName>,
572    /// Which keys need paid-list status in addition to presence.
573    /// Each value is an index into the `keys` vector.
574    pub paid_list_check_indices: Vec<u32>,
575}
576
577/// Per-key verification result from a peer.
578#[derive(Debug, Clone, Serialize, Deserialize)]
579pub struct KeyVerificationResult {
580    /// The key being verified.
581    pub key: XorName,
582    /// Whether this peer holds the record.
583    pub present: bool,
584    /// Paid-list status (only set if peer was asked for paid-list check).
585    ///
586    /// - `Some(true)` -- key is in peer's `PaidForList`.
587    /// - `Some(false)` -- key is NOT in peer's `PaidForList`.
588    /// - `None` -- paid-list check was not requested for this key.
589    pub paid: Option<bool>,
590}
591
592/// Batched verification response with per-key results.
593#[derive(Debug, Clone, Serialize, Deserialize)]
594pub struct VerificationResponse {
595    /// Per-key results (one per requested key, in request order).
596    pub results: Vec<KeyVerificationResult>,
597}
598
599// ---------------------------------------------------------------------------
600// Fetch Messages
601// ---------------------------------------------------------------------------
602
603/// Request to fetch a specific record by key.
604#[derive(Debug, Clone, Serialize, Deserialize)]
605pub struct FetchRequest {
606    /// The key of the record to fetch.
607    pub key: XorName,
608}
609
610/// Response to a fetch request.
611#[derive(Debug, Clone, Serialize, Deserialize)]
612pub enum FetchResponse {
613    /// Record found and returned.
614    Success {
615        /// The record key.
616        key: XorName,
617        /// The record data.
618        data: Vec<u8>,
619    },
620    /// Record not found on this peer.
621    NotFound {
622        /// The requested key.
623        key: XorName,
624    },
625    /// Error during fetch.
626    Error {
627        /// The requested key.
628        key: XorName,
629        /// Human-readable error description.
630        reason: String,
631    },
632}
633
634// ---------------------------------------------------------------------------
635// Commitment fetch by pin (ADR-0004)
636// ---------------------------------------------------------------------------
637
638/// Request a retained commitment by its pin (commitment hash).
639///
640/// ADR-0004: a storer cross-checking a quote whose `commitment_pin` it does not
641/// already hold (no sidecar, no fresh gossip copy) fetches the signed
642/// commitment so it can verify the binding and route the commitment into audit.
643/// The responder answers only from its retained set, so this never forces a
644/// node to reconstruct or re-sign anything.
645#[derive(Debug, Clone, Serialize, Deserialize)]
646pub struct GetCommitmentByPin {
647    /// The commitment hash (pin) being resolved.
648    pub pin: [u8; 32],
649}
650
651/// Response to [`GetCommitmentByPin`].
652#[derive(Debug, Clone, Serialize, Deserialize)]
653pub enum GetCommitmentByPinResponse {
654    /// The pin resolved to a retained, signed commitment.
655    Found {
656        /// The signed commitment matching the requested pin. The fetcher
657        /// re-verifies its signature and peer binding before trusting it.
658        commitment: crate::replication::commitment::StorageCommitment,
659    },
660    /// The pin is not among the responder's retained commitments (rotated/aged
661    /// out, or never held). ADR-0004 treats this as graced, never confirmed:
662    /// an unanswerable pin is indistinguishable from an honest crash-restart.
663    NotRetained {
664        /// Echo of the requested pin, for matching.
665        pin: [u8; 32],
666    },
667}
668
669// ---------------------------------------------------------------------------
670// Audit Messages
671// ---------------------------------------------------------------------------
672
673/// Per-key audit challenge.
674///
675/// The challenger picks a random nonce and a set of keys the challenged peer
676/// should hold, then sends this challenge. The challenged peer proves storage
677/// by returning per-key BLAKE3 digests. Used by the responsible-chunk audit
678/// (audit #2: a node samples keys a close peer should hold) and by the
679/// prune-confirmation path (a node checks a peer still holds a key before
680/// pruning its own copy).
681#[derive(Debug, Clone, Serialize, Deserialize)]
682pub struct AuditChallenge {
683    /// Unique challenge identifier.
684    pub challenge_id: u64,
685    /// Random nonce for digest computation.
686    pub nonce: [u8; 32],
687    /// Challenged peer ID (included in digest computation).
688    pub challenged_peer_id: [u8; 32],
689    /// Ordered list of keys to prove storage of.
690    pub keys: Vec<XorName>,
691}
692
693/// Response to a per-key audit challenge.
694#[derive(Debug, Clone, Serialize, Deserialize)]
695pub enum AuditResponse {
696    /// Per-key digests proving storage.
697    ///
698    /// `digests[i]` corresponds to `challenge.keys[i]`.
699    /// An [`ABSENT_KEY_DIGEST`] sentinel signals key absence.
700    Digests {
701        /// The challenge this response answers.
702        challenge_id: u64,
703        /// One 32-byte digest per challenged key, in challenge order.
704        digests: Vec<[u8; 32]>,
705    },
706    /// Peer is still bootstrapping (not ready for audit).
707    Bootstrapping {
708        /// The challenge this response answers.
709        challenge_id: u64,
710    },
711    /// Challenge rejected (wrong target peer or too many keys).
712    ///
713    /// Distinct from empty `Digests` so the challenger can distinguish a
714    /// legitimate rejection from misbehavior.
715    Rejected {
716        /// The challenge this response answers.
717        challenge_id: u64,
718        /// Human-readable rejection reason.
719        reason: String,
720    },
721}
722
723/// Gossip-triggered contiguous-subtree storage audit challenge (ADR-0002).
724///
725/// The auditor pins the commitment a peer just gossiped and sends a fresh
726/// random nonce. The nonce alone deterministically selects one contiguous
727/// subtree of the peer's committed Merkle tree (see
728/// [`crate::replication::subtree::select_subtree_path`]); the auditor does
729/// **not** name keys. The responder must reply with a
730/// [`SubtreeAuditResponse::Proof`] for that selected subtree against the pinned
731/// commitment, or a [`SubtreeAuditResponse::Rejected`] if it genuinely cannot
732/// (for a recently gossiped pinned commitment a rejection is a confirmed
733/// failure, since the responder retains its last two gossiped commitments).
734#[derive(Debug, Clone, Serialize, Deserialize)]
735pub struct SubtreeAuditChallenge {
736    /// Unique challenge identifier.
737    pub challenge_id: u64,
738    /// Random nonce. Selects the subtree AND freshens each leaf's possession
739    /// hash, so a stored answer cannot be replayed.
740    pub nonce: [u8; 32],
741    /// Challenged peer ID. Bound into each leaf's possession hash.
742    pub challenged_peer_id: [u8; 32],
743    /// The auditor's pin: the [`crate::replication::commitment::commitment_hash`]
744    /// of the commitment the peer just gossiped. The response's commitment must
745    /// hash to exactly this value.
746    pub expected_commitment_hash: [u8; 32],
747}
748
749/// Response to a contiguous-subtree storage audit challenge (ADR-0002).
750#[derive(Debug, Clone, Serialize, Deserialize)]
751pub enum SubtreeAuditResponse {
752    /// The single-contiguous-subtree proof.
753    ///
754    /// Carries the responder's signed commitment (so the auditor re-derives
755    /// `key_count` and confirms the pin and signature) and the
756    /// nonce-selected subtree expanded to its leaves plus the sibling
757    /// cut-hashes on the path to the root. This is **round 1** of the
758    /// two-round audit. The auditor:
759    ///   1. confirms `commitment_hash(commitment) == expected_commitment_hash`
760    ///      and the signature is valid;
761    ///   2. re-derives the selected subtree from `(nonce, key_count)`, rebuilds
762    ///      the root from the proof, and requires it to equal the commitment
763    ///      root (structure).
764    ///
765    /// The leaves carry only hashes (`bytes_hash`, `nonced_hash`), so this round
766    /// proves the tree SHAPE is committed — not that the bytes are still held.
767    /// Real possession is proven in **round 2**: the auditor picks a few of the
768    /// just-verified leaves and sends a [`SubtreeByteChallenge`] requesting their
769    /// original chunk bytes FROM the responder (see that type).
770    Proof {
771        /// The challenge this response answers.
772        challenge_id: u64,
773        /// The signed commitment whose root the proof is against.
774        commitment: crate::replication::commitment::StorageCommitment,
775        /// The nonce-selected contiguous subtree proof.
776        proof: crate::replication::subtree::SubtreeProof,
777    },
778    /// Peer is still bootstrapping (not ready for audit).
779    Bootstrapping {
780        /// The challenge this response answers.
781        challenge_id: u64,
782    },
783    /// Challenge rejected. `kind` drives the auditor's accounting (confirmed vs
784    /// graced); `reason` is the human-readable detail for logs.
785    Rejected {
786        /// The challenge this response answers.
787        challenge_id: u64,
788        /// Machine-readable rejection class (accounting).
789        kind: RejectKind,
790        /// Human-readable rejection reason.
791        reason: String,
792    },
793}
794
795/// Why a responder rejected an audit challenge, in a form the auditor can act
796/// on without string-matching.
797///
798/// ADR-0004 Amendment 1: audit **grace is removed**. Answerability is now
799/// restart-durable (the responder persists and reloads its commitment retention)
800/// and the auditor only pins roots inside the answerability window, so an honest
801/// node can always answer a pin it could be challenged on. The auditor therefore
802/// grades a responsive rejection purely by kind, with no grace:
803/// - `UnknownCommitment` / `Protocol` → **confirmed failure**: repudiating a
804///   pinned root the node published (and may have been paid for), or an explicit
805///   protocol fault.
806/// - `Transient` → routed to the **non-response/timeout lane** (no trust penalty,
807///   but the holder credit for the pinned commitment IS revoked). The responder
808///   retries reads before emitting `Transient`, so one that still reaches the
809///   auditor means the node could not serve data it committed to. A
810///   `Transient`-spammer thus gains no positive standing; deterministically
811///   distinguishing malicious from genuine transient IO network-wide is the
812///   out-of-scope distributed non-response problem.
813#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
814pub enum RejectKind {
815    /// The responder does not retain the pinned commitment. With restart-durable
816    /// retention and in-window auditing this is provable repudiation of a root
817    /// the node published → CONFIRMED failure.
818    UnknownCommitment,
819    /// A transient, recoverable local condition (e.g. a storage read error),
820    /// emitted only after the responder's read retries failed. Routed to the
821    /// timeout lane (holder credit revoked, no trust penalty).
822    Transient,
823    /// Any other rejection (wrong target peer, no commitment state, malformed
824    /// proof plan, oversized byte challenge, …). CONFIRMED failure.
825    Protocol,
826}
827
828/// Round 2 of the storage audit (ADR-0002): the **surprise byte challenge**.
829///
830/// After the auditor has structurally verified a [`SubtreeAuditResponse::Proof`]
831/// it picks a small sample of that subtree's just-proven leaves with FRESH
832/// randomness (chosen now, after the proof is committed — NOT derived from the
833/// round-1 nonce, so the responder could not have predicted it at proof-build
834/// time) and asks the responder to return the ORIGINAL chunk bytes for exactly
835/// those keys. The auditor then checks each returned chunk against the committed
836/// leaf:
837///   - `BLAKE3(bytes) == leaf.bytes_hash` (the chunk's content address), AND
838///   - `compute_audit_digest(nonce, peer, key, bytes) == leaf.nonced_hash`.
839///
840/// This makes possession non-delegable to the auditor: the auditor needs to
841/// hold NONE of the responder's chunks. A responder that committed to a chunk it
842/// no longer holds cannot fabricate bytes that hash to the committed address (a
843/// preimage break), so it is caught regardless of who audits it.
844#[derive(Debug, Clone, Serialize, Deserialize)]
845pub struct SubtreeByteChallenge {
846    /// The same `challenge_id` as the round-1 [`SubtreeAuditChallenge`], so the
847    /// responder/auditor correlate the two rounds.
848    pub challenge_id: u64,
849    /// The same nonce as round 1 — needed for the freshness (`nonced_hash`)
850    /// check and to bind these bytes to this audit.
851    pub nonce: [u8; 32],
852    /// The challenged peer ID (bound into each leaf's possession hash).
853    pub challenged_peer_id: [u8; 32],
854    /// The pinned commitment hash from round 1, so the responder resolves the
855    /// SAME tree it just proved and serves bytes only for keys it committed to.
856    pub expected_commitment_hash: [u8; 32],
857    /// The exact keys whose original bytes the responder must return. These are
858    /// the auditor's freshly-randomised spot-check sample of the round-1 subtree
859    /// (chosen after the proof was received; not nonce-derived).
860    pub keys: Vec<XorName>,
861}
862
863/// One requested chunk in a [`SubtreeByteResponse`].
864#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
865pub enum SubtreeByteItem {
866    /// The responder holds this committed key and returns its original bytes.
867    Present {
868        /// The requested key.
869        key: XorName,
870        /// The original chunk bytes (the auditor re-hashes to verify).
871        bytes: Vec<u8>,
872    },
873    /// The responder committed to this key but cannot serve its bytes. This is a
874    /// PROVABLE cheat (it published a commitment over a chunk it does not hold),
875    /// so the auditor counts it as a confirmed failure — NOT a graced timeout.
876    /// Distinguishing this explicit signal from silence is what separates a
877    /// deleter (instant fail) from a dropped packet (timeout).
878    Absent {
879        /// The committed key the responder could not serve.
880        key: XorName,
881    },
882}
883
884/// Response to a [`SubtreeByteChallenge`] (round 2). One item per requested key,
885/// in the requested order.
886///
887/// Sizing rule: a challenge carries at most
888/// [`MAX_BYTE_CHALLENGE_KEYS`](super::config::MAX_BYTE_CHALLENGE_KEYS) keys —
889/// the auditor batches its sample, the responder rejects larger requests — so
890/// the WORST-CASE `Items` response (every chunk at `MAX_CHUNK_SIZE`) always
891/// encodes under [`MAX_REPLICATION_MESSAGE_SIZE`].
892#[derive(Debug, Clone, Serialize, Deserialize)]
893pub enum SubtreeByteResponse {
894    /// The responder's per-key answers (bytes or an explicit absent signal).
895    Items {
896        /// The challenge this response answers.
897        challenge_id: u64,
898        /// One entry per requested key.
899        items: Vec<SubtreeByteItem>,
900    },
901    /// Peer is still bootstrapping (should not happen mid-audit, but handled).
902    Bootstrapping {
903        /// The challenge this response answers.
904        challenge_id: u64,
905    },
906    /// The responder rejects the byte challenge outright. `kind` drives the
907    /// auditor's accounting (ADR-0004 A1: grace removed): [`RejectKind::Transient`]
908    /// routes to the timeout lane (no trust penalty, holder credit revoked); every
909    /// other kind is a confirmed failure, like round 1.
910    Rejected {
911        /// The challenge this response answers.
912        challenge_id: u64,
913        /// Machine-readable rejection class (accounting).
914        kind: RejectKind,
915        /// Human-readable rejection reason.
916        reason: String,
917    },
918}
919
920// ---------------------------------------------------------------------------
921// Audit digest helper
922// ---------------------------------------------------------------------------
923
924/// Compute `AuditKeyDigest(K_i) = BLAKE3(nonce || challenged_peer_id || K_i || record_bytes_i)`.
925///
926/// Returns the 32-byte BLAKE3 digest binding the nonce, peer identity, key,
927/// and record content together so a peer cannot forge proofs without holding
928/// the actual data.
929#[must_use]
930pub fn compute_audit_digest(
931    nonce: &[u8; 32],
932    challenged_peer_id: &[u8; 32],
933    key: &XorName,
934    record_bytes: &[u8],
935) -> [u8; 32] {
936    let mut hasher = blake3::Hasher::new();
937    hasher.update(nonce);
938    hasher.update(challenged_peer_id);
939    hasher.update(key);
940    hasher.update(record_bytes);
941    *hasher.finalize().as_bytes()
942}
943
944// ---------------------------------------------------------------------------
945// Error type
946// ---------------------------------------------------------------------------
947
948/// Errors from replication protocol encode/decode operations.
949#[derive(Debug, Clone)]
950pub enum ReplicationProtocolError {
951    /// Postcard serialization failed.
952    SerializationFailed(String),
953    /// Postcard deserialization failed.
954    DeserializationFailed(String),
955    /// Wire message exceeds the maximum allowed size.
956    MessageTooLarge {
957        /// Actual size of the message in bytes.
958        size: usize,
959        /// Maximum allowed size.
960        max_size: usize,
961    },
962}
963
964impl std::fmt::Display for ReplicationProtocolError {
965    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
966        match self {
967            Self::SerializationFailed(msg) => {
968                write!(f, "replication serialization failed: {msg}")
969            }
970            Self::DeserializationFailed(msg) => {
971                write!(f, "replication deserialization failed: {msg}")
972            }
973            Self::MessageTooLarge { size, max_size } => {
974                write!(
975                    f,
976                    "replication message size {size} exceeds maximum {max_size}"
977                )
978            }
979        }
980    }
981}
982
983impl std::error::Error for ReplicationProtocolError {}
984
985// ---------------------------------------------------------------------------
986// Tests
987// ---------------------------------------------------------------------------
988
989#[cfg(test)]
990#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
991mod tests {
992    use super::*;
993
994    // === Round-2 byte response sizing ===
995
996    #[test]
997    fn max_batch_worst_case_byte_response_fits_wire_cap() {
998        // The auditor batches its round-2 sample to MAX_BYTE_CHALLENGE_KEYS per
999        // challenge precisely so this worst case — every requested chunk at
1000        // MAX_CHUNK_SIZE — still encodes. If this fails, honest responders
1001        // would hit encode errors and fail otherwise valid byte challenges.
1002        let items: Vec<SubtreeByteItem> = (0..crate::replication::config::MAX_BYTE_CHALLENGE_KEYS)
1003            .map(|i| SubtreeByteItem::Present {
1004                key: [u8::try_from(i).unwrap_or(u8::MAX); 32],
1005                bytes: vec![0xAB; crate::ant_protocol::MAX_CHUNK_SIZE],
1006            })
1007            .collect();
1008        let msg = ReplicationMessage {
1009            request_id: 7,
1010            body: ReplicationMessageBody::SubtreeByteResponse(SubtreeByteResponse::Items {
1011                challenge_id: 7,
1012                items,
1013            }),
1014        };
1015        let encoded = msg
1016            .encode()
1017            .expect("worst-case max-batch byte response must fit the wire cap");
1018        assert!(encoded.len() <= MAX_REPLICATION_MESSAGE_SIZE);
1019    }
1020
1021    // === Fresh Replication roundtrip ===
1022
1023    #[test]
1024    fn fresh_replication_offer_roundtrip() {
1025        let msg = ReplicationMessage {
1026            request_id: 1,
1027            body: ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
1028                key: [0xAA; 32],
1029                data: vec![1, 2, 3, 4, 5],
1030                proof_of_payment: vec![10, 20, 30],
1031            }),
1032        };
1033        let encoded = msg.encode().expect("encode should succeed");
1034        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1035
1036        assert_eq!(decoded.request_id, 1);
1037        if let ReplicationMessageBody::FreshReplicationOffer(offer) = decoded.body {
1038            assert_eq!(offer.key, [0xAA; 32]);
1039            assert_eq!(offer.data, vec![1, 2, 3, 4, 5]);
1040            assert_eq!(offer.proof_of_payment, vec![10, 20, 30]);
1041        } else {
1042            panic!("expected FreshReplicationOffer");
1043        }
1044    }
1045
1046    #[test]
1047    fn fresh_replication_response_accepted_roundtrip() {
1048        let msg = ReplicationMessage {
1049            request_id: 2,
1050            body: ReplicationMessageBody::FreshReplicationResponse(
1051                FreshReplicationResponse::Accepted { key: [0xBB; 32] },
1052            ),
1053        };
1054        let encoded = msg.encode().expect("encode should succeed");
1055        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1056
1057        assert_eq!(decoded.request_id, 2);
1058        if let ReplicationMessageBody::FreshReplicationResponse(
1059            FreshReplicationResponse::Accepted { key },
1060        ) = decoded.body
1061        {
1062            assert_eq!(key, [0xBB; 32]);
1063        } else {
1064            panic!("expected FreshReplicationResponse::Accepted");
1065        }
1066    }
1067
1068    #[test]
1069    fn fresh_replication_response_rejected_roundtrip() {
1070        let msg = ReplicationMessage {
1071            request_id: 3,
1072            body: ReplicationMessageBody::FreshReplicationResponse(
1073                FreshReplicationResponse::Rejected {
1074                    key: [0xCC; 32],
1075                    reason: "out of range".to_string(),
1076                },
1077            ),
1078        };
1079        let encoded = msg.encode().expect("encode should succeed");
1080        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1081
1082        assert_eq!(decoded.request_id, 3);
1083        if let ReplicationMessageBody::FreshReplicationResponse(
1084            FreshReplicationResponse::Rejected { key, reason },
1085        ) = decoded.body
1086        {
1087            assert_eq!(key, [0xCC; 32]);
1088            assert_eq!(reason, "out of range");
1089        } else {
1090            panic!("expected FreshReplicationResponse::Rejected");
1091        }
1092    }
1093
1094    // === PaidNotify roundtrip ===
1095
1096    #[test]
1097    fn paid_notify_roundtrip() {
1098        let msg = ReplicationMessage {
1099            request_id: 4,
1100            body: ReplicationMessageBody::PaidNotify(PaidNotify {
1101                key: [0xDD; 32],
1102                proof_of_payment: vec![99, 100],
1103            }),
1104        };
1105        let encoded = msg.encode().expect("encode should succeed");
1106        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1107
1108        assert_eq!(decoded.request_id, 4);
1109        if let ReplicationMessageBody::PaidNotify(notify) = decoded.body {
1110            assert_eq!(notify.key, [0xDD; 32]);
1111            assert_eq!(notify.proof_of_payment, vec![99, 100]);
1112        } else {
1113            panic!("expected PaidNotify");
1114        }
1115    }
1116
1117    // === Neighbor Sync roundtrips ===
1118
1119    // -- backwards compat across the wire-type extension --------------------
1120
1121    /// Backwards-compat: an old peer that has the v0 layout of
1122    /// `NeighborSyncRequest` (no `commitment` field) can still decode a
1123    /// message encoded by a new peer that emits `commitment: None`. This
1124    /// is the realistic mixed-version case during rollout: new peers
1125    /// gossip with the field; old peers must not crash.
1126    ///
1127    /// The check works because postcard's [`from_bytes`] is lenient on
1128    /// trailing bytes — the old decoder reads what it knows about and
1129    /// stops, the new fields are silently ignored. This test pins that
1130    /// invariant so any future codec/library swap that breaks it is
1131    /// caught immediately.
1132    #[test]
1133    fn old_decoder_tolerates_new_neighbor_sync_request() {
1134        use serde::Deserialize;
1135        #[derive(Deserialize)]
1136        struct OldNeighborSyncRequest {
1137            #[allow(dead_code)]
1138            pub replica_hints: Vec<XorName>,
1139            #[allow(dead_code)]
1140            pub paid_hints: Vec<XorName>,
1141            #[allow(dead_code)]
1142            pub bootstrapping: bool,
1143        }
1144
1145        let new_req = NeighborSyncRequest {
1146            replica_hints: vec![[0x01; 32], [0x02; 32]],
1147            paid_hints: vec![[0x03; 32]],
1148            bootstrapping: true,
1149            commitment: None,
1150        };
1151        let encoded = postcard::to_stdvec(&new_req).expect("encode");
1152        let old_decoded: OldNeighborSyncRequest =
1153            postcard::from_bytes(&encoded).expect("old decoder accepts");
1154        // Field-by-field check would fail if old peer misaligned on the
1155        // length prefix — passing decode is the structural check.
1156        assert_eq!(old_decoded.replica_hints.len(), 2);
1157        assert_eq!(old_decoded.paid_hints.len(), 1);
1158        assert!(old_decoded.bootstrapping);
1159    }
1160
1161    /// Same property for `NeighborSyncResponse`.
1162    #[test]
1163    fn old_decoder_tolerates_new_neighbor_sync_response() {
1164        use serde::Deserialize;
1165        #[derive(Deserialize)]
1166        struct OldNeighborSyncResponse {
1167            #[allow(dead_code)]
1168            pub replica_hints: Vec<XorName>,
1169            #[allow(dead_code)]
1170            pub paid_hints: Vec<XorName>,
1171            #[allow(dead_code)]
1172            pub bootstrapping: bool,
1173            #[allow(dead_code)]
1174            pub rejected_keys: Vec<XorName>,
1175        }
1176
1177        let new_resp = NeighborSyncResponse {
1178            replica_hints: vec![[0x04; 32]],
1179            paid_hints: vec![],
1180            bootstrapping: false,
1181            rejected_keys: vec![[0x05; 32]],
1182            commitment: None,
1183        };
1184        let encoded = postcard::to_stdvec(&new_resp).expect("encode");
1185        let old_decoded: OldNeighborSyncResponse =
1186            postcard::from_bytes(&encoded).expect("old decoder accepts");
1187        assert_eq!(old_decoded.replica_hints.len(), 1);
1188        assert_eq!(old_decoded.rejected_keys.len(), 1);
1189    }
1190
1191    /// Roundtrip: a new peer can decode its own message including the
1192    /// commitment field. Catches accidental serde annotation breakage
1193    /// (e.g. forgetting `#[serde(default)]` on the new field).
1194    #[test]
1195    fn new_peer_roundtrips_with_commitment_some() {
1196        use crate::replication::commitment::{sign_commitment, StorageCommitment};
1197        use saorsa_pqc::api::sig::ml_dsa_65;
1198
1199        let (pk, sk) = ml_dsa_65().generate_keypair().expect("keygen");
1200        let root = [0x7Fu8; 32];
1201        let sender = [0xCCu8; 32];
1202        let pk_bytes = pk.to_bytes();
1203        let sig = sign_commitment(&sk, &root, 3, &sender, &pk_bytes).expect("sign");
1204        let commitment = StorageCommitment {
1205            root,
1206            key_count: 3,
1207            sender_peer_id: sender,
1208            sender_public_key: pk_bytes,
1209            signature: sig,
1210        };
1211
1212        let req = NeighborSyncRequest {
1213            replica_hints: vec![[0x01; 32]],
1214            paid_hints: vec![],
1215            bootstrapping: false,
1216            commitment: Some(commitment.clone()),
1217        };
1218        let encoded = postcard::to_stdvec(&req).expect("encode");
1219        let decoded: NeighborSyncRequest = postcard::from_bytes(&encoded).expect("new decoder");
1220        assert_eq!(decoded.commitment, Some(commitment));
1221    }
1222
1223    #[test]
1224    fn neighbor_sync_request_roundtrip() {
1225        let msg = ReplicationMessage {
1226            request_id: 5,
1227            body: ReplicationMessageBody::NeighborSyncRequest(NeighborSyncRequest {
1228                replica_hints: vec![[0x01; 32], [0x02; 32]],
1229                paid_hints: vec![[0x03; 32]],
1230                bootstrapping: true,
1231                commitment: None,
1232            }),
1233        };
1234        let encoded = msg.encode().expect("encode should succeed");
1235        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1236
1237        assert_eq!(decoded.request_id, 5);
1238        if let ReplicationMessageBody::NeighborSyncRequest(req) = decoded.body {
1239            assert_eq!(req.replica_hints.len(), 2);
1240            assert_eq!(req.paid_hints.len(), 1);
1241            assert!(req.bootstrapping);
1242        } else {
1243            panic!("expected NeighborSyncRequest");
1244        }
1245    }
1246
1247    #[test]
1248    fn neighbor_sync_response_roundtrip() {
1249        let msg = ReplicationMessage {
1250            request_id: 6,
1251            body: ReplicationMessageBody::NeighborSyncResponse(NeighborSyncResponse {
1252                replica_hints: vec![[0x04; 32]],
1253                paid_hints: vec![],
1254                bootstrapping: false,
1255                rejected_keys: vec![[0x05; 32], [0x06; 32]],
1256                commitment: None,
1257            }),
1258        };
1259        let encoded = msg.encode().expect("encode should succeed");
1260        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1261
1262        assert_eq!(decoded.request_id, 6);
1263        if let ReplicationMessageBody::NeighborSyncResponse(resp) = decoded.body {
1264            assert_eq!(resp.replica_hints.len(), 1);
1265            assert!(resp.paid_hints.is_empty());
1266            assert!(!resp.bootstrapping);
1267            assert_eq!(resp.rejected_keys.len(), 2);
1268        } else {
1269            panic!("expected NeighborSyncResponse");
1270        }
1271    }
1272
1273    // === Verification roundtrips ===
1274
1275    #[test]
1276    fn verification_request_roundtrip() {
1277        let msg = ReplicationMessage {
1278            request_id: 7,
1279            body: ReplicationMessageBody::VerificationRequest(VerificationRequest {
1280                keys: vec![[0x10; 32], [0x20; 32], [0x30; 32]],
1281                paid_list_check_indices: vec![0, 2],
1282            }),
1283        };
1284        let encoded = msg.encode().expect("encode should succeed");
1285        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1286
1287        assert_eq!(decoded.request_id, 7);
1288        if let ReplicationMessageBody::VerificationRequest(req) = decoded.body {
1289            assert_eq!(req.keys.len(), 3);
1290            assert_eq!(req.paid_list_check_indices, vec![0, 2]);
1291        } else {
1292            panic!("expected VerificationRequest");
1293        }
1294    }
1295
1296    #[test]
1297    fn verification_response_roundtrip() {
1298        let results = vec![
1299            KeyVerificationResult {
1300                key: [0x10; 32],
1301                present: true,
1302                paid: Some(true),
1303            },
1304            KeyVerificationResult {
1305                key: [0x20; 32],
1306                present: false,
1307                paid: None,
1308            },
1309            KeyVerificationResult {
1310                key: [0x30; 32],
1311                present: true,
1312                paid: Some(false),
1313            },
1314        ];
1315        let msg = ReplicationMessage {
1316            request_id: 8,
1317            body: ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
1318        };
1319        let encoded = msg.encode().expect("encode should succeed");
1320        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1321
1322        assert_eq!(decoded.request_id, 8);
1323        if let ReplicationMessageBody::VerificationResponse(resp) = decoded.body {
1324            assert_eq!(resp.results.len(), 3);
1325            assert!(resp.results[0].present);
1326            assert_eq!(resp.results[0].paid, Some(true));
1327            assert!(!resp.results[1].present);
1328            assert_eq!(resp.results[1].paid, None);
1329            assert!(resp.results[2].present);
1330            assert_eq!(resp.results[2].paid, Some(false));
1331        } else {
1332            panic!("expected VerificationResponse");
1333        }
1334    }
1335
1336    // === Fetch roundtrips ===
1337
1338    #[test]
1339    fn fetch_request_roundtrip() {
1340        let msg = ReplicationMessage {
1341            request_id: 9,
1342            body: ReplicationMessageBody::FetchRequest(FetchRequest { key: [0x40; 32] }),
1343        };
1344        let encoded = msg.encode().expect("encode should succeed");
1345        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1346
1347        assert_eq!(decoded.request_id, 9);
1348        if let ReplicationMessageBody::FetchRequest(req) = decoded.body {
1349            assert_eq!(req.key, [0x40; 32]);
1350        } else {
1351            panic!("expected FetchRequest");
1352        }
1353    }
1354
1355    #[test]
1356    fn fetch_response_success_roundtrip() {
1357        let msg = ReplicationMessage {
1358            request_id: 10,
1359            body: ReplicationMessageBody::FetchResponse(FetchResponse::Success {
1360                key: [0x50; 32],
1361                data: vec![7, 8, 9],
1362            }),
1363        };
1364        let encoded = msg.encode().expect("encode should succeed");
1365        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1366
1367        assert_eq!(decoded.request_id, 10);
1368        if let ReplicationMessageBody::FetchResponse(FetchResponse::Success { key, data }) =
1369            decoded.body
1370        {
1371            assert_eq!(key, [0x50; 32]);
1372            assert_eq!(data, vec![7, 8, 9]);
1373        } else {
1374            panic!("expected FetchResponse::Success");
1375        }
1376    }
1377
1378    #[test]
1379    fn fetch_response_not_found_roundtrip() {
1380        let msg = ReplicationMessage {
1381            request_id: 11,
1382            body: ReplicationMessageBody::FetchResponse(FetchResponse::NotFound {
1383                key: [0x60; 32],
1384            }),
1385        };
1386        let encoded = msg.encode().expect("encode should succeed");
1387        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1388
1389        assert_eq!(decoded.request_id, 11);
1390        if let ReplicationMessageBody::FetchResponse(FetchResponse::NotFound { key }) = decoded.body
1391        {
1392            assert_eq!(key, [0x60; 32]);
1393        } else {
1394            panic!("expected FetchResponse::NotFound");
1395        }
1396    }
1397
1398    #[test]
1399    fn fetch_response_error_roundtrip() {
1400        let msg = ReplicationMessage {
1401            request_id: 12,
1402            body: ReplicationMessageBody::FetchResponse(FetchResponse::Error {
1403                key: [0x70; 32],
1404                reason: "disk full".to_string(),
1405            }),
1406        };
1407        let encoded = msg.encode().expect("encode should succeed");
1408        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1409
1410        assert_eq!(decoded.request_id, 12);
1411        if let ReplicationMessageBody::FetchResponse(FetchResponse::Error { key, reason }) =
1412            decoded.body
1413        {
1414            assert_eq!(key, [0x70; 32]);
1415            assert_eq!(reason, "disk full");
1416        } else {
1417            panic!("expected FetchResponse::Error");
1418        }
1419    }
1420
1421    // === Audit roundtrips ===
1422
1423    #[test]
1424    fn audit_challenge_roundtrip() {
1425        let msg = ReplicationMessage {
1426            request_id: 13,
1427            body: ReplicationMessageBody::AuditChallenge(AuditChallenge {
1428                challenge_id: 999,
1429                nonce: [0xAB; 32],
1430                challenged_peer_id: [0xCD; 32],
1431                keys: vec![[0x01; 32], [0x02; 32]],
1432            }),
1433        };
1434        let encoded = msg.encode().expect("encode should succeed");
1435        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1436
1437        assert_eq!(decoded.request_id, 13);
1438        if let ReplicationMessageBody::AuditChallenge(challenge) = decoded.body {
1439            assert_eq!(challenge.challenge_id, 999);
1440            assert_eq!(challenge.nonce, [0xAB; 32]);
1441            assert_eq!(challenge.challenged_peer_id, [0xCD; 32]);
1442            assert_eq!(challenge.keys.len(), 2);
1443        } else {
1444            panic!("expected AuditChallenge");
1445        }
1446    }
1447
1448    #[test]
1449    fn audit_response_digests_roundtrip() {
1450        let digests = vec![[0x11; 32], ABSENT_KEY_DIGEST];
1451        let msg = ReplicationMessage {
1452            request_id: 14,
1453            body: ReplicationMessageBody::AuditResponse(AuditResponse::Digests {
1454                challenge_id: 999,
1455                digests: digests.clone(),
1456            }),
1457        };
1458        let encoded = msg.encode().expect("encode should succeed");
1459        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1460
1461        assert_eq!(decoded.request_id, 14);
1462        if let ReplicationMessageBody::AuditResponse(AuditResponse::Digests {
1463            challenge_id,
1464            digests: decoded_digests,
1465        }) = decoded.body
1466        {
1467            assert_eq!(challenge_id, 999);
1468            assert_eq!(decoded_digests, digests);
1469        } else {
1470            panic!("expected AuditResponse::Digests");
1471        }
1472    }
1473
1474    #[test]
1475    fn audit_response_bootstrapping_roundtrip() {
1476        let msg = ReplicationMessage {
1477            request_id: 15,
1478            body: ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping {
1479                challenge_id: 42,
1480            }),
1481        };
1482        let encoded = msg.encode().expect("encode should succeed");
1483        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1484
1485        assert_eq!(decoded.request_id, 15);
1486        if let ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping {
1487            challenge_id,
1488        }) = decoded.body
1489        {
1490            assert_eq!(challenge_id, 42);
1491        } else {
1492            panic!("expected AuditResponse::Bootstrapping");
1493        }
1494    }
1495
1496    // === Oversized message rejection ===
1497
1498    #[test]
1499    fn decode_rejects_oversized_payload() {
1500        let oversized = vec![0u8; MAX_REPLICATION_MESSAGE_SIZE + 1];
1501        let result = ReplicationMessage::decode(&oversized);
1502        assert!(result.is_err());
1503        let err = result.unwrap_err();
1504        assert!(
1505            matches!(err, ReplicationProtocolError::MessageTooLarge { .. }),
1506            "expected MessageTooLarge, got {err:?}"
1507        );
1508    }
1509
1510    #[test]
1511    fn encode_rejects_oversized_message() {
1512        // Build a message whose serialized form exceeds the limit.
1513        let msg = ReplicationMessage {
1514            request_id: 0,
1515            body: ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
1516                key: [0; 32],
1517                data: vec![0xFF; MAX_REPLICATION_MESSAGE_SIZE],
1518                proof_of_payment: vec![],
1519            }),
1520        };
1521        let result = msg.encode();
1522        assert!(result.is_err());
1523        let err = result.unwrap_err();
1524        assert!(
1525            matches!(err, ReplicationProtocolError::MessageTooLarge { .. }),
1526            "expected MessageTooLarge, got {err:?}"
1527        );
1528    }
1529
1530    // === Invalid data rejection ===
1531
1532    #[test]
1533    fn decode_rejects_invalid_data() {
1534        let invalid = vec![0xFF, 0xFF, 0xFF];
1535        let result = ReplicationMessage::decode(&invalid);
1536        assert!(result.is_err());
1537        let err = result.unwrap_err();
1538        assert!(
1539            matches!(err, ReplicationProtocolError::DeserializationFailed(_)),
1540            "expected DeserializationFailed, got {err:?}"
1541        );
1542    }
1543
1544    // === Audit digest computation ===
1545
1546    #[test]
1547    fn audit_digest_is_deterministic() {
1548        let nonce = [0x01; 32];
1549        let peer_id = [0x02; 32];
1550        let key: XorName = [0x03; 32];
1551        let record_bytes = b"hello world";
1552
1553        let digest_a = compute_audit_digest(&nonce, &peer_id, &key, record_bytes);
1554        let digest_b = compute_audit_digest(&nonce, &peer_id, &key, record_bytes);
1555
1556        assert_eq!(digest_a, digest_b, "same inputs must produce same digest");
1557    }
1558
1559    #[test]
1560    fn audit_digest_differs_with_different_nonce() {
1561        let peer_id = [0x02; 32];
1562        let key: XorName = [0x03; 32];
1563        let record_bytes = b"hello world";
1564
1565        let digest_a = compute_audit_digest(&[0x01; 32], &peer_id, &key, record_bytes);
1566        let digest_b = compute_audit_digest(&[0xFF; 32], &peer_id, &key, record_bytes);
1567
1568        assert_ne!(
1569            digest_a, digest_b,
1570            "different nonces must produce different digests"
1571        );
1572    }
1573
1574    #[test]
1575    fn audit_digest_differs_with_different_data() {
1576        let nonce = [0x01; 32];
1577        let peer_id = [0x02; 32];
1578        let key: XorName = [0x03; 32];
1579
1580        let digest_a = compute_audit_digest(&nonce, &peer_id, &key, b"data-A");
1581        let digest_b = compute_audit_digest(&nonce, &peer_id, &key, b"data-B");
1582
1583        assert_ne!(
1584            digest_a, digest_b,
1585            "different data must produce different digests"
1586        );
1587    }
1588
1589    #[test]
1590    fn audit_digest_differs_with_different_peer() {
1591        let nonce = [0x01; 32];
1592        let key: XorName = [0x03; 32];
1593        let record_bytes = b"hello";
1594
1595        let digest_a = compute_audit_digest(&nonce, &[0x02; 32], &key, record_bytes);
1596        let digest_b = compute_audit_digest(&nonce, &[0xFF; 32], &key, record_bytes);
1597
1598        assert_ne!(
1599            digest_a, digest_b,
1600            "different peer IDs must produce different digests"
1601        );
1602    }
1603
1604    #[test]
1605    fn audit_digest_differs_with_different_key() {
1606        let nonce = [0x01; 32];
1607        let peer_id = [0x02; 32];
1608        let record_bytes = b"hello";
1609
1610        let digest_a = compute_audit_digest(&nonce, &peer_id, &[0x03; 32], record_bytes);
1611        let digest_b = compute_audit_digest(&nonce, &peer_id, &[0xFF; 32], record_bytes);
1612
1613        assert_ne!(
1614            digest_a, digest_b,
1615            "different keys must produce different digests"
1616        );
1617    }
1618
1619    // === Absent key digest sentinel ===
1620
1621    #[test]
1622    fn absent_key_digest_is_all_zeros() {
1623        assert_eq!(ABSENT_KEY_DIGEST, [0u8; 32]);
1624    }
1625
1626    #[test]
1627    fn real_digest_differs_from_absent_sentinel() {
1628        let nonce = [0x01; 32];
1629        let peer_id = [0x02; 32];
1630        let key: XorName = [0x03; 32];
1631        let record_bytes = b"non-empty data";
1632
1633        let digest = compute_audit_digest(&nonce, &peer_id, &key, record_bytes);
1634        assert_ne!(
1635            digest, ABSENT_KEY_DIGEST,
1636            "a real digest should not collide with the all-zeros sentinel"
1637        );
1638    }
1639
1640    // === Error Display ===
1641
1642    #[test]
1643    fn error_display_serialization_failed() {
1644        let err = ReplicationProtocolError::SerializationFailed("boom".to_string());
1645        assert_eq!(err.to_string(), "replication serialization failed: boom");
1646    }
1647
1648    #[test]
1649    fn error_display_deserialization_failed() {
1650        let err = ReplicationProtocolError::DeserializationFailed("bad data".to_string());
1651        assert_eq!(
1652            err.to_string(),
1653            "replication deserialization failed: bad data"
1654        );
1655    }
1656
1657    #[test]
1658    fn error_display_message_too_large() {
1659        let err = ReplicationProtocolError::MessageTooLarge {
1660            size: 20_000_000,
1661            max_size: MAX_REPLICATION_MESSAGE_SIZE,
1662        };
1663        let display = err.to_string();
1664        assert!(display.contains("20000000"));
1665        assert!(display.contains(&MAX_REPLICATION_MESSAGE_SIZE.to_string()));
1666    }
1667}