Skip to main content

ant_node/replication/
protocol.rs

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