ant_protocol/chunk.rs
1//! Chunk message types for the ANT protocol.
2//!
3//! Chunks are immutable, content-addressed data blocks where the address
4//! is the BLAKE3 hash of the content. Maximum size is 4MB.
5//!
6//! This module defines the wire protocol messages for chunk operations
7//! using postcard serialization for compact, fast encoding.
8
9use bytes::Bytes;
10use serde::{Deserialize, Serialize};
11
12/// Protocol identifier for chunk operations.
13pub const CHUNK_PROTOCOL_ID: &str = "autonomi.ant.chunk.v1";
14
15/// Current protocol version.
16pub const PROTOCOL_VERSION: u16 = 1;
17
18/// Maximum chunk size in bytes (4MB).
19pub const MAX_CHUNK_SIZE: usize = 4 * 1024 * 1024;
20
21/// Maximum wire message size in bytes (5MB).
22///
23/// Limits the input buffer accepted by [`ChunkMessage::decode`] to prevent
24/// unbounded allocation from malicious or corrupted payloads. Set slightly
25/// above [`MAX_CHUNK_SIZE`] to accommodate message envelope overhead.
26pub const MAX_WIRE_MESSAGE_SIZE: usize = 5 * 1024 * 1024;
27
28/// Data type identifier for chunks.
29pub const DATA_TYPE_CHUNK: u32 = 0;
30
31/// User-agent token a node announces when it answers
32/// [`ChunkMessageBody::GetOrCloserRequest`] (ant-node ADR-0020).
33///
34/// Native QUIC peers exchange no capabilities, and a node built before that
35/// request existed drops it without a reply. A client sends it only to a peer
36/// whose user agent carries this token; see [`advertises_get_or_closer`].
37pub const GET_OR_CLOSER_AGENT_TOKEN: &str = "get-or-closer/1";
38
39/// Settlement rules this build pays and verifies under.
40///
41/// Separate from [`PROTOCOL_VERSION`] on purpose. That one tracks the *wire*:
42/// what a peer can parse. This one tracks the *money*: how a client turns a
43/// signed quote into an on-chain payment. The two move independently, and
44/// conflating them is what made this constant necessary.
45///
46/// Version 1 is the ADR-0008 rule set: a merkle batch settles at
47/// `3 x median16(price) x 2^depth`, matching the single-node path.
48///
49/// **Bump this whenever a change makes an older client pay an amount storers
50/// will refuse.** The multiplier moving, the median rule changing, the payable
51/// field being redefined: all of those. A change that only alters *how much* a
52/// node quotes does not qualify, because the client pays whatever it is
53/// quoted; a change to the arithmetic *applied* to that quote does.
54///
55/// # Why this exists
56///
57/// ADR-0008 raised the merkle multiplier to 3x in client code and enforced it
58/// in node code, but changed no wire type. Nothing gated the two together, so
59/// clients built before the change kept collecting quotes, kept paying 1x, and
60/// had their uploads refused by every storer *after* the on-chain payment had
61/// already settled. The money was unrecoverable and the client had no idea why.
62///
63/// Carrying the version in the quote request lets a storer refuse to quote a
64/// client it knows cannot pay correctly, before that client spends anything.
65pub const CURRENT_SETTLEMENT_VERSION: u32 = 1;
66
67/// Oldest settlement version this build will issue a quote for.
68///
69/// Kept as a separate constant from [`CURRENT_SETTLEMENT_VERSION`] so a
70/// settlement change can ship without immediately locking out the previous
71/// client generation: raise `CURRENT` first, let clients adopt, raise `MIN`
72/// once the payment rule actually changes. They are equal today because
73/// version 1 is the first versioned rule set, so there is no earlier one to
74/// keep serving.
75pub const MIN_SUPPORTED_SETTLEMENT_VERSION: u32 = 1;
76
77/// Whether a storer on this build can promise to accept what a client
78/// settling under `client_version` will pay.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub enum SettlementCompatibility {
81 /// Both sides settle the same way. Safe to quote.
82 Compatible,
83 /// The client settles under rules this build has superseded. Its payment
84 /// would be refused, so it must not be quoted.
85 ClientTooOld,
86 /// The client settles under rules this build does not know. **This build
87 /// is the old one**, and it cannot promise to accept the resulting
88 /// payment, so it must not be quoted either.
89 NodeTooOld,
90}
91
92/// Can a storer on this build safely quote a client settling under
93/// `client_version`?
94///
95/// Unversioned clients never reach this: they send the legacy request variants
96/// and are handled by policy in the storer, not here.
97///
98/// # Why both ends are bounded
99///
100/// An earlier revision accepted everything at or above
101/// [`MIN_SUPPORTED_SETTLEMENT_VERSION`], on the reasoning that a storer
102/// verifies whatever payment actually arrives so letting a newer client
103/// through weakens nothing. That is only true when a settlement change raises
104/// what is paid: ADR-0008's 3x cleared an old node's 1x minimum, so old nodes
105/// accepted new clients for free. It is **not** true in general. A change that
106/// redefines the median rule, or which field the contract pays from, produces
107/// a payment an older verifier rejects, and by then the client has already
108/// settled on-chain and cannot be refunded. That is the exact failure this
109/// mechanism exists to prevent, so an unknown-newer version is refused rather
110/// than assumed compatible.
111///
112/// The two refusals are kept apart because they need opposite handling.
113/// [`SettlementCompatibility::ClientTooOld`] is terminal and the user must
114/// upgrade. [`SettlementCompatibility::NodeTooOld`] says nothing about the
115/// client, which should simply use a different storer. Collapsing them would
116/// either tell up-to-date users to upgrade, or strand new clients whenever the
117/// node fleet lags, which is the normal state during a client-first rollout.
118#[must_use]
119pub const fn settlement_compatibility(client_version: u32) -> SettlementCompatibility {
120 if client_version < MIN_SUPPORTED_SETTLEMENT_VERSION {
121 SettlementCompatibility::ClientTooOld
122 } else if client_version > CURRENT_SETTLEMENT_VERSION {
123 SettlementCompatibility::NodeTooOld
124 } else {
125 SettlementCompatibility::Compatible
126 }
127}
128
129/// Number of nodes in a Kademlia close group.
130///
131/// Clients fetch quotes from the `CLOSE_GROUP_SIZE` closest nodes to a target
132/// address and select the median-priced quote for payment.
133pub const CLOSE_GROUP_SIZE: usize = 7;
134
135/// Minimum number of close group members that must agree for a decision to be valid.
136///
137/// This is a simple majority: `(CLOSE_GROUP_SIZE / 2) + 1`.
138pub const CLOSE_GROUP_MAJORITY: usize = (CLOSE_GROUP_SIZE / 2) + 1;
139
140/// Content-addressed identifier (32 bytes).
141pub type XorName = [u8; 32];
142
143/// Byte length of an [`XorName`].
144pub const XORNAME_LEN: usize = std::mem::size_of::<XorName>();
145
146/// Enum of all chunk protocol message types.
147///
148/// Uses a single-byte discriminant for efficient wire encoding.
149///
150/// Marked `#[non_exhaustive]` so new message variants can be added
151/// in a minor release without breaking downstream `match` expressions.
152#[derive(Debug, Clone, Serialize, Deserialize)]
153#[non_exhaustive]
154pub enum ChunkMessageBody {
155 /// Request to store a chunk.
156 PutRequest(ChunkPutRequest),
157 /// Response to a PUT request.
158 PutResponse(ChunkPutResponse),
159 /// Request to retrieve a chunk.
160 GetRequest(ChunkGetRequest),
161 /// Response to a GET request.
162 GetResponse(ChunkGetResponse),
163 /// Request a storage quote.
164 QuoteRequest(ChunkQuoteRequest),
165 /// Response with a storage quote.
166 QuoteResponse(ChunkQuoteResponse),
167 /// Request a merkle candidate quote for batch payments.
168 MerkleCandidateQuoteRequest(MerkleCandidateQuoteRequest),
169 /// Response with a merkle candidate quote.
170 MerkleCandidateQuoteResponse(MerkleCandidateQuoteResponse),
171 /// Request a storage quote, declaring the client's settlement version.
172 ///
173 /// Appended after [`Self::MerkleCandidateQuoteResponse`] so every
174 /// discriminant above keeps its wire value and existing peers decode
175 /// unchanged. A peer built before this variant existed rejects it cleanly
176 /// as an unknown discriminant rather than misreading it.
177 QuoteRequestV2(ChunkQuoteRequestV2),
178 /// Request a merkle candidate quote, declaring the client's settlement
179 /// version. Appended for the same reason as [`Self::QuoteRequestV2`].
180 MerkleCandidateQuoteRequestV2(MerkleCandidateQuoteRequestV2),
181 /// Request to store or update a pointer.
182 ///
183 /// Appended after every existing variant for the reason given on
184 /// [`Self::QuoteRequestV2`]: discriminants above keep their wire values, and
185 /// a peer built before pointers existed rejects this cleanly as an unknown
186 /// discriminant rather than misreading it.
187 PointerPutRequest(PointerPutRequest),
188 /// Response to a pointer PUT.
189 PointerPutResponse(PointerPutResponse),
190 /// Request to retrieve a pointer.
191 PointerGetRequest(PointerGetRequest),
192 /// Response to a pointer GET.
193 PointerGetResponse(PointerGetResponse),
194 /// Request a chunk, or the responder's closest peers to it when it does
195 /// not hold the chunk: Kademlia's `FIND_VALUE` (ant-node ADR-0020).
196 ///
197 /// Appended after every existing variant for the reason given on
198 /// [`Self::QuoteRequestV2`]. A node built before this variant drops it
199 /// without a reply, so a client sends it only to a peer whose user agent
200 /// carries [`GET_OR_CLOSER_AGENT_TOKEN`].
201 GetOrCloserRequest(ChunkGetOrCloserRequest),
202 /// Response to a get-or-closer request.
203 GetOrCloserResponse(ChunkGetOrCloserResponse),
204}
205
206/// Whether a peer's user agent says it answers
207/// [`ChunkMessageBody::GetOrCloserRequest`].
208#[must_use]
209pub fn advertises_get_or_closer(user_agent: &str) -> bool {
210 user_agent
211 .split_whitespace()
212 .any(|token| token == GET_OR_CLOSER_AGENT_TOKEN)
213}
214
215// =============================================================================
216// Pointer PUT / GET
217// =============================================================================
218
219/// Request to store or update a pointer.
220///
221/// `record` is the whole [`Pointer`](crate::pointer::Pointer) encoding. There is
222/// no separate address field: a pointer's address is a pure function of the
223/// owner key inside the record, so a second copy could only ever disagree with
224/// it.
225#[derive(Debug, Clone, Serialize, Deserialize)]
226pub struct PointerPutRequest {
227 /// The canonical pointer encoding.
228 pub record: Bytes,
229 /// Optional payment proof (serialized `ProofOfPayment`).
230 ///
231 /// Quoted and paid against the record's `state_id`, not its address: the
232 /// address is stable for the pointer's life, so paying against it would
233 /// make every update after the first free.
234 pub payment_proof: Option<Vec<u8>>,
235}
236
237impl PointerPutRequest {
238 /// Create a PUT request with no payment proof.
239 #[must_use]
240 pub const fn new(record: Bytes) -> Self {
241 Self {
242 record,
243 payment_proof: None,
244 }
245 }
246
247 /// Create a PUT request carrying a payment proof.
248 #[must_use]
249 pub const fn with_payment(record: Bytes, payment_proof: Vec<u8>) -> Self {
250 Self {
251 record,
252 payment_proof: Some(payment_proof),
253 }
254 }
255}
256
257/// Response to a pointer PUT.
258#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
259pub enum PointerPutResponse {
260 /// The pointer was stored, or replaced what was held.
261 ///
262 /// `state_id` names what the node now holds, so a client can tell an
263 /// accepted update from one that lost a race.
264 Success {
265 /// The pointer's address.
266 address: XorName,
267 /// The state now held at that address.
268 state_id: XorName,
269 },
270 /// The node already held this exact state. Nothing was written.
271 ///
272 /// Distinct from `Success` because it is what a re-submission of a paid
273 /// state gets: the update is not lost, but it bought nothing either.
274 Unchanged {
275 /// The pointer's address.
276 address: XorName,
277 /// The state held, which equals the one submitted.
278 state_id: XorName,
279 },
280 /// The submitted record lost to what the node already holds.
281 Stale {
282 /// The pointer's address.
283 address: XorName,
284 /// The state the node holds instead.
285 state_id: XorName,
286 },
287 /// Payment is required to store this state.
288 PaymentRequired {
289 /// Error message.
290 message: String,
291 },
292 /// An error occurred.
293 Error(ProtocolError),
294}
295
296/// Request to retrieve a pointer.
297#[derive(Debug, Clone, Serialize, Deserialize)]
298pub struct PointerGetRequest {
299 /// The pointer address to retrieve.
300 pub address: XorName,
301}
302
303impl PointerGetRequest {
304 /// Create a GET request for `address`.
305 #[must_use]
306 pub const fn new(address: XorName) -> Self {
307 Self { address }
308 }
309}
310
311/// Response to a pointer GET.
312#[derive(Debug, Clone, Serialize, Deserialize)]
313pub enum PointerGetResponse {
314 /// The pointer held at the requested address.
315 Success {
316 /// The canonical pointer encoding.
317 record: Bytes,
318 },
319 /// No pointer is held at that address.
320 NotFound {
321 /// The address asked for.
322 address: XorName,
323 },
324 /// An error occurred.
325 Error(ProtocolError),
326}
327
328/// Wire-format wrapper that pairs a sender-assigned `request_id` with
329/// a [`ChunkMessageBody`].
330///
331/// The sender picks a unique `request_id`; the handler echoes it back
332/// in the response so callers can correlate replies by ID rather than
333/// by source peer.
334#[derive(Debug, Clone, Serialize, Deserialize)]
335pub struct ChunkMessage {
336 /// Sender-assigned identifier, echoed back in the response.
337 pub request_id: u64,
338 /// The protocol message body.
339 pub body: ChunkMessageBody,
340}
341
342impl ChunkMessage {
343 /// Encode the message to bytes using postcard.
344 ///
345 /// # Errors
346 ///
347 /// Returns an error if serialization fails.
348 pub fn encode(&self) -> Result<Vec<u8>, ProtocolError> {
349 postcard::to_stdvec(self).map_err(|e| ProtocolError::SerializationFailed(e.to_string()))
350 }
351
352 /// Decode a message from bytes using postcard.
353 ///
354 /// Rejects payloads larger than [`MAX_WIRE_MESSAGE_SIZE`] before
355 /// attempting deserialization.
356 ///
357 /// # Errors
358 ///
359 /// Returns [`ProtocolError::MessageTooLarge`] if the input exceeds the
360 /// size limit, or [`ProtocolError::DeserializationFailed`] if postcard
361 /// cannot parse the data.
362 pub fn decode(data: &[u8]) -> Result<Self, ProtocolError> {
363 if data.len() > MAX_WIRE_MESSAGE_SIZE {
364 return Err(ProtocolError::MessageTooLarge {
365 size: data.len(),
366 max_size: MAX_WIRE_MESSAGE_SIZE,
367 });
368 }
369 postcard::from_bytes(data).map_err(|e| ProtocolError::DeserializationFailed(e.to_string()))
370 }
371}
372
373// =============================================================================
374// PUT Request/Response
375// =============================================================================
376
377/// Request to store a chunk.
378///
379/// `content` is held as `bytes::Bytes` so that callers fanning the same
380/// chunk out to multiple recipients (e.g. close-group replication) share a
381/// single backing buffer via refcount instead of deep-copying the 4 MB
382/// payload per peer. Wire format is unchanged: `Bytes` serializes as a
383/// byte sequence, identical to `Vec<u8>` under postcard/serde.
384#[derive(Debug, Clone, Serialize, Deserialize)]
385pub struct ChunkPutRequest {
386 /// The content-addressed identifier (BLAKE3 of content).
387 pub address: XorName,
388 /// The chunk data.
389 pub content: Bytes,
390 /// Optional payment proof (serialized `ProofOfPayment`).
391 /// Required for new chunks unless already verified.
392 pub payment_proof: Option<Vec<u8>>,
393}
394
395impl ChunkPutRequest {
396 /// Create a new PUT request.
397 #[must_use]
398 pub fn new(address: XorName, content: Bytes) -> Self {
399 Self {
400 address,
401 content,
402 payment_proof: None,
403 }
404 }
405
406 /// Create a new PUT request with payment proof.
407 #[must_use]
408 pub fn with_payment(address: XorName, content: Bytes, payment_proof: Vec<u8>) -> Self {
409 Self {
410 address,
411 content,
412 payment_proof: Some(payment_proof),
413 }
414 }
415}
416
417/// Response to a PUT request.
418#[derive(Debug, Clone, Serialize, Deserialize)]
419#[non_exhaustive]
420pub enum ChunkPutResponse {
421 /// Chunk stored successfully.
422 Success {
423 /// The address where the chunk was stored.
424 address: XorName,
425 },
426 /// Chunk already exists (idempotent success).
427 AlreadyExists {
428 /// The existing chunk address.
429 address: XorName,
430 },
431 /// Payment is required to store this chunk.
432 PaymentRequired {
433 /// Error message.
434 message: String,
435 },
436 /// An error occurred.
437 Error(ProtocolError),
438}
439
440// =============================================================================
441// GET Request/Response
442// =============================================================================
443
444/// Request to retrieve a chunk.
445#[derive(Debug, Clone, Serialize, Deserialize)]
446pub struct ChunkGetRequest {
447 /// The content-addressed identifier to retrieve.
448 pub address: XorName,
449}
450
451impl ChunkGetRequest {
452 /// Create a new GET request.
453 #[must_use]
454 pub fn new(address: XorName) -> Self {
455 Self { address }
456 }
457}
458
459/// Response to a GET request.
460#[derive(Debug, Clone, Serialize, Deserialize)]
461#[non_exhaustive]
462pub enum ChunkGetResponse {
463 /// Chunk found and returned.
464 Success {
465 /// The chunk address.
466 address: XorName,
467 /// The chunk data.
468 content: Vec<u8>,
469 },
470 /// Chunk not found.
471 NotFound {
472 /// The requested address.
473 address: XorName,
474 },
475 /// An error occurred.
476 Error(ProtocolError),
477}
478
479// =============================================================================
480// Get-or-closer Request/Response
481// =============================================================================
482
483/// Request a chunk, or the responder's closest peers to it when it does not
484/// hold the chunk.
485#[derive(Debug, Clone, Serialize, Deserialize)]
486pub struct ChunkGetOrCloserRequest {
487 /// The content-addressed identifier to retrieve.
488 pub address: XorName,
489}
490
491impl ChunkGetOrCloserRequest {
492 /// Create a new get-or-closer request.
493 #[must_use]
494 pub const fn new(address: XorName) -> Self {
495 Self { address }
496 }
497}
498
499/// Response to a get-or-closer request.
500#[derive(Debug, Clone, Serialize, Deserialize)]
501#[non_exhaustive]
502pub enum ChunkGetOrCloserResponse {
503 /// The responder holds the chunk.
504 Found {
505 /// The chunk address.
506 address: XorName,
507 /// The chunk data.
508 content: Bytes,
509 },
510 /// The responder does not hold the chunk.
511 Closer {
512 /// The requested address.
513 address: XorName,
514 /// The responder's closest known peers to `address`, as its `FIND_NODE`
515 /// answer to the requester would hold them.
516 ///
517 /// Encoded by saorsa-core's `DhtNetworkManager::encode_closer_peers`
518 /// and checked by `decode_closer_peers`. Opaque here, so the peer
519 /// format is versioned in one place, as it is for `FIND_NODE`.
520 peers: Bytes,
521 },
522 /// An error occurred.
523 Error(ProtocolError),
524}
525
526// =============================================================================
527// Quote Request/Response
528// =============================================================================
529
530/// Request a storage quote for a chunk.
531#[derive(Debug, Clone, Serialize, Deserialize)]
532pub struct ChunkQuoteRequest {
533 /// The content address of the data to store.
534 pub address: XorName,
535 /// Size of the data in bytes.
536 pub data_size: u64,
537 /// Data type identifier (0 for chunks).
538 pub data_type: u32,
539}
540
541impl ChunkQuoteRequest {
542 /// Create a new quote request.
543 #[must_use]
544 pub fn new(address: XorName, data_size: u64) -> Self {
545 Self {
546 address,
547 data_size,
548 data_type: DATA_TYPE_CHUNK,
549 }
550 }
551}
552
553/// Request a storage quote, declaring the settlement rules the client pays
554/// under.
555///
556/// Same fields as [`ChunkQuoteRequest`] plus `settlement_version`. A separate
557/// struct rather than a field on the original, because [`ChunkMessage`] is
558/// postcard-encoded and postcard is not self-describing: adding a field would
559/// silently change how every existing peer reads the message, while adding a
560/// variant is rejected cleanly by peers that do not know it.
561#[derive(Debug, Clone, Serialize, Deserialize)]
562pub struct ChunkQuoteRequestV2 {
563 /// The content address of the data to store.
564 pub address: XorName,
565 /// Size of the data in bytes.
566 pub data_size: u64,
567 /// Data type identifier (0 for chunks).
568 pub data_type: u32,
569 /// The settlement rules this client pays under. See
570 /// [`CURRENT_SETTLEMENT_VERSION`].
571 pub settlement_version: u32,
572}
573
574impl ChunkQuoteRequestV2 {
575 /// Create a new quote request declaring this build's settlement version.
576 #[must_use]
577 pub fn new(address: XorName, data_size: u64) -> Self {
578 Self {
579 address,
580 data_size,
581 data_type: DATA_TYPE_CHUNK,
582 settlement_version: CURRENT_SETTLEMENT_VERSION,
583 }
584 }
585}
586
587/// Response with a storage quote.
588#[derive(Debug, Clone, Serialize, Deserialize)]
589#[non_exhaustive]
590pub enum ChunkQuoteResponse {
591 /// Quote generated successfully.
592 ///
593 /// When `already_stored` is `true` the node already holds this chunk and no
594 /// payment is required — the client should skip the pay-then-PUT cycle for
595 /// this address. The quote is still included for informational purposes.
596 Success {
597 /// Serialized `PaymentQuote`.
598 quote: Vec<u8>,
599 /// `true` when the chunk already exists on this node (skip payment).
600 already_stored: bool,
601 /// ADR-0004: the serialized signed storage commitment the quote's price
602 /// was derived from, so the client can verify the binding before paying
603 /// ("the commitment arrived with the quote") and forward it as a sidecar
604 /// in the PUT bundle. `None` for a baseline quote (no commitment to
605 /// pin), or from a node that has not yet rotated a commitment. Opaque
606 /// bytes: `ant-protocol` stays agnostic of `ant-node`'s commitment type;
607 /// the client resolves it only to match the quote's `commitment_pin`.
608 ///
609 /// NOTE: this enum is encoded with **postcard** (see [`ChunkMessage::encode`]),
610 /// which is non-self-describing — `#[serde(default)]` does NOT make an
611 /// old-format `Success` (without this field) decode against new code, and
612 /// vice versa. ADR-0004 is a HARD CUTOVER: the whole fleet and clients
613 /// upgrade together, so old/new `ChunkQuoteResponse` never interoperate.
614 /// The attribute only keeps `Default`-based construction ergonomic; it is
615 /// not a wire-compat guarantee. (Contrast `PaymentQuote`/`PaymentProof`,
616 /// which ARE rmp-encoded, where tail `serde(default)` is decode-compatible.)
617 #[serde(default)]
618 commitment: Option<Vec<u8>>,
619 },
620 /// Quote generation failed.
621 Error(ProtocolError),
622}
623
624// =============================================================================
625// Merkle Candidate Quote Request/Response
626// =============================================================================
627
628/// Request a merkle candidate quote for batch payments.
629///
630/// Part of the merkle batch payment system where clients collect
631/// signed candidate quotes from 16 closest peers per pool.
632#[derive(Debug, Clone, Serialize, Deserialize)]
633pub struct MerkleCandidateQuoteRequest {
634 /// The candidate pool address (hash of midpoint || root || timestamp).
635 pub address: XorName,
636 /// Data type identifier (0 for chunks).
637 pub data_type: u32,
638 /// Size of the data in bytes.
639 pub data_size: u64,
640 /// Client-provided merkle payment timestamp (unix seconds).
641 pub merkle_payment_timestamp: u64,
642}
643
644/// Request a merkle candidate quote, declaring the settlement rules the client
645/// pays under.
646///
647/// Same fields as [`MerkleCandidateQuoteRequest`] plus `settlement_version`.
648/// See [`ChunkQuoteRequestV2`] for why this is a separate struct.
649///
650/// This is the variant that matters most for the merkle path: a batch pays
651/// on-chain **before** any storer sees a PUT, so a storer that only checks the
652/// settlement rule at PUT time is checking it after the money is gone.
653#[derive(Debug, Clone, Serialize, Deserialize)]
654pub struct MerkleCandidateQuoteRequestV2 {
655 /// The candidate pool address (hash of midpoint || root || timestamp).
656 pub address: XorName,
657 /// Data type identifier (0 for chunks).
658 pub data_type: u32,
659 /// Size of the data in bytes.
660 pub data_size: u64,
661 /// Client-provided merkle payment timestamp (unix seconds).
662 pub merkle_payment_timestamp: u64,
663 /// The settlement rules this client pays under. See
664 /// [`CURRENT_SETTLEMENT_VERSION`].
665 pub settlement_version: u32,
666}
667
668impl MerkleCandidateQuoteRequestV2 {
669 /// Create a new merkle candidate quote request declaring this build's
670 /// settlement version.
671 #[must_use]
672 pub fn new(address: XorName, data_size: u64, merkle_payment_timestamp: u64) -> Self {
673 Self {
674 address,
675 data_type: DATA_TYPE_CHUNK,
676 data_size,
677 merkle_payment_timestamp,
678 settlement_version: CURRENT_SETTLEMENT_VERSION,
679 }
680 }
681}
682
683/// Response with a merkle candidate quote.
684#[derive(Debug, Clone, Serialize, Deserialize)]
685#[non_exhaustive]
686pub enum MerkleCandidateQuoteResponse {
687 /// Candidate quote generated successfully.
688 /// Contains the serialized `MerklePaymentCandidateNode`.
689 Success {
690 /// Serialized `MerklePaymentCandidateNode`.
691 candidate_node: Vec<u8>,
692 /// ADR-0004: the serialized signed storage commitment the candidate's
693 /// price was derived from, so the client can fully resolve the binding
694 /// BEFORE paying (resolve-before-pay). `None` for a baseline candidate.
695 /// Unlike the single-node path, this commitment is NOT forwarded in the
696 /// merkle PUT bundle — sixteen per-candidate sidecars exceeded the
697 /// storer's payment-proof size budget, so current clients omit them and
698 /// storers resolve merkle pins from gossip or a `GetCommitmentByPin`
699 /// fetch (`MerklePaymentProof.commitment_sidecars` stays for legacy
700 /// bundles). Same semantics as
701 /// [`ChunkQuoteResponse::Success::commitment`]; postcard-encoded, so
702 /// this is a hard-cutover field, not an interop guarantee.
703 #[serde(default)]
704 commitment: Option<Vec<u8>>,
705 },
706 /// Quote generation failed.
707 Error(ProtocolError),
708}
709
710// =============================================================================
711// Payment Proof Type Tags
712// =============================================================================
713
714/// Version byte prefix for payment proof serialization.
715/// Allows the verifier to detect proof type before deserialization.
716pub const PROOF_TAG_SINGLE_NODE: u8 = 0x01;
717/// Version byte prefix for merkle payment proofs.
718pub const PROOF_TAG_MERKLE: u8 = 0x02;
719
720// =============================================================================
721// Protocol Errors
722// =============================================================================
723
724/// Errors that can occur during protocol operations.
725#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
726#[non_exhaustive]
727pub enum ProtocolError {
728 /// Message serialization failed.
729 SerializationFailed(String),
730 /// Message deserialization failed.
731 DeserializationFailed(String),
732 /// Wire message exceeds the maximum allowed size.
733 MessageTooLarge {
734 /// Actual size of the message in bytes.
735 size: usize,
736 /// Maximum allowed size.
737 max_size: usize,
738 },
739 /// Chunk exceeds maximum size.
740 ChunkTooLarge {
741 /// Size of the chunk in bytes.
742 size: usize,
743 /// Maximum allowed size.
744 max_size: usize,
745 },
746 /// Content address mismatch (hash(content) != address).
747 AddressMismatch {
748 /// Expected address.
749 expected: XorName,
750 /// Actual address computed from content.
751 actual: XorName,
752 },
753 /// Storage operation failed.
754 StorageFailed(String),
755 /// Payment verification failed.
756 PaymentFailed(String),
757 /// Quote generation failed.
758 QuoteFailed(String),
759 /// Internal error.
760 Internal(String),
761 /// The client settles payments under rules this node no longer accepts, so
762 /// no quote was issued.
763 ///
764 /// Refused at quote time on purpose. A client that pays under superseded
765 /// rules produces an on-chain payment every storer will reject, and that
766 /// payment cannot be refunded, so the only useful place to stop it is
767 /// before the client spends anything.
768 ///
769 /// Appended last so existing variants keep their wire discriminants. A
770 /// peer old enough not to know this variant cannot be sent it: it would
771 /// have had to send a V2 request to earn it, and only builds that carry
772 /// this variant do that.
773 ClientUpdateRequired {
774 /// Settlement version the client declared.
775 client_settlement_version: u32,
776 /// Oldest settlement version this node will quote for.
777 min_settlement_version: u32,
778 },
779 /// This node settles under older rules than the client, so it declined to
780 /// quote rather than promise to accept a payment it may not recognise.
781 ///
782 /// The mirror image of [`Self::ClientUpdateRequired`], and deliberately a
783 /// separate variant: it is not a verdict about the client, and a client
784 /// that receives it should quietly use a different storer rather than tell
785 /// its user anything. During a client-first rollout most of the fleet is
786 /// briefly in this state, so treating it as a client fault would strand
787 /// every up-to-date user.
788 StorerUpdateRequired {
789 /// Settlement version the client declared.
790 client_settlement_version: u32,
791 /// Newest settlement version this node understands.
792 node_settlement_version: u32,
793 },
794}
795
796impl std::fmt::Display for ProtocolError {
797 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
798 match self {
799 Self::SerializationFailed(msg) => write!(f, "serialization failed: {msg}"),
800 Self::DeserializationFailed(msg) => write!(f, "deserialization failed: {msg}"),
801 Self::MessageTooLarge { size, max_size } => {
802 write!(f, "message size {size} exceeds maximum {max_size}")
803 }
804 Self::ChunkTooLarge { size, max_size } => {
805 write!(f, "chunk size {size} exceeds maximum {max_size}")
806 }
807 Self::AddressMismatch { expected, actual } => {
808 write!(
809 f,
810 "address mismatch: expected {}, got {}",
811 hex::encode(expected),
812 hex::encode(actual)
813 )
814 }
815 Self::StorageFailed(msg) => write!(f, "storage failed: {msg}"),
816 Self::PaymentFailed(msg) => write!(f, "payment failed: {msg}"),
817 Self::QuoteFailed(msg) => write!(f, "quote failed: {msg}"),
818 Self::Internal(msg) => write!(f, "internal error: {msg}"),
819 Self::ClientUpdateRequired {
820 client_settlement_version,
821 min_settlement_version,
822 } => write!(
823 f,
824 "{}",
825 client_update_required_message(*client_settlement_version, *min_settlement_version)
826 ),
827 Self::StorerUpdateRequired {
828 client_settlement_version,
829 node_settlement_version,
830 } => write!(
831 f,
832 "this node settles under version {node_settlement_version} and cannot \
833 promise to accept a version {client_settlement_version} payment, so it \
834 issued no quote. Nothing was charged; use a different storer."
835 ),
836 }
837 }
838}
839
840/// The upgrade instruction shown to a user whose client cannot settle
841/// correctly.
842///
843/// A free function rather than only a `Display` arm so the storer can log the
844/// same wording it sends back, and so the client can reuse it when it
845/// translates the rejection into a CLI error. Kept deliberately plain: the
846/// reader is an end user staring at a failed upload, not an operator.
847#[must_use]
848pub fn client_update_required_message(
849 client_settlement_version: u32,
850 min_settlement_version: u32,
851) -> String {
852 format!(
853 "your client is too old to pay the current storage rate \
854 (it settles under version {client_settlement_version}, this node requires \
855 at least {min_settlement_version}), so no quote was issued and nothing was \
856 charged. Run `ant update` to upgrade, or reinstall from \
857 https://github.com/WithAutonomi/ant-client/releases/latest"
858 )
859}
860
861impl std::error::Error for ProtocolError {}
862
863#[cfg(test)]
864#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
865mod tests {
866 use super::*;
867
868 #[test]
869 fn test_put_request_encode_decode() {
870 let address = [0xAB; 32];
871 let content = Bytes::from_static(&[1, 2, 3, 4, 5]);
872 let request = ChunkPutRequest::new(address, content.clone());
873 let msg = ChunkMessage {
874 request_id: 42,
875 body: ChunkMessageBody::PutRequest(request),
876 };
877
878 let encoded = msg.encode().expect("encode should succeed");
879 let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");
880
881 assert_eq!(decoded.request_id, 42);
882 if let ChunkMessageBody::PutRequest(req) = decoded.body {
883 assert_eq!(req.address, address);
884 assert_eq!(req.content, content);
885 assert!(req.payment_proof.is_none());
886 } else {
887 panic!("expected PutRequest");
888 }
889 }
890
891 #[test]
892 fn test_put_request_with_payment() {
893 let address = [0xAB; 32];
894 let content = Bytes::from_static(&[1, 2, 3, 4, 5]);
895 let payment = vec![10, 20, 30];
896 let request = ChunkPutRequest::with_payment(address, content.clone(), payment.clone());
897
898 assert_eq!(request.address, address);
899 assert_eq!(request.content, content);
900 assert_eq!(request.payment_proof, Some(payment));
901 }
902
903 #[test]
904 fn test_get_request_encode_decode() {
905 let address = [0xCD; 32];
906 let request = ChunkGetRequest::new(address);
907 let msg = ChunkMessage {
908 request_id: 7,
909 body: ChunkMessageBody::GetRequest(request),
910 };
911
912 let encoded = msg.encode().expect("encode should succeed");
913 let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");
914
915 assert_eq!(decoded.request_id, 7);
916 if let ChunkMessageBody::GetRequest(req) = decoded.body {
917 assert_eq!(req.address, address);
918 } else {
919 panic!("expected GetRequest");
920 }
921 }
922
923 #[test]
924 fn test_put_response_success() {
925 let address = [0xEF; 32];
926 let response = ChunkPutResponse::Success { address };
927 let msg = ChunkMessage {
928 request_id: 99,
929 body: ChunkMessageBody::PutResponse(response),
930 };
931
932 let encoded = msg.encode().expect("encode should succeed");
933 let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");
934
935 assert_eq!(decoded.request_id, 99);
936 if let ChunkMessageBody::PutResponse(ChunkPutResponse::Success { address: addr }) =
937 decoded.body
938 {
939 assert_eq!(addr, address);
940 } else {
941 panic!("expected PutResponse::Success");
942 }
943 }
944
945 #[test]
946 fn test_get_response_not_found() {
947 let address = [0x12; 32];
948 let response = ChunkGetResponse::NotFound { address };
949 let msg = ChunkMessage {
950 request_id: 0,
951 body: ChunkMessageBody::GetResponse(response),
952 };
953
954 let encoded = msg.encode().expect("encode should succeed");
955 let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");
956
957 assert_eq!(decoded.request_id, 0);
958 if let ChunkMessageBody::GetResponse(ChunkGetResponse::NotFound { address: addr }) =
959 decoded.body
960 {
961 assert_eq!(addr, address);
962 } else {
963 panic!("expected GetResponse::NotFound");
964 }
965 }
966
967 #[test]
968 fn test_quote_request_encode_decode() {
969 let address = [0x34; 32];
970 let request = ChunkQuoteRequest::new(address, 1024);
971 let msg = ChunkMessage {
972 request_id: 1,
973 body: ChunkMessageBody::QuoteRequest(request),
974 };
975
976 let encoded = msg.encode().expect("encode should succeed");
977 let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");
978
979 assert_eq!(decoded.request_id, 1);
980 if let ChunkMessageBody::QuoteRequest(req) = decoded.body {
981 assert_eq!(req.address, address);
982 assert_eq!(req.data_size, 1024);
983 assert_eq!(req.data_type, DATA_TYPE_CHUNK);
984 } else {
985 panic!("expected QuoteRequest");
986 }
987 }
988
989 #[test]
990 fn test_protocol_error_display() {
991 let err = ProtocolError::ChunkTooLarge {
992 size: 5_000_000,
993 max_size: MAX_CHUNK_SIZE,
994 };
995 assert!(err.to_string().contains("5000000"));
996 assert!(err.to_string().contains(&MAX_CHUNK_SIZE.to_string()));
997
998 let err = ProtocolError::AddressMismatch {
999 expected: [0xAA; 32],
1000 actual: [0xBB; 32],
1001 };
1002 let display = err.to_string();
1003 assert!(display.contains("address mismatch"));
1004 }
1005
1006 #[test]
1007 fn test_decode_rejects_oversized_payload() {
1008 let oversized = vec![0u8; MAX_WIRE_MESSAGE_SIZE + 1];
1009 let result = ChunkMessage::decode(&oversized);
1010 assert!(result.is_err());
1011 let err = result.unwrap_err();
1012 assert!(
1013 matches!(err, ProtocolError::MessageTooLarge { .. }),
1014 "expected MessageTooLarge, got {err:?}"
1015 );
1016 }
1017
1018 #[test]
1019 fn test_invalid_decode() {
1020 let invalid_data = vec![0xFF, 0xFF, 0xFF];
1021 let result = ChunkMessage::decode(&invalid_data);
1022 assert!(result.is_err());
1023 }
1024
1025 #[test]
1026 fn test_constants() {
1027 assert_eq!(CHUNK_PROTOCOL_ID, "autonomi.ant.chunk.v1");
1028 assert_eq!(PROTOCOL_VERSION, 1);
1029 assert_eq!(MAX_CHUNK_SIZE, 4 * 1024 * 1024);
1030 assert_eq!(DATA_TYPE_CHUNK, 0);
1031 }
1032
1033 #[test]
1034 fn test_proof_tag_constants() {
1035 // Tags must be distinct non-zero bytes
1036 assert_ne!(PROOF_TAG_SINGLE_NODE, PROOF_TAG_MERKLE);
1037 assert_ne!(PROOF_TAG_SINGLE_NODE, 0x00);
1038 assert_ne!(PROOF_TAG_MERKLE, 0x00);
1039 assert_eq!(PROOF_TAG_SINGLE_NODE, 0x01);
1040 assert_eq!(PROOF_TAG_MERKLE, 0x02);
1041 }
1042
1043 #[test]
1044 fn test_merkle_candidate_quote_request_encode_decode() {
1045 let address = [0x56; 32];
1046 let request = MerkleCandidateQuoteRequest {
1047 address,
1048 data_type: DATA_TYPE_CHUNK,
1049 data_size: 2048,
1050 merkle_payment_timestamp: 1_700_000_000,
1051 };
1052 let msg = ChunkMessage {
1053 request_id: 500,
1054 body: ChunkMessageBody::MerkleCandidateQuoteRequest(request),
1055 };
1056
1057 let encoded = msg.encode().expect("encode should succeed");
1058 let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");
1059
1060 assert_eq!(decoded.request_id, 500);
1061 if let ChunkMessageBody::MerkleCandidateQuoteRequest(req) = decoded.body {
1062 assert_eq!(req.address, address);
1063 assert_eq!(req.data_type, DATA_TYPE_CHUNK);
1064 assert_eq!(req.data_size, 2048);
1065 assert_eq!(req.merkle_payment_timestamp, 1_700_000_000);
1066 } else {
1067 panic!("expected MerkleCandidateQuoteRequest");
1068 }
1069 }
1070
1071 #[test]
1072 fn test_merkle_candidate_quote_response_success_encode_decode() {
1073 let candidate_node_bytes = vec![0xAA, 0xBB, 0xCC, 0xDD];
1074 let response = MerkleCandidateQuoteResponse::Success {
1075 candidate_node: candidate_node_bytes.clone(),
1076 commitment: Some(vec![0x11, 0x22]),
1077 };
1078 let msg = ChunkMessage {
1079 request_id: 501,
1080 body: ChunkMessageBody::MerkleCandidateQuoteResponse(response),
1081 };
1082
1083 let encoded = msg.encode().expect("encode should succeed");
1084 let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");
1085
1086 assert_eq!(decoded.request_id, 501);
1087 if let ChunkMessageBody::MerkleCandidateQuoteResponse(
1088 MerkleCandidateQuoteResponse::Success {
1089 candidate_node,
1090 commitment,
1091 },
1092 ) = decoded.body
1093 {
1094 assert_eq!(candidate_node, candidate_node_bytes);
1095 assert_eq!(commitment, Some(vec![0x11, 0x22]));
1096 } else {
1097 panic!("expected MerkleCandidateQuoteResponse::Success");
1098 }
1099 }
1100
1101 #[test]
1102 fn test_merkle_candidate_quote_response_error_encode_decode() {
1103 let error = ProtocolError::QuoteFailed("no libp2p keypair".to_string());
1104 let response = MerkleCandidateQuoteResponse::Error(error.clone());
1105 let msg = ChunkMessage {
1106 request_id: 502,
1107 body: ChunkMessageBody::MerkleCandidateQuoteResponse(response),
1108 };
1109
1110 let encoded = msg.encode().expect("encode should succeed");
1111 let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");
1112
1113 assert_eq!(decoded.request_id, 502);
1114 if let ChunkMessageBody::MerkleCandidateQuoteResponse(
1115 MerkleCandidateQuoteResponse::Error(err),
1116 ) = decoded.body
1117 {
1118 assert_eq!(err, error);
1119 } else {
1120 panic!("expected MerkleCandidateQuoteResponse::Error");
1121 }
1122 }
1123
1124 // =========================================================================
1125 // Settlement version
1126 // =========================================================================
1127
1128 /// Discriminant of a message body, read straight off the wire.
1129 ///
1130 /// `request_id: 0` encodes as a single varint byte, so the body's variant
1131 /// index is byte 1. Reading it directly is the point: it is what a peer
1132 /// built against an older `ant-protocol` sees.
1133 fn wire_discriminant(body: ChunkMessageBody) -> u8 {
1134 let encoded = ChunkMessage {
1135 request_id: 0,
1136 body,
1137 }
1138 .encode()
1139 .expect("encode should succeed");
1140 *encoded.get(1).expect("body discriminant should be present")
1141 }
1142
1143 /// The load-bearing test for this whole design.
1144 ///
1145 /// The settlement version ships as appended variants precisely so existing
1146 /// peers keep decoding. That only holds while every prior variant keeps
1147 /// its wire index, which postcard assigns by declaration order. Insert a
1148 /// variant anywhere but the end and every older peer silently misreads
1149 /// every message from this one. Pinning the indices turns that from a
1150 /// production incident into a failing test.
1151 #[test]
1152 fn appending_v2_variants_leaves_existing_discriminants_untouched() {
1153 let address = [0x11; 32];
1154
1155 assert_eq!(
1156 wire_discriminant(ChunkMessageBody::PutRequest(ChunkPutRequest::new(
1157 address,
1158 Bytes::from_static(&[1]),
1159 ))),
1160 0,
1161 );
1162 assert_eq!(
1163 wire_discriminant(ChunkMessageBody::GetRequest(ChunkGetRequest { address })),
1164 2,
1165 );
1166 assert_eq!(
1167 wire_discriminant(ChunkMessageBody::QuoteRequest(ChunkQuoteRequest::new(
1168 address, 1024,
1169 ))),
1170 4,
1171 );
1172 assert_eq!(
1173 wire_discriminant(ChunkMessageBody::MerkleCandidateQuoteRequest(
1174 MerkleCandidateQuoteRequest {
1175 address,
1176 data_type: DATA_TYPE_CHUNK,
1177 data_size: 1024,
1178 merkle_payment_timestamp: 1_785_855_600,
1179 }
1180 )),
1181 6,
1182 );
1183
1184 // Responses carry the same obligation as requests: a peer decoding a
1185 // reply reads the same discriminant space, so pinning only the request
1186 // half would let a response variant be reordered without any test
1187 // noticing.
1188 assert_eq!(
1189 wire_discriminant(ChunkMessageBody::PutResponse(ChunkPutResponse::Success {
1190 address
1191 })),
1192 1,
1193 );
1194 assert_eq!(
1195 wire_discriminant(ChunkMessageBody::GetResponse(ChunkGetResponse::NotFound {
1196 address
1197 })),
1198 3,
1199 );
1200 assert_eq!(
1201 wire_discriminant(ChunkMessageBody::QuoteResponse(ChunkQuoteResponse::Error(
1202 ProtocolError::Internal(String::new())
1203 ))),
1204 5,
1205 );
1206 assert_eq!(
1207 wire_discriminant(ChunkMessageBody::MerkleCandidateQuoteResponse(
1208 MerkleCandidateQuoteResponse::Error(ProtocolError::Internal(String::new()))
1209 )),
1210 7,
1211 );
1212
1213 // The new variants take the next free indices, above everything an
1214 // older peer knows, so it rejects them as unknown rather than
1215 // misreading a variant it does know.
1216 assert_eq!(
1217 wire_discriminant(ChunkMessageBody::QuoteRequestV2(ChunkQuoteRequestV2::new(
1218 address, 1024,
1219 ))),
1220 8,
1221 );
1222 assert_eq!(
1223 wire_discriminant(ChunkMessageBody::MerkleCandidateQuoteRequestV2(
1224 MerkleCandidateQuoteRequestV2::new(address, 1024, 1_785_855_600)
1225 )),
1226 9,
1227 );
1228 }
1229
1230 /// `ProtocolError` rides inside quote responses, so its variants carry the
1231 /// same append-only obligation as the message bodies.
1232 #[test]
1233 fn client_update_required_is_appended_to_protocol_error() {
1234 let encode = |e: &ProtocolError| postcard::to_stdvec(e).expect("encode should succeed");
1235
1236 assert_eq!(
1237 encode(&ProtocolError::SerializationFailed(String::new()))
1238 .first()
1239 .copied(),
1240 Some(0),
1241 );
1242 assert_eq!(
1243 encode(&ProtocolError::DeserializationFailed(String::new()))
1244 .first()
1245 .copied(),
1246 Some(1),
1247 );
1248 assert_eq!(
1249 encode(&ProtocolError::MessageTooLarge {
1250 size: 0,
1251 max_size: 0
1252 })
1253 .first()
1254 .copied(),
1255 Some(2),
1256 );
1257 assert_eq!(
1258 encode(&ProtocolError::ChunkTooLarge {
1259 size: 0,
1260 max_size: 0
1261 })
1262 .first()
1263 .copied(),
1264 Some(3),
1265 );
1266 assert_eq!(
1267 encode(&ProtocolError::AddressMismatch {
1268 expected: [0u8; 32],
1269 actual: [0u8; 32]
1270 })
1271 .first()
1272 .copied(),
1273 Some(4),
1274 );
1275 assert_eq!(
1276 encode(&ProtocolError::StorageFailed(String::new()))
1277 .first()
1278 .copied(),
1279 Some(5),
1280 );
1281 assert_eq!(
1282 encode(&ProtocolError::PaymentFailed(String::new()))
1283 .first()
1284 .copied(),
1285 Some(6),
1286 );
1287 assert_eq!(
1288 encode(&ProtocolError::QuoteFailed(String::new()))
1289 .first()
1290 .copied(),
1291 Some(7),
1292 );
1293 assert_eq!(
1294 encode(&ProtocolError::Internal(String::new()))
1295 .first()
1296 .copied(),
1297 Some(8),
1298 );
1299 assert_eq!(
1300 encode(&ProtocolError::ClientUpdateRequired {
1301 client_settlement_version: 0,
1302 min_settlement_version: 1,
1303 })
1304 .first()
1305 .copied(),
1306 Some(9),
1307 );
1308 assert_eq!(
1309 encode(&ProtocolError::StorerUpdateRequired {
1310 client_settlement_version: 2,
1311 node_settlement_version: 1,
1312 })
1313 .first()
1314 .copied(),
1315 Some(10),
1316 );
1317 }
1318
1319 #[test]
1320 fn v2_quote_request_round_trips_with_the_settlement_version() {
1321 let address = [0x22; 32];
1322 let msg = ChunkMessage {
1323 request_id: 600,
1324 body: ChunkMessageBody::QuoteRequestV2(ChunkQuoteRequestV2::new(address, 4096)),
1325 };
1326
1327 let encoded = msg.encode().expect("encode should succeed");
1328 let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");
1329
1330 assert_eq!(decoded.request_id, 600);
1331 if let ChunkMessageBody::QuoteRequestV2(req) = decoded.body {
1332 assert_eq!(req.address, address);
1333 assert_eq!(req.data_size, 4096);
1334 assert_eq!(req.data_type, DATA_TYPE_CHUNK);
1335 assert_eq!(req.settlement_version, CURRENT_SETTLEMENT_VERSION);
1336 } else {
1337 panic!("expected QuoteRequestV2");
1338 }
1339 }
1340
1341 #[test]
1342 fn v2_merkle_candidate_request_round_trips_with_the_settlement_version() {
1343 let address = [0x33; 32];
1344 let msg = ChunkMessage {
1345 request_id: 601,
1346 body: ChunkMessageBody::MerkleCandidateQuoteRequestV2(
1347 MerkleCandidateQuoteRequestV2::new(address, 4096, 1_785_855_600),
1348 ),
1349 };
1350
1351 let encoded = msg.encode().expect("encode should succeed");
1352 let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");
1353
1354 assert_eq!(decoded.request_id, 601);
1355 if let ChunkMessageBody::MerkleCandidateQuoteRequestV2(req) = decoded.body {
1356 assert_eq!(req.address, address);
1357 assert_eq!(req.data_size, 4096);
1358 assert_eq!(req.merkle_payment_timestamp, 1_785_855_600);
1359 assert_eq!(req.settlement_version, CURRENT_SETTLEMENT_VERSION);
1360 } else {
1361 panic!("expected MerkleCandidateQuoteRequestV2");
1362 }
1363 }
1364
1365 #[test]
1366 fn settlement_compatibility_is_bounded_at_both_ends() {
1367 assert_eq!(
1368 settlement_compatibility(CURRENT_SETTLEMENT_VERSION),
1369 SettlementCompatibility::Compatible,
1370 );
1371 // The lower bound is inclusive: the oldest version still served is
1372 // served, not refused.
1373 assert_eq!(
1374 settlement_compatibility(MIN_SUPPORTED_SETTLEMENT_VERSION),
1375 SettlementCompatibility::Compatible,
1376 );
1377 assert_eq!(
1378 settlement_compatibility(MIN_SUPPORTED_SETTLEMENT_VERSION.saturating_sub(1)),
1379 SettlementCompatibility::ClientTooOld,
1380 );
1381 }
1382
1383 /// The correction this replaced an earlier revision for. Serving a client
1384 /// whose settlement rules this build does not know means promising to
1385 /// accept a payment it may reject, and by the time it rejects, the client
1386 /// has settled on-chain and cannot be refunded. Only monotonic increases
1387 /// are safe to wave through, and nothing here can tell whether the next
1388 /// change is one.
1389 #[test]
1390 fn a_newer_settlement_version_is_refused_rather_than_assumed_compatible() {
1391 assert_eq!(
1392 settlement_compatibility(CURRENT_SETTLEMENT_VERSION.saturating_add(1)),
1393 SettlementCompatibility::NodeTooOld,
1394 );
1395 }
1396
1397 /// The two refusals must stay distinct on the wire. One tells a user to
1398 /// upgrade; the other tells a client to pick a different peer and say
1399 /// nothing. Rendering them alike would strand every up-to-date user during
1400 /// a client-first rollout, when most of the fleet is briefly the old side.
1401 #[test]
1402 fn the_two_refusals_do_not_blame_the_same_party() {
1403 let client_at_fault = ProtocolError::ClientUpdateRequired {
1404 client_settlement_version: 0,
1405 min_settlement_version: 1,
1406 }
1407 .to_string();
1408 let node_at_fault = ProtocolError::StorerUpdateRequired {
1409 client_settlement_version: 2,
1410 node_settlement_version: 1,
1411 }
1412 .to_string();
1413
1414 assert!(
1415 client_at_fault.contains("your client is too old"),
1416 "{client_at_fault}"
1417 );
1418 assert!(
1419 !node_at_fault.contains("your client is too old"),
1420 "{node_at_fault}"
1421 );
1422 assert!(
1423 node_at_fault.contains("use a different storer"),
1424 "{node_at_fault}"
1425 );
1426 // Neither costs the user anything, and both must say so.
1427 assert!(
1428 client_at_fault.contains("nothing was charged"),
1429 "{client_at_fault}"
1430 );
1431 assert!(
1432 node_at_fault.contains("Nothing was charged"),
1433 "{node_at_fault}"
1434 );
1435 }
1436
1437 /// The rejection exists to get a user unstuck, so the wording is part of
1438 /// the contract, not decoration.
1439 #[test]
1440 fn update_required_message_tells_the_user_how_to_fix_it() {
1441 let rendered = ProtocolError::ClientUpdateRequired {
1442 client_settlement_version: 0,
1443 min_settlement_version: 1,
1444 }
1445 .to_string();
1446
1447 assert!(rendered.contains("ant update"), "{rendered}");
1448 assert!(rendered.contains("too old"), "{rendered}");
1449 // The whole point is that refusing to quote costs the user nothing.
1450 assert!(rendered.contains("nothing was charged"), "{rendered}");
1451 }
1452
1453 #[test]
1454 fn test_get_or_closer_request_encode_decode() {
1455 let address = [0x61; 32];
1456 let msg = ChunkMessage {
1457 request_id: 600,
1458 body: ChunkMessageBody::GetOrCloserRequest(ChunkGetOrCloserRequest::new(address)),
1459 };
1460
1461 let encoded = msg.encode().expect("encode should succeed");
1462 let decoded = ChunkMessage::decode(&encoded).expect("decode should succeed");
1463
1464 assert_eq!(decoded.request_id, 600);
1465 let ChunkMessageBody::GetOrCloserRequest(request) = decoded.body else {
1466 panic!("expected GetOrCloserRequest");
1467 };
1468 assert_eq!(request.address, address);
1469 }
1470
1471 #[test]
1472 fn test_get_or_closer_responses_encode_decode() {
1473 let address = [0x62; 32];
1474 let found = ChunkMessage {
1475 request_id: 601,
1476 body: ChunkMessageBody::GetOrCloserResponse(ChunkGetOrCloserResponse::Found {
1477 address,
1478 content: Bytes::from_static(b"chunk"),
1479 }),
1480 };
1481 let decoded = ChunkMessage::decode(&found.encode().expect("encode")).expect("decode");
1482 let ChunkMessageBody::GetOrCloserResponse(ChunkGetOrCloserResponse::Found {
1483 address: found_address,
1484 content,
1485 }) = decoded.body
1486 else {
1487 panic!("expected Found");
1488 };
1489 assert_eq!(found_address, address);
1490 assert_eq!(content.as_ref(), b"chunk");
1491
1492 let closer = ChunkMessage {
1493 request_id: 602,
1494 body: ChunkMessageBody::GetOrCloserResponse(ChunkGetOrCloserResponse::Closer {
1495 address,
1496 peers: Bytes::from_static(&[1, 2, 3]),
1497 }),
1498 };
1499 let decoded = ChunkMessage::decode(&closer.encode().expect("encode")).expect("decode");
1500 let ChunkMessageBody::GetOrCloserResponse(ChunkGetOrCloserResponse::Closer {
1501 address: closer_address,
1502 peers,
1503 }) = decoded.body
1504 else {
1505 panic!("expected Closer");
1506 };
1507 assert_eq!(closer_address, address);
1508 assert_eq!(peers.as_ref(), &[1, 2, 3]);
1509 }
1510
1511 /// Variants are only ever appended, so a peer built before a variant
1512 /// existed still reads every older one at its old wire value.
1513 #[test]
1514 fn test_message_discriminants_keep_their_wire_values() {
1515 let address = [0x63; 32];
1516 let discriminant = |body: ChunkMessageBody| {
1517 let encoded = ChunkMessage {
1518 request_id: 0,
1519 body,
1520 }
1521 .encode()
1522 .expect("encode should succeed");
1523 // A zero request id is one varint byte; the variant index follows.
1524 encoded[1]
1525 };
1526 assert_eq!(
1527 discriminant(ChunkMessageBody::GetRequest(ChunkGetRequest::new(address))),
1528 2
1529 );
1530 assert_eq!(
1531 discriminant(ChunkMessageBody::PointerGetRequest(PointerGetRequest::new(
1532 address
1533 ))),
1534 12
1535 );
1536 assert_eq!(
1537 discriminant(ChunkMessageBody::GetOrCloserRequest(
1538 ChunkGetOrCloserRequest::new(address)
1539 )),
1540 14
1541 );
1542 assert_eq!(
1543 discriminant(ChunkMessageBody::GetOrCloserResponse(
1544 ChunkGetOrCloserResponse::Error(ProtocolError::Internal("x".to_string()))
1545 )),
1546 15
1547 );
1548 }
1549
1550 #[test]
1551 fn test_advertises_get_or_closer() {
1552 assert!(advertises_get_or_closer(
1553 "node/0.22.0 migration/files get-or-closer/1"
1554 ));
1555 assert!(!advertises_get_or_closer("node/0.21.0 migration/files"));
1556 assert!(!advertises_get_or_closer("node/0.22.0 get-or-closer/10"));
1557 assert!(!advertises_get_or_closer(""));
1558 }
1559}