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