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