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 serde::{Deserialize, Serialize};
7
8use crate::ant_protocol::XorName;
9
10pub use super::config::MAX_REPLICATION_MESSAGE_SIZE;
11
12/// Sentinel digest value indicating the challenged key is absent from storage.
13///
14/// Used in [`AuditResponse::Digests`] for keys the peer does not hold.
15pub const ABSENT_KEY_DIGEST: [u8; 32] = [0u8; 32];
16
17// ---------------------------------------------------------------------------
18// Top-level envelope
19// ---------------------------------------------------------------------------
20
21/// Top-level replication message envelope.
22///
23/// Every replication wire message carries a sender-assigned `request_id` so
24/// that the receiver can correlate responses without relying on transport-layer
25/// ordering.
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct ReplicationMessage {
28    /// Sender-assigned request ID for correlation.
29    pub request_id: u64,
30    /// The message body.
31    pub body: ReplicationMessageBody,
32}
33
34impl ReplicationMessage {
35    /// Encode the message to bytes using postcard.
36    ///
37    /// # Errors
38    ///
39    /// Returns [`ReplicationProtocolError::SerializationFailed`] if postcard
40    /// serialization fails.
41    pub fn encode(&self) -> Result<Vec<u8>, ReplicationProtocolError> {
42        let bytes = postcard::to_stdvec(self)
43            .map_err(|e| ReplicationProtocolError::SerializationFailed(e.to_string()))?;
44
45        if bytes.len() > MAX_REPLICATION_MESSAGE_SIZE {
46            return Err(ReplicationProtocolError::MessageTooLarge {
47                size: bytes.len(),
48                max_size: MAX_REPLICATION_MESSAGE_SIZE,
49            });
50        }
51
52        Ok(bytes)
53    }
54
55    /// Decode a message from bytes using postcard.
56    ///
57    /// Rejects payloads larger than [`MAX_REPLICATION_MESSAGE_SIZE`] before
58    /// attempting deserialization.
59    ///
60    /// # Errors
61    ///
62    /// Returns [`ReplicationProtocolError::MessageTooLarge`] if the input
63    /// exceeds the size limit, or
64    /// [`ReplicationProtocolError::DeserializationFailed`] if postcard cannot
65    /// parse the data.
66    pub fn decode(data: &[u8]) -> Result<Self, ReplicationProtocolError> {
67        if data.len() > MAX_REPLICATION_MESSAGE_SIZE {
68            return Err(ReplicationProtocolError::MessageTooLarge {
69                size: data.len(),
70                max_size: MAX_REPLICATION_MESSAGE_SIZE,
71            });
72        }
73        postcard::from_bytes(data)
74            .map_err(|e| ReplicationProtocolError::DeserializationFailed(e.to_string()))
75    }
76}
77
78// ---------------------------------------------------------------------------
79// Message body enum
80// ---------------------------------------------------------------------------
81
82/// All replication protocol message types.
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub enum ReplicationMessageBody {
85    // === Fresh Replication (Section 6.1) ===
86    /// Fresh replication offer with `PoP` (sent to close group members).
87    FreshReplicationOffer(FreshReplicationOffer),
88    /// Response to a fresh replication offer.
89    FreshReplicationResponse(FreshReplicationResponse),
90
91    /// Paid-list notification with `PoP` (sent to `PaidCloseGroup` members).
92    PaidNotify(PaidNotify),
93
94    // === Neighbor Sync (Section 6.2) ===
95    /// Neighbor sync hint exchange (bidirectional).
96    NeighborSyncRequest(NeighborSyncRequest),
97    /// Response to neighbor sync with own hints.
98    NeighborSyncResponse(NeighborSyncResponse),
99
100    // === Verification (Section 9) ===
101    /// Batched verification request (presence + paid-list queries).
102    VerificationRequest(VerificationRequest),
103    /// Response to verification request with per-key evidence.
104    VerificationResponse(VerificationResponse),
105
106    // === Fetch (record retrieval) ===
107    /// Request to fetch a record by key.
108    FetchRequest(FetchRequest),
109    /// Response with the record data.
110    FetchResponse(FetchResponse),
111
112    // === Responsible-chunk audit (per-key digests) ===
113    /// Per-key audit challenge: used by the responsible-chunk audit and the
114    /// prune-confirmation path.
115    AuditChallenge(AuditChallenge),
116    /// Response to a per-key audit challenge.
117    AuditResponse(AuditResponse),
118
119    // === Storage-bound subtree audit (ADR-0002) ===
120    /// Gossip-triggered contiguous-subtree storage audit challenge (round 1).
121    SubtreeAuditChallenge(SubtreeAuditChallenge),
122    /// Response to a contiguous-subtree storage audit challenge (round 1).
123    SubtreeAuditResponse(SubtreeAuditResponse),
124    /// Surprise byte challenge for the spot-checked leaves (round 2).
125    SubtreeByteChallenge(SubtreeByteChallenge),
126    /// Response carrying the requested chunks' original bytes (round 2).
127    SubtreeByteResponse(SubtreeByteResponse),
128
129    // === Commitment fetch by pin (ADR-0004) ===
130    // APPENDED at the end so postcard variant discriminants of all the
131    // pre-existing variants are unchanged — old nodes keep decoding every
132    // message they already understood; only these two new indices are unknown
133    // to them (and they never receive them, since old nodes never send the
134    // matching request).
135    /// Fetch a retained commitment by its pin (ADR-0004): used to resolve a
136    /// quote's `commitment_pin` when the sidecar is absent and the gossip cache
137    /// has no fresh copy.
138    GetCommitmentByPin(GetCommitmentByPin),
139    /// Response to [`Self::GetCommitmentByPin`].
140    GetCommitmentByPinResponse(GetCommitmentByPinResponse),
141}
142
143// ---------------------------------------------------------------------------
144// Fresh Replication Messages
145// ---------------------------------------------------------------------------
146
147/// Fresh replication offer (includes record + `PoP`).
148///
149/// Sent to close-group members when a node receives a new chunk via client PUT.
150#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct FreshReplicationOffer {
152    /// The record key.
153    pub key: XorName,
154    /// The record data.
155    pub data: Vec<u8>,
156    /// Proof of Payment (required, validated by receiver).
157    pub proof_of_payment: Vec<u8>,
158}
159
160/// Response to a fresh replication offer.
161#[derive(Debug, Clone, Serialize, Deserialize)]
162pub enum FreshReplicationResponse {
163    /// Record accepted and stored.
164    Accepted {
165        /// The accepted record key.
166        key: XorName,
167    },
168    /// Record rejected (with reason).
169    Rejected {
170        /// The rejected record key.
171        key: XorName,
172        /// Human-readable rejection reason.
173        reason: String,
174    },
175}
176
177/// Paid-list notification carrying key + `PoP` (Section 7.3).
178///
179/// Sent to `PaidCloseGroup` members so they record the key in their
180/// `PaidForList` without needing to hold the record data.
181#[derive(Debug, Clone, Serialize, Deserialize)]
182pub struct PaidNotify {
183    /// The record key.
184    pub key: XorName,
185    /// Proof of Payment for receiver-side verification.
186    pub proof_of_payment: Vec<u8>,
187}
188
189// ---------------------------------------------------------------------------
190// Neighbor Sync Messages
191// ---------------------------------------------------------------------------
192
193/// Neighbor sync request carrying hint sets (Section 6.2).
194///
195/// Exchanged between close neighbors to detect and repair missing replicas.
196#[derive(Debug, Clone, Serialize, Deserialize)]
197pub struct NeighborSyncRequest {
198    /// Keys sender believes receiver should hold (replica hints).
199    pub replica_hints: Vec<XorName>,
200    /// Keys sender believes receiver should track in `PaidForList` (paid hints).
201    pub paid_hints: Vec<XorName>,
202    /// Whether sender is currently bootstrapping.
203    pub bootstrapping: bool,
204    /// Sender's signed storage commitment (optional, see
205    /// [`crate::replication::commitment`]). `None` from old peers; from
206    /// new peers this carries the Merkle-root commitment over the
207    /// sender's claimed keys. Receivers that recognize it store it as
208    /// the per-peer "last known commitment" used to pin commitment-bound
209    /// audits.
210    #[serde(default)]
211    pub commitment: Option<crate::replication::commitment::StorageCommitment>,
212}
213
214/// Neighbor sync response carrying own hint sets.
215#[derive(Debug, Clone, Serialize, Deserialize)]
216pub struct NeighborSyncResponse {
217    /// Keys receiver believes sender should hold (replica hints).
218    pub replica_hints: Vec<XorName>,
219    /// Keys receiver believes sender should track in `PaidForList` (paid hints).
220    pub paid_hints: Vec<XorName>,
221    /// Whether receiver is currently bootstrapping.
222    pub bootstrapping: bool,
223    /// Keys that receiver rejected (optional feedback to sender).
224    pub rejected_keys: Vec<XorName>,
225    /// Receiver's signed storage commitment (optional, see
226    /// [`NeighborSyncRequest::commitment`]).
227    #[serde(default)]
228    pub commitment: Option<crate::replication::commitment::StorageCommitment>,
229}
230
231// ---------------------------------------------------------------------------
232// Verification Messages
233// ---------------------------------------------------------------------------
234
235/// Batched verification request for multiple keys (Section 9).
236///
237/// Sent to peers in `VerifyTargets` (union of `QuorumTargets` and
238/// `PaidTargets`). Each peer returns per-key presence and optionally
239/// paid-list status.
240#[derive(Debug, Clone, Serialize, Deserialize)]
241pub struct VerificationRequest {
242    /// Keys to verify (batched).
243    pub keys: Vec<XorName>,
244    /// Which keys need paid-list status in addition to presence.
245    /// Each value is an index into the `keys` vector.
246    pub paid_list_check_indices: Vec<u32>,
247}
248
249/// Per-key verification result from a peer.
250#[derive(Debug, Clone, Serialize, Deserialize)]
251pub struct KeyVerificationResult {
252    /// The key being verified.
253    pub key: XorName,
254    /// Whether this peer holds the record.
255    pub present: bool,
256    /// Paid-list status (only set if peer was asked for paid-list check).
257    ///
258    /// - `Some(true)` -- key is in peer's `PaidForList`.
259    /// - `Some(false)` -- key is NOT in peer's `PaidForList`.
260    /// - `None` -- paid-list check was not requested for this key.
261    pub paid: Option<bool>,
262}
263
264/// Batched verification response with per-key results.
265#[derive(Debug, Clone, Serialize, Deserialize)]
266pub struct VerificationResponse {
267    /// Per-key results (one per requested key, in request order).
268    pub results: Vec<KeyVerificationResult>,
269}
270
271// ---------------------------------------------------------------------------
272// Fetch Messages
273// ---------------------------------------------------------------------------
274
275/// Request to fetch a specific record by key.
276#[derive(Debug, Clone, Serialize, Deserialize)]
277pub struct FetchRequest {
278    /// The key of the record to fetch.
279    pub key: XorName,
280}
281
282/// Response to a fetch request.
283#[derive(Debug, Clone, Serialize, Deserialize)]
284pub enum FetchResponse {
285    /// Record found and returned.
286    Success {
287        /// The record key.
288        key: XorName,
289        /// The record data.
290        data: Vec<u8>,
291    },
292    /// Record not found on this peer.
293    NotFound {
294        /// The requested key.
295        key: XorName,
296    },
297    /// Error during fetch.
298    Error {
299        /// The requested key.
300        key: XorName,
301        /// Human-readable error description.
302        reason: String,
303    },
304}
305
306// ---------------------------------------------------------------------------
307// Commitment fetch by pin (ADR-0004)
308// ---------------------------------------------------------------------------
309
310/// Request a retained commitment by its pin (commitment hash).
311///
312/// ADR-0004: a storer cross-checking a quote whose `commitment_pin` it does not
313/// already hold (no sidecar, no fresh gossip copy) fetches the signed
314/// commitment so it can verify the binding and route the commitment into audit.
315/// The responder answers only from its retained set, so this never forces a
316/// node to reconstruct or re-sign anything.
317#[derive(Debug, Clone, Serialize, Deserialize)]
318pub struct GetCommitmentByPin {
319    /// The commitment hash (pin) being resolved.
320    pub pin: [u8; 32],
321}
322
323/// Response to [`GetCommitmentByPin`].
324#[derive(Debug, Clone, Serialize, Deserialize)]
325pub enum GetCommitmentByPinResponse {
326    /// The pin resolved to a retained, signed commitment.
327    Found {
328        /// The signed commitment matching the requested pin. The fetcher
329        /// re-verifies its signature and peer binding before trusting it.
330        commitment: crate::replication::commitment::StorageCommitment,
331    },
332    /// The pin is not among the responder's retained commitments (rotated/aged
333    /// out, or never held). ADR-0004 treats this as graced, never confirmed:
334    /// an unanswerable pin is indistinguishable from an honest crash-restart.
335    NotRetained {
336        /// Echo of the requested pin, for matching.
337        pin: [u8; 32],
338    },
339}
340
341// ---------------------------------------------------------------------------
342// Audit Messages
343// ---------------------------------------------------------------------------
344
345/// Per-key audit challenge.
346///
347/// The challenger picks a random nonce and a set of keys the challenged peer
348/// should hold, then sends this challenge. The challenged peer proves storage
349/// by returning per-key BLAKE3 digests. Used by the responsible-chunk audit
350/// (audit #2: a node samples keys a close peer should hold) and by the
351/// prune-confirmation path (a node checks a peer still holds a key before
352/// pruning its own copy).
353#[derive(Debug, Clone, Serialize, Deserialize)]
354pub struct AuditChallenge {
355    /// Unique challenge identifier.
356    pub challenge_id: u64,
357    /// Random nonce for digest computation.
358    pub nonce: [u8; 32],
359    /// Challenged peer ID (included in digest computation).
360    pub challenged_peer_id: [u8; 32],
361    /// Ordered list of keys to prove storage of.
362    pub keys: Vec<XorName>,
363}
364
365/// Response to a per-key audit challenge.
366#[derive(Debug, Clone, Serialize, Deserialize)]
367pub enum AuditResponse {
368    /// Per-key digests proving storage.
369    ///
370    /// `digests[i]` corresponds to `challenge.keys[i]`.
371    /// An [`ABSENT_KEY_DIGEST`] sentinel signals key absence.
372    Digests {
373        /// The challenge this response answers.
374        challenge_id: u64,
375        /// One 32-byte digest per challenged key, in challenge order.
376        digests: Vec<[u8; 32]>,
377    },
378    /// Peer is still bootstrapping (not ready for audit).
379    Bootstrapping {
380        /// The challenge this response answers.
381        challenge_id: u64,
382    },
383    /// Challenge rejected (wrong target peer or too many keys).
384    ///
385    /// Distinct from empty `Digests` so the challenger can distinguish a
386    /// legitimate rejection from misbehavior.
387    Rejected {
388        /// The challenge this response answers.
389        challenge_id: u64,
390        /// Human-readable rejection reason.
391        reason: String,
392    },
393}
394
395/// Gossip-triggered contiguous-subtree storage audit challenge (ADR-0002).
396///
397/// The auditor pins the commitment a peer just gossiped and sends a fresh
398/// random nonce. The nonce alone deterministically selects one contiguous
399/// subtree of the peer's committed Merkle tree (see
400/// [`crate::replication::subtree::select_subtree_path`]); the auditor does
401/// **not** name keys. The responder must reply with a
402/// [`SubtreeAuditResponse::Proof`] for that selected subtree against the pinned
403/// commitment, or a [`SubtreeAuditResponse::Rejected`] if it genuinely cannot
404/// (for a recently gossiped pinned commitment a rejection is a confirmed
405/// failure, since the responder retains its last two gossiped commitments).
406#[derive(Debug, Clone, Serialize, Deserialize)]
407pub struct SubtreeAuditChallenge {
408    /// Unique challenge identifier.
409    pub challenge_id: u64,
410    /// Random nonce. Selects the subtree AND freshens each leaf's possession
411    /// hash, so a stored answer cannot be replayed.
412    pub nonce: [u8; 32],
413    /// Challenged peer ID. Bound into each leaf's possession hash.
414    pub challenged_peer_id: [u8; 32],
415    /// The auditor's pin: the [`crate::replication::commitment::commitment_hash`]
416    /// of the commitment the peer just gossiped. The response's commitment must
417    /// hash to exactly this value.
418    pub expected_commitment_hash: [u8; 32],
419}
420
421/// Response to a contiguous-subtree storage audit challenge (ADR-0002).
422#[derive(Debug, Clone, Serialize, Deserialize)]
423pub enum SubtreeAuditResponse {
424    /// The single-contiguous-subtree proof.
425    ///
426    /// Carries the responder's signed commitment (so the auditor re-derives
427    /// `key_count` and confirms the pin and signature) and the
428    /// nonce-selected subtree expanded to its leaves plus the sibling
429    /// cut-hashes on the path to the root. This is **round 1** of the
430    /// two-round audit. The auditor:
431    ///   1. confirms `commitment_hash(commitment) == expected_commitment_hash`
432    ///      and the signature is valid;
433    ///   2. re-derives the selected subtree from `(nonce, key_count)`, rebuilds
434    ///      the root from the proof, and requires it to equal the commitment
435    ///      root (structure).
436    ///
437    /// The leaves carry only hashes (`bytes_hash`, `nonced_hash`), so this round
438    /// proves the tree SHAPE is committed — not that the bytes are still held.
439    /// Real possession is proven in **round 2**: the auditor picks a few of the
440    /// just-verified leaves and sends a [`SubtreeByteChallenge`] requesting their
441    /// original chunk bytes FROM the responder (see that type).
442    Proof {
443        /// The challenge this response answers.
444        challenge_id: u64,
445        /// The signed commitment whose root the proof is against.
446        commitment: crate::replication::commitment::StorageCommitment,
447        /// The nonce-selected contiguous subtree proof.
448        proof: crate::replication::subtree::SubtreeProof,
449    },
450    /// Peer is still bootstrapping (not ready for audit).
451    Bootstrapping {
452        /// The challenge this response answers.
453        challenge_id: u64,
454    },
455    /// Challenge rejected. `kind` drives the auditor's accounting (confirmed vs
456    /// graced); `reason` is the human-readable detail for logs.
457    Rejected {
458        /// The challenge this response answers.
459        challenge_id: u64,
460        /// Machine-readable rejection class (accounting).
461        kind: RejectKind,
462        /// Human-readable rejection reason.
463        reason: String,
464    },
465}
466
467/// Why a responder rejected an audit challenge, in a form the auditor can act
468/// on without string-matching.
469///
470/// ADR-0004 Amendment 1: audit **grace is removed**. Answerability is now
471/// restart-durable (the responder persists and reloads its commitment retention)
472/// and the auditor only pins roots inside the answerability window, so an honest
473/// node can always answer a pin it could be challenged on. The auditor therefore
474/// grades a responsive rejection purely by kind, with no grace:
475/// - `UnknownCommitment` / `Protocol` → **confirmed failure**: repudiating a
476///   pinned root the node published (and may have been paid for), or an explicit
477///   protocol fault.
478/// - `Transient` → routed to the **non-response/timeout lane** (no trust penalty,
479///   but the holder credit for the pinned commitment IS revoked). The responder
480///   retries reads before emitting `Transient`, so one that still reaches the
481///   auditor means the node could not serve data it committed to. A
482///   `Transient`-spammer thus gains no positive standing; deterministically
483///   distinguishing malicious from genuine transient IO network-wide is the
484///   out-of-scope distributed non-response problem.
485#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
486pub enum RejectKind {
487    /// The responder does not retain the pinned commitment. With restart-durable
488    /// retention and in-window auditing this is provable repudiation of a root
489    /// the node published → CONFIRMED failure.
490    UnknownCommitment,
491    /// A transient, recoverable local condition (e.g. a storage read error),
492    /// emitted only after the responder's read retries failed. Routed to the
493    /// timeout lane (holder credit revoked, no trust penalty).
494    Transient,
495    /// Any other rejection (wrong target peer, no commitment state, malformed
496    /// proof plan, oversized byte challenge, …). CONFIRMED failure.
497    Protocol,
498}
499
500/// Round 2 of the storage audit (ADR-0002): the **surprise byte challenge**.
501///
502/// After the auditor has structurally verified a [`SubtreeAuditResponse::Proof`]
503/// it picks a small sample of that subtree's just-proven leaves with FRESH
504/// randomness (chosen now, after the proof is committed — NOT derived from the
505/// round-1 nonce, so the responder could not have predicted it at proof-build
506/// time) and asks the responder to return the ORIGINAL chunk bytes for exactly
507/// those keys. The auditor then checks each returned chunk against the committed
508/// leaf:
509///   - `BLAKE3(bytes) == leaf.bytes_hash` (the chunk's content address), AND
510///   - `compute_audit_digest(nonce, peer, key, bytes) == leaf.nonced_hash`.
511///
512/// This makes possession non-delegable to the auditor: the auditor needs to
513/// hold NONE of the responder's chunks. A responder that committed to a chunk it
514/// no longer holds cannot fabricate bytes that hash to the committed address (a
515/// preimage break), so it is caught regardless of who audits it.
516#[derive(Debug, Clone, Serialize, Deserialize)]
517pub struct SubtreeByteChallenge {
518    /// The same `challenge_id` as the round-1 [`SubtreeAuditChallenge`], so the
519    /// responder/auditor correlate the two rounds.
520    pub challenge_id: u64,
521    /// The same nonce as round 1 — needed for the freshness (`nonced_hash`)
522    /// check and to bind these bytes to this audit.
523    pub nonce: [u8; 32],
524    /// The challenged peer ID (bound into each leaf's possession hash).
525    pub challenged_peer_id: [u8; 32],
526    /// The pinned commitment hash from round 1, so the responder resolves the
527    /// SAME tree it just proved and serves bytes only for keys it committed to.
528    pub expected_commitment_hash: [u8; 32],
529    /// The exact keys whose original bytes the responder must return. These are
530    /// the auditor's freshly-randomised spot-check sample of the round-1 subtree
531    /// (chosen after the proof was received; not nonce-derived).
532    pub keys: Vec<XorName>,
533}
534
535/// One requested chunk in a [`SubtreeByteResponse`].
536#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
537pub enum SubtreeByteItem {
538    /// The responder holds this committed key and returns its original bytes.
539    Present {
540        /// The requested key.
541        key: XorName,
542        /// The original chunk bytes (the auditor re-hashes to verify).
543        bytes: Vec<u8>,
544    },
545    /// The responder committed to this key but cannot serve its bytes. This is a
546    /// PROVABLE cheat (it published a commitment over a chunk it does not hold),
547    /// so the auditor counts it as a confirmed failure — NOT a graced timeout.
548    /// Distinguishing this explicit signal from silence is what separates a
549    /// deleter (instant fail) from a dropped packet (timeout).
550    Absent {
551        /// The committed key the responder could not serve.
552        key: XorName,
553    },
554}
555
556/// Response to a [`SubtreeByteChallenge`] (round 2). One item per requested key,
557/// in the requested order.
558///
559/// Sizing rule: a challenge carries at most
560/// [`MAX_BYTE_CHALLENGE_KEYS`](super::config::MAX_BYTE_CHALLENGE_KEYS) keys —
561/// the auditor batches its sample, the responder rejects larger requests — so
562/// the WORST-CASE `Items` response (every chunk at `MAX_CHUNK_SIZE`) always
563/// encodes under [`MAX_REPLICATION_MESSAGE_SIZE`].
564#[derive(Debug, Clone, Serialize, Deserialize)]
565pub enum SubtreeByteResponse {
566    /// The responder's per-key answers (bytes or an explicit absent signal).
567    Items {
568        /// The challenge this response answers.
569        challenge_id: u64,
570        /// One entry per requested key.
571        items: Vec<SubtreeByteItem>,
572    },
573    /// Peer is still bootstrapping (should not happen mid-audit, but handled).
574    Bootstrapping {
575        /// The challenge this response answers.
576        challenge_id: u64,
577    },
578    /// The responder rejects the byte challenge outright. `kind` drives the
579    /// auditor's accounting (ADR-0004 A1: grace removed): [`RejectKind::Transient`]
580    /// routes to the timeout lane (no trust penalty, holder credit revoked); every
581    /// other kind is a confirmed failure, like round 1.
582    Rejected {
583        /// The challenge this response answers.
584        challenge_id: u64,
585        /// Machine-readable rejection class (accounting).
586        kind: RejectKind,
587        /// Human-readable rejection reason.
588        reason: String,
589    },
590}
591
592// ---------------------------------------------------------------------------
593// Audit digest helper
594// ---------------------------------------------------------------------------
595
596/// Compute `AuditKeyDigest(K_i) = BLAKE3(nonce || challenged_peer_id || K_i || record_bytes_i)`.
597///
598/// Returns the 32-byte BLAKE3 digest binding the nonce, peer identity, key,
599/// and record content together so a peer cannot forge proofs without holding
600/// the actual data.
601#[must_use]
602pub fn compute_audit_digest(
603    nonce: &[u8; 32],
604    challenged_peer_id: &[u8; 32],
605    key: &XorName,
606    record_bytes: &[u8],
607) -> [u8; 32] {
608    let mut hasher = blake3::Hasher::new();
609    hasher.update(nonce);
610    hasher.update(challenged_peer_id);
611    hasher.update(key);
612    hasher.update(record_bytes);
613    *hasher.finalize().as_bytes()
614}
615
616// ---------------------------------------------------------------------------
617// Error type
618// ---------------------------------------------------------------------------
619
620/// Errors from replication protocol encode/decode operations.
621#[derive(Debug, Clone)]
622pub enum ReplicationProtocolError {
623    /// Postcard serialization failed.
624    SerializationFailed(String),
625    /// Postcard deserialization failed.
626    DeserializationFailed(String),
627    /// Wire message exceeds the maximum allowed size.
628    MessageTooLarge {
629        /// Actual size of the message in bytes.
630        size: usize,
631        /// Maximum allowed size.
632        max_size: usize,
633    },
634}
635
636impl std::fmt::Display for ReplicationProtocolError {
637    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
638        match self {
639            Self::SerializationFailed(msg) => {
640                write!(f, "replication serialization failed: {msg}")
641            }
642            Self::DeserializationFailed(msg) => {
643                write!(f, "replication deserialization failed: {msg}")
644            }
645            Self::MessageTooLarge { size, max_size } => {
646                write!(
647                    f,
648                    "replication message size {size} exceeds maximum {max_size}"
649                )
650            }
651        }
652    }
653}
654
655impl std::error::Error for ReplicationProtocolError {}
656
657// ---------------------------------------------------------------------------
658// Tests
659// ---------------------------------------------------------------------------
660
661#[cfg(test)]
662#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
663mod tests {
664    use super::*;
665
666    // === Round-2 byte response sizing ===
667
668    #[test]
669    fn max_batch_worst_case_byte_response_fits_wire_cap() {
670        // The auditor batches its round-2 sample to MAX_BYTE_CHALLENGE_KEYS per
671        // challenge precisely so this worst case — every requested chunk at
672        // MAX_CHUNK_SIZE — still encodes. If this fails, honest responders
673        // would hit encode errors and fail otherwise valid byte challenges.
674        let items: Vec<SubtreeByteItem> = (0..crate::replication::config::MAX_BYTE_CHALLENGE_KEYS)
675            .map(|i| SubtreeByteItem::Present {
676                key: [u8::try_from(i).unwrap_or(u8::MAX); 32],
677                bytes: vec![0xAB; crate::ant_protocol::MAX_CHUNK_SIZE],
678            })
679            .collect();
680        let msg = ReplicationMessage {
681            request_id: 7,
682            body: ReplicationMessageBody::SubtreeByteResponse(SubtreeByteResponse::Items {
683                challenge_id: 7,
684                items,
685            }),
686        };
687        let encoded = msg
688            .encode()
689            .expect("worst-case max-batch byte response must fit the wire cap");
690        assert!(encoded.len() <= MAX_REPLICATION_MESSAGE_SIZE);
691    }
692
693    // === Fresh Replication roundtrip ===
694
695    #[test]
696    fn fresh_replication_offer_roundtrip() {
697        let msg = ReplicationMessage {
698            request_id: 1,
699            body: ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
700                key: [0xAA; 32],
701                data: vec![1, 2, 3, 4, 5],
702                proof_of_payment: vec![10, 20, 30],
703            }),
704        };
705        let encoded = msg.encode().expect("encode should succeed");
706        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
707
708        assert_eq!(decoded.request_id, 1);
709        if let ReplicationMessageBody::FreshReplicationOffer(offer) = decoded.body {
710            assert_eq!(offer.key, [0xAA; 32]);
711            assert_eq!(offer.data, vec![1, 2, 3, 4, 5]);
712            assert_eq!(offer.proof_of_payment, vec![10, 20, 30]);
713        } else {
714            panic!("expected FreshReplicationOffer");
715        }
716    }
717
718    #[test]
719    fn fresh_replication_response_accepted_roundtrip() {
720        let msg = ReplicationMessage {
721            request_id: 2,
722            body: ReplicationMessageBody::FreshReplicationResponse(
723                FreshReplicationResponse::Accepted { key: [0xBB; 32] },
724            ),
725        };
726        let encoded = msg.encode().expect("encode should succeed");
727        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
728
729        assert_eq!(decoded.request_id, 2);
730        if let ReplicationMessageBody::FreshReplicationResponse(
731            FreshReplicationResponse::Accepted { key },
732        ) = decoded.body
733        {
734            assert_eq!(key, [0xBB; 32]);
735        } else {
736            panic!("expected FreshReplicationResponse::Accepted");
737        }
738    }
739
740    #[test]
741    fn fresh_replication_response_rejected_roundtrip() {
742        let msg = ReplicationMessage {
743            request_id: 3,
744            body: ReplicationMessageBody::FreshReplicationResponse(
745                FreshReplicationResponse::Rejected {
746                    key: [0xCC; 32],
747                    reason: "out of range".to_string(),
748                },
749            ),
750        };
751        let encoded = msg.encode().expect("encode should succeed");
752        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
753
754        assert_eq!(decoded.request_id, 3);
755        if let ReplicationMessageBody::FreshReplicationResponse(
756            FreshReplicationResponse::Rejected { key, reason },
757        ) = decoded.body
758        {
759            assert_eq!(key, [0xCC; 32]);
760            assert_eq!(reason, "out of range");
761        } else {
762            panic!("expected FreshReplicationResponse::Rejected");
763        }
764    }
765
766    // === PaidNotify roundtrip ===
767
768    #[test]
769    fn paid_notify_roundtrip() {
770        let msg = ReplicationMessage {
771            request_id: 4,
772            body: ReplicationMessageBody::PaidNotify(PaidNotify {
773                key: [0xDD; 32],
774                proof_of_payment: vec![99, 100],
775            }),
776        };
777        let encoded = msg.encode().expect("encode should succeed");
778        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
779
780        assert_eq!(decoded.request_id, 4);
781        if let ReplicationMessageBody::PaidNotify(notify) = decoded.body {
782            assert_eq!(notify.key, [0xDD; 32]);
783            assert_eq!(notify.proof_of_payment, vec![99, 100]);
784        } else {
785            panic!("expected PaidNotify");
786        }
787    }
788
789    // === Neighbor Sync roundtrips ===
790
791    // -- backwards compat across the wire-type extension --------------------
792
793    /// Backwards-compat: an old peer that has the v0 layout of
794    /// `NeighborSyncRequest` (no `commitment` field) can still decode a
795    /// message encoded by a new peer that emits `commitment: None`. This
796    /// is the realistic mixed-version case during rollout: new peers
797    /// gossip with the field; old peers must not crash.
798    ///
799    /// The check works because postcard's [`from_bytes`] is lenient on
800    /// trailing bytes — the old decoder reads what it knows about and
801    /// stops, the new fields are silently ignored. This test pins that
802    /// invariant so any future codec/library swap that breaks it is
803    /// caught immediately.
804    #[test]
805    fn old_decoder_tolerates_new_neighbor_sync_request() {
806        use serde::Deserialize;
807        #[derive(Deserialize)]
808        struct OldNeighborSyncRequest {
809            #[allow(dead_code)]
810            pub replica_hints: Vec<XorName>,
811            #[allow(dead_code)]
812            pub paid_hints: Vec<XorName>,
813            #[allow(dead_code)]
814            pub bootstrapping: bool,
815        }
816
817        let new_req = NeighborSyncRequest {
818            replica_hints: vec![[0x01; 32], [0x02; 32]],
819            paid_hints: vec![[0x03; 32]],
820            bootstrapping: true,
821            commitment: None,
822        };
823        let encoded = postcard::to_stdvec(&new_req).expect("encode");
824        let old_decoded: OldNeighborSyncRequest =
825            postcard::from_bytes(&encoded).expect("old decoder accepts");
826        // Field-by-field check would fail if old peer misaligned on the
827        // length prefix — passing decode is the structural check.
828        assert_eq!(old_decoded.replica_hints.len(), 2);
829        assert_eq!(old_decoded.paid_hints.len(), 1);
830        assert!(old_decoded.bootstrapping);
831    }
832
833    /// Same property for `NeighborSyncResponse`.
834    #[test]
835    fn old_decoder_tolerates_new_neighbor_sync_response() {
836        use serde::Deserialize;
837        #[derive(Deserialize)]
838        struct OldNeighborSyncResponse {
839            #[allow(dead_code)]
840            pub replica_hints: Vec<XorName>,
841            #[allow(dead_code)]
842            pub paid_hints: Vec<XorName>,
843            #[allow(dead_code)]
844            pub bootstrapping: bool,
845            #[allow(dead_code)]
846            pub rejected_keys: Vec<XorName>,
847        }
848
849        let new_resp = NeighborSyncResponse {
850            replica_hints: vec![[0x04; 32]],
851            paid_hints: vec![],
852            bootstrapping: false,
853            rejected_keys: vec![[0x05; 32]],
854            commitment: None,
855        };
856        let encoded = postcard::to_stdvec(&new_resp).expect("encode");
857        let old_decoded: OldNeighborSyncResponse =
858            postcard::from_bytes(&encoded).expect("old decoder accepts");
859        assert_eq!(old_decoded.replica_hints.len(), 1);
860        assert_eq!(old_decoded.rejected_keys.len(), 1);
861    }
862
863    /// Roundtrip: a new peer can decode its own message including the
864    /// commitment field. Catches accidental serde annotation breakage
865    /// (e.g. forgetting `#[serde(default)]` on the new field).
866    #[test]
867    fn new_peer_roundtrips_with_commitment_some() {
868        use crate::replication::commitment::{sign_commitment, StorageCommitment};
869        use saorsa_pqc::api::sig::ml_dsa_65;
870
871        let (pk, sk) = ml_dsa_65().generate_keypair().expect("keygen");
872        let root = [0x7Fu8; 32];
873        let sender = [0xCCu8; 32];
874        let pk_bytes = pk.to_bytes();
875        let sig = sign_commitment(&sk, &root, 3, &sender, &pk_bytes).expect("sign");
876        let commitment = StorageCommitment {
877            root,
878            key_count: 3,
879            sender_peer_id: sender,
880            sender_public_key: pk_bytes,
881            signature: sig,
882        };
883
884        let req = NeighborSyncRequest {
885            replica_hints: vec![[0x01; 32]],
886            paid_hints: vec![],
887            bootstrapping: false,
888            commitment: Some(commitment.clone()),
889        };
890        let encoded = postcard::to_stdvec(&req).expect("encode");
891        let decoded: NeighborSyncRequest = postcard::from_bytes(&encoded).expect("new decoder");
892        assert_eq!(decoded.commitment, Some(commitment));
893    }
894
895    #[test]
896    fn neighbor_sync_request_roundtrip() {
897        let msg = ReplicationMessage {
898            request_id: 5,
899            body: ReplicationMessageBody::NeighborSyncRequest(NeighborSyncRequest {
900                replica_hints: vec![[0x01; 32], [0x02; 32]],
901                paid_hints: vec![[0x03; 32]],
902                bootstrapping: true,
903                commitment: None,
904            }),
905        };
906        let encoded = msg.encode().expect("encode should succeed");
907        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
908
909        assert_eq!(decoded.request_id, 5);
910        if let ReplicationMessageBody::NeighborSyncRequest(req) = decoded.body {
911            assert_eq!(req.replica_hints.len(), 2);
912            assert_eq!(req.paid_hints.len(), 1);
913            assert!(req.bootstrapping);
914        } else {
915            panic!("expected NeighborSyncRequest");
916        }
917    }
918
919    #[test]
920    fn neighbor_sync_response_roundtrip() {
921        let msg = ReplicationMessage {
922            request_id: 6,
923            body: ReplicationMessageBody::NeighborSyncResponse(NeighborSyncResponse {
924                replica_hints: vec![[0x04; 32]],
925                paid_hints: vec![],
926                bootstrapping: false,
927                rejected_keys: vec![[0x05; 32], [0x06; 32]],
928                commitment: None,
929            }),
930        };
931        let encoded = msg.encode().expect("encode should succeed");
932        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
933
934        assert_eq!(decoded.request_id, 6);
935        if let ReplicationMessageBody::NeighborSyncResponse(resp) = decoded.body {
936            assert_eq!(resp.replica_hints.len(), 1);
937            assert!(resp.paid_hints.is_empty());
938            assert!(!resp.bootstrapping);
939            assert_eq!(resp.rejected_keys.len(), 2);
940        } else {
941            panic!("expected NeighborSyncResponse");
942        }
943    }
944
945    // === Verification roundtrips ===
946
947    #[test]
948    fn verification_request_roundtrip() {
949        let msg = ReplicationMessage {
950            request_id: 7,
951            body: ReplicationMessageBody::VerificationRequest(VerificationRequest {
952                keys: vec![[0x10; 32], [0x20; 32], [0x30; 32]],
953                paid_list_check_indices: vec![0, 2],
954            }),
955        };
956        let encoded = msg.encode().expect("encode should succeed");
957        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
958
959        assert_eq!(decoded.request_id, 7);
960        if let ReplicationMessageBody::VerificationRequest(req) = decoded.body {
961            assert_eq!(req.keys.len(), 3);
962            assert_eq!(req.paid_list_check_indices, vec![0, 2]);
963        } else {
964            panic!("expected VerificationRequest");
965        }
966    }
967
968    #[test]
969    fn verification_response_roundtrip() {
970        let results = vec![
971            KeyVerificationResult {
972                key: [0x10; 32],
973                present: true,
974                paid: Some(true),
975            },
976            KeyVerificationResult {
977                key: [0x20; 32],
978                present: false,
979                paid: None,
980            },
981            KeyVerificationResult {
982                key: [0x30; 32],
983                present: true,
984                paid: Some(false),
985            },
986        ];
987        let msg = ReplicationMessage {
988            request_id: 8,
989            body: ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
990        };
991        let encoded = msg.encode().expect("encode should succeed");
992        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
993
994        assert_eq!(decoded.request_id, 8);
995        if let ReplicationMessageBody::VerificationResponse(resp) = decoded.body {
996            assert_eq!(resp.results.len(), 3);
997            assert!(resp.results[0].present);
998            assert_eq!(resp.results[0].paid, Some(true));
999            assert!(!resp.results[1].present);
1000            assert_eq!(resp.results[1].paid, None);
1001            assert!(resp.results[2].present);
1002            assert_eq!(resp.results[2].paid, Some(false));
1003        } else {
1004            panic!("expected VerificationResponse");
1005        }
1006    }
1007
1008    // === Fetch roundtrips ===
1009
1010    #[test]
1011    fn fetch_request_roundtrip() {
1012        let msg = ReplicationMessage {
1013            request_id: 9,
1014            body: ReplicationMessageBody::FetchRequest(FetchRequest { key: [0x40; 32] }),
1015        };
1016        let encoded = msg.encode().expect("encode should succeed");
1017        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1018
1019        assert_eq!(decoded.request_id, 9);
1020        if let ReplicationMessageBody::FetchRequest(req) = decoded.body {
1021            assert_eq!(req.key, [0x40; 32]);
1022        } else {
1023            panic!("expected FetchRequest");
1024        }
1025    }
1026
1027    #[test]
1028    fn fetch_response_success_roundtrip() {
1029        let msg = ReplicationMessage {
1030            request_id: 10,
1031            body: ReplicationMessageBody::FetchResponse(FetchResponse::Success {
1032                key: [0x50; 32],
1033                data: vec![7, 8, 9],
1034            }),
1035        };
1036        let encoded = msg.encode().expect("encode should succeed");
1037        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1038
1039        assert_eq!(decoded.request_id, 10);
1040        if let ReplicationMessageBody::FetchResponse(FetchResponse::Success { key, data }) =
1041            decoded.body
1042        {
1043            assert_eq!(key, [0x50; 32]);
1044            assert_eq!(data, vec![7, 8, 9]);
1045        } else {
1046            panic!("expected FetchResponse::Success");
1047        }
1048    }
1049
1050    #[test]
1051    fn fetch_response_not_found_roundtrip() {
1052        let msg = ReplicationMessage {
1053            request_id: 11,
1054            body: ReplicationMessageBody::FetchResponse(FetchResponse::NotFound {
1055                key: [0x60; 32],
1056            }),
1057        };
1058        let encoded = msg.encode().expect("encode should succeed");
1059        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1060
1061        assert_eq!(decoded.request_id, 11);
1062        if let ReplicationMessageBody::FetchResponse(FetchResponse::NotFound { key }) = decoded.body
1063        {
1064            assert_eq!(key, [0x60; 32]);
1065        } else {
1066            panic!("expected FetchResponse::NotFound");
1067        }
1068    }
1069
1070    #[test]
1071    fn fetch_response_error_roundtrip() {
1072        let msg = ReplicationMessage {
1073            request_id: 12,
1074            body: ReplicationMessageBody::FetchResponse(FetchResponse::Error {
1075                key: [0x70; 32],
1076                reason: "disk full".to_string(),
1077            }),
1078        };
1079        let encoded = msg.encode().expect("encode should succeed");
1080        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1081
1082        assert_eq!(decoded.request_id, 12);
1083        if let ReplicationMessageBody::FetchResponse(FetchResponse::Error { key, reason }) =
1084            decoded.body
1085        {
1086            assert_eq!(key, [0x70; 32]);
1087            assert_eq!(reason, "disk full");
1088        } else {
1089            panic!("expected FetchResponse::Error");
1090        }
1091    }
1092
1093    // === Audit roundtrips ===
1094
1095    #[test]
1096    fn audit_challenge_roundtrip() {
1097        let msg = ReplicationMessage {
1098            request_id: 13,
1099            body: ReplicationMessageBody::AuditChallenge(AuditChallenge {
1100                challenge_id: 999,
1101                nonce: [0xAB; 32],
1102                challenged_peer_id: [0xCD; 32],
1103                keys: vec![[0x01; 32], [0x02; 32]],
1104            }),
1105        };
1106        let encoded = msg.encode().expect("encode should succeed");
1107        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1108
1109        assert_eq!(decoded.request_id, 13);
1110        if let ReplicationMessageBody::AuditChallenge(challenge) = decoded.body {
1111            assert_eq!(challenge.challenge_id, 999);
1112            assert_eq!(challenge.nonce, [0xAB; 32]);
1113            assert_eq!(challenge.challenged_peer_id, [0xCD; 32]);
1114            assert_eq!(challenge.keys.len(), 2);
1115        } else {
1116            panic!("expected AuditChallenge");
1117        }
1118    }
1119
1120    #[test]
1121    fn audit_response_digests_roundtrip() {
1122        let digests = vec![[0x11; 32], ABSENT_KEY_DIGEST];
1123        let msg = ReplicationMessage {
1124            request_id: 14,
1125            body: ReplicationMessageBody::AuditResponse(AuditResponse::Digests {
1126                challenge_id: 999,
1127                digests: digests.clone(),
1128            }),
1129        };
1130        let encoded = msg.encode().expect("encode should succeed");
1131        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1132
1133        assert_eq!(decoded.request_id, 14);
1134        if let ReplicationMessageBody::AuditResponse(AuditResponse::Digests {
1135            challenge_id,
1136            digests: decoded_digests,
1137        }) = decoded.body
1138        {
1139            assert_eq!(challenge_id, 999);
1140            assert_eq!(decoded_digests, digests);
1141        } else {
1142            panic!("expected AuditResponse::Digests");
1143        }
1144    }
1145
1146    #[test]
1147    fn audit_response_bootstrapping_roundtrip() {
1148        let msg = ReplicationMessage {
1149            request_id: 15,
1150            body: ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping {
1151                challenge_id: 42,
1152            }),
1153        };
1154        let encoded = msg.encode().expect("encode should succeed");
1155        let decoded = ReplicationMessage::decode(&encoded).expect("decode should succeed");
1156
1157        assert_eq!(decoded.request_id, 15);
1158        if let ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping {
1159            challenge_id,
1160        }) = decoded.body
1161        {
1162            assert_eq!(challenge_id, 42);
1163        } else {
1164            panic!("expected AuditResponse::Bootstrapping");
1165        }
1166    }
1167
1168    // === Oversized message rejection ===
1169
1170    #[test]
1171    fn decode_rejects_oversized_payload() {
1172        let oversized = vec![0u8; MAX_REPLICATION_MESSAGE_SIZE + 1];
1173        let result = ReplicationMessage::decode(&oversized);
1174        assert!(result.is_err());
1175        let err = result.unwrap_err();
1176        assert!(
1177            matches!(err, ReplicationProtocolError::MessageTooLarge { .. }),
1178            "expected MessageTooLarge, got {err:?}"
1179        );
1180    }
1181
1182    #[test]
1183    fn encode_rejects_oversized_message() {
1184        // Build a message whose serialized form exceeds the limit.
1185        let msg = ReplicationMessage {
1186            request_id: 0,
1187            body: ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
1188                key: [0; 32],
1189                data: vec![0xFF; MAX_REPLICATION_MESSAGE_SIZE],
1190                proof_of_payment: vec![],
1191            }),
1192        };
1193        let result = msg.encode();
1194        assert!(result.is_err());
1195        let err = result.unwrap_err();
1196        assert!(
1197            matches!(err, ReplicationProtocolError::MessageTooLarge { .. }),
1198            "expected MessageTooLarge, got {err:?}"
1199        );
1200    }
1201
1202    // === Invalid data rejection ===
1203
1204    #[test]
1205    fn decode_rejects_invalid_data() {
1206        let invalid = vec![0xFF, 0xFF, 0xFF];
1207        let result = ReplicationMessage::decode(&invalid);
1208        assert!(result.is_err());
1209        let err = result.unwrap_err();
1210        assert!(
1211            matches!(err, ReplicationProtocolError::DeserializationFailed(_)),
1212            "expected DeserializationFailed, got {err:?}"
1213        );
1214    }
1215
1216    // === Audit digest computation ===
1217
1218    #[test]
1219    fn audit_digest_is_deterministic() {
1220        let nonce = [0x01; 32];
1221        let peer_id = [0x02; 32];
1222        let key: XorName = [0x03; 32];
1223        let record_bytes = b"hello world";
1224
1225        let digest_a = compute_audit_digest(&nonce, &peer_id, &key, record_bytes);
1226        let digest_b = compute_audit_digest(&nonce, &peer_id, &key, record_bytes);
1227
1228        assert_eq!(digest_a, digest_b, "same inputs must produce same digest");
1229    }
1230
1231    #[test]
1232    fn audit_digest_differs_with_different_nonce() {
1233        let peer_id = [0x02; 32];
1234        let key: XorName = [0x03; 32];
1235        let record_bytes = b"hello world";
1236
1237        let digest_a = compute_audit_digest(&[0x01; 32], &peer_id, &key, record_bytes);
1238        let digest_b = compute_audit_digest(&[0xFF; 32], &peer_id, &key, record_bytes);
1239
1240        assert_ne!(
1241            digest_a, digest_b,
1242            "different nonces must produce different digests"
1243        );
1244    }
1245
1246    #[test]
1247    fn audit_digest_differs_with_different_data() {
1248        let nonce = [0x01; 32];
1249        let peer_id = [0x02; 32];
1250        let key: XorName = [0x03; 32];
1251
1252        let digest_a = compute_audit_digest(&nonce, &peer_id, &key, b"data-A");
1253        let digest_b = compute_audit_digest(&nonce, &peer_id, &key, b"data-B");
1254
1255        assert_ne!(
1256            digest_a, digest_b,
1257            "different data must produce different digests"
1258        );
1259    }
1260
1261    #[test]
1262    fn audit_digest_differs_with_different_peer() {
1263        let nonce = [0x01; 32];
1264        let key: XorName = [0x03; 32];
1265        let record_bytes = b"hello";
1266
1267        let digest_a = compute_audit_digest(&nonce, &[0x02; 32], &key, record_bytes);
1268        let digest_b = compute_audit_digest(&nonce, &[0xFF; 32], &key, record_bytes);
1269
1270        assert_ne!(
1271            digest_a, digest_b,
1272            "different peer IDs must produce different digests"
1273        );
1274    }
1275
1276    #[test]
1277    fn audit_digest_differs_with_different_key() {
1278        let nonce = [0x01; 32];
1279        let peer_id = [0x02; 32];
1280        let record_bytes = b"hello";
1281
1282        let digest_a = compute_audit_digest(&nonce, &peer_id, &[0x03; 32], record_bytes);
1283        let digest_b = compute_audit_digest(&nonce, &peer_id, &[0xFF; 32], record_bytes);
1284
1285        assert_ne!(
1286            digest_a, digest_b,
1287            "different keys must produce different digests"
1288        );
1289    }
1290
1291    // === Absent key digest sentinel ===
1292
1293    #[test]
1294    fn absent_key_digest_is_all_zeros() {
1295        assert_eq!(ABSENT_KEY_DIGEST, [0u8; 32]);
1296    }
1297
1298    #[test]
1299    fn real_digest_differs_from_absent_sentinel() {
1300        let nonce = [0x01; 32];
1301        let peer_id = [0x02; 32];
1302        let key: XorName = [0x03; 32];
1303        let record_bytes = b"non-empty data";
1304
1305        let digest = compute_audit_digest(&nonce, &peer_id, &key, record_bytes);
1306        assert_ne!(
1307            digest, ABSENT_KEY_DIGEST,
1308            "a real digest should not collide with the all-zeros sentinel"
1309        );
1310    }
1311
1312    // === Error Display ===
1313
1314    #[test]
1315    fn error_display_serialization_failed() {
1316        let err = ReplicationProtocolError::SerializationFailed("boom".to_string());
1317        assert_eq!(err.to_string(), "replication serialization failed: boom");
1318    }
1319
1320    #[test]
1321    fn error_display_deserialization_failed() {
1322        let err = ReplicationProtocolError::DeserializationFailed("bad data".to_string());
1323        assert_eq!(
1324            err.to_string(),
1325            "replication deserialization failed: bad data"
1326        );
1327    }
1328
1329    #[test]
1330    fn error_display_message_too_large() {
1331        let err = ReplicationProtocolError::MessageTooLarge {
1332            size: 20_000_000,
1333            max_size: MAX_REPLICATION_MESSAGE_SIZE,
1334        };
1335        let display = err.to_string();
1336        assert!(display.contains("20000000"));
1337        assert!(display.contains(&MAX_REPLICATION_MESSAGE_SIZE.to_string()));
1338    }
1339}