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