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;
17use super::config::MAX_SUBTREE_AUDIT_MESSAGE_SIZE;
18
19/// Sentinel digest value indicating the challenged key is absent from storage.
20///
21/// Used in [`AuditResponse::Digests`] for keys the peer does not hold.
22pub const ABSENT_KEY_DIGEST: [u8; 32] = [0u8; 32];
23
24// ---------------------------------------------------------------------------
25// Top-level envelope
26// ---------------------------------------------------------------------------
27
28/// Top-level replication message envelope.
29///
30/// Every replication wire message carries a sender-assigned `request_id` so
31/// that the receiver can correlate responses without relying on transport-layer
32/// ordering.
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct ReplicationMessage {
35    /// Sender-assigned request ID for correlation.
36    pub request_id: u64,
37    /// The message body.
38    pub body: ReplicationMessageBody,
39}
40
41impl ReplicationMessage {
42    /// Encode the message to bytes using postcard.
43    ///
44    /// # Errors
45    ///
46    /// Returns [`ReplicationProtocolError::SerializationFailed`] if postcard
47    /// serialization fails.
48    pub fn encode(&self) -> Result<Vec<u8>, ReplicationProtocolError> {
49        let bytes = postcard::to_stdvec(self)
50            .map_err(|e| ReplicationProtocolError::SerializationFailed(e.to_string()))?;
51
52        // The same family ceiling the decoder applies, from the same table and
53        // with the same arms, including the unclassified case. Every receiver
54        // drops a subtree-audit body over that ceiling before decoding it, so
55        // encoding one and putting it on the wire produces a message nobody can
56        // read, and the responder is then scored for the resulting silence.
57        // Failing here turns that into a local, attributable error at the point
58        // the oversized body was built.
59        //
60        // Matching `decode` exactly also means a body added later without a
61        // family entry is measured against the same limit at both ends, so it
62        // cannot become traffic that encodes here and is dropped there. It fails
63        // loudly only if it exceeds the strict ceiling; a small unclassified body
64        // still encodes, which is fine, because the receiver applies the same
65        // ceiling and will accept it too. No legitimate body reaches the ceiling:
66        // the largest is a round-1 proof at the commitment
67        // key-count cap, pinned under it with headroom by
68        // `max_round1_proof_fits_the_audit_family_ceiling`.
69        let max_size = ceiling_for(family_of_variant(self.body.variant_index()));
70        if bytes.len() > max_size {
71            return Err(ReplicationProtocolError::MessageTooLarge {
72                size: bytes.len(),
73                max_size,
74            });
75        }
76
77        // V2-623: cumulative per-variant tx accounting. Every replication send
78        // funnels through here, so this is the single tx choke point.
79        record_tx(&self.body, bytes.len());
80
81        Ok(bytes)
82    }
83
84    /// Decode a message from bytes using postcard.
85    ///
86    /// Rejects payloads larger than [`MAX_REPLICATION_MESSAGE_SIZE`] before
87    /// attempting deserialization.
88    ///
89    /// # Errors
90    ///
91    /// Returns [`ReplicationProtocolError::MessageTooLarge`] if the input
92    /// exceeds the size limit, or
93    /// [`ReplicationProtocolError::DeserializationFailed`] if postcard cannot
94    /// parse the data.
95    pub fn decode(data: &[u8]) -> Result<Self, ReplicationProtocolError> {
96        // The ceiling follows the body's own family, read from its discriminant
97        // before anything attacker-sized is touched. Putting it here rather than
98        // only on the receive path is what makes it unskippable: a *response* is
99        // decoded by whichever lane asked, and an audit lane asks a question a
100        // few hundred bytes long, so without this a challenged peer could answer
101        // with megabytes and be allocated all of it. Core bodies keep the core
102        // allowance — a fetch response legitimately carries a whole chunk.
103        // A prefix too malformed to classify takes the strict ceiling too: it
104        // cannot be a legitimate message of any family, so it is not one to
105        // decode generously.
106        // `and_then`, not `map`: an index no variant declares classifies as
107        // nothing, and `ceiling_for` gives nothing the strict ceiling exactly
108        // like an unparseable prefix rather than the core allowance.
109        let max_size = ceiling_for(peek_variant_index(data).and_then(family_of_variant));
110        if data.len() > max_size {
111            return Err(ReplicationProtocolError::MessageTooLarge {
112                size: data.len(),
113                max_size,
114            });
115        }
116        let message: Self = postcard::from_bytes(data)
117            .map_err(|e| ReplicationProtocolError::DeserializationFailed(e.to_string()))?;
118
119        // V2-623: cumulative per-variant rx accounting. Every replication
120        // receive funnels through here, so this is the single rx choke point.
121        record_rx(&message.body, data.len());
122
123        Ok(message)
124    }
125
126    /// Decode a reply to a subtree-audit challenge under the subtree-family ceiling.
127    ///
128    /// The pre-decode ceiling on the receive path bounds what an auditor can
129    /// make a responder decode. This is that same bound in the other direction.
130    /// A subtree challenge costs a few hundred bytes to send, so without it a challenged
131    /// peer could answer with up to [`MAX_REPLICATION_MESSAGE_SIZE`] and make
132    /// the auditor allocate and decode all of it — the cheap side of the
133    /// exchange paying for the expensive one, which is the shape the responder
134    /// ceiling exists to prevent. Subtree-audit bodies are ~110 KiB at worst (see
135    /// [`MAX_SUBTREE_AUDIT_MESSAGE_SIZE`]), so this costs an honest responder nothing.
136    ///
137    /// No discriminant peek is needed here, unlike the receive path: the auditor
138    /// asked the question, so it already knows the reply belongs to the subtree
139    /// family, and a body that turns out not to be the expected one is rejected
140    /// by the subtree lane's own matching afterwards.
141    ///
142    /// # Errors
143    ///
144    /// Returns [`ReplicationProtocolError::MessageTooLarge`] above the subtree
145    /// audit ceiling.
146    pub fn decode_subtree_audit_response(data: &[u8]) -> Result<Self, ReplicationProtocolError> {
147        if data.len() > MAX_SUBTREE_AUDIT_MESSAGE_SIZE {
148            return Err(ReplicationProtocolError::MessageTooLarge {
149                size: data.len(),
150                max_size: MAX_SUBTREE_AUDIT_MESSAGE_SIZE,
151            });
152        }
153        Self::decode(data)
154    }
155}
156
157// ---------------------------------------------------------------------------
158// Message body enum
159// ---------------------------------------------------------------------------
160
161/// All replication protocol message types.
162#[derive(Debug, Clone, Serialize, Deserialize)]
163pub enum ReplicationMessageBody {
164    // === Fresh Replication (Section 6.1) ===
165    /// Fresh replication offer with `PoP` (sent to close group members).
166    FreshReplicationOffer(FreshReplicationOffer),
167    /// Response to a fresh replication offer.
168    FreshReplicationResponse(FreshReplicationResponse),
169
170    /// Paid-list notification with `PoP` (sent to `PaidCloseGroup` members).
171    PaidNotify(PaidNotify),
172
173    // === Neighbor Sync (Section 6.2) ===
174    /// Neighbor sync hint exchange (bidirectional).
175    NeighborSyncRequest(NeighborSyncRequest),
176    /// Response to neighbor sync with own hints.
177    NeighborSyncResponse(NeighborSyncResponse),
178
179    // === Verification (Section 9) ===
180    /// Batched verification request (presence + paid-list queries).
181    VerificationRequest(VerificationRequest),
182    /// Response to verification request with per-key evidence.
183    VerificationResponse(VerificationResponse),
184
185    // === Fetch (record retrieval) ===
186    /// Request to fetch a record by key.
187    FetchRequest(FetchRequest),
188    /// Response with the record data.
189    FetchResponse(FetchResponse),
190
191    // === Responsible-chunk audit (per-key digests) ===
192    /// Per-key audit challenge: used by the responsible-chunk audit and the
193    /// prune-confirmation path.
194    AuditChallenge(AuditChallenge),
195    /// Response to a per-key audit challenge.
196    AuditResponse(AuditResponse),
197
198    // === Storage-bound subtree audit (ADR-0002) ===
199    /// Gossip-triggered contiguous-subtree storage audit challenge (round 1).
200    SubtreeAuditChallenge(SubtreeAuditChallenge),
201    /// Response to a contiguous-subtree storage audit challenge (round 1).
202    SubtreeAuditResponse(SubtreeAuditResponse),
203    /// Surprise slice challenge for the spot-checked leaves (round 2).
204    SubtreeSliceChallenge(SubtreeSliceChallenge),
205    /// Response carrying verified slices for the opened blocks (round 2).
206    SubtreeSliceResponse(SubtreeSliceResponse),
207
208    // === Commitment fetch by pin (ADR-0004) ===
209    // APPENDED at the end so postcard variant discriminants of all the
210    // pre-existing variants are unchanged — old nodes keep decoding every
211    // message they already understood; only these two new indices are unknown
212    // to them (and they never receive them, since old nodes never send the
213    // matching request).
214    /// Fetch a retained commitment by its pin (ADR-0004): used to resolve a
215    /// quote's `commitment_pin` when the sidecar is absent and the gossip cache
216    /// has no fresh copy.
217    GetCommitmentByPin(GetCommitmentByPin),
218    /// Response to [`Self::GetCommitmentByPin`].
219    GetCommitmentByPinResponse(GetCommitmentByPinResponse),
220
221    // === Pointers (ADR-0016) ===
222    // APPENDED for the same reason: every earlier discriminant keeps its value.
223    // A peer built before pointers cannot decode these and drops them. The two
224    // one-way pushes are then simply lost, and the requests are only ever sent
225    // to peers that have sent a pointer message themselves, so an older peer is
226    // never asked something it cannot answer and never penalised for silence.
227    /// A newly paid pointer state, with the proof that paid for it.
228    PointerFreshOffer(PointerFreshOffer),
229    /// The pointer states the sender holds that the receiver should hold too.
230    PointerHints(PointerHints),
231    /// Ask a peer for the pointer record it holds at an address.
232    PointerFetchRequest(PointerFetchRequest),
233    /// Response to [`Self::PointerFetchRequest`].
234    PointerFetchResponse(PointerFetchResponse),
235    /// Ask a peer which state it holds at each of some addresses.
236    PointerStateRequest(PointerStateRequest),
237    /// Response to [`Self::PointerStateRequest`].
238    PointerStateResponse(PointerStateResponse),
239}
240
241// ---------------------------------------------------------------------------
242// Cumulative per-variant traffic accounting (V2-623)
243// ---------------------------------------------------------------------------
244//
245// Process-global relaxed-atomic counter table, indexed by variant. The
246// encode/decode choke points bump these on every replication tx/rx; a periodic
247// task in the replication engine emits them as `replication traffic summary
248// (cumulative)` INFO lines. Values are monotonic since process start — rates
249// are computed as deltas at query time, so a dropped/delayed log line cannot
250// corrupt the data.
251//
252// A process-global static (rather than engine-owned state) is used because the
253// encode/decode call sites are free functions scattered across the replication
254// modules that do not carry any shared engine handle.
255
256/// Number of [`ReplicationMessageBody`] variants (the counter-table width).
257pub(crate) const N_REPLICATION_VARIANTS: usize = 23;
258
259static REPL_TX_BYTES: [AtomicU64; N_REPLICATION_VARIANTS] =
260    [const { AtomicU64::new(0) }; N_REPLICATION_VARIANTS];
261static REPL_TX_COUNT: [AtomicU64; N_REPLICATION_VARIANTS] =
262    [const { AtomicU64::new(0) }; N_REPLICATION_VARIANTS];
263static REPL_RX_BYTES: [AtomicU64; N_REPLICATION_VARIANTS] =
264    [const { AtomicU64::new(0) }; N_REPLICATION_VARIANTS];
265static REPL_RX_COUNT: [AtomicU64; N_REPLICATION_VARIANTS] =
266    [const { AtomicU64::new(0) }; N_REPLICATION_VARIANTS];
267
268impl ReplicationMessageBody {
269    /// Stable counter-table index for this variant.
270    ///
271    /// Matches declaration order. The last two variants were deliberately
272    /// appended (see the enum comment) so this order is postcard-stable.
273    pub(crate) fn variant_index(&self) -> usize {
274        match self {
275            Self::FreshReplicationOffer(_) => 0,
276            Self::FreshReplicationResponse(_) => 1,
277            Self::PaidNotify(_) => 2,
278            Self::NeighborSyncRequest(_) => 3,
279            Self::NeighborSyncResponse(_) => 4,
280            Self::VerificationRequest(_) => 5,
281            Self::VerificationResponse(_) => 6,
282            Self::FetchRequest(_) => 7,
283            Self::FetchResponse(_) => 8,
284            Self::AuditChallenge(_) => 9,
285            Self::AuditResponse(_) => 10,
286            Self::SubtreeAuditChallenge(_) => 11,
287            Self::SubtreeAuditResponse(_) => 12,
288            Self::SubtreeSliceChallenge(_) => 13,
289            Self::SubtreeSliceResponse(_) => 14,
290            Self::GetCommitmentByPin(_) => 15,
291            Self::GetCommitmentByPinResponse(_) => 16,
292            Self::PointerFreshOffer(_) => 17,
293            Self::PointerHints(_) => 18,
294            Self::PointerFetchRequest(_) => 19,
295            Self::PointerFetchResponse(_) => 20,
296            Self::PointerStateRequest(_) => 21,
297            Self::PointerStateResponse(_) => 22,
298        }
299    }
300
301    /// Whether this body is a subtree storage-commitment audit message (both
302    /// rounds). These ride [`SUBTREE_AUDIT_PROTOCOL_ID`], not the core
303    /// [`REPLICATION_PROTOCOL_ID`]; the receive dispatch uses this to enforce
304    /// that audit bodies only arrive on the audit id and core bodies only on the
305    /// core id, so a mixed-version peer's message can never be honoured on the
306    /// wrong handler even if postcard misdecodes it into a valid-looking value.
307    ///
308    /// [`SUBTREE_AUDIT_PROTOCOL_ID`]: crate::replication::config::SUBTREE_AUDIT_PROTOCOL_ID
309    /// [`REPLICATION_PROTOCOL_ID`]: crate::replication::config::REPLICATION_PROTOCOL_ID
310    #[must_use]
311    pub fn is_subtree_audit(&self) -> bool {
312        family_of_variant(self.variant_index()) == Some(BodyFamily::SubtreeAudit)
313    }
314}
315
316/// Which protocol family a body belongs to.
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318pub(crate) enum BodyFamily {
319    /// Core replication, including digest-based responsible, possession, and
320    /// prune-confirmation audits.
321    Core,
322    /// The four subtree storage-commitment audit bodies, both rounds.
323    SubtreeAudit,
324}
325
326impl BodyFamily {
327    /// Whether this family takes the tighter audit wire ceiling.
328    #[must_use]
329    pub(crate) fn is_audit(self) -> bool {
330        matches!(self, Self::SubtreeAudit)
331    }
332}
333
334/// The family of a body, keyed by its postcard discriminant.
335///
336/// Keyed by discriminant rather than by `&self` on purpose: the receive path has
337/// to classify a message BEFORE decoding it, because the pre-decode size ceiling
338/// is the only check that can run before an attacker-sized collection is
339/// allocated. The discriminant is the one field reachable that early (see
340/// [`peek_variant_index`]).
341///
342/// Everything that classifies a body reads this one table —
343/// [`ReplicationMessageBody::is_subtree_audit`], outbound response routing, the
344/// post-decode family guard, and the pre-decode ceiling — so the
345/// pre- and post-decode views of "which family is this" cannot drift apart. A
346/// drift is exactly what let an audit body sent on the core id skip the audit
347/// ceiling and decode under the 10 MiB core allowance.
348///
349/// Indices match [`ReplicationMessageBody::variant_index`], which is declaration
350/// order and postcard-stable.
351///
352/// `None` for an index that is not a variant of this enum. That is not the same
353/// as "core": an index nothing declares cannot be a legitimate message of any
354/// family, so callers selecting a wire ceiling must give it the strict audit one
355/// rather than the generous core allowance. Postcard rejects an unknown outer
356/// discriminant before decoding any trailing collection, so this is closing the
357/// invariant rather than a demonstrated hole — but the rule "failing to classify
358/// means do not decode generously" should hold everywhere, not just for a prefix
359/// too malformed to parse.
360#[must_use]
361pub(crate) fn family_of_variant(index: usize) -> Option<BodyFamily> {
362    match index {
363        11..=14 => Some(BodyFamily::SubtreeAudit),
364        0..=10 | 15..=22 => Some(BodyFamily::Core),
365        _ => None,
366    }
367}
368
369/// The wire ceiling a body of this family takes.
370///
371/// One definition for both directions: `encode` measures what it produced
372/// against it, `decode` measures what arrived before allocating anything. They
373/// were duplicated matches that had to be kept in step by hand, which is the
374/// kind of pair that silently drifts.
375///
376/// `None` — an index no declared variant uses — takes the STRICT ceiling.
377/// Failing to classify must never mean "decode generously".
378#[must_use]
379pub(crate) fn ceiling_for(family: Option<BodyFamily>) -> usize {
380    match family {
381        Some(family) if !family.is_audit() => MAX_REPLICATION_MESSAGE_SIZE,
382        _ => MAX_SUBTREE_AUDIT_MESSAGE_SIZE,
383    }
384}
385
386/// Maximum bytes a postcard varint can occupy for a `u64`.
387const MAX_VARINT_LEN: usize = 10;
388
389/// Read one postcard varint (LEB128, little-endian base-128) from `bytes`.
390///
391/// Returns the value and how many bytes it consumed. Bounded by `max_bytes` and
392/// by the 64-bit shift, so a hostile prefix cannot spin here.
393fn read_varint(bytes: &[u8], max_bytes: usize) -> Option<(u64, usize)> {
394    let mut value: u64 = 0;
395    let mut shift: u32 = 0;
396    for (i, byte) in bytes.iter().take(max_bytes).enumerate() {
397        let payload = u64::from(byte & 0x7F);
398        // A u64 LEB128 has only one payload bit left in byte ten. Rust's
399        // shifts discard high bits rather than reporting value overflow, so
400        // `checked_shl` alone would accept (and wrap) a terminal payload > 1.
401        // Treat that malformed prefix as unclassifiable and apply the strict
402        // audit ceiling.
403        if shift == 63 && payload > 1 {
404            return None;
405        }
406        value |= payload.checked_shl(shift)?;
407        if byte & 0x80 == 0 {
408            return Some((value, i + 1));
409        }
410        shift = shift.checked_add(7)?;
411        if shift >= u64::BITS {
412            return None;
413        }
414    }
415    None
416}
417
418/// Read a message's body discriminant without decoding the body.
419///
420/// `ReplicationMessage` is `{ request_id: u64, body: ReplicationMessageBody }`,
421/// and postcard writes struct fields in order with no length prefix: a varint
422/// `request_id`, then the enum's varint discriminant. So the discriminant sits
423/// behind at most [`MAX_VARINT_LEN`] bytes and costs two bounded varint reads to
424/// reach — no allocation, and nothing attacker-sized is touched.
425///
426/// `None` means the prefix is not even well-formed enough to classify; the
427/// caller treats that as "apply the strictest ceiling", since a message we
428/// cannot classify is one we should not decode generously.
429///
430/// A test round-trips every variant through `encode` to prove this agrees with
431/// [`ReplicationMessageBody::variant_index`] for real messages, rather than
432/// trusting this reading of postcard's format.
433#[must_use]
434pub(crate) fn peek_variant_index(data: &[u8]) -> Option<usize> {
435    let (_request_id, consumed) = read_varint(data, MAX_VARINT_LEN)?;
436    let rest = data.get(consumed..)?;
437    let (variant, _) = read_varint(rest, MAX_VARINT_LEN)?;
438    usize::try_from(variant).ok()
439}
440
441// ---------------------------------------------------------------------------
442// Cumulative audit outcome accounting (extends V2-623)
443// ---------------------------------------------------------------------------
444//
445// The per-variant traffic counters above already give audit *volume* (challenge
446// tx = launched, response tx = served). These tally the *outcomes*, which the
447// traffic counters cannot express: auditor-side pass/fail per failure reason,
448// and responder-side admission drops (challenges refused at the flood-fair
449// caps). Same conventions: process-global relaxed atomics, monotonic since
450// process start, emitted next to the traffic summary and diffed at query time.
451
452/// Auditor-side audit kinds with pass/fail outcome tallies.
453#[derive(Clone, Copy)]
454pub(crate) enum AuditOutcomeKind {
455    /// Responsible-chunk audit (audit #2, `AuditChallenge`).
456    Responsible = 0,
457    /// Storage-bound subtree audit (ADR-0002).
458    Subtree = 1,
459}
460
461/// Responder-side challenge kinds dropped at the admission caps.
462#[derive(Clone, Copy)]
463pub(crate) enum AuditDropKind {
464    /// Responsible-chunk / prune-confirmation `AuditChallenge`.
465    Responsible = 0,
466    /// Subtree audit round-1 challenge.
467    Subtree = 1,
468    /// Subtree audit round-2 slice challenge.
469    ///
470    /// The emitted counter is still named `audit_dropped_byte` (see
471    /// `log_audit_outcome_summary`): round 2 no longer serves full chunk bytes,
472    /// but keeping the wire-visible counter name fixed is what lets a v2 fleet
473    /// and a v3 fleet be compared with no field mapping. The name is a metric
474    /// identifier, not a description of the payload.
475    Slice = 2,
476}
477
478/// One slot per [`AuditFailureReason`] variant, per [`AuditOutcomeKind`].
479const N_FAIL_REASONS: usize = 5;
480const N_OUTCOME_KINDS: usize = 2;
481const N_DROP_KINDS: usize = 3;
482
483static AUDIT_PASS: [AtomicU64; N_OUTCOME_KINDS] = [const { AtomicU64::new(0) }; N_OUTCOME_KINDS];
484static AUDIT_FAIL: [AtomicU64; N_OUTCOME_KINDS * N_FAIL_REASONS] =
485    [const { AtomicU64::new(0) }; N_OUTCOME_KINDS * N_FAIL_REASONS];
486static AUDIT_DROPPED: [AtomicU64; N_DROP_KINDS] = [const { AtomicU64::new(0) }; N_DROP_KINDS];
487
488/// Stable counter index for a failure reason. Matches declaration order of
489/// [`AuditFailureReason`]; exhaustive so a new variant is a compile error here.
490fn fail_reason_index(reason: &AuditFailureReason) -> usize {
491    match reason {
492        AuditFailureReason::Timeout => 0,
493        AuditFailureReason::MalformedResponse => 1,
494        AuditFailureReason::DigestMismatch => 2,
495        AuditFailureReason::KeyAbsent => 3,
496        AuditFailureReason::Rejected => 4,
497    }
498}
499
500/// Record an auditor-side audit pass.
501pub(crate) fn record_audit_pass(kind: AuditOutcomeKind) {
502    AUDIT_PASS[kind as usize].fetch_add(1, Ordering::Relaxed);
503}
504
505/// Record an auditor-side audit failure with its reason.
506pub(crate) fn record_audit_fail(kind: AuditOutcomeKind, reason: &AuditFailureReason) {
507    AUDIT_FAIL[kind as usize * N_FAIL_REASONS + fail_reason_index(reason)]
508        .fetch_add(1, Ordering::Relaxed);
509}
510
511/// Record a responder-side challenge dropped at the admission caps.
512pub(crate) fn record_audit_drop(kind: AuditDropKind) {
513    AUDIT_DROPPED[kind as usize].fetch_add(1, Ordering::Relaxed);
514}
515
516/// Emit the cumulative audit outcome tallies as one INFO summary line, same
517/// target and cadence as [`log_traffic_summary`] (`group = 4`), so the
518/// telegraf→Elasticsearch pipeline lifts each key into a `tail.*` field and
519/// pass/fail/drop rates per hour fall out of max-per-hour deltas.
520pub(crate) fn log_audit_outcome_summary() {
521    let pass = |k: usize| AUDIT_PASS[k].load(Ordering::Relaxed);
522    let fail = |k: usize, r: usize| AUDIT_FAIL[k * N_FAIL_REASONS + r].load(Ordering::Relaxed);
523    let drop = |k: usize| AUDIT_DROPPED[k].load(Ordering::Relaxed);
524
525    crate::logging::info!(
526        target: "ant_node::replication::traffic",
527        group = 4,
528        responsible_audit_pass = pass(0),
529        responsible_audit_fail_timeout = fail(0, 0),
530        responsible_audit_fail_malformed = fail(0, 1),
531        responsible_audit_fail_digest_mismatch = fail(0, 2),
532        responsible_audit_fail_key_absent = fail(0, 3),
533        responsible_audit_fail_rejected = fail(0, 4),
534        subtree_audit_pass = pass(1),
535        subtree_audit_fail_timeout = fail(1, 0),
536        subtree_audit_fail_malformed = fail(1, 1),
537        subtree_audit_fail_digest_mismatch = fail(1, 2),
538        subtree_audit_fail_key_absent = fail(1, 3),
539        subtree_audit_fail_rejected = fail(1, 4),
540        audit_dropped_responsible = drop(0),
541        audit_dropped_subtree = drop(1),
542        audit_dropped_byte = drop(2),
543        "audit outcome summary (cumulative)"
544    );
545}
546
547/// Record an encoded (tx) replication message against its variant.
548fn record_tx(body: &ReplicationMessageBody, bytes: usize) {
549    let i = body.variant_index();
550    REPL_TX_BYTES[i].fetch_add(bytes as u64, Ordering::Relaxed);
551    REPL_TX_COUNT[i].fetch_add(1, Ordering::Relaxed);
552}
553
554/// Record a decoded (rx) replication message against its variant.
555fn record_rx(body: &ReplicationMessageBody, bytes: usize) {
556    let i = body.variant_index();
557    REPL_RX_BYTES[i].fetch_add(bytes as u64, Ordering::Relaxed);
558    REPL_RX_COUNT[i].fetch_add(1, Ordering::Relaxed);
559}
560
561/// Emit the cumulative per-variant replication traffic as INFO summary lines
562/// (V2-623), target `ant_node::replication::traffic`.
563///
564/// The fields are flat snake-case keys (`<stem>_tx_bytes`, `<stem>_rx_count`,
565/// …) so the telegraf→Elasticsearch pipeline lifts each into a first-class
566/// `tail.*` field and the acceptance query (`max` per field per hour → delta)
567/// yields per-variant MB/h directly.
568///
569/// 17 variants × 4 fields = 68 flat keys. `tracing` caps an event at 32 fields,
570/// so the keys are split across three lines that share the same `target` and
571/// message and are distinguished by a `group` field — telegraf still lifts
572/// every key into its own ES field, so the split is transparent at query time.
573pub(crate) fn log_traffic_summary() {
574    // Relaxed loads — a slightly skewed read across counters is fine because
575    // rates are computed as deltas over many intervals at query time.
576    let tb = |i: usize| REPL_TX_BYTES[i].load(Ordering::Relaxed);
577    let tc = |i: usize| REPL_TX_COUNT[i].load(Ordering::Relaxed);
578    let rb = |i: usize| REPL_RX_BYTES[i].load(Ordering::Relaxed);
579    let rc = |i: usize| REPL_RX_COUNT[i].load(Ordering::Relaxed);
580
581    crate::logging::info!(
582        target: "ant_node::replication::traffic",
583        group = 1,
584        fresh_offer_tx_bytes = tb(0), fresh_offer_tx_count = tc(0),
585        fresh_offer_rx_bytes = rb(0), fresh_offer_rx_count = rc(0),
586        fresh_response_tx_bytes = tb(1), fresh_response_tx_count = tc(1),
587        fresh_response_rx_bytes = rb(1), fresh_response_rx_count = rc(1),
588        paid_notify_tx_bytes = tb(2), paid_notify_tx_count = tc(2),
589        paid_notify_rx_bytes = rb(2), paid_notify_rx_count = rc(2),
590        neighbor_sync_request_tx_bytes = tb(3), neighbor_sync_request_tx_count = tc(3),
591        neighbor_sync_request_rx_bytes = rb(3), neighbor_sync_request_rx_count = rc(3),
592        neighbor_sync_response_tx_bytes = tb(4), neighbor_sync_response_tx_count = tc(4),
593        neighbor_sync_response_rx_bytes = rb(4), neighbor_sync_response_rx_count = rc(4),
594        verification_request_tx_bytes = tb(5), verification_request_tx_count = tc(5),
595        verification_request_rx_bytes = rb(5), verification_request_rx_count = rc(5),
596        "replication traffic summary (cumulative)"
597    );
598    crate::logging::info!(
599        target: "ant_node::replication::traffic",
600        group = 2,
601        verification_response_tx_bytes = tb(6), verification_response_tx_count = tc(6),
602        verification_response_rx_bytes = rb(6), verification_response_rx_count = rc(6),
603        fetch_request_tx_bytes = tb(7), fetch_request_tx_count = tc(7),
604        fetch_request_rx_bytes = rb(7), fetch_request_rx_count = rc(7),
605        fetch_response_tx_bytes = tb(8), fetch_response_tx_count = tc(8),
606        fetch_response_rx_bytes = rb(8), fetch_response_rx_count = rc(8),
607        audit_challenge_tx_bytes = tb(9), audit_challenge_tx_count = tc(9),
608        audit_challenge_rx_bytes = rb(9), audit_challenge_rx_count = rc(9),
609        audit_response_tx_bytes = tb(10), audit_response_tx_count = tc(10),
610        audit_response_rx_bytes = rb(10), audit_response_rx_count = rc(10),
611        subtree_audit_challenge_tx_bytes = tb(11), subtree_audit_challenge_tx_count = tc(11),
612        subtree_audit_challenge_rx_bytes = rb(11), subtree_audit_challenge_rx_count = rc(11),
613        "replication traffic summary (cumulative)"
614    );
615    crate::logging::info!(
616        target: "ant_node::replication::traffic",
617        group = 3,
618        subtree_audit_response_tx_bytes = tb(12), subtree_audit_response_tx_count = tc(12),
619        subtree_audit_response_rx_bytes = rb(12), subtree_audit_response_rx_count = rc(12),
620        // Indices 13/14 are the round-2 pair, renamed on the wire to
621        // `SubtreeSliceChallenge`/`SubtreeSliceResponse`. The COUNTER names stay
622        // `subtree_byte_*` on purpose: they are the field names an operator
623        // queries, and holding them fixed is what let the V2-685 testnet compare
624        // a 0.15.0 cohort against a slice-audit cohort with no field mapping
625        // (6.19 MB vs 14.49 KB per response, same query). Renaming them would
626        // silently zero every existing dashboard and alert. The variant index,
627        // not the label, is the source of truth for what is being counted.
628        subtree_byte_challenge_tx_bytes = tb(13), subtree_byte_challenge_tx_count = tc(13),
629        subtree_byte_challenge_rx_bytes = rb(13), subtree_byte_challenge_rx_count = rc(13),
630        subtree_byte_response_tx_bytes = tb(14), subtree_byte_response_tx_count = tc(14),
631        subtree_byte_response_rx_bytes = rb(14), subtree_byte_response_rx_count = rc(14),
632        get_commitment_by_pin_tx_bytes = tb(15), get_commitment_by_pin_tx_count = tc(15),
633        get_commitment_by_pin_rx_bytes = rb(15), get_commitment_by_pin_rx_count = rc(15),
634        get_commitment_by_pin_response_tx_bytes = tb(16),
635        get_commitment_by_pin_response_tx_count = tc(16),
636        get_commitment_by_pin_response_rx_bytes = rb(16),
637        get_commitment_by_pin_response_rx_count = rc(16),
638        "replication traffic summary (cumulative)"
639    );
640}
641
642// ---------------------------------------------------------------------------
643// Per-peer served-bytes accounting (V2-684)
644// ---------------------------------------------------------------------------
645//
646// Follow-up to V2-623: the per-variant table above says how many bytes each
647// message type served, but not WHICH peers pulled them. This adds per-peer
648// attribution for the heavy serve paths (`FetchResponse`, `NeighborSyncResponse`
649// — ~99% of served bytes), emitted as a top-10-by-bytes INFO line on the same
650// cadence and target as `log_traffic_summary`.
651//
652// Design (mirrors V2-623's process-global-static choice for the same reason —
653// the serve choke point is a free function with no engine handle):
654//
655//   * A bounded, sharded table caps memory at `SERVED_SHARDS * SERVED_SHARD_CAP`
656//     peers total.
657//   * The serve hot path takes only a shared read lock on one shard plus two
658//     relaxed `fetch_add`s when the peer is already tracked — no global lock per
659//     response. A previously-unseen peer takes a one-shard write lock (rare).
660//   * Per-shard eviction of the smallest-bytes entry when a shard is full. The
661//     peers that matter are the largest accumulators and are never the minimum,
662//     so they cannot be evicted by transient noise.
663//   * Values are cumulative/monotonic since process start, so a dropped or
664//     delayed log line cannot corrupt query-time deltas.
665
666/// Number of shards in the served-peers table. Peers are assigned by the low
667/// nibble of their first ID byte; peer IDs are hash-random (BLAKE3), so the
668/// distribution across shards is uniform. Must be a power of two.
669const SERVED_SHARDS: usize = 16;
670
671/// Max peers tracked per shard. `SERVED_SHARDS * SERVED_SHARD_CAP` = 256 total.
672const SERVED_SHARD_CAP: usize = 16;
673
674/// Cumulative served counters for a single peer.
675struct PeerServeStats {
676    bytes: AtomicU64,
677    count: AtomicU64,
678}
679
680/// One shard of the served-peers table: a small, cap-bounded list of
681/// `(peer, counters)`. A `Vec` linear-scanned over at most `SERVED_SHARD_CAP`
682/// entries is cheaper than hashing and — unlike `HashMap` — is
683/// const-constructible, so the whole table is a plain `static` with no lazy
684/// initialisation.
685struct ServedShard {
686    entries: RwLock<Vec<(PeerId, PeerServeStats)>>,
687}
688
689impl ServedShard {
690    const fn new() -> Self {
691        Self {
692            entries: RwLock::new(Vec::new()),
693        }
694    }
695}
696
697static SERVED_PEERS: [ServedShard; SERVED_SHARDS] = [const { ServedShard::new() }; SERVED_SHARDS];
698
699/// Cumulative count of peers evicted from the table (bounded-map pressure
700/// indicator; emitted as `evictions`).
701static SERVED_EVICTIONS: AtomicU64 = AtomicU64::new(0);
702
703/// Shard index for a peer: the low `log2(SERVED_SHARDS)` bits of the first ID
704/// byte.
705fn served_shard_index(peer: &PeerId) -> usize {
706    (peer.to_bytes()[0] as usize) & (SERVED_SHARDS - 1)
707}
708
709/// Record `bytes` served to `peer` (V2-684), called from the replication serve
710/// choke point for the heavy response variants.
711///
712/// Fast path (peer already tracked): a shared read lock on one shard plus two
713/// relaxed `fetch_add`s. Slow path (new peer): a one-shard write lock that
714/// inserts the peer and, if the shard is at capacity, first evicts its
715/// smallest-bytes entry.
716pub(crate) fn record_served(peer: &PeerId, bytes: usize) {
717    let shard = &SERVED_PEERS[served_shard_index(peer)];
718    let bytes = bytes as u64;
719
720    // Fast path: peer already present — no structural change, shared lock only.
721    {
722        let guard = shard.entries.read();
723        if let Some((_, stats)) = guard.iter().find(|(p, _)| p == peer) {
724            stats.bytes.fetch_add(bytes, Ordering::Relaxed);
725            stats.count.fetch_add(1, Ordering::Relaxed);
726            return;
727        }
728    }
729
730    // Slow path: insert the new peer. Re-check under the write lock in case a
731    // racing writer added it between our read and write.
732    let mut guard = shard.entries.write();
733    if let Some((_, stats)) = guard.iter().find(|(p, _)| p == peer) {
734        stats.bytes.fetch_add(bytes, Ordering::Relaxed);
735        stats.count.fetch_add(1, Ordering::Relaxed);
736        return;
737    }
738    if guard.len() >= SERVED_SHARD_CAP {
739        // Evict the smallest-bytes entry; the peers we care about are the
740        // largest accumulators and are never the per-shard minimum.
741        if let Some((min_idx, _)) = guard
742            .iter()
743            .enumerate()
744            .min_by_key(|(_, (_, s))| s.bytes.load(Ordering::Relaxed))
745        {
746            guard.swap_remove(min_idx);
747            SERVED_EVICTIONS.fetch_add(1, Ordering::Relaxed);
748        }
749    }
750    guard.push((
751        *peer,
752        PeerServeStats {
753            bytes: AtomicU64::new(bytes),
754            count: AtomicU64::new(1),
755        },
756    ));
757}
758
759/// Emit the cumulative top-K per-peer served-bytes summary (V2-684) as one INFO
760/// line, target `ant_node::replication::traffic`, on the same cadence as
761/// [`log_traffic_summary`].
762///
763/// The top 10 peers × 3 fields + `tracked_peers` + `evictions` = 32 fields,
764/// exactly the `tracing` per-event field cap, so it fits on one line. Peer IDs
765/// are full hex ([`PeerId::to_hex`]), matching the `claiming bootstrap` /
766/// `per-source pending cap` log lines so the two can be joined in Elasticsearch.
767/// Empty slots (fewer than 10 tracked peers) emit an empty id and zero counters
768/// to keep the ES field schema stable.
769pub(crate) fn log_served_peers_summary() {
770    // Snapshot every shard, then rank. Reads are relaxed and short-lived; a
771    // slightly skewed snapshot is fine because values are cumulative and
772    // compared as deltas at query time.
773    let mut all: Vec<(PeerId, u64, u64)> = Vec::new();
774    for shard in &SERVED_PEERS {
775        let guard = shard.entries.read();
776        for (peer, stats) in guard.iter() {
777            all.push((
778                *peer,
779                stats.bytes.load(Ordering::Relaxed),
780                stats.count.load(Ordering::Relaxed),
781            ));
782        }
783    }
784    let tracked_peers = all.len() as u64;
785    let evictions = SERVED_EVICTIONS.load(Ordering::Relaxed);
786
787    // Top-K by bytes served, descending.
788    all.sort_unstable_by_key(|(_, bytes, _)| std::cmp::Reverse(*bytes));
789
790    // Fixed slots keep the emitted field set stable regardless of how many peers
791    // are currently tracked.
792    let id = |n: usize| all.get(n).map(|(p, _, _)| p.to_hex()).unwrap_or_default();
793    let by = |n: usize| all.get(n).map_or(0, |(_, b, _)| *b);
794    let ct = |n: usize| all.get(n).map_or(0, |(_, _, c)| *c);
795
796    crate::logging::info!(
797        target: "ant_node::replication::traffic",
798        peer_1_id = %id(0), peer_1_bytes = by(0), peer_1_count = ct(0),
799        peer_2_id = %id(1), peer_2_bytes = by(1), peer_2_count = ct(1),
800        peer_3_id = %id(2), peer_3_bytes = by(2), peer_3_count = ct(2),
801        peer_4_id = %id(3), peer_4_bytes = by(3), peer_4_count = ct(3),
802        peer_5_id = %id(4), peer_5_bytes = by(4), peer_5_count = ct(4),
803        peer_6_id = %id(5), peer_6_bytes = by(5), peer_6_count = ct(5),
804        peer_7_id = %id(6), peer_7_bytes = by(6), peer_7_count = ct(6),
805        peer_8_id = %id(7), peer_8_bytes = by(7), peer_8_count = ct(7),
806        peer_9_id = %id(8), peer_9_bytes = by(8), peer_9_count = ct(8),
807        peer_10_id = %id(9), peer_10_bytes = by(9), peer_10_count = ct(9),
808        tracked_peers = tracked_peers,
809        evictions = evictions,
810        "replication served-peers summary (cumulative)"
811    );
812}
813
814// ---------------------------------------------------------------------------
815// Fresh Replication Messages
816// ---------------------------------------------------------------------------
817
818/// Fresh replication offer (includes record + `PoP`).
819///
820/// Sent to close-group members when a node receives a new chunk via client PUT.
821#[derive(Debug, Clone, Serialize, Deserialize)]
822pub struct FreshReplicationOffer {
823    /// The record key.
824    pub key: XorName,
825    /// The record data.
826    pub data: Vec<u8>,
827    /// Proof of Payment (required, validated by receiver).
828    pub proof_of_payment: Vec<u8>,
829}
830
831/// Response to a fresh replication offer.
832#[derive(Debug, Clone, Serialize, Deserialize)]
833pub enum FreshReplicationResponse {
834    /// Record accepted and stored.
835    Accepted {
836        /// The accepted record key.
837        key: XorName,
838    },
839    /// Record rejected (with reason).
840    Rejected {
841        /// The rejected record key.
842        key: XorName,
843        /// Human-readable rejection reason.
844        reason: String,
845    },
846}
847
848/// Paid-list notification carrying key + `PoP` (Section 7.3).
849///
850/// Sent to `PaidCloseGroup` members so they record the key in their
851/// `PaidForList` without needing to hold the record data.
852#[derive(Debug, Clone, Serialize, Deserialize)]
853pub struct PaidNotify {
854    /// The record key.
855    pub key: XorName,
856    /// Proof of Payment for receiver-side verification.
857    pub proof_of_payment: Vec<u8>,
858}
859
860// ---------------------------------------------------------------------------
861// Neighbor Sync Messages
862// ---------------------------------------------------------------------------
863
864/// Neighbor sync request carrying hint sets (Section 6.2).
865///
866/// Exchanged between close neighbors to detect and repair missing replicas.
867#[derive(Debug, Clone, Serialize, Deserialize)]
868pub struct NeighborSyncRequest {
869    /// Keys sender believes receiver should hold (replica hints).
870    pub replica_hints: Vec<XorName>,
871    /// Keys sender believes receiver should track in `PaidForList` (paid hints).
872    pub paid_hints: Vec<XorName>,
873    /// Whether sender is currently bootstrapping.
874    pub bootstrapping: bool,
875    /// Sender's signed storage commitment (optional, see
876    /// [`crate::replication::commitment`]). `None` from old peers; from
877    /// new peers this carries the Merkle-root commitment over the
878    /// sender's claimed keys. Receivers that recognize it store it as
879    /// the per-peer "last known commitment" used to pin commitment-bound
880    /// audits.
881    #[serde(default)]
882    pub commitment: Option<crate::replication::commitment::StorageCommitment>,
883}
884
885/// Neighbor sync response carrying own hint sets.
886#[derive(Debug, Clone, Serialize, Deserialize)]
887pub struct NeighborSyncResponse {
888    /// Keys receiver believes sender should hold (replica hints).
889    pub replica_hints: Vec<XorName>,
890    /// Keys receiver believes sender should track in `PaidForList` (paid hints).
891    pub paid_hints: Vec<XorName>,
892    /// Whether receiver is currently bootstrapping.
893    pub bootstrapping: bool,
894    /// Keys that receiver rejected (optional feedback to sender).
895    pub rejected_keys: Vec<XorName>,
896    /// Receiver's signed storage commitment (optional, see
897    /// [`NeighborSyncRequest::commitment`]).
898    #[serde(default)]
899    pub commitment: Option<crate::replication::commitment::StorageCommitment>,
900}
901
902// ---------------------------------------------------------------------------
903// Verification Messages
904// ---------------------------------------------------------------------------
905
906/// Batched verification request for multiple keys (Section 9).
907///
908/// Sent to peers in `VerifyTargets` (union of `QuorumTargets` and
909/// `PaidTargets`). Each peer returns per-key presence and optionally
910/// paid-list status.
911#[derive(Debug, Clone, Serialize, Deserialize)]
912pub struct VerificationRequest {
913    /// Keys to verify (batched).
914    pub keys: Vec<XorName>,
915    /// Which keys need paid-list status in addition to presence.
916    /// Each value is an index into the `keys` vector.
917    pub paid_list_check_indices: Vec<u32>,
918}
919
920/// Per-key verification result from a peer.
921#[derive(Debug, Clone, Serialize, Deserialize)]
922pub struct KeyVerificationResult {
923    /// The key being verified.
924    pub key: XorName,
925    /// Whether this peer holds the record.
926    pub present: bool,
927    /// Paid-list status (only set if peer was asked for paid-list check).
928    ///
929    /// - `Some(true)` -- key is in peer's `PaidForList`.
930    /// - `Some(false)` -- key is NOT in peer's `PaidForList`.
931    /// - `None` -- paid-list check was not requested for this key.
932    pub paid: Option<bool>,
933}
934
935/// Batched verification response with per-key results.
936#[derive(Debug, Clone, Serialize, Deserialize)]
937pub struct VerificationResponse {
938    /// Per-key results (one per requested key, in request order).
939    pub results: Vec<KeyVerificationResult>,
940}
941
942// ---------------------------------------------------------------------------
943// Fetch Messages
944// ---------------------------------------------------------------------------
945
946/// Request to fetch a specific record by key.
947#[derive(Debug, Clone, Serialize, Deserialize)]
948pub struct FetchRequest {
949    /// The key of the record to fetch.
950    pub key: XorName,
951}
952
953/// Response to a fetch request.
954#[derive(Debug, Clone, Serialize, Deserialize)]
955pub enum FetchResponse {
956    /// Record found and returned.
957    Success {
958        /// The record key.
959        key: XorName,
960        /// The record data.
961        data: Vec<u8>,
962    },
963    /// Record not found on this peer.
964    NotFound {
965        /// The requested key.
966        key: XorName,
967    },
968    /// Error during fetch.
969    Error {
970        /// The requested key.
971        key: XorName,
972        /// Human-readable error description.
973        reason: String,
974    },
975}
976
977// ---------------------------------------------------------------------------
978// Commitment fetch by pin (ADR-0004)
979// ---------------------------------------------------------------------------
980
981/// Request a retained commitment by its pin (commitment hash).
982///
983/// ADR-0004: a storer cross-checking a quote whose `commitment_pin` it does not
984/// already hold (no sidecar, no fresh gossip copy) fetches the signed
985/// commitment so it can verify the binding and route the commitment into audit.
986/// The responder answers only from its retained set, so this never forces a
987/// node to reconstruct or re-sign anything.
988#[derive(Debug, Clone, Serialize, Deserialize)]
989pub struct GetCommitmentByPin {
990    /// The commitment hash (pin) being resolved.
991    pub pin: [u8; 32],
992}
993
994/// Response to [`GetCommitmentByPin`].
995#[derive(Debug, Clone, Serialize, Deserialize)]
996pub enum GetCommitmentByPinResponse {
997    /// The pin resolved to a retained, signed commitment.
998    Found {
999        /// The signed commitment matching the requested pin. The fetcher
1000        /// re-verifies its signature and peer binding before trusting it.
1001        commitment: crate::replication::commitment::StorageCommitment,
1002    },
1003    /// The pin is not among the responder's retained commitments (rotated/aged
1004    /// out, or never held). ADR-0004 treats this as graced, never confirmed:
1005    /// an unanswerable pin is indistinguishable from an honest crash-restart.
1006    NotRetained {
1007        /// Echo of the requested pin, for matching.
1008        pin: [u8; 32],
1009    },
1010}
1011
1012// ---------------------------------------------------------------------------
1013// Pointer Messages (ADR-0016)
1014// ---------------------------------------------------------------------------
1015
1016/// Most hints one [`PointerHints`] message carries. A sender with more splits
1017/// them across messages; a receiver ignores anything past this in one message.
1018pub const MAX_POINTER_HINTS_PER_MESSAGE: usize = 8192;
1019
1020/// Most addresses one [`PointerStateRequest`] asks about. A responder answers
1021/// only this many, and the requester treats the rest as unanswered.
1022pub const MAX_POINTER_STATE_REQUEST_ADDRESSES: usize = 512;
1023
1024/// A pointer state, as a hint or as an answer about what a node holds.
1025///
1026/// The fields the merge rule orders by, and the state they identify, so a
1027/// receiver can tell whether a hinted state would replace what it holds without
1028/// fetching it. Unauthenticated on its own: nothing is stored on the strength
1029/// of a summary. A receiver acts on one only through quorum verification and a
1030/// fetched record whose signature it checks itself.
1031#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1032pub struct PointerStateSummary {
1033    /// The pointer's address.
1034    pub address: XorName,
1035    /// The state's identifier.
1036    pub state_id: XorName,
1037    /// The update counter, the merge rule's first key.
1038    pub counter: u64,
1039    /// The target's kind tag.
1040    pub target_tag: u8,
1041    /// The target's address. With the tag, the merge rule's second key.
1042    pub target_address: XorName,
1043}
1044
1045impl From<ant_protocol::pointer::PointerState> for PointerStateSummary {
1046    fn from(state: ant_protocol::pointer::PointerState) -> Self {
1047        Self {
1048            address: state.address,
1049            state_id: state.state_id,
1050            counter: state.counter,
1051            target_tag: state.target.kind_tag(),
1052            target_address: state.target.address,
1053        }
1054    }
1055}
1056
1057impl From<PointerStateSummary> for ant_protocol::pointer::PointerState {
1058    fn from(summary: PointerStateSummary) -> Self {
1059        Self {
1060            state_id: summary.state_id,
1061            address: summary.address,
1062            counter: summary.counter,
1063            target: ant_protocol::pointer::PointerTarget::from_raw_tag(
1064                summary.target_tag,
1065                summary.target_address,
1066            ),
1067        }
1068    }
1069}
1070
1071/// A newly paid pointer state, with the proof that paid for it.
1072///
1073/// Sent by a node that accepted the state from a paying client to the rest of
1074/// the pointer's close group, which verifies the proof itself.
1075#[derive(Debug, Clone, Serialize, Deserialize)]
1076pub struct PointerFreshOffer {
1077    /// The pointer record, in its canonical encoding.
1078    pub record: Vec<u8>,
1079    /// Serialized proof of payment for the record's state.
1080    pub proof_of_payment: Vec<u8>,
1081}
1082
1083/// The pointer states the sender holds that the receiver should hold too.
1084///
1085/// Sent on every neighbour-sync round, empty if there is nothing to say: an
1086/// empty message still tells the receiver the sender understands pointers.
1087#[derive(Debug, Clone, Serialize, Deserialize)]
1088pub struct PointerHints {
1089    /// The states, at most [`MAX_POINTER_HINTS_PER_MESSAGE`] of them.
1090    pub hints: Vec<PointerStateSummary>,
1091}
1092
1093/// Ask a peer for the pointer record it holds at an address.
1094#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
1095pub struct PointerFetchRequest {
1096    /// The pointer's address.
1097    pub address: XorName,
1098}
1099
1100/// Response to [`PointerFetchRequest`].
1101#[derive(Debug, Clone, Serialize, Deserialize)]
1102pub struct PointerFetchResponse {
1103    /// Echo of the requested address.
1104    pub address: XorName,
1105    /// The record held there, if any.
1106    pub record: Option<Vec<u8>>,
1107}
1108
1109/// Ask a peer which state it holds at each of some addresses.
1110#[derive(Debug, Clone, Serialize, Deserialize)]
1111pub struct PointerStateRequest {
1112    /// The addresses, at most [`MAX_POINTER_STATE_REQUEST_ADDRESSES`].
1113    pub addresses: Vec<XorName>,
1114}
1115
1116/// Response to [`PointerStateRequest`].
1117#[derive(Debug, Clone, Serialize, Deserialize)]
1118pub struct PointerStateResponse {
1119    /// One entry per requested address, in order: the state held, or `None`.
1120    pub states: Vec<Option<PointerStateSummary>>,
1121}
1122
1123// ---------------------------------------------------------------------------
1124// Audit Messages
1125// ---------------------------------------------------------------------------
1126
1127/// Per-key audit challenge.
1128///
1129/// The challenger picks a random nonce and a set of keys the challenged peer
1130/// should hold, then sends this challenge. The challenged peer proves storage
1131/// by returning per-key BLAKE3 digests. Used by the responsible-chunk audit
1132/// (audit #2: a node samples keys a close peer should hold) and by the
1133/// prune-confirmation path (a node checks a peer still holds a key before
1134/// pruning its own copy).
1135#[derive(Debug, Clone, Serialize, Deserialize)]
1136pub struct AuditChallenge {
1137    /// Unique challenge identifier.
1138    pub challenge_id: u64,
1139    /// Random nonce for digest computation.
1140    pub nonce: [u8; 32],
1141    /// Challenged peer ID (included in digest computation).
1142    pub challenged_peer_id: [u8; 32],
1143    /// Ordered list of keys to prove storage of.
1144    pub keys: Vec<XorName>,
1145}
1146
1147/// Response to a per-key audit challenge.
1148#[derive(Debug, Clone, Serialize, Deserialize)]
1149pub enum AuditResponse {
1150    /// Per-key digests proving storage.
1151    ///
1152    /// `digests[i]` corresponds to `challenge.keys[i]`.
1153    /// An [`ABSENT_KEY_DIGEST`] sentinel signals key absence.
1154    Digests {
1155        /// The challenge this response answers.
1156        challenge_id: u64,
1157        /// One 32-byte digest per challenged key, in challenge order.
1158        digests: Vec<[u8; 32]>,
1159    },
1160    /// Peer is still bootstrapping (not ready for audit).
1161    Bootstrapping {
1162        /// The challenge this response answers.
1163        challenge_id: u64,
1164    },
1165    /// Challenge rejected (wrong target peer or too many keys).
1166    ///
1167    /// Distinct from empty `Digests` so the challenger can distinguish a
1168    /// legitimate rejection from misbehavior.
1169    Rejected {
1170        /// The challenge this response answers.
1171        challenge_id: u64,
1172        /// Human-readable rejection reason.
1173        reason: String,
1174    },
1175}
1176
1177/// Gossip-triggered contiguous-subtree storage audit challenge (ADR-0002).
1178///
1179/// The auditor pins the commitment a peer just gossiped and sends a fresh
1180/// random nonce. The nonce alone deterministically selects one contiguous
1181/// subtree of the peer's committed Merkle tree (see
1182/// [`crate::replication::subtree::select_subtree_path`]); the auditor does
1183/// **not** name keys. The responder must reply with a
1184/// [`SubtreeAuditResponse::Proof`] for that selected subtree against the pinned
1185/// commitment, or a [`SubtreeAuditResponse::Rejected`] if it genuinely cannot
1186/// (for a recently gossiped pinned commitment a rejection is a confirmed
1187/// failure, since the responder retains its recently gossiped commitments for a
1188/// bounded TTL window).
1189#[derive(Debug, Clone, Serialize, Deserialize)]
1190pub struct SubtreeAuditChallenge {
1191    /// Unique challenge identifier.
1192    pub challenge_id: u64,
1193    /// Random nonce. Selects the subtree AND freshens each leaf's possession
1194    /// hash, so a stored answer cannot be replayed.
1195    pub nonce: [u8; 32],
1196    /// Challenged peer ID. Bound into each leaf's possession hash.
1197    pub challenged_peer_id: [u8; 32],
1198    /// The auditor's pin: the [`crate::replication::commitment::commitment_hash`]
1199    /// of the commitment the peer just gossiped. The response's commitment must
1200    /// hash to exactly this value.
1201    pub expected_commitment_hash: [u8; 32],
1202}
1203
1204/// Response to a contiguous-subtree storage audit challenge (ADR-0002).
1205#[derive(Debug, Clone, Serialize, Deserialize)]
1206pub enum SubtreeAuditResponse {
1207    /// The single-contiguous-subtree proof.
1208    ///
1209    /// Carries the responder's signed commitment (so the auditor re-derives
1210    /// `key_count` and confirms the pin and signature) and the
1211    /// nonce-selected subtree expanded to its leaves plus the sibling
1212    /// cut-hashes on the path to the root. This is **round 1** of the
1213    /// two-round audit. The auditor:
1214    ///   1. confirms `commitment_hash(commitment) == expected_commitment_hash`
1215    ///      and the signature is valid;
1216    ///   2. re-derives the selected subtree from `(nonce, key_count)`, rebuilds
1217    ///      the root from the proof, and requires it to equal the commitment
1218    ///      root (structure).
1219    ///
1220    /// The leaves carry only hashes (`bytes_hash`, `nonced_root`), so this round
1221    /// proves the tree SHAPE is committed — not that the bytes are still held.
1222    /// Real possession is proven in **round 2**: the auditor picks a few of the
1223    /// just-verified leaves and sends a [`SubtreeSliceChallenge`] opening one
1224    /// random 1 KiB block of each against both the chunk address and the round-1
1225    /// `nonced_root` (see that type).
1226    Proof {
1227        /// The challenge this response answers.
1228        challenge_id: u64,
1229        /// The signed commitment whose root the proof is against.
1230        commitment: crate::replication::commitment::StorageCommitment,
1231        /// The nonce-selected contiguous subtree proof.
1232        proof: crate::replication::subtree::SubtreeProof,
1233    },
1234    /// Peer is still bootstrapping (not ready for audit).
1235    Bootstrapping {
1236        /// The challenge this response answers.
1237        challenge_id: u64,
1238    },
1239    /// Challenge rejected. `kind` drives the auditor's accounting (confirmed vs
1240    /// graced); `reason` is the human-readable detail for logs.
1241    Rejected {
1242        /// The challenge this response answers.
1243        challenge_id: u64,
1244        /// Machine-readable rejection class (accounting).
1245        kind: RejectKind,
1246        /// Human-readable rejection reason.
1247        reason: String,
1248    },
1249}
1250
1251/// Why a responder rejected an audit challenge, in a form the auditor can act
1252/// on without string-matching.
1253///
1254/// ADR-0004 Amendment 1: audit **grace is removed**. Answerability is now
1255/// restart-durable (the responder persists and reloads its commitment retention)
1256/// and the auditor only pins roots inside the answerability window, so an honest
1257/// node can always answer a pin it could be challenged on. The auditor therefore
1258/// grades a responsive rejection purely by kind, with no grace:
1259/// - `UnknownCommitment` / `Protocol` → **confirmed failure**: repudiating a
1260///   pinned root the node published (and may have been paid for), or an explicit
1261///   protocol fault.
1262/// - `Transient` → routed to the **non-response/timeout lane** (no trust penalty,
1263///   but the holder credit for the pinned commitment IS revoked). The responder
1264///   retries reads before emitting `Transient`, so one that still reaches the
1265///   auditor means the node could not serve data it committed to. A
1266///   `Transient`-spammer thus gains no positive standing; deterministically
1267///   distinguishing malicious from genuine transient IO network-wide is the
1268///   out-of-scope distributed non-response problem.
1269#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1270pub enum RejectKind {
1271    /// The responder does not retain the pinned commitment. With restart-durable
1272    /// retention and in-window auditing this is provable repudiation of a root
1273    /// the node published → CONFIRMED failure.
1274    UnknownCommitment,
1275    /// A transient, recoverable local condition (e.g. a storage read error),
1276    /// emitted only after the responder's read retries failed. Routed to the
1277    /// timeout lane (holder credit revoked, no trust penalty).
1278    Transient,
1279    /// Any other rejection (wrong target peer, no commitment state, malformed
1280    /// proof plan, oversized slice challenge, …). CONFIRMED failure.
1281    Protocol,
1282}
1283
1284/// A single block the round-2 slice challenge opens: which committed key, and
1285/// which 1 KiB block within it.
1286///
1287/// The `block_index` is drawn with FRESH auditor randomness after round 1 (never
1288/// nonce-derived), so the responder cannot have prepared only the opened block.
1289#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1290pub struct SubtreeSliceOpening {
1291    /// The committed key whose block is opened.
1292    pub key: XorName,
1293    /// The 1 KiB block index within the chunk, in `0..block_count(content_len)`.
1294    pub block_index: u32,
1295}
1296
1297/// Round 2 of the storage audit (ADR-0002 / V2-685): the **surprise slice
1298/// challenge**.
1299///
1300/// After structurally verifying a [`SubtreeAuditResponse::Proof`] the auditor
1301/// picks a small sample of the just-proven leaves with FRESH randomness (chosen
1302/// now, after the proof is committed — NOT derived from the round-1 nonce) and,
1303/// for each, a fresh-random 1 KiB block index. It asks the responder to open
1304/// exactly those blocks. For each opened block the responder returns a Bao
1305/// verified slice plus a nonced block-tree opening; the auditor checks, over the
1306/// same block bytes:
1307///   - the Bao slice against `leaf.bytes_hash` (the chunk's content address), AND
1308///   - the nonced opening against `leaf.nonced_root` (round-1 possession commit).
1309///
1310/// The pair binds the opened block to bytes that were held when round 1 was
1311/// answered, cheaply: the response is a few KB, not up to two 4 MiB chunks.
1312/// Whoever answered round 1 without the bytes cannot have committed a correct
1313/// `nonced_root`, and cannot fold an after-the-fact-fetched block to a foreign
1314/// root without a preimage break.
1315///
1316/// What it does NOT bind is *which* party held them. Every input is public, so
1317/// a backend holding one copy can answer for any number of front-end
1318/// identities; the proof is delegable, and cheaper to delegate than the
1319/// full-byte round 2 it replaces, which priced delegation by forcing the chunk
1320/// through the relay. ADR-0009 records that as a known gap. Anything in this
1321/// tree that reads as "non-delegable" or "a relay blows the deadline" is a
1322/// claim about the older design and is superseded there.
1323#[derive(Debug, Clone, Serialize, Deserialize)]
1324pub struct SubtreeSliceChallenge {
1325    /// The same `challenge_id` as the round-1 [`SubtreeAuditChallenge`], so the
1326    /// responder/auditor correlate the two rounds.
1327    pub challenge_id: u64,
1328    /// The same nonce as round 1 — binds each nonced block opening to this audit.
1329    pub nonce: [u8; 32],
1330    /// The challenged peer ID (bound into every nonced block leaf).
1331    pub challenged_peer_id: [u8; 32],
1332    /// The pinned commitment hash from round 1, so the responder resolves the
1333    /// SAME tree it just proved and opens blocks only for keys it committed to.
1334    pub expected_commitment_hash: [u8; 32],
1335    /// The exact blocks to open: the auditor's freshly-randomised spot-check
1336    /// sample of the round-1 subtree (chosen after the proof was received; not
1337    /// nonce-derived), up to two blocks per sampled leaf (a fresh-random block
1338    /// plus the final block, for the content-length pin).
1339    pub openings: Vec<SubtreeSliceOpening>,
1340}
1341
1342/// One opened block in a [`SubtreeSliceResponse`].
1343#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1344pub enum SubtreeSliceItem {
1345    /// The responder holds this committed key and opens the requested block.
1346    Present {
1347        /// The requested key.
1348        key: XorName,
1349        /// The 1 KiB block index that was opened.
1350        block_index: u32,
1351        /// Bao verified slice: the block bytes plus the BLAKE3 parent hashes that
1352        /// authenticate them against the chunk address. The auditor decodes this
1353        /// to recover the verified block bytes.
1354        bao_slice: Vec<u8>,
1355        /// Sibling hashes on the path from this block up to the committed
1356        /// `nonced_root`, bottom-up. The auditor folds the block leaf with these
1357        /// to prove the block was committed under round 1's fresh nonce.
1358        nonced_siblings: Vec<[u8; 32]>,
1359    },
1360    /// The responder committed to this key but cannot serve its block. This is a
1361    /// PROVABLE cheat (it published a commitment over a chunk it does not hold),
1362    /// so the auditor counts it as a confirmed failure — NOT a graced timeout.
1363    /// Distinguishing this explicit signal from silence is what separates a
1364    /// deleter (instant fail) from a dropped packet (timeout).
1365    Absent {
1366        /// The committed key the responder could not serve.
1367        key: XorName,
1368    },
1369    /// The responder holds this committed pointer (ADR-0016) and serves the
1370    /// whole signed record. A pointer's address is not a content hash, so no
1371    /// slice of it could be authenticated against the address; the record can
1372    /// be, by its signature, and against the nonced root round 1 bound over
1373    /// its bytes. One per requested pointer key, whatever blocks were named.
1374    PointerRecord {
1375        /// The requested key: the pointer's address.
1376        key: XorName,
1377        /// The record held now, and the one an update replaced since round 1
1378        /// if there was one, each in its canonical encoding. At most
1379        /// [`MAX_POINTER_RECORDS_PER_ITEM`]: round 1 bound one of them, and
1380        /// the responder cannot tell which without keeping round 1's answer.
1381        records: Vec<Vec<u8>>,
1382    },
1383}
1384
1385/// Most records one [`SubtreeSliceItem::PointerRecord`] may carry: the one
1386/// held now and the one it replaced.
1387pub const MAX_POINTER_RECORDS_PER_ITEM: usize = 2;
1388
1389/// Response to a [`SubtreeSliceChallenge`] (round 2).
1390///
1391/// The contract is **coalesced and order-independent**: the responder groups the
1392/// requested openings by key (reading and hashing each chunk once), so
1393/// - a `Present` item is unique per distinct `(key, block_index)`;
1394/// - an `Absent` item is at most one per key and covers ALL of that key's
1395///   requested openings (it has no `block_index`);
1396/// - duplicate requested openings do not multiply work or response items;
1397/// - item order is unspecified — the auditor matches by identity, not position.
1398///
1399/// The auditor rejects a response whose identities collide (a duplicate
1400/// `(key, block_index)`, or a key that is both `Present` and `Absent`) as
1401/// malformed, so first-match ambiguity cannot decide a verdict.
1402///
1403/// Each item is a few KB (a 1 KiB block plus O(log n) hashes on two short
1404/// chains), so even the worst-case sample fits far under
1405/// [`MAX_REPLICATION_MESSAGE_SIZE`] with no batching — the auditor bounds the
1406/// sample to [`MAX_SLICE_OPENINGS`](super::config::MAX_SLICE_OPENINGS) and the
1407/// responder rejects larger requests.
1408#[derive(Debug, Clone, Serialize, Deserialize)]
1409pub enum SubtreeSliceResponse {
1410    /// The responder's per-opening answers (a verified slice or an absent signal).
1411    Items {
1412        /// The challenge this response answers.
1413        challenge_id: u64,
1414        /// One item per DISTINCT requested opening, coalesced and
1415        /// order-independent (see the type-level contract above): duplicate
1416        /// openings do not multiply items, and one `Absent` covers all of a
1417        /// key's openings.
1418        items: Vec<SubtreeSliceItem>,
1419    },
1420    /// Peer is still bootstrapping (should not happen mid-audit, but handled).
1421    Bootstrapping {
1422        /// The challenge this response answers.
1423        challenge_id: u64,
1424    },
1425    /// The responder rejects the slice challenge outright. `kind` drives the
1426    /// auditor's accounting (ADR-0004 A1: grace removed): [`RejectKind::Transient`]
1427    /// routes to the timeout lane (no trust penalty, holder credit revoked); every
1428    /// other kind is a confirmed failure, like round 1.
1429    Rejected {
1430        /// The challenge this response answers.
1431        challenge_id: u64,
1432        /// Machine-readable rejection class (accounting).
1433        kind: RejectKind,
1434        /// Human-readable rejection reason.
1435        reason: String,
1436    },
1437}
1438
1439// ---------------------------------------------------------------------------
1440// Audit digest helper
1441// ---------------------------------------------------------------------------
1442
1443/// Compute `AuditKeyDigest(K_i) = BLAKE3(nonce || challenged_peer_id || K_i || record_bytes_i)`.
1444///
1445/// This is the existing digest construction used by the core responsible-chunk,
1446/// post-replication possession, and prune-confirmation audit lanes. The subtree
1447/// slice audit has its own proof-specific keyed construction in `slice.rs`.
1448#[must_use]
1449pub fn compute_audit_digest(
1450    nonce: &[u8; 32],
1451    challenged_peer_id: &[u8; 32],
1452    key: &XorName,
1453    record_bytes: &[u8],
1454) -> [u8; 32] {
1455    let mut hasher = blake3::Hasher::new();
1456    hasher.update(nonce);
1457    hasher.update(challenged_peer_id);
1458    hasher.update(key);
1459    hasher.update(record_bytes);
1460    *hasher.finalize().as_bytes()
1461}
1462
1463// ---------------------------------------------------------------------------
1464// Error type
1465// ---------------------------------------------------------------------------
1466
1467/// Errors from replication protocol encode/decode operations.
1468#[derive(Debug, Clone)]
1469pub enum ReplicationProtocolError {
1470    /// Postcard serialization failed.
1471    SerializationFailed(String),
1472    /// Postcard deserialization failed.
1473    DeserializationFailed(String),
1474    /// Wire message exceeds the maximum allowed size.
1475    MessageTooLarge {
1476        /// Actual size of the message in bytes.
1477        size: usize,
1478        /// Maximum allowed size.
1479        max_size: usize,
1480    },
1481}
1482
1483impl std::fmt::Display for ReplicationProtocolError {
1484    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1485        match self {
1486            Self::SerializationFailed(msg) => {
1487                write!(f, "replication serialization failed: {msg}")
1488            }
1489            Self::DeserializationFailed(msg) => {
1490                write!(f, "replication deserialization failed: {msg}")
1491            }
1492            Self::MessageTooLarge { size, max_size } => {
1493                write!(
1494                    f,
1495                    "replication message size {size} exceeds maximum {max_size}"
1496                )
1497            }
1498        }
1499    }
1500}
1501
1502impl std::error::Error for ReplicationProtocolError {}
1503
1504// ---------------------------------------------------------------------------
1505// Tests
1506// ---------------------------------------------------------------------------
1507
1508#[cfg(test)]
1509#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1510mod tests {
1511    use super::*;
1512
1513    // === Audit outcome counters ===
1514
1515    /// No other test mutates the audit outcome counters, so per-slot deltas are
1516    /// stable even under parallel test execution.
1517    #[test]
1518    fn audit_outcome_counters_tally_by_kind_and_reason() {
1519        let pass_slot = AuditOutcomeKind::Subtree as usize;
1520        let before = AUDIT_PASS[pass_slot].load(Ordering::Relaxed);
1521        record_audit_pass(AuditOutcomeKind::Subtree);
1522        assert_eq!(AUDIT_PASS[pass_slot].load(Ordering::Relaxed), before + 1);
1523
1524        let reasons = [
1525            AuditFailureReason::Timeout,
1526            AuditFailureReason::MalformedResponse,
1527            AuditFailureReason::DigestMismatch,
1528            AuditFailureReason::KeyAbsent,
1529            AuditFailureReason::Rejected,
1530        ];
1531        for (kind, kind_index) in [
1532            (AuditOutcomeKind::Responsible, 0usize),
1533            (AuditOutcomeKind::Subtree, 1usize),
1534        ] {
1535            for (reason_index, reason) in reasons.iter().enumerate() {
1536                let slot = kind_index * N_FAIL_REASONS + reason_index;
1537                let before = AUDIT_FAIL[slot].load(Ordering::Relaxed);
1538                record_audit_fail(kind, reason);
1539                assert_eq!(
1540                    AUDIT_FAIL[slot].load(Ordering::Relaxed),
1541                    before + 1,
1542                    "kind {kind_index} reason {reason:?} must land in its own slot",
1543                );
1544            }
1545        }
1546
1547        for (kind, kind_index) in [
1548            (AuditDropKind::Responsible, 0usize),
1549            (AuditDropKind::Subtree, 1usize),
1550            (AuditDropKind::Slice, 2usize),
1551        ] {
1552            let before = AUDIT_DROPPED[kind_index].load(Ordering::Relaxed);
1553            record_audit_drop(kind);
1554            assert_eq!(
1555                AUDIT_DROPPED[kind_index].load(Ordering::Relaxed),
1556                before + 1
1557            );
1558        }
1559    }
1560
1561    // === Round-2 slice response sizing ===
1562
1563    #[test]
1564    fn max_slice_response_is_tiny_relative_to_wire_cap() {
1565        // A worst-case round-2 slice response is MAX_SLICE_OPENINGS openings, each
1566        // a 1 KiB block plus a Bao proof and a nonced sibling chain. For a 4 MiB
1567        // chunk that is ~4096 BLAKE3 chunks → ~12 parent hashes per chain. We
1568        // overestimate generously (16 KiB slice + 24 sibling hashes per opening)
1569        // and assert it encodes far under the wire cap — the whole point of the
1570        // change is that round 2 is now KB-scale, not up to 8 MiB.
1571        let items: Vec<SubtreeSliceItem> = (0..crate::replication::config::MAX_SLICE_OPENINGS)
1572            .map(|i| SubtreeSliceItem::Present {
1573                key: [u8::try_from(i).unwrap_or(u8::MAX); 32],
1574                block_index: u32::try_from(i).unwrap_or(u32::MAX),
1575                bao_slice: vec![0xAB; 16 * 1024],
1576                nonced_siblings: vec![[0x5A; 32]; 24],
1577            })
1578            .collect();
1579        let msg = ReplicationMessage {
1580            request_id: 7,
1581            body: ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Items {
1582                challenge_id: 7,
1583                items,
1584            }),
1585        };
1586        let encoded = msg
1587            .encode()
1588            .expect("worst-case slice response must fit the wire cap");
1589        // Comfortably under 1 MiB, itself a fraction of the 10 MiB wire cap.
1590        assert!(encoded.len() <= 1024 * 1024);
1591        assert!(encoded.len() <= MAX_REPLICATION_MESSAGE_SIZE);
1592        assert!(
1593            encoded.len() <= crate::replication::config::MAX_SUBTREE_AUDIT_MESSAGE_SIZE,
1594            "round 2 must fit the tighter audit-family ceiling"
1595        );
1596    }
1597
1598    // The audit families take a much tighter wire ceiling than the 10 MiB core
1599    // one, checked before decoding so an unknown peer cannot make this node
1600    // allocate megabytes before any admission check has run. That ceiling is
1601    // only safe if it clears the largest body an honest audit can produce, which
1602    // is the round-1 proof at the commitment key-count cap: 1,024 leaves plus
1603    // the sibling cut hashes and the signed commitment. Build that worst case
1604    // and pin the headroom, so a later change to leaf size or commitment
1605    // encoding cannot quietly start dropping honest proofs.
1606    #[test]
1607    fn max_round1_proof_fits_the_audit_family_ceiling() {
1608        use crate::replication::commitment::{StorageCommitment, MAX_COMMITMENT_KEY_COUNT};
1609        use crate::replication::config::MAX_SUBTREE_AUDIT_MESSAGE_SIZE;
1610        use crate::replication::subtree::{max_subtree_leaves, SubtreeLeaf, SubtreeProof};
1611
1612        let leaf_count = max_subtree_leaves(MAX_COMMITMENT_KEY_COUNT) as usize;
1613        let leaves: Vec<SubtreeLeaf> = (0..leaf_count)
1614            .map(|_| SubtreeLeaf {
1615                key: [0xAB; 32],
1616                bytes_hash: [0xCD; 32],
1617                content_len: u32::MAX,
1618                nonced_root: [0xEF; 32],
1619            })
1620            .collect();
1621        let msg = ReplicationMessage {
1622            request_id: 11,
1623            body: ReplicationMessageBody::SubtreeAuditResponse(SubtreeAuditResponse::Proof {
1624                challenge_id: 11,
1625                commitment: StorageCommitment {
1626                    root: [0x01; 32],
1627                    key_count: MAX_COMMITMENT_KEY_COUNT,
1628                    sender_peer_id: [0x02; 32],
1629                    // Over-sized stand-ins for the ML-DSA-65 key and signature.
1630                    sender_public_key: vec![0x03; 4096],
1631                    signature: vec![0x04; 8192],
1632                },
1633                proof: SubtreeProof {
1634                    leaves,
1635                    // One per level down to the subtree root; 32 is far past the
1636                    // real depth at this key count.
1637                    sibling_cut_hashes: vec![[0x05; 32]; 32],
1638                },
1639            }),
1640        };
1641        // Measure without going through `encode`, which now enforces this very
1642        // ceiling: encoding first would turn a regression into an opaque
1643        // `MessageTooLarge` from the guard instead of the explicit, diagnosable
1644        // assertion below.
1645        let encoded = postcard::to_stdvec(&msg).expect("serialize");
1646        assert!(
1647            encoded.len() <= MAX_SUBTREE_AUDIT_MESSAGE_SIZE,
1648            "worst legitimate round-1 proof is {} bytes, over the audit ceiling of \
1649             {MAX_SUBTREE_AUDIT_MESSAGE_SIZE}",
1650            encoded.len()
1651        );
1652        // And it must genuinely pass the guard, not merely fit the number.
1653        assert!(
1654            msg.encode().is_ok(),
1655            "the worst legitimate round-1 proof must still be encodable"
1656        );
1657    }
1658
1659    /// Every body variant, in declaration order, so a test can walk the whole
1660    /// enum rather than a hand-picked sample.
1661    fn all_bodies() -> Vec<ReplicationMessageBody> {
1662        let z = [0u8; 32];
1663        vec![
1664            ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
1665                key: z,
1666                data: vec![],
1667                proof_of_payment: vec![],
1668            }),
1669            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Accepted {
1670                key: z,
1671            }),
1672            ReplicationMessageBody::PaidNotify(PaidNotify {
1673                key: z,
1674                proof_of_payment: vec![],
1675            }),
1676            ReplicationMessageBody::NeighborSyncRequest(NeighborSyncRequest {
1677                replica_hints: vec![],
1678                paid_hints: vec![],
1679                bootstrapping: false,
1680                commitment: None,
1681            }),
1682            ReplicationMessageBody::NeighborSyncResponse(NeighborSyncResponse {
1683                replica_hints: vec![],
1684                paid_hints: vec![],
1685                bootstrapping: false,
1686                rejected_keys: vec![],
1687                commitment: None,
1688            }),
1689            ReplicationMessageBody::VerificationRequest(VerificationRequest {
1690                keys: vec![],
1691                paid_list_check_indices: vec![],
1692            }),
1693            ReplicationMessageBody::VerificationResponse(VerificationResponse { results: vec![] }),
1694            ReplicationMessageBody::FetchRequest(FetchRequest { key: z }),
1695            ReplicationMessageBody::FetchResponse(FetchResponse::NotFound { key: z }),
1696            ReplicationMessageBody::AuditChallenge(AuditChallenge {
1697                challenge_id: 1,
1698                nonce: z,
1699                challenged_peer_id: z,
1700                keys: vec![],
1701            }),
1702            ReplicationMessageBody::AuditResponse(AuditResponse::Digests {
1703                challenge_id: 1,
1704                digests: vec![],
1705            }),
1706            ReplicationMessageBody::SubtreeAuditChallenge(SubtreeAuditChallenge {
1707                challenge_id: 1,
1708                nonce: z,
1709                challenged_peer_id: z,
1710                expected_commitment_hash: z,
1711            }),
1712            ReplicationMessageBody::SubtreeAuditResponse(SubtreeAuditResponse::Bootstrapping {
1713                challenge_id: 1,
1714            }),
1715            ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
1716                challenge_id: 1,
1717                nonce: z,
1718                challenged_peer_id: z,
1719                expected_commitment_hash: z,
1720                openings: vec![],
1721            }),
1722            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Bootstrapping {
1723                challenge_id: 1,
1724            }),
1725            ReplicationMessageBody::GetCommitmentByPin(GetCommitmentByPin { pin: z }),
1726            ReplicationMessageBody::GetCommitmentByPinResponse(
1727                GetCommitmentByPinResponse::NotRetained { pin: z },
1728            ),
1729            ReplicationMessageBody::PointerFreshOffer(PointerFreshOffer {
1730                record: vec![],
1731                proof_of_payment: vec![],
1732            }),
1733            ReplicationMessageBody::PointerHints(PointerHints { hints: vec![] }),
1734            ReplicationMessageBody::PointerFetchRequest(PointerFetchRequest { address: z }),
1735            ReplicationMessageBody::PointerFetchResponse(PointerFetchResponse {
1736                address: z,
1737                record: None,
1738            }),
1739            ReplicationMessageBody::PointerStateRequest(PointerStateRequest { addresses: vec![] }),
1740            ReplicationMessageBody::PointerStateResponse(PointerStateResponse { states: vec![] }),
1741        ]
1742    }
1743
1744    // The pre-decode ceiling reads the body's discriminant straight off the
1745    // wire, so `peek_variant_index` MUST agree with `variant_index()` for every
1746    // variant, at request ids that straddle postcard's varint width boundaries.
1747    // If it ever disagreed, a body would be sized against the wrong family's
1748    // ceiling — which is the bug this whole path exists to prevent.
1749    #[test]
1750    fn peeked_discriminant_matches_the_decoded_one_for_every_variant() {
1751        // 1-byte, 2-byte, 5-byte and 10-byte `request_id` varints.
1752        for request_id in [0u64, 1, 127, 128, 300, u64::from(u32::MAX), u64::MAX] {
1753            for body in all_bodies() {
1754                let expected = body.variant_index();
1755                let encoded = ReplicationMessage { request_id, body }
1756                    .encode()
1757                    .expect("encode");
1758                assert_eq!(
1759                    peek_variant_index(&encoded),
1760                    Some(expected),
1761                    "peek disagreed with variant_index at request_id {request_id}"
1762                );
1763            }
1764        }
1765    }
1766
1767    // A truncated or nonsense prefix must not classify as `Core`, because Core
1768    // is the LENIENT ceiling. Failing to classify has to mean "apply the strict
1769    // one", never "let it through".
1770    #[test]
1771    fn unclassifiable_prefix_yields_no_family() {
1772        assert_eq!(peek_variant_index(&[]), None);
1773        // A varint that never terminates: all continuation bits set.
1774        assert_eq!(peek_variant_index(&[0xFF; 32]), None);
1775        // A well-formed request_id with nothing after it.
1776        assert_eq!(peek_variant_index(&[0x01]), None);
1777        // Ten-byte u64 varints have only one payload bit in the final byte.
1778        // Reject overflow in either prefix field instead of letting the shift
1779        // discard high bits and classify attacker-controlled trailing bytes.
1780        let mut overflowing_request_id = vec![0x80; 9];
1781        overflowing_request_id.extend([0x02, 0x0B]);
1782        assert_eq!(peek_variant_index(&overflowing_request_id), None);
1783
1784        let mut overflowing_discriminant = vec![0x01];
1785        overflowing_discriminant.extend([0x80; 9]);
1786        overflowing_discriminant.push(0x02);
1787        assert_eq!(peek_variant_index(&overflowing_discriminant), None);
1788    }
1789
1790    // Regression (dirvine, PR #181): the pre-decode ceiling used to be chosen
1791    // from the protocol id the message arrived on, so an audit body addressed to
1792    // the CORE id skipped the audit ceiling and was decoded under the 10 MiB core
1793    // allowance — its collections allocated — before the family guard dropped it.
1794    //
1795    // The reproduction from that review: a valid `SubtreeSliceChallenge` with
1796    // 200,000 openings encodes to ~6.6 MB, far past the 512 KiB audit ceiling.
1797    // Classifying by discriminant catches it wherever it is addressed.
1798    #[test]
1799    fn oversized_audit_body_is_classified_as_audit_wherever_it_is_addressed() {
1800        let z = [0u8; 32];
1801        let challenge = SubtreeSliceChallenge {
1802            challenge_id: 1,
1803            nonce: z,
1804            challenged_peer_id: z,
1805            expected_commitment_hash: z,
1806            openings: (0..200_000u32)
1807                .map(|i| SubtreeSliceOpening {
1808                    key: z,
1809                    block_index: i,
1810                })
1811                .collect(),
1812        };
1813        // Serialised directly rather than through `encode`, which now refuses to
1814        // emit an audit body over the audit ceiling. That guard protects honest
1815        // senders; it says nothing about what arrives, since a hostile peer does
1816        // not run our encoder. Building the bytes the way an attacker would is
1817        // what keeps this a test of the RECEIVE path.
1818        let encoded = postcard::to_stdvec(&ReplicationMessage {
1819            request_id: 1,
1820            body: ReplicationMessageBody::SubtreeSliceChallenge(challenge),
1821        })
1822        .expect("serialize");
1823        // Pin BOTH bounds. Going through `encode` used to imply the upper one;
1824        // asserting it keeps the reproduction meaningful, since a body over the
1825        // core ceiling would be refused by size alone and would no longer
1826        // demonstrate that classification is what catches it.
1827        assert!(
1828            encoded.len() < crate::replication::config::MAX_REPLICATION_MESSAGE_SIZE,
1829            "the reproduction must sit UNDER the core ceiling, or it proves \
1830             nothing about family classification; got {} bytes",
1831            encoded.len()
1832        );
1833
1834        assert!(
1835            encoded.len() > crate::replication::config::MAX_SUBTREE_AUDIT_MESSAGE_SIZE,
1836            "the reproduction must exceed the audit ceiling to be meaningful; got {} bytes",
1837            encoded.len()
1838        );
1839        // The classification the receive path performs, before any decode.
1840        let family = peek_variant_index(&encoded).and_then(family_of_variant);
1841        assert_eq!(family, Some(BodyFamily::SubtreeAudit));
1842        assert!(
1843            family.is_none_or(BodyFamily::is_audit),
1844            "an audit body must take the audit ceiling regardless of the id it rode"
1845        );
1846    }
1847
1848    // The family table is the single source of truth: the `&self` predicates,
1849    // the response routing and the pre-decode ceiling all read it, so they
1850    // cannot drift. Walk every variant and check both views agree.
1851    #[test]
1852    fn family_table_agrees_with_the_body_predicates() {
1853        for body in all_bodies() {
1854            let family = family_of_variant(body.variant_index());
1855            // Every DECLARED variant must classify. `None` is reserved for an
1856            // index no variant uses; a real body landing there would silently
1857            // take the strict ceiling on both encode and decode.
1858            let family = family.expect("every declared variant must have a family");
1859            assert_eq!(body.is_subtree_audit(), family == BodyFamily::SubtreeAudit);
1860            assert_eq!(family.is_audit(), body.is_subtree_audit());
1861        }
1862    }
1863
1864    /// The encoder applies the same family ceiling the decoder does. Without
1865    /// this, an audit body that outgrew the audit ceiling would serialise
1866    /// happily and then be dropped pre-decode by every peer that received it —
1867    /// and since the drop is silent, the sender would be scored for the
1868    /// resulting non-answer rather than told its message was unsendable.
1869    ///
1870    /// No legitimate body reaches the ceiling today; this is about where the
1871    /// failure surfaces if one ever does.
1872    ///
1873    /// FLIPS IF: `encode` goes back to checking only the core ceiling.
1874    #[test]
1875    fn the_encoder_refuses_an_audit_body_over_the_audit_ceiling() {
1876        let z = [0u8; 32];
1877        let oversized = ReplicationMessage {
1878            request_id: 1,
1879            body: ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
1880                challenge_id: 1,
1881                nonce: z,
1882                challenged_peer_id: z,
1883                expected_commitment_hash: z,
1884                openings: (0..200_000u32)
1885                    .map(|i| SubtreeSliceOpening {
1886                        key: z,
1887                        block_index: i,
1888                    })
1889                    .collect(),
1890            }),
1891        };
1892        // Sits under the core ceiling, so only the family-aware check can catch
1893        // it — this is the exact gap, not merely an enormous message.
1894        let raw = postcard::to_stdvec(&oversized).expect("serialize");
1895        assert!(raw.len() > MAX_SUBTREE_AUDIT_MESSAGE_SIZE);
1896        assert!(raw.len() < MAX_REPLICATION_MESSAGE_SIZE);
1897
1898        match oversized.encode() {
1899            Err(ReplicationProtocolError::MessageTooLarge { max_size, .. }) => {
1900                assert_eq!(
1901                    max_size, MAX_SUBTREE_AUDIT_MESSAGE_SIZE,
1902                    "an audit body must be measured against the audit ceiling"
1903                );
1904            }
1905            // Report only the length on the success arm: debug-printing the body
1906            // would dump megabytes of payload into the failure output.
1907            other => panic!(
1908                "expected the audit ceiling to refuse this, got {:?}",
1909                other.map(|bytes| bytes.len())
1910            ),
1911        }
1912
1913        // A core body of the same size still encodes: the tighter ceiling is
1914        // scoped to the audit families and must not shrink core traffic, which
1915        // legitimately carries a whole chunk.
1916        let core = ReplicationMessage {
1917            request_id: 1,
1918            body: ReplicationMessageBody::FetchResponse(FetchResponse::Success {
1919                key: z,
1920                data: vec![0u8; MAX_SUBTREE_AUDIT_MESSAGE_SIZE * 2],
1921            }),
1922        };
1923        assert!(core.encode().is_ok(), "core bodies keep the core allowance");
1924    }
1925
1926    /// An index no variant declares classifies as nothing, and "nothing" takes
1927    /// the strict audit ceiling rather than the generous core allowance on both
1928    /// sides of the wire. Postcard rejects an unknown outer discriminant before
1929    /// decoding any trailing collection, so this closes the invariant rather than
1930    /// a demonstrated hole — but the rule has to hold uniformly, or a later
1931    /// variant added without a family entry would quietly inherit 10 MiB.
1932    ///
1933    /// FLIPS IF: the family table regains a catch-all that answers `Core`.
1934    #[test]
1935    fn an_undeclared_variant_index_classifies_as_nothing() {
1936        let declared = all_bodies().len();
1937        assert_eq!(
1938            declared, 23,
1939            "update this test's bounds when a variant is added or removed"
1940        );
1941        for index in [declared, declared + 1, 99, usize::MAX] {
1942            assert_eq!(
1943                family_of_variant(index),
1944                None,
1945                "index {index} is not a declared variant and must not classify"
1946            );
1947        }
1948        // Call the REAL selector both wire paths use. Restating its arms here, or
1949        // asserting a property that `None` satisfies vacuously, would pass no
1950        // matter how the production selection changed.
1951        assert_eq!(
1952            ceiling_for(family_of_variant(declared)),
1953            MAX_SUBTREE_AUDIT_MESSAGE_SIZE,
1954            "an unclassifiable variant must take the strict audit ceiling, not \
1955             the generous core allowance"
1956        );
1957        // And a declared core body still takes the generous one, so the
1958        // assertion above is about being unclassifiable rather than about the
1959        // selector returning one answer for everything.
1960        assert_eq!(
1961            ceiling_for(family_of_variant(0)),
1962            MAX_REPLICATION_MESSAGE_SIZE,
1963            "core bodies keep the core allowance"
1964        );
1965    }
1966
1967    // `is_subtree_audit()` classifies exactly the four subtree-audit variants
1968    // (both rounds), and NOTHING else — crucially not the digest-based
1969    // `AuditChallenge`/`AuditResponse` pair, which remains on the core protocol.
1970    // The receive guard and response routing key off this predicate, so it must
1971    // be exact.
1972    #[test]
1973    fn is_subtree_audit_covers_both_rounds_only() {
1974        let z = [0u8; 32];
1975        let audit = [
1976            ReplicationMessageBody::SubtreeAuditChallenge(SubtreeAuditChallenge {
1977                challenge_id: 1,
1978                nonce: z,
1979                challenged_peer_id: z,
1980                expected_commitment_hash: z,
1981            }),
1982            ReplicationMessageBody::SubtreeAuditResponse(SubtreeAuditResponse::Bootstrapping {
1983                challenge_id: 1,
1984            }),
1985            ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
1986                challenge_id: 1,
1987                nonce: z,
1988                challenged_peer_id: z,
1989                expected_commitment_hash: z,
1990                openings: vec![],
1991            }),
1992            ReplicationMessageBody::SubtreeSliceResponse(SubtreeSliceResponse::Bootstrapping {
1993                challenge_id: 1,
1994            }),
1995        ];
1996        for body in &audit {
1997            assert!(
1998                body.is_subtree_audit(),
1999                "variant {} must be subtree-audit",
2000                body.variant_index()
2001            );
2002        }
2003        let core = [
2004            ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
2005                key: z,
2006                data: vec![],
2007                proof_of_payment: vec![],
2008            }),
2009            // Periodic possession audit — core replication, not subtree audit.
2010            ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping { challenge_id: 1 }),
2011        ];
2012        for body in &core {
2013            assert!(
2014                !body.is_subtree_audit(),
2015                "variant {} must be core, not subtree-audit",
2016                body.variant_index()
2017            );
2018        }
2019    }
2020
2021    // === Fresh Replication roundtrip ===
2022
2023    #[test]
2024    fn fresh_replication_offer_roundtrip() {
2025        let msg = ReplicationMessage {
2026            request_id: 1,
2027            body: ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
2028                key: [0xAA; 32],
2029                data: vec![1, 2, 3, 4, 5],
2030                proof_of_payment: vec![10, 20, 30],
2031            }),
2032        };
2033        let encoded = msg.encode().expect("encode should succeed");
2034        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
2035
2036        assert_eq!(decoded.request_id, 1);
2037        if let ReplicationMessageBody::FreshReplicationOffer(offer) = decoded.body {
2038            assert_eq!(offer.key, [0xAA; 32]);
2039            assert_eq!(offer.data, vec![1, 2, 3, 4, 5]);
2040            assert_eq!(offer.proof_of_payment, vec![10, 20, 30]);
2041        } else {
2042            panic!("expected FreshReplicationOffer");
2043        }
2044    }
2045
2046    #[test]
2047    fn fresh_replication_response_accepted_roundtrip() {
2048        let msg = ReplicationMessage {
2049            request_id: 2,
2050            body: ReplicationMessageBody::FreshReplicationResponse(
2051                FreshReplicationResponse::Accepted { key: [0xBB; 32] },
2052            ),
2053        };
2054        let encoded = msg.encode().expect("encode should succeed");
2055        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
2056
2057        assert_eq!(decoded.request_id, 2);
2058        if let ReplicationMessageBody::FreshReplicationResponse(
2059            FreshReplicationResponse::Accepted { key },
2060        ) = decoded.body
2061        {
2062            assert_eq!(key, [0xBB; 32]);
2063        } else {
2064            panic!("expected FreshReplicationResponse::Accepted");
2065        }
2066    }
2067
2068    #[test]
2069    fn fresh_replication_response_rejected_roundtrip() {
2070        let msg = ReplicationMessage {
2071            request_id: 3,
2072            body: ReplicationMessageBody::FreshReplicationResponse(
2073                FreshReplicationResponse::Rejected {
2074                    key: [0xCC; 32],
2075                    reason: "out of range".to_string(),
2076                },
2077            ),
2078        };
2079        let encoded = msg.encode().expect("encode should succeed");
2080        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
2081
2082        assert_eq!(decoded.request_id, 3);
2083        if let ReplicationMessageBody::FreshReplicationResponse(
2084            FreshReplicationResponse::Rejected { key, reason },
2085        ) = decoded.body
2086        {
2087            assert_eq!(key, [0xCC; 32]);
2088            assert_eq!(reason, "out of range");
2089        } else {
2090            panic!("expected FreshReplicationResponse::Rejected");
2091        }
2092    }
2093
2094    // === PaidNotify roundtrip ===
2095
2096    #[test]
2097    fn paid_notify_roundtrip() {
2098        let msg = ReplicationMessage {
2099            request_id: 4,
2100            body: ReplicationMessageBody::PaidNotify(PaidNotify {
2101                key: [0xDD; 32],
2102                proof_of_payment: vec![99, 100],
2103            }),
2104        };
2105        let encoded = msg.encode().expect("encode should succeed");
2106        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
2107
2108        assert_eq!(decoded.request_id, 4);
2109        if let ReplicationMessageBody::PaidNotify(notify) = decoded.body {
2110            assert_eq!(notify.key, [0xDD; 32]);
2111            assert_eq!(notify.proof_of_payment, vec![99, 100]);
2112        } else {
2113            panic!("expected PaidNotify");
2114        }
2115    }
2116
2117    // === Neighbor Sync roundtrips ===
2118
2119    // -- backwards compat across the wire-type extension --------------------
2120
2121    /// Backwards-compat: an old peer that has the v0 layout of
2122    /// `NeighborSyncRequest` (no `commitment` field) can still decode a
2123    /// message encoded by a new peer that emits `commitment: None`. This
2124    /// is the realistic mixed-version case during rollout: new peers
2125    /// gossip with the field; old peers must not crash.
2126    ///
2127    /// The check works because postcard's [`from_bytes`] is lenient on
2128    /// trailing bytes — the old decoder reads what it knows about and
2129    /// stops, the new fields are silently ignored. This test pins that
2130    /// invariant so any future codec/library swap that breaks it is
2131    /// caught immediately.
2132    #[test]
2133    fn old_decoder_tolerates_new_neighbor_sync_request() {
2134        use serde::Deserialize;
2135        #[derive(Deserialize)]
2136        struct OldNeighborSyncRequest {
2137            #[allow(dead_code)]
2138            pub replica_hints: Vec<XorName>,
2139            #[allow(dead_code)]
2140            pub paid_hints: Vec<XorName>,
2141            #[allow(dead_code)]
2142            pub bootstrapping: bool,
2143        }
2144
2145        let new_req = NeighborSyncRequest {
2146            replica_hints: vec![[0x01; 32], [0x02; 32]],
2147            paid_hints: vec![[0x03; 32]],
2148            bootstrapping: true,
2149            commitment: None,
2150        };
2151        let encoded = postcard::to_stdvec(&new_req).expect("encode");
2152        let old_decoded: OldNeighborSyncRequest =
2153            postcard::from_bytes(&encoded).expect("old decoder accepts");
2154        // Field-by-field check would fail if old peer misaligned on the
2155        // length prefix — passing decode is the structural check.
2156        assert_eq!(old_decoded.replica_hints.len(), 2);
2157        assert_eq!(old_decoded.paid_hints.len(), 1);
2158        assert!(old_decoded.bootstrapping);
2159    }
2160
2161    /// Same property for `NeighborSyncResponse`.
2162    #[test]
2163    fn old_decoder_tolerates_new_neighbor_sync_response() {
2164        use serde::Deserialize;
2165        #[derive(Deserialize)]
2166        struct OldNeighborSyncResponse {
2167            #[allow(dead_code)]
2168            pub replica_hints: Vec<XorName>,
2169            #[allow(dead_code)]
2170            pub paid_hints: Vec<XorName>,
2171            #[allow(dead_code)]
2172            pub bootstrapping: bool,
2173            #[allow(dead_code)]
2174            pub rejected_keys: Vec<XorName>,
2175        }
2176
2177        let new_resp = NeighborSyncResponse {
2178            replica_hints: vec![[0x04; 32]],
2179            paid_hints: vec![],
2180            bootstrapping: false,
2181            rejected_keys: vec![[0x05; 32]],
2182            commitment: None,
2183        };
2184        let encoded = postcard::to_stdvec(&new_resp).expect("encode");
2185        let old_decoded: OldNeighborSyncResponse =
2186            postcard::from_bytes(&encoded).expect("old decoder accepts");
2187        assert_eq!(old_decoded.replica_hints.len(), 1);
2188        assert_eq!(old_decoded.rejected_keys.len(), 1);
2189    }
2190
2191    /// Roundtrip: a new peer can decode its own message including the
2192    /// commitment field. Catches accidental serde annotation breakage
2193    /// (e.g. forgetting `#[serde(default)]` on the new field).
2194    #[test]
2195    fn new_peer_roundtrips_with_commitment_some() {
2196        use crate::replication::commitment::{sign_commitment, StorageCommitment};
2197        use saorsa_pqc::api::sig::ml_dsa_65;
2198
2199        let (pk, sk) = ml_dsa_65().generate_keypair().expect("keygen");
2200        let root = [0x7Fu8; 32];
2201        let sender = [0xCCu8; 32];
2202        let pk_bytes = pk.to_bytes();
2203        let sig = sign_commitment(&sk, &root, 3, &sender, &pk_bytes).expect("sign");
2204        let commitment = StorageCommitment {
2205            root,
2206            key_count: 3,
2207            sender_peer_id: sender,
2208            sender_public_key: pk_bytes,
2209            signature: sig,
2210        };
2211
2212        let req = NeighborSyncRequest {
2213            replica_hints: vec![[0x01; 32]],
2214            paid_hints: vec![],
2215            bootstrapping: false,
2216            commitment: Some(commitment.clone()),
2217        };
2218        let encoded = postcard::to_stdvec(&req).expect("encode");
2219        let decoded: NeighborSyncRequest = postcard::from_bytes(&encoded).expect("new decoder");
2220        assert_eq!(decoded.commitment, Some(commitment));
2221    }
2222
2223    #[test]
2224    fn neighbor_sync_request_roundtrip() {
2225        let msg = ReplicationMessage {
2226            request_id: 5,
2227            body: ReplicationMessageBody::NeighborSyncRequest(NeighborSyncRequest {
2228                replica_hints: vec![[0x01; 32], [0x02; 32]],
2229                paid_hints: vec![[0x03; 32]],
2230                bootstrapping: true,
2231                commitment: None,
2232            }),
2233        };
2234        let encoded = msg.encode().expect("encode should succeed");
2235        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
2236
2237        assert_eq!(decoded.request_id, 5);
2238        if let ReplicationMessageBody::NeighborSyncRequest(req) = decoded.body {
2239            assert_eq!(req.replica_hints.len(), 2);
2240            assert_eq!(req.paid_hints.len(), 1);
2241            assert!(req.bootstrapping);
2242        } else {
2243            panic!("expected NeighborSyncRequest");
2244        }
2245    }
2246
2247    #[test]
2248    fn neighbor_sync_response_roundtrip() {
2249        let msg = ReplicationMessage {
2250            request_id: 6,
2251            body: ReplicationMessageBody::NeighborSyncResponse(NeighborSyncResponse {
2252                replica_hints: vec![[0x04; 32]],
2253                paid_hints: vec![],
2254                bootstrapping: false,
2255                rejected_keys: vec![[0x05; 32], [0x06; 32]],
2256                commitment: None,
2257            }),
2258        };
2259        let encoded = msg.encode().expect("encode should succeed");
2260        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
2261
2262        assert_eq!(decoded.request_id, 6);
2263        if let ReplicationMessageBody::NeighborSyncResponse(resp) = decoded.body {
2264            assert_eq!(resp.replica_hints.len(), 1);
2265            assert!(resp.paid_hints.is_empty());
2266            assert!(!resp.bootstrapping);
2267            assert_eq!(resp.rejected_keys.len(), 2);
2268        } else {
2269            panic!("expected NeighborSyncResponse");
2270        }
2271    }
2272
2273    // === Verification roundtrips ===
2274
2275    #[test]
2276    fn verification_request_roundtrip() {
2277        let msg = ReplicationMessage {
2278            request_id: 7,
2279            body: ReplicationMessageBody::VerificationRequest(VerificationRequest {
2280                keys: vec![[0x10; 32], [0x20; 32], [0x30; 32]],
2281                paid_list_check_indices: vec![0, 2],
2282            }),
2283        };
2284        let encoded = msg.encode().expect("encode should succeed");
2285        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
2286
2287        assert_eq!(decoded.request_id, 7);
2288        if let ReplicationMessageBody::VerificationRequest(req) = decoded.body {
2289            assert_eq!(req.keys.len(), 3);
2290            assert_eq!(req.paid_list_check_indices, vec![0, 2]);
2291        } else {
2292            panic!("expected VerificationRequest");
2293        }
2294    }
2295
2296    #[test]
2297    fn verification_response_roundtrip() {
2298        let results = vec![
2299            KeyVerificationResult {
2300                key: [0x10; 32],
2301                present: true,
2302                paid: Some(true),
2303            },
2304            KeyVerificationResult {
2305                key: [0x20; 32],
2306                present: false,
2307                paid: None,
2308            },
2309            KeyVerificationResult {
2310                key: [0x30; 32],
2311                present: true,
2312                paid: Some(false),
2313            },
2314        ];
2315        let msg = ReplicationMessage {
2316            request_id: 8,
2317            body: ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
2318        };
2319        let encoded = msg.encode().expect("encode should succeed");
2320        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
2321
2322        assert_eq!(decoded.request_id, 8);
2323        if let ReplicationMessageBody::VerificationResponse(resp) = decoded.body {
2324            assert_eq!(resp.results.len(), 3);
2325            assert!(resp.results[0].present);
2326            assert_eq!(resp.results[0].paid, Some(true));
2327            assert!(!resp.results[1].present);
2328            assert_eq!(resp.results[1].paid, None);
2329            assert!(resp.results[2].present);
2330            assert_eq!(resp.results[2].paid, Some(false));
2331        } else {
2332            panic!("expected VerificationResponse");
2333        }
2334    }
2335
2336    // === Fetch roundtrips ===
2337
2338    #[test]
2339    fn fetch_request_roundtrip() {
2340        let msg = ReplicationMessage {
2341            request_id: 9,
2342            body: ReplicationMessageBody::FetchRequest(FetchRequest { key: [0x40; 32] }),
2343        };
2344        let encoded = msg.encode().expect("encode should succeed");
2345        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
2346
2347        assert_eq!(decoded.request_id, 9);
2348        if let ReplicationMessageBody::FetchRequest(req) = decoded.body {
2349            assert_eq!(req.key, [0x40; 32]);
2350        } else {
2351            panic!("expected FetchRequest");
2352        }
2353    }
2354
2355    #[test]
2356    fn fetch_response_success_roundtrip() {
2357        let msg = ReplicationMessage {
2358            request_id: 10,
2359            body: ReplicationMessageBody::FetchResponse(FetchResponse::Success {
2360                key: [0x50; 32],
2361                data: vec![7, 8, 9],
2362            }),
2363        };
2364        let encoded = msg.encode().expect("encode should succeed");
2365        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
2366
2367        assert_eq!(decoded.request_id, 10);
2368        if let ReplicationMessageBody::FetchResponse(FetchResponse::Success { key, data }) =
2369            decoded.body
2370        {
2371            assert_eq!(key, [0x50; 32]);
2372            assert_eq!(data, vec![7, 8, 9]);
2373        } else {
2374            panic!("expected FetchResponse::Success");
2375        }
2376    }
2377
2378    #[test]
2379    fn fetch_response_not_found_roundtrip() {
2380        let msg = ReplicationMessage {
2381            request_id: 11,
2382            body: ReplicationMessageBody::FetchResponse(FetchResponse::NotFound {
2383                key: [0x60; 32],
2384            }),
2385        };
2386        let encoded = msg.encode().expect("encode should succeed");
2387        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
2388
2389        assert_eq!(decoded.request_id, 11);
2390        if let ReplicationMessageBody::FetchResponse(FetchResponse::NotFound { key }) = decoded.body
2391        {
2392            assert_eq!(key, [0x60; 32]);
2393        } else {
2394            panic!("expected FetchResponse::NotFound");
2395        }
2396    }
2397
2398    #[test]
2399    fn fetch_response_error_roundtrip() {
2400        let msg = ReplicationMessage {
2401            request_id: 12,
2402            body: ReplicationMessageBody::FetchResponse(FetchResponse::Error {
2403                key: [0x70; 32],
2404                reason: "disk full".to_string(),
2405            }),
2406        };
2407        let encoded = msg.encode().expect("encode should succeed");
2408        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
2409
2410        assert_eq!(decoded.request_id, 12);
2411        if let ReplicationMessageBody::FetchResponse(FetchResponse::Error { key, reason }) =
2412            decoded.body
2413        {
2414            assert_eq!(key, [0x70; 32]);
2415            assert_eq!(reason, "disk full");
2416        } else {
2417            panic!("expected FetchResponse::Error");
2418        }
2419    }
2420
2421    // === Audit roundtrips ===
2422
2423    #[test]
2424    fn audit_challenge_roundtrip() {
2425        let msg = ReplicationMessage {
2426            request_id: 13,
2427            body: ReplicationMessageBody::AuditChallenge(AuditChallenge {
2428                challenge_id: 999,
2429                nonce: [0xAB; 32],
2430                challenged_peer_id: [0xCD; 32],
2431                keys: vec![[0x01; 32], [0x02; 32]],
2432            }),
2433        };
2434        let encoded = msg.encode().expect("encode should succeed");
2435        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
2436
2437        assert_eq!(decoded.request_id, 13);
2438        if let ReplicationMessageBody::AuditChallenge(challenge) = decoded.body {
2439            assert_eq!(challenge.challenge_id, 999);
2440            assert_eq!(challenge.nonce, [0xAB; 32]);
2441            assert_eq!(challenge.challenged_peer_id, [0xCD; 32]);
2442            assert_eq!(challenge.keys.len(), 2);
2443        } else {
2444            panic!("expected AuditChallenge");
2445        }
2446    }
2447
2448    #[test]
2449    fn audit_response_digests_roundtrip() {
2450        let digests = vec![[0x11; 32], ABSENT_KEY_DIGEST];
2451        let msg = ReplicationMessage {
2452            request_id: 14,
2453            body: ReplicationMessageBody::AuditResponse(AuditResponse::Digests {
2454                challenge_id: 999,
2455                digests: digests.clone(),
2456            }),
2457        };
2458        let encoded = msg.encode().expect("encode should succeed");
2459        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
2460
2461        assert_eq!(decoded.request_id, 14);
2462        if let ReplicationMessageBody::AuditResponse(AuditResponse::Digests {
2463            challenge_id,
2464            digests: decoded_digests,
2465        }) = decoded.body
2466        {
2467            assert_eq!(challenge_id, 999);
2468            assert_eq!(decoded_digests, digests);
2469        } else {
2470            panic!("expected AuditResponse::Digests");
2471        }
2472    }
2473
2474    #[test]
2475    fn audit_response_bootstrapping_roundtrip() {
2476        let msg = ReplicationMessage {
2477            request_id: 15,
2478            body: ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping {
2479                challenge_id: 42,
2480            }),
2481        };
2482        let encoded = msg.encode().expect("encode should succeed");
2483        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
2484
2485        assert_eq!(decoded.request_id, 15);
2486        if let ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping {
2487            challenge_id,
2488        }) = decoded.body
2489        {
2490            assert_eq!(challenge_id, 42);
2491        } else {
2492            panic!("expected AuditResponse::Bootstrapping");
2493        }
2494    }
2495
2496    // === Oversized message rejection ===
2497
2498    #[test]
2499    fn decode_rejects_oversized_payload() {
2500        let oversized = vec![0u8; MAX_REPLICATION_MESSAGE_SIZE + 1];
2501        let result = ReplicationMessage::decode(&oversized);
2502        assert!(result.is_err());
2503        let err = result.unwrap_err();
2504        assert!(
2505            matches!(err, ReplicationProtocolError::MessageTooLarge { .. }),
2506            "expected MessageTooLarge, got {err:?}"
2507        );
2508    }
2509
2510    // A challenge is a few hundred bytes; without the tighter ceiling the reply
2511    // to it could cost the auditor up to the full core allowance in allocation
2512    // and decode. The gap between the two ceilings is exactly what an audited
2513    // peer could spend the auditor's memory on, so pin that it is refused as an
2514    // audit reply while still being a legal core message.
2515    #[test]
2516    fn an_audit_reply_above_the_audit_ceiling_is_refused_before_decode() {
2517        let between_the_ceilings = vec![0u8; MAX_SUBTREE_AUDIT_MESSAGE_SIZE + 1];
2518        assert!(between_the_ceilings.len() < MAX_REPLICATION_MESSAGE_SIZE);
2519
2520        let err = ReplicationMessage::decode_subtree_audit_response(&between_the_ceilings)
2521            .expect_err("an audit reply over the audit ceiling must not be decoded");
2522        assert!(
2523            matches!(
2524                err,
2525                ReplicationProtocolError::MessageTooLarge { max_size, .. }
2526                    if max_size == MAX_SUBTREE_AUDIT_MESSAGE_SIZE
2527            ),
2528            "expected the audit ceiling to be the one reported, got {err:?}"
2529        );
2530    }
2531
2532    // The ceiling lives in `decode` itself, so it cannot be skipped by reaching
2533    // a decode site that forgot to ask. A core lane that gets answered with an
2534    // audit-discriminant body still gets the audit ceiling, even though the same
2535    // lane may legitimately receive a whole chunk when the body is a core one.
2536    #[test]
2537    fn the_family_ceiling_is_enforced_by_decode_itself() {
2538        let mut oversized_audit_body = ReplicationMessage {
2539            request_id: 1,
2540            body: ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
2541                challenge_id: 1,
2542                nonce: [0u8; 32],
2543                challenged_peer_id: [0u8; 32],
2544                expected_commitment_hash: [0u8; 32],
2545                openings: vec![],
2546            }),
2547        }
2548        .encode()
2549        .expect("a small audit body encodes");
2550        // Postcard ignores trailing bytes, so padding keeps this a decodable
2551        // audit body while pushing it between the two ceilings.
2552        oversized_audit_body.resize(MAX_SUBTREE_AUDIT_MESSAGE_SIZE + 1, 0);
2553        assert!(oversized_audit_body.len() < MAX_REPLICATION_MESSAGE_SIZE);
2554
2555        let err = ReplicationMessage::decode(&oversized_audit_body)
2556            .expect_err("an audit-family body over the audit ceiling must not be decoded");
2557        assert!(
2558            matches!(
2559                err,
2560                ReplicationProtocolError::MessageTooLarge { max_size, .. }
2561                    if max_size == MAX_SUBTREE_AUDIT_MESSAGE_SIZE
2562            ),
2563            "the audit ceiling must be the one applied, got {err:?}"
2564        );
2565
2566        // A core body of the same size is still fine: that is the allowance a
2567        // fetched chunk needs.
2568        let mut core_body = ReplicationMessage {
2569            request_id: 1,
2570            body: ReplicationMessageBody::FetchRequest(FetchRequest { key: [0u8; 32] }),
2571        }
2572        .encode()
2573        .expect("a small core body encodes");
2574        core_body.resize(MAX_SUBTREE_AUDIT_MESSAGE_SIZE + 1, 0);
2575        assert!(
2576            ReplicationMessage::decode(&core_body).is_ok(),
2577            "a core body must keep the core allowance"
2578        );
2579    }
2580
2581    // The tighter ceiling must not clip a legitimate subtree reply. Round 1's
2582    // `Proof` is the largest subtree-audit body, and `MAX_SUBTREE_AUDIT_MESSAGE_SIZE` is
2583    // sized against it; this checks the auditor accepts a small valid reply.
2584    #[test]
2585    fn a_legitimate_audit_reply_still_decodes_under_the_audit_ceiling() {
2586        let msg = ReplicationMessage {
2587            request_id: 7,
2588            body: ReplicationMessageBody::SubtreeAuditResponse(
2589                SubtreeAuditResponse::Bootstrapping { challenge_id: 42 },
2590            ),
2591        };
2592        let encoded = msg.encode().expect("encode should succeed");
2593        let decoded = ReplicationMessage::decode_subtree_audit_response(&encoded)
2594            .expect("a small audit reply must decode");
2595        assert_eq!(decoded.request_id, 7);
2596    }
2597
2598    #[test]
2599    fn encode_rejects_oversized_message() {
2600        // Build a message whose serialized form exceeds the limit.
2601        let msg = ReplicationMessage {
2602            request_id: 0,
2603            body: ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
2604                key: [0; 32],
2605                data: vec![0xFF; MAX_REPLICATION_MESSAGE_SIZE],
2606                proof_of_payment: vec![],
2607            }),
2608        };
2609        let result = msg.encode();
2610        assert!(result.is_err());
2611        let err = result.unwrap_err();
2612        assert!(
2613            matches!(err, ReplicationProtocolError::MessageTooLarge { .. }),
2614            "expected MessageTooLarge, got {err:?}"
2615        );
2616    }
2617
2618    // === Invalid data rejection ===
2619
2620    #[test]
2621    fn decode_rejects_invalid_data() {
2622        let invalid = vec![0xFF, 0xFF, 0xFF];
2623        let result = ReplicationMessage::decode(&invalid);
2624        assert!(result.is_err());
2625        let err = result.unwrap_err();
2626        assert!(
2627            matches!(err, ReplicationProtocolError::DeserializationFailed(_)),
2628            "expected DeserializationFailed, got {err:?}"
2629        );
2630    }
2631
2632    // === Audit digest computation ===
2633
2634    #[test]
2635    fn audit_digest_matches_core_replication_construction() {
2636        let nonce = [0x01; 32];
2637        let peer_id = [0x02; 32];
2638        let key: XorName = [0x03; 32];
2639        let record_bytes = vec![0x5A; 8 * 1024];
2640
2641        let mut expected = blake3::Hasher::new();
2642        expected.update(&nonce);
2643        expected.update(&peer_id);
2644        expected.update(&key);
2645        expected.update(&record_bytes);
2646        assert_eq!(
2647            compute_audit_digest(&nonce, &peer_id, &key, &record_bytes),
2648            *expected.finalize().as_bytes(),
2649            "digest must remain BLAKE3(nonce || peer || key || bytes)"
2650        );
2651    }
2652
2653    #[test]
2654    fn audit_digest_is_deterministic() {
2655        let nonce = [0x01; 32];
2656        let peer_id = [0x02; 32];
2657        let key: XorName = [0x03; 32];
2658        let record_bytes = b"hello world";
2659
2660        let digest_a = compute_audit_digest(&nonce, &peer_id, &key, record_bytes);
2661        let digest_b = compute_audit_digest(&nonce, &peer_id, &key, record_bytes);
2662
2663        assert_eq!(digest_a, digest_b, "same inputs must produce same digest");
2664    }
2665
2666    #[test]
2667    fn audit_digest_differs_with_different_nonce() {
2668        let peer_id = [0x02; 32];
2669        let key: XorName = [0x03; 32];
2670        let record_bytes = b"hello world";
2671
2672        let digest_a = compute_audit_digest(&[0x01; 32], &peer_id, &key, record_bytes);
2673        let digest_b = compute_audit_digest(&[0xFF; 32], &peer_id, &key, record_bytes);
2674
2675        assert_ne!(
2676            digest_a, digest_b,
2677            "different nonces must produce different digests"
2678        );
2679    }
2680
2681    #[test]
2682    fn audit_digest_differs_with_different_data() {
2683        let nonce = [0x01; 32];
2684        let peer_id = [0x02; 32];
2685        let key: XorName = [0x03; 32];
2686
2687        let digest_a = compute_audit_digest(&nonce, &peer_id, &key, b"data-A");
2688        let digest_b = compute_audit_digest(&nonce, &peer_id, &key, b"data-B");
2689
2690        assert_ne!(
2691            digest_a, digest_b,
2692            "different data must produce different digests"
2693        );
2694    }
2695
2696    #[test]
2697    fn audit_digest_differs_with_different_peer() {
2698        let nonce = [0x01; 32];
2699        let key: XorName = [0x03; 32];
2700        let record_bytes = b"hello";
2701
2702        let digest_a = compute_audit_digest(&nonce, &[0x02; 32], &key, record_bytes);
2703        let digest_b = compute_audit_digest(&nonce, &[0xFF; 32], &key, record_bytes);
2704
2705        assert_ne!(
2706            digest_a, digest_b,
2707            "different peer IDs must produce different digests"
2708        );
2709    }
2710
2711    #[test]
2712    fn audit_digest_differs_with_different_key() {
2713        let nonce = [0x01; 32];
2714        let peer_id = [0x02; 32];
2715        let record_bytes = b"hello";
2716
2717        let digest_a = compute_audit_digest(&nonce, &peer_id, &[0x03; 32], record_bytes);
2718        let digest_b = compute_audit_digest(&nonce, &peer_id, &[0xFF; 32], record_bytes);
2719
2720        assert_ne!(
2721            digest_a, digest_b,
2722            "different keys must produce different digests"
2723        );
2724    }
2725
2726    // === Absent key digest sentinel ===
2727
2728    #[test]
2729    fn absent_key_digest_is_all_zeros() {
2730        assert_eq!(ABSENT_KEY_DIGEST, [0u8; 32]);
2731    }
2732
2733    #[test]
2734    fn real_digest_differs_from_absent_sentinel() {
2735        let nonce = [0x01; 32];
2736        let peer_id = [0x02; 32];
2737        let key: XorName = [0x03; 32];
2738        let record_bytes = b"non-empty data";
2739
2740        let digest = compute_audit_digest(&nonce, &peer_id, &key, record_bytes);
2741        assert_ne!(
2742            digest, ABSENT_KEY_DIGEST,
2743            "a real digest should not collide with the all-zeros sentinel"
2744        );
2745    }
2746
2747    // === Error Display ===
2748
2749    #[test]
2750    fn error_display_serialization_failed() {
2751        let err = ReplicationProtocolError::SerializationFailed("boom".to_string());
2752        assert_eq!(err.to_string(), "replication serialization failed: boom");
2753    }
2754
2755    #[test]
2756    fn error_display_deserialization_failed() {
2757        let err = ReplicationProtocolError::DeserializationFailed("bad data".to_string());
2758        assert_eq!(
2759            err.to_string(),
2760            "replication deserialization failed: bad data"
2761        );
2762    }
2763
2764    #[test]
2765    fn error_display_message_too_large() {
2766        let err = ReplicationProtocolError::MessageTooLarge {
2767            size: 20_000_000,
2768            max_size: MAX_REPLICATION_MESSAGE_SIZE,
2769        };
2770        let display = err.to_string();
2771        assert!(display.contains("20000000"));
2772        assert!(display.contains(&MAX_REPLICATION_MESSAGE_SIZE.to_string()));
2773    }
2774}