Skip to main content

hopr_protocol_start/
lib.rs

1//! This crate defines the Start sub-protocol used for HOPR Session initiation and management.
2//!
3//! The Start protocol is used to establish Session as described in HOPR
4//! [`RFC-0012`](https://github.com/hoprnet/rfc/tree/main/rfcs/RFC-0012-session-start-protocol).
5//! and is implemented via the [`StartProtocol`] enum.
6//!
7//! The protocol is defined via generic arguments `I` (for Session ID), `T` (for Session Target),
8//! `C` (for Session capabilities) and `G` (for Session Stealth Address commitment representation).
9//!
10//! Per `RFC-0012`, the types `I` and `T` are serialized/deserialized to the CBOR binary format
11//! (see [`RFC7049`](https://datatracker.ietf.org/doc/html/rfc7049)) and therefore must implement
12//! `serde::Serialize + serde::Deserialize`.
13//! The capability type `C` must be expressible as a single unsigned byte.
14//!
15//! The `G` type is used to represent the Session Stealth Address commitment representation.
16//! It is typically a [`PixGroupRepr`](hopr_protocol_pix::PixGroupRepr)
17//!
18//! See [`StartProtocol`] docs for the protocol diagram.
19
20/// Contains errors raised by the Start protocol.
21pub mod errors;
22
23use hopr_crypto_packet::prelude::HoprPacket;
24use hopr_protocol_app::prelude::{ApplicationData, ReservedTag, Tag};
25use hopr_protocol_pix::{MAX_POLYS_PER_SSA, SsaCommitment};
26
27use crate::errors::StartProtocolError;
28
29/// Challenge that identifies a Start initiation protocol message.
30pub type StartChallenge = u64;
31
32/// Lists all Start protocol error reasons.
33#[repr(u8)]
34#[derive(Debug, Copy, Clone, PartialEq, Eq, strum::Display, strum::FromRepr)]
35pub enum StartErrorReason {
36    /// Unknown error.
37    Unknown = 0,
38    /// No more slots are available at the recipient.
39    NoSlotsAvailable = 1,
40    /// Recipient is busy.
41    Busy = 2,
42    /// The recipient requires incentivization or the incentivization parameters are not acceptable.
43    UnacceptablePixParams = 3,
44    /// The recipient does not serve this Session's target, or does not serve it on the offered
45    /// terms.
46    ///
47    /// Distinct from [`UnacceptablePixParams`](Self::UnacceptablePixParams) because the two call for
48    /// different responses: those parameters could be re-offered differently, whereas this target
49    /// will not be served by this recipient however the request is phrased. Distinct from
50    /// [`Busy`](Self::Busy) because that one is transient and worth retrying.
51    TargetNotAdmitted = 4,
52}
53
54/// Identifies which entity a [`StartErrorType`] refers to.
55///
56/// During session establishment (before `SessionEstablished` is sent), errors
57/// refer back to the initiation [`StartChallenge`]. After the session is
58/// established, errors refer to the established session by its `SessionId`.
59#[derive(Debug, Clone, PartialEq, Eq, strum::EnumDiscriminants)]
60#[strum_discriminants(vis(pub))]
61#[strum_discriminants(derive(strum::FromRepr, strum::EnumCount), repr(u8))]
62pub enum ErrorIdentifier<I> {
63    /// The error relates to a pending session initiation identified by this challenge.
64    Challenge(StartChallenge),
65    /// The error relates to an established session identified by this session ID.
66    SessionId(I),
67}
68
69/// Error message in the Start protocol.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct StartErrorType<I> {
72    /// Identifies the session initiation or established session this error refers to.
73    pub identifier: ErrorIdentifier<I>,
74    /// The [reason](StartErrorReason) of this error.
75    pub reason: StartErrorReason,
76}
77
78/// The session initiation message of the Start protocol.
79///
80/// ## Generic parameters
81/// - `T` is the session target
82/// - `C` are session capabilities
83///
84/// The `additional_data` are set dependent on the `capabilities`
85/// or set to `0` to be ignored.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct StartInitiation<T, C> {
88    /// Random challenge for this initiation.
89    pub challenge: StartChallenge,
90    /// Target of the session, i.e., what should the other party do with the traffic.
91    pub target: T,
92    /// Requested capabilities of the session.
93    ///
94    /// This might also contain information required for the PIX protocol.
95    pub capabilities: C,
96    /// Additional options (might be `capabilities` dependent), ignored if `0`.
97    ///
98    /// The most significant 64 bits carry the negotiated options: when PIX is offered, the upper
99    /// 32 bits of them are the [`PixParams`](hopr_protocol_pix::PixParams) word — see
100    /// [`PixParams::into_additional_data`](hopr_protocol_pix::PixParams::into_additional_data) —
101    /// and the lower 32 bits of them are the SURB balancer target.
102    ///
103    /// The least significant 64 bits are reserved: the lowest 32 carry the sender's session idle timeout in
104    /// whole seconds (`0` if not announced), and the 32 above them are unused. Senders set unused bits to `0`
105    /// and receivers ignore them, so that they can be allocated later without breaking older decoders.
106    pub additional_data: u128,
107}
108
109/// Message of the Start protocol that confirms the establishment of a session.
110///
111/// ## Generic parameters
112/// `I` is for session identifier.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct StartEstablished<I> {
115    /// Challenge that was used in the [initiation message](StartInitiation) to establish correspondence.
116    pub orig_challenge: StartChallenge,
117    /// Session ID that was selected by the recipient.
118    pub session_id: I,
119}
120
121#[cfg_attr(doc, aquamarine::aquamarine)]
122/// Lists all messages of the Start protocol for a session establishment.
123///
124/// ## Generic parameters
125/// - `I` is the session identifier.
126/// - `T` is the session target.
127/// - `C` are session capabilities.
128/// - `G` is the type of the commitment to the Session Stealth Address (SSA).
129/// - `K` is the wire form of the proof of knowledge going with a client SSA commitment.
130/// - `D` is the type of the deposit data carried in the Server's SSA commitment.
131///
132/// # Diagram of the protocol
133/// ```mermaid
134/// sequenceDiagram
135///      Entry->>Exit: SessionInitiation (Challenge)
136///      alt If Exit can accept a new session
137///      Note right of Exit: SessionID [Pseudonym, Tag]
138///      Exit->>Entry: SessionEstablished (Challenge, SessionID)
139///      Note left of Entry: SessionID [Pseudonym, Tag]
140///      Exit->>Entry: SsaRequest (SessionID, SsaIndex, ServerCommitments)
141///      Entry->>Exit: SsaCommit (SessionID, SsaIndex, CoeffIndex, PolyCoeffs)
142///      Entry->>Exit: KeepAlive (SessionID)
143///      Exit->>Entry: KeepAlive (SessionID)
144///      Note over Entry,Exit: Data
145///      else If Exit cannot accept a new session
146///      Exit->>Entry: SessionError (Challenge, Reason)
147///      end
148///      opt If initiation attempt times out
149///      Note left of Entry: Failure
150///      end
151/// ```
152#[derive(Debug, Clone, PartialEq, Eq, strum::EnumDiscriminants)]
153#[strum_discriminants(vis(pub))]
154#[strum_discriminants(derive(strum::FromRepr, strum::EnumCount), repr(u8))]
155pub enum StartProtocol<I, T, C, G, K, D> {
156    /// Request to initiate a new session.
157    StartSession(StartInitiation<T, C>),
158    /// Confirmation that a new session has been established by the counterparty.
159    SessionEstablished(StartEstablished<I>),
160    /// Client's message to fill Client commitments to establish a Session Stealth Address (SSA).
161    SsaCommit(SsaClientCommitmentMessage<I, G, K>),
162    /// Server-side commitment to Session Stealth Address (SSA).
163    SsaRequest(SsaServerCommitmentMessage<I, G, D>),
164    /// Counterparty could not establish a new session due to an error.
165    SessionError(StartErrorType<I>),
166    /// A ping message to keep the session alive.
167    KeepAlive(KeepAliveMessage<I>),
168}
169
170/// Filling up the Client's commitment to the Session Stealth Address (SSA).
171///
172/// The generic argument `G` typically represents a [`PixGroupRepr`](hopr_protocol_pix::PixGroupRepr).
173///
174/// The overall Client's commitment to a single new SSA usually requires multiple messages, all
175/// sharing the same [`SsaIndex`](hopr_protocol_pix::SsaIndex).
176///
177/// Each of these messages contains commitments to polynomial coefficients that all belong
178/// to the same coefficient in each polynomial.
179///
180/// In practice every message carries `coefficient_index == 0`: PIX commits to each polynomial's
181/// constant term and nothing else, so the constant-term pass *is* the whole commitment. The field
182/// (and phase 2 of [`new_multiple`](Self::new_multiple), which now has nothing to emit) is retained
183/// because the wire format still admits higher coefficient indices; a peer that sends them merely
184/// wastes bandwidth, since the receiver ignores them.
185///
186/// See [`hopr_protocol_pix::SsaPartCommitment`] for why the non-constant coefficient commitments
187/// were dropped and what that costs.
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct SsaClientCommitmentMessage<I, G, K> {
190    /// Session ID.
191    pub session_id: I,
192    /// Index of the Session Stealth Address (SSA) that is being committed.
193    pub ssa_index: hopr_protocol_pix::SsaIndex,
194    /// Index of the polynomial coefficient that is being committed.
195    ///
196    /// Zero value indicates the polynomial constant term commitment, which when summed over
197    /// all polynomials for a given [`SsaIndex`](hopr_protocol_pix::SsaIndex)
198    /// results in the Client's SSA commitment.
199    ///
200    /// This is always zero in practice — see the type-level documentation.
201    pub coefficient_index: u16,
202    /// Proof that the Client knows the discrete logarithm of its SSA commitment.
203    ///
204    /// Present exactly when `coefficient_index == 0`: the commitment it opens is the *sum* of all
205    /// constant terms, so it belongs with the messages that deliver them, and there is no
206    /// separate presence flag on the wire — the coefficient index decides it. Every constant-term
207    /// message carries it rather than only one, so no single lost packet can strand a cycle that
208    /// would otherwise be recoverable, and the receiver keeps the first it sees.
209    ///
210    /// Without it the receiver cannot distinguish a genuine commitment from one crafted so the
211    /// *combined* deposit key is known to the sender alone. See
212    /// [`hopr_protocol_pix::SsaCommitmentProof`].
213    pub commitment_proof: Option<K>,
214    /// Contains the serialized coefficient commitments of multiple polynomials,
215    /// all belonging to the same `coefficient_index` in each polynomial.
216    ///
217    /// This might not be the complete set yet and might require multiple messages to deliver
218    /// the complete commitment to the given coefficient of all polynomials for the given SSA.
219    pub coefficient_commitments: std::collections::HashMap<hopr_protocol_pix::PolynomialIndex, G>,
220}
221
222impl<I: serde::Serialize + Clone, G: Clone, K: Clone> SsaClientCommitmentMessage<I, G, K> {
223    /// Uses given the `session_id` and an [`SsaCommitment`] that will be split across multiple messages.
224    ///
225    /// The returned messages are ordered by coefficient index, making sure the constant terms
226    /// of the polynomials are delivered first.
227    pub fn new_multiple<S: hopr_protocol_pix::PixSpec>(
228        session_id: I,
229        commitment: SsaCommitment<S, S::Pseudonym>,
230    ) -> Result<Vec<Self>, StartProtocolError>
231    where
232        G: From<hopr_protocol_pix::PixGroupRepr<S>>,
233        K: From<hopr_protocol_pix::SsaCommitmentProof<S>>,
234    {
235        let ssa_index = commitment.ssa_id.ssa_index();
236        let commitment_proof = K::from(commitment.commitment_proof);
237
238        // A single message can only carry a limited number of coefficient commitments so that the
239        // resulting encoded message still fits within a HOPR packet payload. The commitments of a
240        // single coefficient (across all polynomials) might therefore need to be split across
241        // multiple messages. The encode layout this is derived from is documented on the helper.
242        let SsaCommitChunking {
243            max_commitments_per_message,
244            max_constant_terms_per_message,
245        } = StartProtocol::<I, (), (), G, K, ()>::ssa_commit_chunking(&session_id)?;
246
247        // Group the transposed verifiers by coefficient index, each group sorted by polynomial
248        // index. A `BTreeMap` keeps the coefficient order deterministic; the inner sort is what
249        // lets a block of polynomials be addressed as the same slice range in every coefficient.
250        let mut by_coefficient: std::collections::BTreeMap<u16, Vec<(hopr_protocol_pix::PolynomialIndex, G)>> =
251            std::collections::BTreeMap::new();
252
253        for (coefficient_index, coefficients) in commitment.verifiers {
254            let entry = by_coefficient.entry(coefficient_index).or_default();
255            for (poly_index, coefficient_commitment) in coefficients {
256                entry.push((poly_index, G::from(coefficient_commitment)));
257            }
258        }
259        for coefficients in by_coefficient.values_mut() {
260            coefficients.sort_unstable_by_key(|(poly_index, _)| *poly_index);
261        }
262
263        let mut messages = Vec::new();
264        let mut push_chunk = |coefficient_index: u16, chunk: &[(hopr_protocol_pix::PolynomialIndex, G)]| {
265            messages.push(Self {
266                session_id: session_id.clone(),
267                ssa_index,
268                coefficient_index,
269                // Presence is decided by the coefficient index, matching what the decoder expects.
270                commitment_proof: (coefficient_index == 0).then(|| commitment_proof.clone()),
271                coefficient_commitments: chunk.iter().cloned().collect(),
272            });
273        };
274
275        // Phase 1 — every polynomial's constant term, so the Exit can derive the SSA deposit
276        // address as early as possible. This is the one coefficient that must be delivered across
277        // *all* polynomials before anything else, because the address is their sum.
278        let constant_terms = by_coefficient.remove(&0).unwrap_or_default();
279        for chunk in constant_terms.chunks(max_constant_terms_per_message) {
280            push_chunk(0, chunk);
281        }
282
283        // Phase 2 — any remaining coefficients, a block of polynomials at a time.
284        //
285        // Dead in practice: PIX commits to constant terms only, so `by_coefficient` is empty after
286        // the `remove(&0)` above and this loop body never runs. It is kept because the wire format
287        // still admits higher coefficient indices, and because the block-major layout is the
288        // non-obvious part — emitting one polynomial's row at a time would waste most of each
289        // packet, while walking coefficient-major would complete no polynomial until the very last
290        // message.
291        let num_polys = constant_terms
292            .len()
293            .max(by_coefficient.values().map(|c| c.len()).max().unwrap_or(0));
294        for block_start in (0..num_polys).step_by(max_commitments_per_message) {
295            for (&coefficient_index, coefficients) in &by_coefficient {
296                if block_start >= coefficients.len() {
297                    continue;
298                }
299                let block_end = (block_start + max_commitments_per_message).min(coefficients.len());
300                push_chunk(coefficient_index, &coefficients[block_start..block_end]);
301            }
302        }
303
304        Ok(messages)
305    }
306}
307
308/// Inclusive run of polynomial indices, as carried by
309/// [`SsaServerCommitmentMessage::missing`].
310///
311/// A run rather than a list of indices because commitment loss is chunk-shaped: the sender slices a
312/// cycle's commitment into packet-sized slices of *consecutive* polynomial indices, so one lost
313/// packet is one run of a couple of dozen, and a burst that never arrived at all is a single run.
314pub type PolynomialRun = (hopr_protocol_pix::PolynomialIndex, hopr_protocol_pix::PolynomialIndex);
315
316/// Sent by the Server either to deliver the commitment to new Session Stealth Addresses (SSAs), or
317/// to ask for the parts of an earlier commitment it never received.
318///
319/// The first kind is typically sent right after the [`StartEstablished`] message if PIX capabilities
320/// are indicated in the [`StartInitiation`] message and the Server accepts it, and then again every
321/// time the Server needs the next batch of SSAs (with indices strictly greater than in the last
322/// batch) to be committed to.
323///
324/// The second kind exists because the Client's answer to the first is not one message but hundreds,
325/// and the Server can use none of it until every one of them has landed. It names the gaps in
326/// [`missing`](Self::missing) and asks for nothing new; see there.
327///
328/// Exactly one of [`commitments`](Self::commitments) and [`missing`](Self::missing) is populated,
329/// which is what makes the two kinds impossible to confuse — [`Self::new`] and [`Self::recommit`]
330/// each build one of them, and both encoding and decoding refuse a message that is neither.
331#[derive(Debug, Clone, PartialEq, Eq)]
332pub struct SsaServerCommitmentMessage<I, G, D> {
333    /// Session ID.
334    pub session_id: I,
335    /// Parameters of the PIX protocol the server requires, packed by
336    /// [`PixParams::to_u32`](hopr_protocol_pix::PixParams::to_u32).
337    pub params: u32,
338    /// Per-SSA deposit/payment data, carried in CBOR as a single map keyed by the same
339    /// [`SsaIndex`](hopr_protocol_pix::SsaIndex) as [`commitments`](Self::commitments).
340    ///
341    /// Empty on a retransmission request: it asks for no new SSA, and the deposit data of the cycles
342    /// it names was delivered when they were first requested.
343    pub deposit_data: std::collections::HashMap<hopr_protocol_pix::SsaIndex, D>,
344    /// Server's serialized commitments to the SSAs, ordered by the SSA index.
345    ///
346    /// Empty on a retransmission request — see the type-level documentation.
347    pub commitments: std::collections::BTreeMap<hopr_protocol_pix::SsaIndex, G>,
348    /// Polynomial-index runs whose commitments the Server never received, per SSA.
349    ///
350    /// Empty on a request for new SSAs. Non-empty makes this a *retransmission* request: the Server
351    /// is asking the Client to re-send the commitments it names for cycles it has already committed
352    /// to, and nothing else. Nothing new is requested, no deposit follows, and the Client must not
353    /// announce one — the deposit address of a cycle is fixed when it is first committed.
354    ///
355    /// The runs of one SSA are ascending and disjoint, which the decoder enforces: it makes the scope
356    /// canonical, bounds the indices one request can name at the cycle's polynomial count, and lets
357    /// the answer be assembled without deduplicating.
358    pub missing: std::collections::BTreeMap<hopr_protocol_pix::SsaIndex, Vec<PolynomialRun>>,
359}
360
361impl<I, G, D> SsaServerCommitmentMessage<I, G, D> {
362    /// Convenience constructor for creating a new `SsaServerCommitmentMessage`.
363    pub fn new(
364        session_id: I,
365        params: hopr_protocol_pix::PixParams,
366        commitments: impl IntoIterator<Item = (hopr_protocol_pix::SsaIndex, G)>,
367        deposit_data: impl IntoIterator<Item = (hopr_protocol_pix::SsaIndex, D)>,
368    ) -> Self {
369        Self {
370            session_id,
371            params: params.to_u32(),
372            deposit_data: deposit_data.into_iter().collect(),
373            commitments: commitments.into_iter().collect(),
374            missing: Default::default(),
375        }
376    }
377
378    /// Asks the Client to re-send the commitments of polynomial runs the Server never received.
379    ///
380    /// A constructor of its own rather than a field to fill in, so the two request kinds cannot be
381    /// mixed: this one carries no commitments and no deposit data, which is the invariant the codec
382    /// enforces. `params` is echoed so the recipient can check the request against what was
383    /// negotiated, exactly as it does for a request for new SSAs.
384    ///
385    /// The caller is responsible for keeping the runs of each SSA ascending and disjoint, and for
386    /// naming no more of them than [`StartProtocol::max_missing_runs`] allows.
387    pub fn recommit(
388        session_id: I,
389        params: hopr_protocol_pix::PixParams,
390        missing: impl IntoIterator<Item = (hopr_protocol_pix::SsaIndex, Vec<PolynomialRun>)>,
391    ) -> Self {
392        Self {
393            session_id,
394            params: params.to_u32(),
395            deposit_data: Default::default(),
396            commitments: Default::default(),
397            missing: missing.into_iter().collect(),
398        }
399    }
400
401    /// Total number of polynomial runs this request names, across every SSA.
402    ///
403    /// The wire form is a flat table, so this — not the number of SSAs — is what has to fit a packet.
404    pub fn missing_run_count(&self) -> usize {
405        self.missing.values().map(Vec::len).sum()
406    }
407
408    /// The PIX dimensions this request was made under, and the curve suite they are dimensions of.
409    ///
410    /// Fails if the peer packed values outside the protocol ranges, or named a curve suite that does
411    /// not exist. The name predates the suite and is kept because the callers read it for the
412    /// dimensions; the suite rides along because both sides must agree on it too.
413    pub fn dimensions(&self) -> errors::Result<hopr_protocol_pix::PixParams> {
414        hopr_protocol_pix::PixParams::try_from_u32(self.params)
415            .map_err(|error| StartProtocolError::ParseError(format!("ssa_req.params: {error}")))
416    }
417}
418
419/// Keep-alive message for a Session with the identifier `T`.
420#[derive(Debug, Clone, PartialEq, Eq)]
421pub struct KeepAliveMessage<I> {
422    /// Session ID.
423    pub session_id: I,
424    /// Additional flags that govern how the `additional_data` field is interpreted or 0.
425    pub flags: KeepAliveFlags,
426    /// Additional data (usually `flags` dependent), ignored if `0`.
427    pub additional_data: u64,
428}
429
430/// [Flags](KeepAliveFlag) that can be sent via the [`KeepAliveMessage`].
431///
432/// The flags can define the meaning of the `additional_data` field.
433pub type KeepAliveFlags = flagset::FlagSet<KeepAliveFlag>;
434
435flagset::flags! {
436    /// Individual flags that can be set in a [`KeepAliveMessage`].
437    pub enum KeepAliveFlag: u8 {
438        /// The `additional_data` field contains load balancer target information.
439        ///
440        /// The value of `additional_data` represents the optimal number of SURBs that the
441        /// Session Initiator wishes to maintain at the Session Recipient.
442        ///
443        /// Mutually exclusive with `BalancerState`.
444        BalancerTarget = 0x01,
445        /// The `additional_data` field contains load balancer state information.
446        ///
447        /// The value of `additional_data` represents the current number of SURBs
448        /// that the Session Recipient estimates to have.
449        ///
450        /// Mutually exclusive with `BalancerTarget`.
451        BalancerState = 0x02,
452        /// The keep-alive was sent by an explicit ping, not by a SURB balancer.
453        ///
454        /// It gives `additional_data` no meaning of its own; any other flag set beside it keeps its
455        /// meaning, but the keep-alive still does not count as a balancer's. A recipient must not read
456        /// it as evidence that the sender runs a SURB balancer and refills SURBs: a sender without one
457        /// can ping by hand, and an unflagged keep-alive cannot say so, because a balancer that does not
458        /// announce its target sends those too.
459        ///
460        /// A node that predates this flag drops the bit when it decodes the message, and treats the
461        /// ping as it always did.
462        ManualPing = 0x04,
463    }
464}
465
466impl<I: serde::Serialize> KeepAliveMessage<I> {
467    /// Number of SURBs that fit alongside this message, including the application tag.
468    pub fn max_surbs(&self) -> errors::Result<usize> {
469        // Start header (version, discriminant, body length), flags, additional data and CBOR session ID.
470        let message_len = 4 + size_of::<u8>() + size_of::<u64>() + serde_cbor_2::to_vec(&self.session_id)?.len();
471        Ok(HoprPacket::max_surbs_with_message(Tag::SIZE + message_len))
472    }
473}
474
475impl<I> From<I> for KeepAliveMessage<I> {
476    fn from(value: I) -> Self {
477        Self {
478            session_id: value,
479            flags: None.into(),
480            additional_data: 0,
481        }
482    }
483}
484
485impl<I, T, C, G, K, D> StartProtocol<I, T, C, G, K, D> {
486    /// Maximum size of the CBOR-serialized
487    /// [`deposit_data`](SsaServerCommitmentMessage::deposit_data) map an
488    /// [`SsaRequest`](StartProtocol::SsaRequest) message can carry.
489    pub const MAX_DEPOSIT_DATA_SIZE: usize = ApplicationData::PAYLOAD_SIZE.saturating_sub(
490        4 + size_of::<u32>()
491            + size_of::<u16>()
492            + size_of::<hopr_protocol_pix::SsaIndex>()
493            + Self::PIX_COEFF_COMMITMENT_REPR_SIZE
494            + size_of::<u16>()
495            + 1,
496    );
497    /// Maximum number of SSAs that can be requested in a single SsaRequest message.
498    pub const MAX_SSAS_PER_REQUEST: u16 = ((ApplicationData::PAYLOAD_SIZE - 13)
499        / (size_of::<hopr_protocol_pix::SsaIndex>() + Self::PIX_COEFF_COMMITMENT_REPR_SIZE))
500        as u16;
501    /// Wire size of one [`missing`](SsaServerCommitmentMessage::missing) table entry: the SSA index
502    /// it belongs to, then the run's inclusive first and last polynomial index.
503    pub const MISSING_RUN_ENTRY_SIZE: usize =
504        size_of::<hopr_protocol_pix::SsaIndex>() + 2 * size_of::<hopr_protocol_pix::PolynomialIndex>();
505    /// Size of the PIX coefficient commitment representation in bytes.
506    pub const PIX_COEFF_COMMITMENT_REPR_SIZE: usize = size_of::<G>();
507    /// Size of the serialized client SSA commitment proof of knowledge in bytes.
508    ///
509    /// Carried only by constant-term `SsaCommit` messages, so it reduces the entry budget of those
510    /// and of no others.
511    pub const PIX_COMMITMENT_PROOF_SIZE: usize = size_of::<K>();
512    /// Size of the Start protocol message header in bytes.
513    pub const START_HEADER_SIZE: usize =
514        size_of_val(&Self::START_PROTOCOL_MESSAGE_TAG) + size_of::<u8>() + size_of::<u16>();
515    /// Fixed [`Tag`] of every protocol message.
516    pub const START_PROTOCOL_MESSAGE_TAG: Tag = Tag::Reserved(ReservedTag::SessionStart as u64);
517    /// Current version of the Start protocol.
518    pub const START_PROTOCOL_VERSION: u8 = 0x04;
519
520    /// How many commitment entries one [`SsaCommit`](StartProtocol::SsaCommit) message can carry,
521    /// for each of the two delivery phases.
522    ///
523    /// This is the bound
524    /// [`SsaClientCommitmentMessage::new_multiple`] chunks by, exposed so that a caller predicting
525    /// the message count for a commitment does not have to restate the encode layout. Restating it
526    /// is error-prone in a way that hides: the copy this replaced used `SsaIndex` (4 B) where an
527    /// `SsaCommit` entry prefix is a `PolynomialIndex` (2 B), against a different fixed overhead,
528    /// and agreed with the encoder only because the two mistakes floored to the same divisor at the
529    /// dimensions it ran at.
530    ///
531    /// Takes the `session_id` itself rather than a precomputed length: its CBOR encoding is part of
532    /// the layout, so leaving the caller to measure it is the same footgun one level up.
533    pub fn ssa_commit_chunking(session_id: &I) -> Result<SsaCommitChunking, StartProtocolError>
534    where
535        I: serde::Serialize,
536    {
537        // A single message can only carry a limited number of coefficient commitments
538        // so that the resulting encoded message still fits within a HOPR packet payload.
539        // The commitments of a single coefficient (across all polynomials) might therefore
540        // need to be split across multiple messages.
541        //
542        // The bound is derived from the actual SsaCommit encode layout:
543        //   header:     version(1) + disc(1) + data_len(2) = 4
544        //   fixed:      ssa_index(4) + coefficient_index(2) + poly_count(2) = 8
545        //   proof:      PIX_COMMITMENT_PROOF_SIZE, constant-term messages only
546        //   per-entry:  PolynomialIndex(2) + commitment_repr(PIX_COEFF_COMMITMENT_REPR_SIZE)
547        //   trailer:    CBOR-encoded session_id
548        let header_and_fixed: usize = 4 + 4 + 2 + 2; // header + ssa_index + coeff_index + num_polys
549        let per_entry = size_of::<hopr_protocol_pix::PolynomialIndex>() + Self::PIX_COEFF_COMMITMENT_REPR_SIZE;
550        // Compute the exact CBOR size of the session_id for this instantiation.
551        let cbor_session_id_size = serde_cbor_2::to_vec(session_id)?.len();
552        let budget = ApplicationData::PAYLOAD_SIZE.saturating_sub(header_and_fixed + cbor_session_id_size);
553
554        Ok(SsaCommitChunking {
555            max_commitments_per_message: (budget / per_entry).max(1),
556            // Constant-term messages additionally carry the proof, so they fit fewer entries. Phase
557            // 2 keeps the full budget, which is what the block size in `new_multiple` is aligned to;
558            // only phase 1 pays for the proof, costing a handful of extra messages per cycle.
559            max_constant_terms_per_message: (budget.saturating_sub(Self::PIX_COMMITMENT_PROOF_SIZE) / per_entry).max(1),
560        })
561    }
562
563    /// How many [`missing`](SsaServerCommitmentMessage::missing) runs one retransmission request can
564    /// carry.
565    ///
566    /// Exposed for the same reason as [`ssa_commit_chunking`](Self::ssa_commit_chunking): the caller
567    /// choosing the scope must not restate the encode layout, because a copy that drifts either
568    /// overflows a packet or silently under-reports what is missing. It takes the `session_id`
569    /// itself rather than a length, since the id's CBOR encoding is part of that layout.
570    ///
571    /// Derived against a request built by [`SsaServerCommitmentMessage::recommit`], which carries no
572    /// commitments and an empty `deposit_data` map:
573    ///
574    /// ```text
575    ///   header:    version(1) + disc(1) + data_len(2) = 4
576    ///   fixed:     params(4) + empty CBOR map(1) + num_commitments(2) + num_missing_runs(2) = 9
577    ///   per-entry: MISSING_RUN_ENTRY_SIZE
578    ///   trailer:   CBOR-encoded session_id
579    /// ```
580    ///
581    /// At least one, so a caller can always ask for something: a budget that rounded to zero would
582    /// leave a repairable cycle with no way to be repaired.
583    pub fn max_missing_runs(session_id: &I) -> Result<usize, StartProtocolError>
584    where
585        I: serde::Serialize,
586    {
587        let header_and_fixed: usize = 4 + size_of::<u32>() + 1 + size_of::<u16>() + size_of::<u16>();
588        let cbor_session_id_size = serde_cbor_2::to_vec(session_id)?.len();
589        let budget = ApplicationData::PAYLOAD_SIZE.saturating_sub(header_and_fixed + cbor_session_id_size);
590
591        Ok((budget / Self::MISSING_RUN_ENTRY_SIZE).max(1))
592    }
593}
594
595/// How many commitment entries one `SsaCommit` message can carry, per delivery phase.
596///
597/// Returned by [`StartProtocol::ssa_commit_chunking`]. The two are easy to confuse and differ only
598/// by the proof of knowledge, so they are named rather than returned as a pair.
599#[derive(Debug, Clone, Copy, PartialEq, Eq)]
600pub struct SsaCommitChunking {
601    /// Phase 2 — higher-coefficient messages, which get the full entry budget.
602    pub max_commitments_per_message: usize,
603    /// Phase 1 — constant-term messages, which also carry the proof of knowledge and so fit fewer.
604    pub max_constant_terms_per_message: usize,
605}
606
607impl<I, T, C, G, K, D> StartProtocol<I, T, C, G, K, D>
608where
609    I: serde::Serialize,
610    T: serde::Serialize,
611    C: Into<u8>,
612    G: AsRef<[u8]>,
613    K: AsRef<[u8]>,
614    D: serde::Serialize,
615{
616    /// Tries to encode the message into binary format and [`Tag`]
617    pub fn encode(self) -> errors::Result<(Tag, Box<[u8]>)> {
618        let mut out = Vec::with_capacity(ApplicationData::PAYLOAD_SIZE);
619        out.push(Self::START_PROTOCOL_VERSION);
620        out.push(StartProtocolDiscriminants::from(&self) as u8);
621
622        let mut data = Vec::with_capacity(ApplicationData::PAYLOAD_SIZE - 2);
623        match self {
624            StartProtocol::StartSession(init) => {
625                data.extend_from_slice(&init.challenge.to_be_bytes());
626                data.push(init.capabilities.into());
627                data.extend_from_slice(&init.additional_data.to_be_bytes());
628                let target = serde_cbor_2::to_vec(&init.target)?;
629                data.extend_from_slice(&target);
630            }
631            StartProtocol::SessionEstablished(est) => {
632                data.extend_from_slice(&est.orig_challenge.to_be_bytes());
633                let session_id = serde_cbor_2::to_vec(&est.session_id)?;
634                data.extend(session_id);
635            }
636            StartProtocol::SessionError(err) => {
637                match err.identifier {
638                    ErrorIdentifier::Challenge(challenge) => {
639                        data.push(ErrorIdentifierDiscriminants::Challenge as u8);
640                        data.extend_from_slice(&challenge.to_be_bytes());
641                    }
642                    ErrorIdentifier::SessionId(id) => {
643                        data.push(ErrorIdentifierDiscriminants::SessionId as u8);
644                        let id_bytes = serde_cbor_2::to_vec(&id)?;
645                        data.extend(id_bytes);
646                    }
647                }
648                data.push(err.reason as u8);
649            }
650            StartProtocol::KeepAlive(ping) => {
651                data.push(ping.flags.bits());
652                data.extend_from_slice(&ping.additional_data.to_be_bytes());
653                let session_id = serde_cbor_2::to_vec(&ping.session_id)?;
654                data.extend(session_id);
655            }
656            StartProtocol::SsaCommit(commit) => {
657                data.extend_from_slice(&commit.ssa_index.get().to_be_bytes());
658                data.extend_from_slice(&commit.coefficient_index.to_be_bytes());
659
660                let num_polys = commit.coefficient_commitments.len() as hopr_protocol_pix::PolynomialIndex;
661                data.extend_from_slice(&num_polys.to_be_bytes());
662
663                // The proof goes immediately after the fixed prefix, and only on constant-term
664                // messages. Its presence is implied by `coefficient_index == 0` rather than by a
665                // flag, so the two must agree — a mismatch would desynchronise the decoder.
666                match (commit.coefficient_index, &commit.commitment_proof) {
667                    (0, Some(proof)) => {
668                        let proof = proof.as_ref();
669                        if proof.len() != Self::PIX_COMMITMENT_PROOF_SIZE {
670                            return Err(StartProtocolError::ParseError("commitment_proof_size".into()));
671                        }
672                        data.extend_from_slice(proof);
673                    }
674                    (0, None) => return Err(StartProtocolError::ParseError("missing commitment_proof".into())),
675                    (_, Some(_)) => {
676                        return Err(StartProtocolError::ParseError(
677                            "commitment_proof on a non-constant term".into(),
678                        ));
679                    }
680                    (_, None) => {}
681                }
682
683                let session_id = serde_cbor_2::to_vec(&commit.session_id)?;
684                let total_coeff_commit_len = (size_of::<hopr_protocol_pix::PolynomialIndex>()
685                    + Self::PIX_COEFF_COMMITMENT_REPR_SIZE)
686                    * commit.coefficient_commitments.len();
687
688                // Remaining payload budget: the final `out` buffer contains
689                // version (1) + disc (1) + data_len (2) + data contents = 4 + data.len(),
690                // which must fit within PAYLOAD_SIZE.  Check using explicit arithmetic
691                // rather than Vec::spare_capacity_mut() which reflects pre-allocation.
692                let avail_space = ApplicationData::PAYLOAD_SIZE.saturating_sub(4 + data.len() + session_id.len());
693                if commit.coefficient_commitments.is_empty() || total_coeff_commit_len > avail_space {
694                    return Err(StartProtocolError::NumberOfCommitments);
695                }
696
697                for (index, commitment) in commit.coefficient_commitments {
698                    let commitment_repr = commitment.as_ref();
699                    if commitment_repr.len() != Self::PIX_COEFF_COMMITMENT_REPR_SIZE {
700                        return Err(StartProtocolError::ParseError("commitment_repr_size".into()));
701                    }
702
703                    // Prepending 16-bit representation of the polynomial index
704                    // will possibly consume less space than putting an entire 1024-bit bitmap
705                    // of polynomials present in each message (assuming 1024 polynomials per SSA).
706                    data.extend_from_slice(&index.to_be_bytes());
707                    data.extend_from_slice(commitment_repr);
708                }
709
710                data.extend(session_id);
711            }
712            StartProtocol::SsaRequest(req) => {
713                // A request either asks for new SSAs or asks for pieces of ones already committed
714                // to, never both and never neither. Refusing the other two combinations here is what
715                // lets the recipient tell the two kinds apart by looking at one field, and stops a
716                // retransmission request from carrying an index nothing asked for.
717                //
718                // Deposit data goes with SSAs being requested, so a retransmission carries none of
719                // it either. Both rules are enforced on the way out as well as on the way in, so a
720                // message this side is willing to build is one the peer is willing to read.
721                let num_missing_runs = req.missing_run_count();
722                if req.commitments.is_empty() == (num_missing_runs == 0) {
723                    return Err(StartProtocolError::NumberOfCommitments);
724                }
725                if num_missing_runs > 0 && !req.deposit_data.is_empty() {
726                    return Err(StartProtocolError::ParseError(
727                        "deposit_data on a retransmission request".into(),
728                    ));
729                }
730
731                data.extend_from_slice(&req.params.to_be_bytes());
732
733                let deposit_data =
734                    serde_cbor_2::to_vec(&req.deposit_data.iter().collect::<std::collections::BTreeMap<_, _>>())?;
735
736                if deposit_data.len() > Self::MAX_DEPOSIT_DATA_SIZE {
737                    return Err(StartProtocolError::DepositDataTooLarge {
738                        size: deposit_data.len(),
739                        max: Self::MAX_DEPOSIT_DATA_SIZE,
740                    });
741                }
742
743                data.extend_from_slice(&deposit_data);
744
745                let num_commitments = req.commitments.len() as u16;
746                data.extend_from_slice(&num_commitments.to_be_bytes());
747
748                let session_id = serde_cbor_2::to_vec(&req.session_id)?;
749
750                let required_size = (size_of::<hopr_protocol_pix::SsaIndex>() + Self::PIX_COEFF_COMMITMENT_REPR_SIZE)
751                    * req.commitments.len()
752                    + size_of::<u16>()
753                    + Self::MISSING_RUN_ENTRY_SIZE * num_missing_runs;
754
755                // Remaining payload budget: the final `out` buffer contains
756                // version (1) + disc (1) + data_len (2) + data contents = 4 + data.len(),
757                // which must fit within PAYLOAD_SIZE.  Check using explicit arithmetic
758                // rather than Vec::spare_capacity_mut() which reflects pre-allocation.
759                //
760                // `data` already holds the serialized deposit data, so a `D` that passed
761                // `MAX_DEPOSIT_DATA_SIZE` above still narrows this budget: past a certain size it
762                // is the commitment count that has to give way, which is what this reports.
763                //
764                // Covers the run table as well, which is also what makes the `as u16` cast below
765                // safe: a count that could not be represented could not have fitted the payload.
766                let avail_space = ApplicationData::PAYLOAD_SIZE.saturating_sub(4 + data.len() + session_id.len());
767                if required_size > avail_space {
768                    return Err(StartProtocolError::NumberOfCommitments);
769                }
770
771                for (ssa_index, commitment) in req.commitments {
772                    let commitment_repr = commitment.as_ref();
773                    if commitment_repr.len() != Self::PIX_COEFF_COMMITMENT_REPR_SIZE {
774                        return Err(StartProtocolError::ParseError("commitment_repr_size".into()));
775                    }
776
777                    data.extend_from_slice(&ssa_index.get().to_be_bytes());
778                    data.extend_from_slice(commitment_repr);
779                }
780
781                data.extend_from_slice(&(num_missing_runs as u16).to_be_bytes());
782                for (ssa_index, runs) in req.missing {
783                    for (first, last) in runs {
784                        // Ascending and disjoint is the decoder's rule, and an inverted run names
785                        // nothing at all, so an encoder must not be able to emit one.
786                        if first > last {
787                            return Err(StartProtocolError::ParseError("missing_run_is_inverted".into()));
788                        }
789                        data.extend_from_slice(&ssa_index.get().to_be_bytes());
790                        data.extend_from_slice(&first.to_be_bytes());
791                        data.extend_from_slice(&last.to_be_bytes());
792                    }
793                }
794
795                data.extend(session_id);
796            }
797        }
798
799        out.extend_from_slice(&(data.len() as u16).to_be_bytes());
800        out.extend(data);
801
802        Ok((Self::START_PROTOCOL_MESSAGE_TAG, out.into_boxed_slice()))
803    }
804}
805
806/// Reads the per-SSA deposit data map, refusing one that announces more entries than a request can
807/// carry.
808fn decode_deposit_data<'de, D, De>(
809    deserializer: De,
810    max_entries: usize,
811) -> Result<std::collections::HashMap<hopr_protocol_pix::SsaIndex, D>, De::Error>
812where
813    D: serde::Deserialize<'de>,
814    De: serde::Deserializer<'de>,
815{
816    struct BoundedMap<D> {
817        max_entries: usize,
818        _deposit_data: std::marker::PhantomData<D>,
819    }
820
821    impl<'de, D: serde::Deserialize<'de>> serde::de::Visitor<'de> for BoundedMap<D> {
822        type Value = std::collections::HashMap<hopr_protocol_pix::SsaIndex, D>;
823
824        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
825            write!(f, "at most {} per-SSA deposit data entries", self.max_entries)
826        }
827
828        fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
829            if let Some(declared) = map.size_hint()
830                && declared > self.max_entries
831            {
832                return Err(serde::de::Error::invalid_length(declared, &self));
833            }
834
835            // Safe to trust now: whatever it says is at or below the bound.
836            let mut out = std::collections::HashMap::with_capacity(map.size_hint().unwrap_or(0));
837            // Counted as they arrive, not by what the map ends up holding: repeating one key
838            // overwrites in place, so `out.len()` would sit at one however many entries followed.
839            let mut entries = 0;
840            while let Some((ssa_index, data)) = map.next_entry()? {
841                entries += 1;
842                if entries > self.max_entries {
843                    return Err(serde::de::Error::invalid_length(entries, &self));
844                }
845                out.insert(ssa_index, data);
846            }
847            Ok(out)
848        }
849    }
850
851    deserializer.deserialize_map(BoundedMap {
852        max_entries,
853        _deposit_data: std::marker::PhantomData,
854    })
855}
856
857impl<I, T, C, G, K, D> StartProtocol<I, T, C, G, K, D>
858where
859    I: for<'de> serde::Deserialize<'de>,
860    T: for<'de> serde::Deserialize<'de>,
861    C: TryFrom<u8>,
862    G: for<'a> TryFrom<&'a [u8]>,
863    K: for<'a> TryFrom<&'a [u8]>,
864    D: for<'de> serde::Deserialize<'de>,
865{
866    /// Tries to decode the message from the binary representation and [`Tag`].
867    ///
868    /// The `tag` must be currently [`START_PROTOCOL_MESSAGE_TAG`](Self::START_PROTOCOL_MESSAGE_TAG)
869    /// and version [`START_PROTOCOL_VERSION`](Self::START_PROTOCOL_VERSION).
870    pub fn decode(tag: Tag, data: &[u8]) -> errors::Result<Self> {
871        if tag != Self::START_PROTOCOL_MESSAGE_TAG {
872            return Err(StartProtocolError::UnknownTag);
873        }
874
875        if data.len() < 5 {
876            return Err(StartProtocolError::InvalidLength);
877        }
878
879        if data[0] != Self::START_PROTOCOL_VERSION {
880            return Err(StartProtocolError::InvalidVersion);
881        }
882
883        let disc = data[1];
884        let len = u16::from_be_bytes(
885            data[2..4]
886                .try_into()
887                .map_err(|_| StartProtocolError::ParseError("len".into()))?,
888        ) as usize;
889        let data_offset = 2 + size_of::<u16>();
890
891        if data.len() != data_offset + len {
892            return Err(StartProtocolError::InvalidLength);
893        }
894        let body = &data[data_offset..data_offset + len];
895
896        Ok(
897            match StartProtocolDiscriminants::from_repr(disc).ok_or(StartProtocolError::UnknownMessage)? {
898                StartProtocolDiscriminants::StartSession => {
899                    if body.len() < size_of::<StartChallenge>() + 1 + size_of::<u128>() {
900                        return Err(StartProtocolError::InvalidLength);
901                    }
902
903                    StartProtocol::StartSession(StartInitiation {
904                        challenge: StartChallenge::from_be_bytes(
905                            body[..size_of::<StartChallenge>()]
906                                .try_into()
907                                .map_err(|_| StartProtocolError::ParseError("init.challenge".into()))?,
908                        ),
909                        capabilities: body[size_of::<StartChallenge>()]
910                            .try_into()
911                            .map_err(|_| StartProtocolError::ParseError("init.capabilities".into()))?,
912                        additional_data: u128::from_be_bytes(
913                            body[size_of::<StartChallenge>() + 1..size_of::<StartChallenge>() + 1 + size_of::<u128>()]
914                                .try_into()
915                                .map_err(|_| StartProtocolError::ParseError("init.additional_data".into()))?,
916                        ),
917                        target: serde_cbor_2::from_slice(&body[size_of::<StartChallenge>() + 1 + size_of::<u128>()..])?,
918                    })
919                }
920                StartProtocolDiscriminants::SessionEstablished => {
921                    if body.len() < size_of::<StartChallenge>() {
922                        return Err(StartProtocolError::InvalidLength);
923                    }
924                    StartProtocol::SessionEstablished(StartEstablished {
925                        orig_challenge: StartChallenge::from_be_bytes(
926                            body[..size_of::<StartChallenge>()]
927                                .try_into()
928                                .map_err(|_| StartProtocolError::ParseError("est.challenge".into()))?,
929                        ),
930                        session_id: serde_cbor_2::from_slice(&body[size_of::<StartChallenge>()..])?,
931                    })
932                }
933                StartProtocolDiscriminants::SessionError => {
934                    if body.is_empty() {
935                        return Err(StartProtocolError::InvalidLength);
936                    }
937                    let (identifier, reason_start) = match ErrorIdentifierDiscriminants::from_repr(body[0])
938                        .ok_or(StartProtocolError::ParseError("err.identifier_tag".into()))?
939                    {
940                        ErrorIdentifierDiscriminants::Challenge => {
941                            if body.len() < 1 + size_of::<StartChallenge>() + 1 {
942                                return Err(StartProtocolError::InvalidLength);
943                            }
944                            let challenge = StartChallenge::from_be_bytes(
945                                body[1..1 + size_of::<StartChallenge>()]
946                                    .try_into()
947                                    .map_err(|_| StartProtocolError::ParseError("err.challenge".into()))?,
948                            );
949                            (ErrorIdentifier::Challenge(challenge), 1 + size_of::<StartChallenge>())
950                        }
951                        ErrorIdentifierDiscriminants::SessionId => {
952                            if body.len() < 2 {
953                                return Err(StartProtocolError::InvalidLength);
954                            }
955                            // Reason byte is the last byte; CBOR session_id is everything
956                            // between the tag byte and the reason.
957                            let reason_start = body.len().saturating_sub(1);
958                            let session_id: I = serde_cbor_2::from_slice(&body[1..reason_start])?;
959                            (ErrorIdentifier::SessionId(session_id), reason_start)
960                        }
961                    };
962                    StartProtocol::SessionError(StartErrorType {
963                        identifier,
964                        // An unrecognized reason is read as [`StartErrorReason::Unknown`] rather
965                        // than failing the message, which is the whole purpose of that variant.
966                        // The alternative loses the error entirely: a peer that added a reason this
967                        // build predates would have its `SessionError` rejected as malformed, and
968                        // the Session it was closing would die on a timeout instead of being
969                        // reported. Refusing to parse tells this node *less* than reading the byte
970                        // it does not recognize as "some reason", so a reason may be added without
971                        // a protocol version bump.
972                        reason: StartErrorReason::from_repr(body[reason_start]).unwrap_or(StartErrorReason::Unknown),
973                    })
974                }
975                StartProtocolDiscriminants::KeepAlive => {
976                    if body.len() < 1 + size_of::<u64>() {
977                        return Err(StartProtocolError::InvalidLength);
978                    }
979
980                    StartProtocol::KeepAlive(KeepAliveMessage {
981                        // Unknown bits are dropped rather than failing the message, for the same
982                        // reason [`StartErrorReason::Unknown`] exists above: a peer that sets a flag
983                        // this build predates would otherwise have its whole keep-alive rejected as
984                        // malformed, and a keep-alive is not a message a Session can afford to lose.
985                        // It carries the Exit's SURB level to the Entry's balancer, it is what keeps
986                        // an otherwise silent Session alive, and on a PIX Session it is one packet of
987                        // the service the Entry's successor gate prices — the gate that decides
988                        // whether the next deposit is admitted at all. Refusing to parse tells this
989                        // node *less* than reading the bits it does recognize, so a flag may be added
990                        // without a protocol version bump.
991                        //
992                        // Truncating is safe because the flags only ever *select* a meaning for
993                        // `additional_data`, and every handler tests for the bit it acts on rather
994                        // than matching the set as a whole. An unknown bit therefore selects no
995                        // behaviour, which is what an older node should do with a meaning it has
996                        // never heard of.
997                        flags: KeepAliveFlags::new_truncated(body[0]),
998                        additional_data: u64::from_be_bytes(
999                            body[1..1 + size_of::<u64>()]
1000                                .try_into()
1001                                .map_err(|_| StartProtocolError::ParseError("ka.additional_data".into()))?,
1002                        ),
1003                        session_id: serde_cbor_2::from_slice(&body[1 + size_of::<u64>()..])?,
1004                    })
1005                }
1006                StartProtocolDiscriminants::SsaCommit => {
1007                    if body.len()
1008                        <= size_of::<hopr_protocol_pix::SsaIndex>()
1009                            + size_of::<hopr_protocol_pix::CoefficientIndex>()
1010                            + 2 * size_of::<hopr_protocol_pix::PolynomialIndex>()
1011                            + Self::PIX_COEFF_COMMITMENT_REPR_SIZE
1012                    {
1013                        return Err(StartProtocolError::InvalidLength);
1014                    }
1015
1016                    let ssa: hopr_protocol_pix::SsaIndex = hopr_protocol_pix::RawSsaIndex::from_be_bytes(
1017                        body[..size_of::<hopr_protocol_pix::SsaIndex>()]
1018                            .try_into()
1019                            .map_err(|_| StartProtocolError::ParseError("ssa_index".into()))?,
1020                    )
1021                    .try_into()
1022                    .map_err(|_| StartProtocolError::ParseError("ssa_index is 0".into()))?;
1023                    let coefficient_index = hopr_protocol_pix::CoefficientIndex::from_be_bytes(
1024                        body[size_of::<hopr_protocol_pix::SsaIndex>()
1025                            ..size_of::<hopr_protocol_pix::SsaIndex>()
1026                                + size_of::<hopr_protocol_pix::CoefficientIndex>()]
1027                            .try_into()
1028                            .map_err(|_| StartProtocolError::ParseError("coefficient_index".into()))?,
1029                    );
1030                    let num_polys =
1031                        hopr_protocol_pix::PolynomialIndex::from_be_bytes(
1032                            body[size_of::<hopr_protocol_pix::SsaIndex>()
1033                                + size_of::<hopr_protocol_pix::CoefficientIndex>()
1034                                ..size_of::<hopr_protocol_pix::SsaIndex>()
1035                                    + size_of::<hopr_protocol_pix::CoefficientIndex>()
1036                                    + size_of::<hopr_protocol_pix::PolynomialIndex>()]
1037                                .try_into()
1038                                .map_err(|_| StartProtocolError::ParseError("polynomial_index".into()))?,
1039                        );
1040                    if num_polys == 0 || num_polys > MAX_POLYS_PER_SSA {
1041                        return Err(StartProtocolError::NumberOfCommitments);
1042                    }
1043
1044                    let mut fixed_prefix_size = size_of::<hopr_protocol_pix::SsaIndex>()
1045                        + size_of::<hopr_protocol_pix::CoefficientIndex>()
1046                        + size_of::<hopr_protocol_pix::PolynomialIndex>();
1047
1048                    // The proof sits right after the fixed prefix on constant-term messages only,
1049                    // with no presence flag — the coefficient index is what says whether it is
1050                    // there, so the encoder is required to keep the two in agreement.
1051                    let commitment_proof = if coefficient_index == 0 {
1052                        if body.len() <= fixed_prefix_size + Self::PIX_COMMITMENT_PROOF_SIZE {
1053                            return Err(StartProtocolError::InvalidLength);
1054                        }
1055                        let proof =
1056                            K::try_from(&body[fixed_prefix_size..fixed_prefix_size + Self::PIX_COMMITMENT_PROOF_SIZE])
1057                                .map_err(|_| StartProtocolError::ParseError("commitment_proof".into()))?;
1058                        fixed_prefix_size += Self::PIX_COMMITMENT_PROOF_SIZE;
1059                        Some(proof)
1060                    } else {
1061                        None
1062                    };
1063
1064                    let mut coefficient_commitments = {
1065                        // Derive the maximum number of polynomial entries this packet
1066                        // can carry from the same per-entry constraints as the encoder
1067                        // (see `new_multiple`).  Enforce it before allocating, so
1068                        // unreasonably large `num_polys` values that pass the
1069                        // `MAX_POLYS_PER_SSA` guard are still caught by the wire limit.
1070                        let per_entry =
1071                            size_of::<hopr_protocol_pix::PolynomialIndex>() + Self::PIX_COEFF_COMMITMENT_REPR_SIZE;
1072                        // Availability: remaining body after the fixed prefix fields
1073                        // (ssa_index + coefficient_index + num_polys), reserving at
1074                        // least one byte for the trailing CBOR session_id.
1075                        let avail = body.len().saturating_sub(fixed_prefix_size);
1076                        let max_by_payload = avail.saturating_sub(1) / per_entry;
1077                        if num_polys as usize > max_by_payload {
1078                            return Err(StartProtocolError::NumberOfCommitments);
1079                        }
1080                        std::collections::HashMap::with_capacity(num_polys as usize)
1081                    };
1082                    let mut next_offset = fixed_prefix_size;
1083                    for _ in 0..num_polys {
1084                        // Still needs to be space left for Session ID at the end of commitments
1085                        if body.len()
1086                            <= next_offset
1087                                + size_of::<hopr_protocol_pix::PolynomialIndex>()
1088                                + Self::PIX_COEFF_COMMITMENT_REPR_SIZE
1089                        {
1090                            return Err(StartProtocolError::InvalidLength);
1091                        }
1092
1093                        let index = hopr_protocol_pix::PolynomialIndex::from_be_bytes(
1094                            body[next_offset..next_offset + size_of::<hopr_protocol_pix::PolynomialIndex>()]
1095                                .try_into()
1096                                .map_err(|_| StartProtocolError::ParseError("polynomial_index".into()))?,
1097                        );
1098                        next_offset += size_of::<hopr_protocol_pix::PolynomialIndex>();
1099
1100                        let commitment =
1101                            G::try_from(&body[next_offset..next_offset + Self::PIX_COEFF_COMMITMENT_REPR_SIZE])
1102                                .map_err(|_| StartProtocolError::ParseError("commitment".into()))?;
1103                        next_offset += Self::PIX_COEFF_COMMITMENT_REPR_SIZE;
1104
1105                        if coefficient_commitments.insert(index, commitment).is_some() {
1106                            return Err(StartProtocolError::DuplicateCommitment);
1107                        }
1108                    }
1109
1110                    StartProtocol::SsaCommit(SsaClientCommitmentMessage {
1111                        session_id: serde_cbor_2::from_slice(&body[next_offset..])?,
1112                        ssa_index: ssa,
1113                        coefficient_index,
1114                        commitment_proof,
1115                        coefficient_commitments,
1116                    })
1117                }
1118                StartProtocolDiscriminants::SsaRequest => {
1119                    if body.len() <= size_of::<u32>() + 1 {
1120                        return Err(StartProtocolError::InvalidLength);
1121                    }
1122
1123                    let params = u32::from_be_bytes(
1124                        body[..size_of::<u32>()]
1125                            .try_into()
1126                            .map_err(|_| StartProtocolError::ParseError("params".into()))?,
1127                    );
1128
1129                    // deposit_data is CBOR — decode using a deserializer that tracks its
1130                    // byte offset so we can skip only its size and leave the rest of the body
1131                    // (num_commitments + entries + session_id) untouched. This holds for the map
1132                    // just as it did for a single value: the offset is where the one CBOR item
1133                    // ended, whatever its shape.
1134                    //
1135                    // The `SsaIndex` keys are `NonZero`, so a peer sending index 0 is rejected here
1136                    // by serde rather than reaching the session layer — the same guard the
1137                    // commitment entries get below, for free.
1138                    let mut de = serde_cbor_2::Deserializer::from_slice(&body[size_of::<u32>()..]);
1139                    let deposit_data = decode_deposit_data::<D, _>(&mut de, Self::MAX_SSAS_PER_REQUEST as usize)
1140                        .map_err(|e| StartProtocolError::ParseError(format!("deposit_data: {e}")))?;
1141                    let deposit_data_len = de.byte_offset();
1142                    let mut next_offset = size_of::<u32>() + deposit_data_len;
1143
1144                    if body.len() <= next_offset + size_of::<u16>() {
1145                        return Err(StartProtocolError::InvalidLength);
1146                    }
1147
1148                    let num_commitments = u16::from_be_bytes(
1149                        body[next_offset..next_offset + size_of::<u16>()]
1150                            .try_into()
1151                            .map_err(|_| StartProtocolError::ParseError("num_commitments".into()))?,
1152                    );
1153                    if num_commitments > Self::MAX_SSAS_PER_REQUEST {
1154                        return Err(StartProtocolError::NumberOfCommitments);
1155                    }
1156                    next_offset += size_of::<u16>();
1157
1158                    let mut commitments = std::collections::BTreeMap::new();
1159                    for _ in 0..num_commitments {
1160                        if body.len()
1161                            <= next_offset
1162                                + size_of::<hopr_protocol_pix::SsaIndex>()
1163                                + Self::PIX_COEFF_COMMITMENT_REPR_SIZE
1164                        {
1165                            return Err(StartProtocolError::InvalidLength);
1166                        }
1167
1168                        let ssa_index: hopr_protocol_pix::SsaIndex = hopr_protocol_pix::RawSsaIndex::from_be_bytes(
1169                            body[next_offset..next_offset + size_of::<hopr_protocol_pix::SsaIndex>()]
1170                                .try_into()
1171                                .map_err(|_| StartProtocolError::ParseError("ssa_index".into()))?,
1172                        )
1173                        .try_into()
1174                        .map_err(|_| StartProtocolError::ParseError("ssa_index is 0".into()))?;
1175                        next_offset += size_of::<hopr_protocol_pix::SsaIndex>();
1176
1177                        let commitment =
1178                            G::try_from(&body[next_offset..next_offset + Self::PIX_COEFF_COMMITMENT_REPR_SIZE])
1179                                .map_err(|_| StartProtocolError::ParseError("commitment".into()))?;
1180                        next_offset += Self::PIX_COEFF_COMMITMENT_REPR_SIZE;
1181
1182                        if commitments.insert(ssa_index, commitment).is_some() {
1183                            return Err(StartProtocolError::DuplicateCommitment);
1184                        }
1185                    }
1186
1187                    if body.len() <= next_offset + size_of::<u16>() {
1188                        return Err(StartProtocolError::InvalidLength);
1189                    }
1190                    let num_missing_runs = u16::from_be_bytes(
1191                        body[next_offset..next_offset + size_of::<u16>()]
1192                            .try_into()
1193                            .map_err(|_| StartProtocolError::ParseError("num_missing_runs".into()))?,
1194                    );
1195                    next_offset += size_of::<u16>();
1196
1197                    // A request asks for new SSAs or for pieces of ones already committed to, never
1198                    // both and never neither — see [`SsaServerCommitmentMessage`]. Enforced before
1199                    // the runs are walked, so a message that is neither is reported as the malformed
1200                    // request it is rather than as a length error further in.
1201                    if (num_commitments == 0) == (num_missing_runs == 0) {
1202                        return Err(StartProtocolError::NumberOfCommitments);
1203                    }
1204
1205                    // The count is the peer's word for what follows, so it is bounded by what the
1206                    // body can actually hold before it is used to size anything — reserving at least
1207                    // one byte for the trailing CBOR session id, as the table above is.
1208                    let max_by_payload = body.len().saturating_sub(next_offset + 1) / Self::MISSING_RUN_ENTRY_SIZE;
1209                    if num_missing_runs as usize > max_by_payload {
1210                        return Err(StartProtocolError::NumberOfCommitments);
1211                    }
1212
1213                    let mut missing: std::collections::BTreeMap<hopr_protocol_pix::SsaIndex, Vec<PolynomialRun>> =
1214                        std::collections::BTreeMap::new();
1215                    for _ in 0..num_missing_runs {
1216                        let ssa_index: hopr_protocol_pix::SsaIndex = hopr_protocol_pix::RawSsaIndex::from_be_bytes(
1217                            body[next_offset..next_offset + size_of::<hopr_protocol_pix::SsaIndex>()]
1218                                .try_into()
1219                                .map_err(|_| StartProtocolError::ParseError("ssa_index".into()))?,
1220                        )
1221                        .try_into()
1222                        .map_err(|_| StartProtocolError::ParseError("ssa_index is 0".into()))?;
1223                        let polynomial_index_at = |offset: usize| {
1224                            Ok::<_, StartProtocolError>(hopr_protocol_pix::PolynomialIndex::from_be_bytes(
1225                                body[offset..offset + size_of::<hopr_protocol_pix::PolynomialIndex>()]
1226                                    .try_into()
1227                                    .map_err(|_| StartProtocolError::ParseError("missing_run".into()))?,
1228                            ))
1229                        };
1230                        let run_offset = next_offset + size_of::<hopr_protocol_pix::SsaIndex>();
1231                        let first = polynomial_index_at(run_offset)?;
1232                        let last = polynomial_index_at(run_offset + size_of::<hopr_protocol_pix::PolynomialIndex>())?;
1233                        next_offset += Self::MISSING_RUN_ENTRY_SIZE;
1234
1235                        // An inverted run names nothing, and one past the largest cycle the protocol
1236                        // admits names nothing that can exist.
1237                        if first > last || last >= MAX_POLYS_PER_SSA {
1238                            return Err(StartProtocolError::ParseError("missing_run_out_of_range".into()));
1239                        }
1240
1241                        // Ascending and disjoint within one SSA. This is what bounds the polynomials
1242                        // one request can name by the cycle's own polynomial count rather than by
1243                        // `runs × count`, and what lets the answer be assembled without
1244                        // deduplicating.
1245                        let runs = missing.entry(ssa_index).or_default();
1246                        if runs.last().is_some_and(|(_, previous_last)| first <= *previous_last) {
1247                            return Err(StartProtocolError::ParseError("missing_runs_not_ascending".into()));
1248                        }
1249                        runs.push((first, last));
1250                    }
1251
1252                    // Deposit data belongs to SSAs being requested, and a retransmission requests
1253                    // none. Checked so that every message which decodes really is exactly one of the
1254                    // two kinds, and a recipient branching on `missing` need not re-establish it.
1255                    if !missing.is_empty() && !deposit_data.is_empty() {
1256                        return Err(StartProtocolError::ParseError(
1257                            "deposit_data on a retransmission request".into(),
1258                        ));
1259                    }
1260
1261                    StartProtocol::SsaRequest(SsaServerCommitmentMessage {
1262                        session_id: serde_cbor_2::from_slice(&body[next_offset..])?,
1263                        params,
1264                        deposit_data,
1265                        commitments,
1266                        missing,
1267                    })
1268                }
1269            },
1270        )
1271    }
1272}
1273
1274impl<I, T, C, G, K, D> TryFrom<StartProtocol<I, T, C, G, K, D>> for ApplicationData
1275where
1276    I: serde::Serialize + for<'de> serde::Deserialize<'de>,
1277    T: serde::Serialize + for<'de> serde::Deserialize<'de>,
1278    C: Into<u8> + TryFrom<u8>,
1279    G: AsRef<[u8]> + for<'a> TryFrom<&'a [u8]>,
1280    K: AsRef<[u8]> + for<'a> TryFrom<&'a [u8]>,
1281    D: serde::Serialize + for<'de> serde::Deserialize<'de>,
1282{
1283    type Error = StartProtocolError;
1284
1285    fn try_from(value: StartProtocol<I, T, C, G, K, D>) -> Result<Self, Self::Error> {
1286        let (application_tag, plain_text) = value.encode()?;
1287        Ok(ApplicationData::new(application_tag, plain_text.into_vec())?)
1288    }
1289}
1290
1291impl<I, T, C, G, K, D> TryFrom<ApplicationData> for StartProtocol<I, T, C, G, K, D>
1292where
1293    I: serde::Serialize + for<'de> serde::Deserialize<'de>,
1294    T: serde::Serialize + for<'de> serde::Deserialize<'de>,
1295    C: Into<u8> + TryFrom<u8>,
1296    G: AsRef<[u8]> + for<'a> TryFrom<&'a [u8]>,
1297    K: AsRef<[u8]> + for<'a> TryFrom<&'a [u8]>,
1298    D: serde::Serialize + for<'de> serde::Deserialize<'de>,
1299{
1300    type Error = StartProtocolError;
1301
1302    fn try_from(value: ApplicationData) -> Result<Self, Self::Error> {
1303        Self::decode(value.application_tag, &value.plain_text)
1304    }
1305}
1306
1307#[cfg(test)]
1308mod tests {
1309    use hopr_crypto_packet::{
1310        HoprPixSpec,
1311        prelude::{HoprPacket, HoprPixCommitmentProof, HoprPixGroupElement},
1312    };
1313    use hopr_protocol_app::prelude::Tag;
1314    use hopr_protocol_pix::{EntryShareGenerator, PolynomialIndex, SsaGeneratorConfig, SsaIndex, SsaShareGenerator};
1315    use hopr_types::{crypto::prelude::SimplePseudonym, crypto_random::Randomizable};
1316
1317    use super::*;
1318
1319    /// A minimal deposit data *value* type for tests: `()` CBOR-encodes as a single byte, so a map of
1320    /// them costs only its keys, and an empty one costs a single byte in total.
1321    type MinimalDeposit = ();
1322
1323    #[test]
1324    fn start_protocol_start_session_message_should_encode_and_decode() -> anyhow::Result<()> {
1325        let msg_1 = StartProtocol::StartSession(StartInitiation {
1326            challenge: 0,
1327            target: "127.0.0.1:1234".to_string(),
1328            capabilities: Default::default(),
1329            additional_data: 0x1234_5678_9abc_def0_0000_0000_0000_0000,
1330        });
1331
1332        let (tag, msg) = msg_1.clone().encode()?;
1333        let expected: Tag = StartProtocol::<(), (), (), (), (), MinimalDeposit>::START_PROTOCOL_MESSAGE_TAG;
1334        assert_eq!(tag, expected);
1335
1336        let msg_2 = StartProtocol::<i32, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::decode(tag, &msg)?;
1337
1338        assert_eq!(msg_1, msg_2);
1339        Ok(())
1340    }
1341
1342    #[test]
1343    fn start_protocol_message_start_session_message_should_allow_for_at_least_two_surbs() -> anyhow::Result<()> {
1344        let msg =
1345            StartProtocol::<i32, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::StartSession(StartInitiation {
1346                challenge: 0,
1347                target: "127.0.0.1:1234".to_string(),
1348                capabilities: 0xff,
1349                additional_data: (u64::MAX as u128) << u64::BITS,
1350            });
1351
1352        // Two SURBs are needed because if the server wants to establish PIX, it needs to send an additional
1353        // SsaRequest message next to the SessionEstablished message.
1354        let len = msg.encode()?.1.len();
1355        assert!(
1356            HoprPacket::max_surbs_with_message(len) >= 2,
1357            "StartSession message size ({len}) must allow for at least 2 SURBs in packet",
1358        );
1359
1360        Ok(())
1361    }
1362
1363    #[test]
1364    fn start_protocol_session_established_message_should_encode_and_decode() -> anyhow::Result<()> {
1365        let msg_1 = StartProtocol::SessionEstablished(StartEstablished {
1366            orig_challenge: 0,
1367            session_id: 10_i32,
1368        });
1369
1370        let (tag, msg) = msg_1.clone().encode()?;
1371        let expected: Tag = StartProtocol::<(), (), (), (), (), MinimalDeposit>::START_PROTOCOL_MESSAGE_TAG;
1372        assert_eq!(tag, expected);
1373
1374        let msg_2 = StartProtocol::<i32, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::decode(tag, &msg)?;
1375
1376        assert_eq!(msg_1, msg_2);
1377        Ok(())
1378    }
1379
1380    #[test]
1381    fn start_protocol_session_error_message_should_encode_and_decode() -> anyhow::Result<()> {
1382        let msg_1 = StartProtocol::SessionError(StartErrorType {
1383            identifier: ErrorIdentifier::Challenge(10),
1384            reason: StartErrorReason::NoSlotsAvailable,
1385        });
1386
1387        let (tag, msg) = msg_1.clone().encode()?;
1388        let expected: Tag = StartProtocol::<(), (), (), (), (), MinimalDeposit>::START_PROTOCOL_MESSAGE_TAG;
1389        assert_eq!(tag, expected);
1390
1391        let msg_2 = StartProtocol::<i32, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::decode(tag, &msg)?;
1392
1393        assert_eq!(msg_1, msg_2);
1394
1395        // Also test SessionId variant
1396        let msg_3 = StartProtocol::SessionError(StartErrorType {
1397            identifier: ErrorIdentifier::SessionId(42_i32),
1398            reason: StartErrorReason::UnacceptablePixParams,
1399        });
1400
1401        let (tag, msg) = msg_3.clone().encode()?;
1402        let msg_4 = StartProtocol::<i32, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::decode(tag, &msg)?;
1403        assert_eq!(msg_3, msg_4);
1404
1405        Ok(())
1406    }
1407
1408    /// The reason travels as a single byte read back through `from_repr`, so a variant that does not
1409    /// survive the round trip is one a peer cannot be told about at all.
1410    #[test]
1411    fn every_session_error_reason_survives_the_round_trip() -> anyhow::Result<()> {
1412        for reason in [
1413            StartErrorReason::Unknown,
1414            StartErrorReason::NoSlotsAvailable,
1415            StartErrorReason::Busy,
1416            StartErrorReason::UnacceptablePixParams,
1417            StartErrorReason::TargetNotAdmitted,
1418        ] {
1419            let sent = StartProtocol::SessionError(StartErrorType {
1420                identifier: ErrorIdentifier::Challenge(10),
1421                reason,
1422            });
1423
1424            let (tag, msg) = sent.clone().encode()?;
1425            let received = StartProtocol::<i32, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::decode(tag, &msg)?;
1426
1427            assert_eq!(sent, received, "round trip of {reason}");
1428        }
1429
1430        Ok(())
1431    }
1432
1433    /// A reason byte this build does not know must still decode, as `Unknown`.
1434    ///
1435    /// Otherwise adding a reason is a protocol break in one direction: the older peer rejects the
1436    /// whole `SessionError` as malformed and loses the close it was being told about, so the
1437    /// Session dies on a timeout instead. Reading the byte as "some reason" tells it strictly more.
1438    #[test]
1439    fn a_session_error_reason_this_build_does_not_know_decodes_as_unknown() -> anyhow::Result<()> {
1440        let sent =
1441            StartProtocol::<i32, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::SessionError(StartErrorType {
1442                identifier: ErrorIdentifier::Challenge(10),
1443                reason: StartErrorReason::TargetNotAdmitted,
1444            });
1445        let (tag, msg) = sent.encode()?;
1446
1447        // Stand in for a reason added after this build: the last byte is the reason.
1448        let mut msg = msg.into_vec();
1449        let reason_byte = msg.len() - 1;
1450        msg[reason_byte] = u8::MAX;
1451
1452        let received = StartProtocol::<i32, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::decode(tag, &msg)?;
1453
1454        assert!(
1455            matches!(
1456                received,
1457                StartProtocol::SessionError(StartErrorType {
1458                    identifier: ErrorIdentifier::Challenge(10),
1459                    reason: StartErrorReason::Unknown,
1460                })
1461            ),
1462            "an unknown reason must survive as Unknown, got {received:?}"
1463        );
1464
1465        Ok(())
1466    }
1467
1468    #[test]
1469    fn start_protocol_session_ssa_request_message_should_encode_and_decode() -> anyhow::Result<()> {
1470        let mut commitments = std::collections::BTreeMap::new();
1471        for i in 1..=10 {
1472            commitments.insert(i.try_into()?, [0u8; 33]);
1473        }
1474
1475        // One deposit entry per commitment, which is the shape a real batch has.
1476        let deposit_data = commitments
1477            .keys()
1478            .map(|&ssa_index| (ssa_index, MinimalDeposit::default()))
1479            .collect();
1480
1481        let msg_1 = StartProtocol::SsaRequest(SsaServerCommitmentMessage {
1482            session_id: 0xfeedbeef,
1483            params: 0xfeedbeef,
1484            deposit_data,
1485            commitments,
1486            missing: Default::default(),
1487        });
1488
1489        let (tag, msg) = msg_1.clone().encode()?;
1490        let expected: Tag = StartProtocol::<(), (), (), [u8; 33], [u8; 65], MinimalDeposit>::START_PROTOCOL_MESSAGE_TAG;
1491        assert_eq!(tag, expected);
1492
1493        let msg_2 = StartProtocol::<u32, String, u8, [u8; 33], [u8; 65], MinimalDeposit>::decode(tag, &msg)?;
1494        assert_eq!(msg_1, msg_2);
1495        Ok(())
1496    }
1497
1498    /// A retransmission request round-trips, and carries the scope rather than any new SSA.
1499    #[test]
1500    fn start_protocol_ssa_recommit_request_should_encode_and_decode() -> anyhow::Result<()> {
1501        type Spec = StartProtocol<u32, String, u8, [u8; 33], [u8; 65], MinimalDeposit>;
1502
1503        let params = hopr_protocol_pix::PixParams::try_new(8192, 64, 32, hopr_protocol_pix::PixSuite::Secp256k1)?;
1504        // Two cycles at once, several runs each: the wire form is a flat table keyed by SSA index, so
1505        // one request can scope a whole batch.
1506        let msg_1 = Spec::SsaRequest(SsaServerCommitmentMessage::recommit(
1507            0xfeedbeef_u32,
1508            params,
1509            [
1510                (1.try_into()?, vec![(0, 25), (104, 129), (8191, 8191)]),
1511                (2.try_into()?, vec![(52, 77)]),
1512            ],
1513        ));
1514
1515        let (tag, encoded) = msg_1.clone().encode()?;
1516        let msg_2 = Spec::decode(tag, &encoded)?;
1517        assert_eq!(msg_1, msg_2);
1518
1519        let Spec::SsaRequest(decoded) = msg_2 else {
1520            anyhow::bail!("expected an SsaRequest");
1521        };
1522        assert_eq!(params, decoded.dimensions()?);
1523        assert_eq!(4, decoded.missing_run_count());
1524        assert!(
1525            decoded.commitments.is_empty() && decoded.deposit_data.is_empty(),
1526            "a retransmission request asks for nothing new"
1527        );
1528        assert!(
1529            encoded.len() <= HoprPacket::PAYLOAD_SIZE,
1530            "a retransmission request must fit within {}",
1531            HoprPacket::PAYLOAD_SIZE
1532        );
1533
1534        Ok(())
1535    }
1536
1537    /// Exactly one of the two tables is populated, so the recipient can tell the two request kinds
1538    /// apart by looking at one field — and a retransmission can never smuggle in a new SSA or the
1539    /// deposit data that would go with one.
1540    #[test]
1541    fn start_protocol_ssa_request_must_ask_for_exactly_one_of_the_two_things() -> anyhow::Result<()> {
1542        type Spec = StartProtocol<u32, String, u8, [u8; 33], [u8; 65], MinimalDeposit>;
1543
1544        let neither = Spec::SsaRequest(SsaServerCommitmentMessage {
1545            session_id: 0xfeedbeef,
1546            params: 0,
1547            deposit_data: Default::default(),
1548            commitments: Default::default(),
1549            missing: Default::default(),
1550        });
1551        assert!(matches!(neither.encode(), Err(StartProtocolError::NumberOfCommitments)));
1552
1553        let both = Spec::SsaRequest(SsaServerCommitmentMessage {
1554            session_id: 0xfeedbeef,
1555            params: 0,
1556            deposit_data: Default::default(),
1557            commitments: [(SsaIndex::MIN, [0u8; 33])].into_iter().collect(),
1558            missing: [(SsaIndex::MIN, vec![(0, 0)])].into_iter().collect(),
1559        });
1560        assert!(matches!(both.encode(), Err(StartProtocolError::NumberOfCommitments)));
1561
1562        // Decode refuses both combinations too, so nothing hand-built gets past it either.
1563        for (declared_commitments, entries, declared_runs, runs) in [
1564            (0u16, &[][..], 0u16, &[][..]),
1565            (1, &[(1u32, [0u8; 33])][..], 1, &[(1u32, 0u16, 0u16)][..]),
1566        ] {
1567            let body = ssa_request_body_with(&[0xa0], declared_commitments, entries, declared_runs, runs);
1568            assert!(
1569                matches!(
1570                    decode_framed(StartProtocolDiscriminants::SsaRequest, &body),
1571                    Err(StartProtocolError::NumberOfCommitments)
1572                ),
1573                "commitments={declared_commitments} runs={declared_runs} must be refused"
1574            );
1575        }
1576
1577        // Deposit data belongs to SSAs being requested, and a retransmission requests none. Refused
1578        // on the way out as well as on the way in, so `encode` never builds what `decode` rejects.
1579        let deposit_data = serde_cbor_2::to_vec(
1580            &[(1u32, MinimalDeposit::default())]
1581                .into_iter()
1582                .collect::<std::collections::BTreeMap<_, _>>(),
1583        )?;
1584        let body = ssa_request_body_with(&deposit_data, 0, &[], 1, &[(1, 0, 0)]);
1585        assert!(
1586            matches!(decode_framed(StartProtocolDiscriminants::SsaRequest, &body), Err(ref e) if is_parse_error(e, "deposit_data on a retransmission request")),
1587            "deposit data on a retransmission request must be refused: {:?}",
1588            decode_framed(StartProtocolDiscriminants::SsaRequest, &body)
1589        );
1590
1591        let with_deposit_data = Spec::SsaRequest(SsaServerCommitmentMessage {
1592            session_id: 0xfeedbeef,
1593            params: 0,
1594            deposit_data: [(SsaIndex::MIN, MinimalDeposit::default())].into_iter().collect(),
1595            commitments: Default::default(),
1596            missing: [(SsaIndex::MIN, vec![(0, 0)])].into_iter().collect(),
1597        });
1598        assert!(
1599            matches!(with_deposit_data.encode(), Err(ref e) if is_parse_error(e, "deposit_data on a retransmission request")),
1600        );
1601
1602        // An inverted run names nothing, so the encoder must not be able to emit one either.
1603        let inverted = Spec::SsaRequest(SsaServerCommitmentMessage::recommit(
1604            0xfeedbeef_u32,
1605            hopr_protocol_pix::PixParams::try_new(8192, 64, 32, hopr_protocol_pix::PixSuite::Secp256k1)?,
1606            [(SsaIndex::MIN, vec![(7, 6)])],
1607        ));
1608        assert!(matches!(inverted.encode(), Err(ref e) if is_parse_error(e, "missing_run_is_inverted")));
1609
1610        Ok(())
1611    }
1612
1613    /// The scope has to be canonical: ascending, disjoint and inside the polynomial range. That is
1614    /// what bounds the polynomials one request can name by the cycle's own count rather than by
1615    /// `runs × count`, and what lets the answer be assembled without deduplicating.
1616    #[test]
1617    fn start_protocol_decode_should_reject_a_malformed_missing_scope() {
1618        let refused = |runs: &[(u32, u16, u16)], what: &str| {
1619            let body = ssa_request_body_with(&[0xa0], 0, &[], runs.len() as u16, runs);
1620            let decoded = decode_framed(StartProtocolDiscriminants::SsaRequest, &body);
1621            assert!(
1622                matches!(&decoded, Err(e) if is_parse_error(e, what)),
1623                "{runs:?} must be refused as {what}, got {decoded:?}"
1624            );
1625        };
1626
1627        refused(&[(1, 7, 6)], "missing_run_out_of_range");
1628        refused(&[(1, 0, MAX_POLYS_PER_SSA)], "missing_run_out_of_range");
1629        // Overlapping, and merely repeated, both break the disjointness the answer relies on.
1630        refused(&[(1, 0, 10), (1, 5, 20)], "missing_runs_not_ascending");
1631        refused(&[(1, 0, 10), (1, 0, 10)], "missing_runs_not_ascending");
1632        // Descending across two runs of one SSA. Two runs of *different* SSAs are unrelated, which
1633        // the accepted case below pins.
1634        refused(&[(1, 20, 30), (1, 0, 10)], "missing_runs_not_ascending");
1635
1636        let interleaved = [(2u32, 20u16, 30u16), (1, 0, 10), (2, 40, 50)];
1637        let body = ssa_request_body_with(&[0xa0], 0, &[], interleaved.len() as u16, &interleaved);
1638        let decoded = decode_framed(StartProtocolDiscriminants::SsaRequest, &body);
1639        assert!(
1640            matches!(&decoded, Ok(StartProtocol::SsaRequest(req)) if req.missing_run_count() == 3),
1641            "the ordering rule is per SSA, so interleaved SSAs must decode: {decoded:?}"
1642        );
1643
1644        // A count the body cannot possibly satisfy is refused on the count, before it sizes anything.
1645        let body = ssa_request_body_with(&[0xa0], 0, &[], u16::MAX, &[(1, 0, 0)]);
1646        assert!(matches!(
1647            decode_framed(StartProtocolDiscriminants::SsaRequest, &body),
1648            Err(StartProtocolError::NumberOfCommitments)
1649        ));
1650
1651        // And a zero SSA index has no representation, in this table as in the other one.
1652        let body = ssa_request_body_with(&[0xa0], 0, &[], 1, &[(0, 0, 0)]);
1653        assert!(
1654            matches!(decode_framed(StartProtocolDiscriminants::SsaRequest, &body), Err(ref e) if is_parse_error(e, "ssa_index is 0")),
1655        );
1656    }
1657
1658    /// Pins [`StartProtocol::max_missing_runs`] against the encoder it exists to predict.
1659    ///
1660    /// The Exit sizes its scope from this and cannot see the layout, so a bound that drifted either
1661    /// overflows a packet or silently under-reports what is missing.
1662    #[test]
1663    fn max_missing_runs_should_match_the_encode_layout() -> anyhow::Result<()> {
1664        type Spec = StartProtocol<(), String, u8, [u8; 33], [u8; 65], MinimalDeposit>;
1665
1666        // PAYLOAD_SIZE(3238) - header(4) - params(4) - empty CBOR map(1) - num_commitments(2)
1667        // - num_missing_runs(2) - CBOR null session_id(1), over 8 bytes per run.
1668        let max_runs = Spec::max_missing_runs(&())?;
1669        assert_eq!(403, max_runs);
1670
1671        let scope = |runs: usize| {
1672            // One run per SSA index, which is the worst case for the flat table: every entry pays
1673            // for its own key.
1674            (1..=runs as u32)
1675                .map(|index| {
1676                    (
1677                        hopr_protocol_pix::SsaIndex::new(index).expect("index must be non-zero"),
1678                        vec![(0u16, 0u16)],
1679                    )
1680                })
1681                .collect::<Vec<_>>()
1682        };
1683
1684        let at_the_bound = Spec::SsaRequest(SsaServerCommitmentMessage::recommit(
1685            (),
1686            hopr_protocol_pix::PixParams::try_new(8192, 64, 32, hopr_protocol_pix::PixSuite::Secp256k1)?,
1687            scope(max_runs),
1688        ));
1689        let (tag, encoded) = at_the_bound.clone().encode()?;
1690        assert!(encoded.len() <= ApplicationData::PAYLOAD_SIZE);
1691        assert_eq!(at_the_bound, Spec::decode(tag, &encoded)?);
1692
1693        let over_the_bound = Spec::SsaRequest(SsaServerCommitmentMessage::recommit(
1694            (),
1695            hopr_protocol_pix::PixParams::try_new(8192, 64, 32, hopr_protocol_pix::PixSuite::Secp256k1)?,
1696            scope(max_runs + 1),
1697        ));
1698        assert!(
1699            matches!(over_the_bound.encode(), Err(StartProtocolError::NumberOfCommitments)),
1700            "one run past the bound must not encode"
1701        );
1702
1703        Ok(())
1704    }
1705
1706    /// The round-trip test above deliberately uses an out-of-range sentinel to prove the codec is
1707    /// total. This one goes through the constructor and the accessor, which is what production uses
1708    /// and what actually pins the packed layout across `encode`/`decode`.
1709    #[test]
1710    fn start_protocol_session_ssa_request_message_should_preserve_pix_params() -> anyhow::Result<()> {
1711        let params = hopr_protocol_pix::PixParams::try_new(8192, 64, 32, hopr_protocol_pix::PixSuite::BabyJubJub)?;
1712        let msg_1 = StartProtocol::<u32, String, u8, [u8; 33], [u8; 65], MinimalDeposit>::SsaRequest(
1713            SsaServerCommitmentMessage::new(
1714                0xfeedbeef_u32,
1715                params,
1716                [(1.try_into()?, [0u8; 33]), (2.try_into()?, [1u8; 33])],
1717                [
1718                    (1.try_into()?, MinimalDeposit::default()),
1719                    (2.try_into()?, MinimalDeposit::default()),
1720                ],
1721            ),
1722        );
1723
1724        let (tag, msg) = msg_1.clone().encode()?;
1725        let msg_2 = StartProtocol::<u32, String, u8, [u8; 33], [u8; 65], MinimalDeposit>::decode(tag, &msg)?;
1726        assert_eq!(msg_1, msg_2);
1727
1728        let StartProtocol::SsaRequest(decoded) = msg_2 else {
1729            anyhow::bail!("expected an SsaRequest");
1730        };
1731        assert_eq!(params, decoded.dimensions()?);
1732        Ok(())
1733    }
1734
1735    /// A peer can put anything in the `params` word, so reading it must fail rather than silently
1736    /// yield nonsense dimensions.
1737    #[test]
1738    fn start_protocol_ssa_request_dimensions_should_reject_out_of_range_params() {
1739        let msg: SsaServerCommitmentMessage<u32, [u8; 33], MinimalDeposit> = SsaServerCommitmentMessage {
1740            session_id: 0xfeedbeef,
1741            params: 0xfeedbeef,
1742            deposit_data: Default::default(),
1743            commitments: Default::default(),
1744            missing: Default::default(),
1745        };
1746        assert!(matches!(msg.dimensions(), Err(StartProtocolError::ParseError(_))));
1747    }
1748
1749    #[test]
1750    fn start_protocol_session_ssa_request_message_should_fail_on_too_many_commitments() -> anyhow::Result<()> {
1751        let mut commitments = std::collections::BTreeMap::new();
1752        // A single commitment is 4 + 33 = 37 bytes.
1753        // Payload size is 432 bytes.
1754        // Header + params + num_commitments + session_id will take some space.
1755        // Let's add many commitments to exceed the limit.
1756        for i in 1..=100 {
1757            commitments.insert(i.try_into()?, [0u8; 33]);
1758        }
1759
1760        let msg =
1761            StartProtocol::<u32, (), u8, [u8; 33], [u8; 65], MinimalDeposit>::SsaRequest(SsaServerCommitmentMessage {
1762                session_id: 0xfeedbeef,
1763                params: 0xfeedbeef,
1764                // Empty: this test is about the commitment count exhausting the payload, and an
1765                // empty map keeps the deposit data out of that arithmetic entirely.
1766                deposit_data: Default::default(),
1767                commitments,
1768                missing: Default::default(),
1769            });
1770
1771        assert!(matches!(msg.encode(), Err(StartProtocolError::NumberOfCommitments)));
1772        Ok(())
1773    }
1774
1775    /// A single-entry deposit map whose CBOR encoding is exactly `target` bytes long.
1776    ///
1777    /// The bound is on the *serialized* size of the whole map, which is what the encoder budgets
1778    /// against, so the two tests below must not have to know how wide a length prefix CBOR spends on
1779    /// the payload they ask for. Searching for the overhead keeps them correct across a prefix
1780    /// boundary. One entry keyed by [`SsaIndex::MIN`] — the cheapest key there is — so what the tests
1781    /// vary is the size of the deposit map and not of its keys.
1782    fn deposit_data_of_cbor_size(target: usize) -> anyhow::Result<std::collections::HashMap<SsaIndex, Vec<u8>>> {
1783        for overhead in 1..=8 {
1784            let candidate: std::collections::HashMap<_, _> =
1785                [(SsaIndex::MIN, vec![0u8; target.saturating_sub(overhead)])]
1786                    .into_iter()
1787                    .collect();
1788            if serde_cbor_2::to_vec(&candidate)?.len() == target {
1789                return Ok(candidate);
1790            }
1791        }
1792        anyhow::bail!("no single-entry deposit map CBOR-encodes to exactly {target} bytes")
1793    }
1794
1795    /// The per-SSA values must survive the round trip *individually*.
1796    ///
1797    /// A codec that kept only one value, or paired values with the wrong indices, would still satisfy
1798    /// a check on the encoded length — so this compares the map itself. One deposit index is
1799    /// deliberately outside the commitment range: the codec does not require the two key sets to
1800    /// agree, and must not quietly normalise them either.
1801    #[test]
1802    fn start_protocol_ssa_request_should_round_trip_per_ssa_deposit_data() -> anyhow::Result<()> {
1803        type Spec = StartProtocol<u32, String, u8, [u8; 33], [u8; 65], Vec<u8>>;
1804
1805        let deposit_data: std::collections::HashMap<SsaIndex, Vec<u8>> = [
1806            (SsaIndex::MIN, vec![1u8, 2, 3]),
1807            (2u32.try_into()?, vec![4u8]),
1808            (0xdead_u32.try_into()?, vec![5u8; 20]),
1809        ]
1810        .into_iter()
1811        .collect();
1812
1813        let msg = Spec::SsaRequest(SsaServerCommitmentMessage {
1814            session_id: 0xfeedbeef,
1815            params: 0xfeedbeef,
1816            deposit_data: deposit_data.clone(),
1817            commitments: [(SsaIndex::MIN, [0u8; 33]), (2u32.try_into()?, [1u8; 33])]
1818                .into_iter()
1819                .collect(),
1820            missing: Default::default(),
1821        });
1822
1823        let (tag, encoded) = msg.clone().encode()?;
1824        let decoded = Spec::decode(tag, &encoded)?;
1825        assert_eq!(msg, decoded);
1826
1827        let StartProtocol::SsaRequest(req) = decoded else {
1828            anyhow::bail!("expected an SsaRequest");
1829        };
1830        assert_eq!(deposit_data, req.deposit_data);
1831
1832        Ok(())
1833    }
1834
1835    /// The encoding is a function of the message, not of the hasher.
1836    ///
1837    /// `deposit_data` is a `HashMap`, and two maps holding equal entries iterate in different orders —
1838    /// `RandomState` varies its seed per instance. Handing that order to CBOR would make the bytes of
1839    /// two equal messages differ, which is why `encode` sorts the map first. Two independently built
1840    /// maps, filled in opposite orders, is what catches its removal.
1841    #[test]
1842    fn start_protocol_ssa_request_encoding_should_not_depend_on_deposit_map_order() -> anyhow::Result<()> {
1843        type Spec = StartProtocol<u32, String, u8, [u8; 33], [u8; 65], Vec<u8>>;
1844
1845        // Twelve entries rather than a handful: two independent maps can coincide on an iteration
1846        // order by luck, and at this width the odds of that (1 in 12!) put the test past the point
1847        // where a passing run means anything other than the sort being there.
1848        let entries = (1u32..=12)
1849            .map(|i| Ok((i.try_into()?, vec![i as u8; 2])))
1850            .collect::<anyhow::Result<Vec<_>>>()?;
1851        let build = |deposit_data: std::collections::HashMap<SsaIndex, Vec<u8>>| {
1852            Spec::SsaRequest(SsaServerCommitmentMessage {
1853                session_id: 0xfeedbeef,
1854                params: 0xfeedbeef,
1855                deposit_data,
1856                commitments: [(SsaIndex::MIN, [0u8; 33])].into_iter().collect(),
1857                missing: Default::default(),
1858            })
1859        };
1860
1861        let forward = build(entries.iter().cloned().collect());
1862        let reverse = build(entries.iter().rev().cloned().collect());
1863
1864        assert_eq!(forward, reverse);
1865        assert_eq!(forward.encode()?.1, reverse.encode()?.1);
1866
1867        Ok(())
1868    }
1869
1870    /// An oversized `D` must be named as such, and not reported as a commitment-count problem.
1871    ///
1872    /// The distinction is what the caller can act on: below this bound the deposit data and the
1873    /// batch size compete for one budget and dropping commitments is a fix, whereas above it no
1874    /// commitment count would have made the message fit.
1875    #[test]
1876    fn start_protocol_ssa_request_should_reject_oversized_deposit_data() -> anyhow::Result<()> {
1877        type Spec = StartProtocol<(), String, u8, [u8; 33], [u8; 65], Vec<u8>>;
1878
1879        let too_large = Spec::MAX_DEPOSIT_DATA_SIZE + 1;
1880        let msg = Spec::SsaRequest(SsaServerCommitmentMessage {
1881            session_id: (),
1882            params: 0xfeedbeef,
1883            deposit_data: deposit_data_of_cbor_size(too_large)?,
1884            commitments: [(SsaIndex::MIN, [0u8; 33])].into_iter().collect(),
1885            missing: Default::default(),
1886        });
1887
1888        assert!(matches!(
1889            msg.encode(),
1890            Err(StartProtocolError::DepositDataTooLarge { size, max })
1891                if size == too_large && max == Spec::MAX_DEPOSIT_DATA_SIZE
1892        ));
1893        Ok(())
1894    }
1895
1896    /// Pins [`StartProtocol::MAX_DEPOSIT_DATA_SIZE`] as *achievable*, not merely safe.
1897    ///
1898    /// A bound a few bytes too conservative would pass a "the message still fits" assertion just as
1899    /// well, so this asserts equality instead: the smallest legal `SsaRequest` built around a
1900    /// maximal `deposit_data` — one commitment, a one-byte CBOR session_id — must fill the payload
1901    /// exactly, and still round-trip.
1902    #[test]
1903    fn max_deposit_data_size_should_match_the_encode_layout() -> anyhow::Result<()> {
1904        type Spec = StartProtocol<(), String, u8, [u8; 33], [u8; 65], Vec<u8>>;
1905
1906        // PAYLOAD_SIZE(3238) - header(4) - params(4) - num_commitments(2) - one entry(4 + 33)
1907        // - num_missing_runs(2) - CBOR null session_id(1). Stated as a literal so a layout change
1908        // has to come through here.
1909        assert_eq!(3188, Spec::MAX_DEPOSIT_DATA_SIZE);
1910
1911        let msg = Spec::SsaRequest(SsaServerCommitmentMessage {
1912            session_id: (),
1913            params: 0xfeedbeef,
1914            deposit_data: deposit_data_of_cbor_size(Spec::MAX_DEPOSIT_DATA_SIZE)?,
1915            commitments: [(SsaIndex::MIN, [0u8; 33])].into_iter().collect(),
1916            missing: Default::default(),
1917        });
1918
1919        let (tag, encoded) = msg.clone().encode()?;
1920        assert_eq!(ApplicationData::PAYLOAD_SIZE, encoded.len());
1921        assert_eq!(msg, Spec::decode(tag, &encoded)?);
1922
1923        Ok(())
1924    }
1925
1926    /// Pins [`StartProtocol::ssa_commit_chunking`] against a fully determined instantiation.
1927    ///
1928    /// The bound's only other consumers ask *it* how many messages to expect, so nothing else can
1929    /// catch a change in the arithmetic. Here every input is fixed, so the outputs can be stated
1930    /// outright: a change to the layout has to come through this test.
1931    #[test]
1932    fn ssa_commit_chunking_should_match_the_encode_layout() -> anyhow::Result<()> {
1933        type Spec = StartProtocol<i32, String, u8, [u8; 33], [u8; 65], MinimalDeposit>;
1934
1935        // header(4) + ssa_index(4) + coeff_index(2) + num_polys(2) = 12, plus the CBOR session id:
1936        // 0xfeedeef exceeds u16, so CBOR spends a 1-byte prefix and 4 bytes of payload on it.
1937        let budget = ApplicationData::PAYLOAD_SIZE - 12 - 5;
1938        // `PolynomialIndex` is a `u16` — an `SsaIndex` prefix belongs to `SsaRequest`, not here.
1939        let per_entry = size_of::<PolynomialIndex>() + Spec::PIX_COEFF_COMMITMENT_REPR_SIZE;
1940
1941        let chunking = Spec::ssa_commit_chunking(&0xfeedeef)?;
1942
1943        assert_eq!(budget / per_entry, chunking.max_commitments_per_message);
1944        assert_eq!(
1945            (budget - Spec::PIX_COMMITMENT_PROOF_SIZE) / per_entry,
1946            chunking.max_constant_terms_per_message
1947        );
1948        // Stated as literals too, so that a change reaching *both* the encoder and the derivation
1949        // above still has to be acknowledged here.
1950        assert_eq!(92, chunking.max_commitments_per_message);
1951        assert_eq!(90, chunking.max_constant_terms_per_message);
1952
1953        // The proof is carried by constant-term messages only, so phase 1 must never fit more
1954        // entries than phase 2 — the invariant `new_multiple`'s two loops rely on.
1955        assert!(chunking.max_constant_terms_per_message < chunking.max_commitments_per_message);
1956
1957        Ok(())
1958    }
1959
1960    #[test]
1961    fn start_protocol_session_ssa_commit_message_should_encode_and_decode() -> anyhow::Result<()> {
1962        assert_eq!(
1963            33,
1964            StartProtocol::<i32, String, u8, [u8; 33], [u8; 65], MinimalDeposit>::PIX_COEFF_COMMITMENT_REPR_SIZE
1965        );
1966        // MAX_SSAS_PER_REQUEST must never drop below 25, which is the number of SSA commitments
1967        // `start_protocol_messages_must_fit_within_hopr_packet` packs into an `SsaRequest`.
1968        let ssas_per_request =
1969            StartProtocol::<i32, String, u8, [u8; 33], [u8; 65], MinimalDeposit>::MAX_SSAS_PER_REQUEST;
1970        assert!(
1971            ssas_per_request >= 25,
1972            "MAX_SSAS_PER_REQUEST={ssas_per_request} is too small to encode 25 SSA commitments",
1973        );
1974
1975        // An `SsaCommit` entry is `(PolynomialIndex, commitment)`, and `PolynomialIndex` is a `u16`
1976        // — the encoder writes `index.to_be_bytes()` and the decoder consumes
1977        // `size_of::<PolynomialIndex>()`. The four-byte prefix belongs to `SsaRequest`, whose
1978        // entries carry an `SsaIndex`; using it here under-fills the message by two bytes an entry,
1979        // so this would stop being the maximum-size encode it is written to be.
1980        let max_coeffs = (ApplicationData::PAYLOAD_SIZE
1981            - StartProtocol::<i32, String, u8, [u8; 33], [u8; 65], MinimalDeposit>::START_HEADER_SIZE)
1982            / (size_of::<PolynomialIndex>()
1983                + StartProtocol::<i32, String, u8, [u8; 33], [u8; 65], MinimalDeposit>::PIX_COEFF_COMMITMENT_REPR_SIZE);
1984
1985        // A non-zero coefficient index, so this message carries no proof and the entry budget is
1986        // the full one.
1987        let msg_1 = StartProtocol::SsaCommit(SsaClientCommitmentMessage {
1988            session_id: 0xfeedeef,
1989            ssa_index: hopr_protocol_pix::SsaIndex::MAX,
1990            coefficient_index: hopr_protocol_pix::CoefficientIndex::MAX,
1991            commitment_proof: None::<[u8; 65]>,
1992            coefficient_commitments: (0..max_coeffs).map(|i| (i as PolynomialIndex, [0u8; 33])).collect(),
1993        });
1994
1995        let (tag, msg) = msg_1.clone().encode()?;
1996        let expected: Tag = StartProtocol::<(), (), (), [u8; 33], [u8; 65], MinimalDeposit>::START_PROTOCOL_MESSAGE_TAG;
1997        assert_eq!(tag, expected);
1998
1999        let msg_2 = StartProtocol::<u32, String, u8, [u8; 33], [u8; 65], MinimalDeposit>::decode(tag, &msg)?;
2000        assert_eq!(msg_1, msg_2);
2001
2002        Ok(())
2003    }
2004
2005    #[test]
2006    fn start_protocol_keep_alive_message_should_encode_and_decode() -> anyhow::Result<()> {
2007        let msg_1 = StartProtocol::KeepAlive(KeepAliveMessage {
2008            session_id: 10_i32,
2009            flags: None.into(),
2010            additional_data: 0xffffffff,
2011        });
2012
2013        let (tag, msg) = msg_1.clone().encode()?;
2014        let expected: Tag = StartProtocol::<(), (), (), (), (), MinimalDeposit>::START_PROTOCOL_MESSAGE_TAG;
2015        assert_eq!(tag, expected);
2016
2017        let msg_2 = StartProtocol::<i32, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::decode(tag, &msg)?;
2018
2019        assert_eq!(msg_1, msg_2);
2020
2021        let msg_1 = StartProtocol::KeepAlive(KeepAliveMessage {
2022            session_id: 10_i32,
2023            flags: KeepAliveFlag::BalancerTarget.into(),
2024            additional_data: 0xffffffff,
2025        });
2026
2027        let (tag, msg) = msg_1.clone().encode()?;
2028        let expected: Tag = StartProtocol::<(), (), (), (), (), MinimalDeposit>::START_PROTOCOL_MESSAGE_TAG;
2029        assert_eq!(tag, expected);
2030
2031        let msg_2 = StartProtocol::<i32, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::decode(tag, &msg)?;
2032
2033        assert_eq!(msg_1, msg_2);
2034        Ok(())
2035    }
2036
2037    /// A keep-alive marked as a manual ping keeps the mark across the wire, and costs the same to send.
2038    ///
2039    /// The mark is what tells a recipient that the sender did not send it as a SURB balancer, and it
2040    /// has to be told from the keep-alives a balancer sends without a flag. It uses a bit of the flag
2041    /// byte the message already has, so it must neither be taken for a balancer flag nor change how many
2042    /// SURBs fit beside the message.
2043    #[test]
2044    fn a_manual_ping_keep_alive_round_trips_with_its_flag() -> anyhow::Result<()> {
2045        type Protocol = StartProtocol<i32, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>;
2046
2047        let ping = KeepAliveMessage {
2048            session_id: 10_i32,
2049            flags: KeepAliveFlag::ManualPing.into(),
2050            additional_data: 0,
2051        };
2052        let unflagged = KeepAliveMessage::from(10_i32);
2053        assert_eq!(
2054            unflagged.max_surbs()?,
2055            ping.max_surbs()?,
2056            "the flag lives in a byte that is already sent"
2057        );
2058        assert_eq!(
2059            Protocol::KeepAlive(unflagged.clone()).encode()?.1.len(),
2060            Protocol::KeepAlive(ping.clone()).encode()?.1.len(),
2061            "the marked ping is no longer on the wire"
2062        );
2063
2064        let (tag, encoded) = Protocol::KeepAlive(ping.clone()).encode()?;
2065        match Protocol::decode(tag, &encoded)? {
2066            StartProtocol::KeepAlive(decoded) => {
2067                assert_eq!(ping, decoded);
2068                assert!(decoded.flags.contains(KeepAliveFlag::ManualPing));
2069                assert!(
2070                    !decoded.flags.contains(KeepAliveFlag::BalancerTarget)
2071                        && !decoded.flags.contains(KeepAliveFlag::BalancerState),
2072                    "a manual ping is neither of the balancer's messages"
2073                );
2074            }
2075            other => anyhow::bail!("expected KeepAlive, got {other:?}"),
2076        }
2077
2078        let (tag, encoded) = Protocol::KeepAlive(unflagged.clone()).encode()?;
2079        match Protocol::decode(tag, &encoded)? {
2080            StartProtocol::KeepAlive(decoded) => {
2081                assert!(
2082                    !decoded.flags.contains(KeepAliveFlag::ManualPing),
2083                    "an unflagged keep-alive must not read as a manual ping"
2084                );
2085            }
2086            other => anyhow::bail!("expected KeepAlive, got {other:?}"),
2087        }
2088        Ok(())
2089    }
2090
2091    /// A keep-alive carrying a flag this build does not know must still decode.
2092    ///
2093    /// The flags are the one field of this message that a later protocol version can extend without
2094    /// changing its layout, so strict decoding here is a forward-compatibility trap rather than a
2095    /// safety property: an Exit that sets a new bit would have every keep-alive rejected by an older
2096    /// Entry as malformed. That Entry then loses the SURB level the message reports, the liveness it
2097    /// provides on an otherwise silent Session, and — on a PIX Session — the credit for one packet of
2098    /// service against its successor gate, which is what decides whether the next deposit is made.
2099    ///
2100    /// The unknown bit itself must not survive: it selects no behaviour on this node, and letting it
2101    /// through would make `flags.contains(..)` answer for a meaning this build cannot implement.
2102    #[test]
2103    fn a_keep_alive_with_an_unknown_flag_decodes_without_the_unknown_bit() -> anyhow::Result<()> {
2104        use anyhow::Context;
2105
2106        let known: KeepAliveFlags = KeepAliveFlag::BalancerState.into();
2107        let msg = StartProtocol::<i32, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::KeepAlive(KeepAliveMessage {
2108            session_id: 10_i32,
2109            flags: known,
2110            additional_data: 0xffffffff,
2111        });
2112
2113        let (tag, mut encoded) = msg.encode()?;
2114
2115        // The flag byte is the first byte of the body, which starts after the version, the
2116        // discriminant and the two-byte length. `0x80` is the highest bit and no flag this build
2117        // knows about, so it stands in for one a later protocol version adds.
2118        const FLAGS_AT: usize = 4;
2119        assert_eq!(
2120            known.bits(),
2121            encoded[FLAGS_AT],
2122            "the flag byte must be where this test patches it"
2123        );
2124        encoded[FLAGS_AT] |= 0x80;
2125
2126        let decoded = StartProtocol::<i32, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::decode(tag, &encoded)
2127            .context("a keep-alive carrying an unknown flag bit must still decode")?;
2128
2129        match decoded {
2130            StartProtocol::KeepAlive(ka) => {
2131                assert_eq!(10_i32, ka.session_id);
2132                assert_eq!(0xffffffff, ka.additional_data);
2133                assert!(
2134                    ka.flags.contains(KeepAliveFlag::BalancerState),
2135                    "the known flag must survive the unknown one"
2136                );
2137                assert_eq!(
2138                    known.bits(),
2139                    ka.flags.bits(),
2140                    "the unknown bit must be dropped, not carried into a flag test"
2141                );
2142            }
2143            other => anyhow::bail!("expected KeepAlive, got {other:?}"),
2144        }
2145
2146        Ok(())
2147    }
2148
2149    #[test]
2150    fn start_protocol_messages_must_fit_within_hopr_packet() -> anyhow::Result<()> {
2151        let msg =
2152            StartProtocol::<i32, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::StartSession(StartInitiation {
2153                challenge: StartChallenge::MAX,
2154                target: "example-of-a-very-very-long-second-level-name.on-a-very-very-long-domain-name.info:65530"
2155                    .to_string(),
2156                capabilities: 0x80,
2157                additional_data: 0xffffffff,
2158            });
2159
2160        assert!(
2161            msg.encode()?.1.len() <= HoprPacket::PAYLOAD_SIZE,
2162            "StartSession must fit within {}",
2163            HoprPacket::PAYLOAD_SIZE
2164        );
2165
2166        let msg = StartProtocol::<String, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::SessionEstablished(
2167            StartEstablished {
2168                orig_challenge: StartChallenge::MAX,
2169                session_id: "example-of-a-very-very-long-session-id-that-should-still-fit-the-packet".to_string(),
2170            },
2171        );
2172
2173        assert!(
2174            msg.encode()?.1.len() <= HoprPacket::PAYLOAD_SIZE,
2175            "SessionEstablished must fit within {}",
2176            HoprPacket::PAYLOAD_SIZE
2177        );
2178
2179        let msg =
2180            StartProtocol::<String, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::SessionError(StartErrorType {
2181                identifier: ErrorIdentifier::Challenge(StartChallenge::MAX),
2182                reason: StartErrorReason::NoSlotsAvailable,
2183            });
2184
2185        assert!(
2186            msg.encode()?.1.len() <= HoprPacket::PAYLOAD_SIZE,
2187            "SessionError(Challenge) must fit within {}",
2188            HoprPacket::PAYLOAD_SIZE
2189        );
2190
2191        let msg =
2192            StartProtocol::<String, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::SessionError(StartErrorType {
2193                identifier: ErrorIdentifier::SessionId(
2194                    "example-of-a-very-very-long-session-id-that-should-still-fit-the-packet".to_string(),
2195                ),
2196                reason: StartErrorReason::UnacceptablePixParams,
2197            });
2198
2199        assert!(
2200            msg.encode()?.1.len() <= HoprPacket::PAYLOAD_SIZE,
2201            "SessionError(SessionId) must fit within {}",
2202            HoprPacket::PAYLOAD_SIZE
2203        );
2204
2205        // The deposit_data map costs a key per SSA on top of the commitments, so 23 of them must
2206        // still fit alongside a realistic long session-id — with a deposit entry for each, which is
2207        // the shape a real batch has.
2208        let mut commitments = std::collections::BTreeMap::new();
2209        for i in 1..24 {
2210            commitments.insert(i.try_into()?, [0u8; 33]);
2211        }
2212
2213        let msg = StartProtocol::<String, String, u8, [u8; 33], [u8; 65], MinimalDeposit>::SsaRequest(
2214            SsaServerCommitmentMessage {
2215                session_id: "example-of-a-very-very-long-session-id-that-should-still-fit-the-packet".to_string(),
2216                params: 0xfeedbeef,
2217                deposit_data: commitments
2218                    .keys()
2219                    .map(|&ssa_index| (ssa_index, MinimalDeposit::default()))
2220                    .collect(),
2221                commitments,
2222                missing: Default::default(),
2223            },
2224        );
2225        assert!(
2226            msg.encode()?.1.len() <= HoprPacket::PAYLOAD_SIZE,
2227            "SsaRequest must fit within {}",
2228            HoprPacket::PAYLOAD_SIZE
2229        );
2230
2231        let msg = StartProtocol::<String, String, u8, [u8; 33], [u8; 65], MinimalDeposit>::SsaCommit(
2232            SsaClientCommitmentMessage {
2233                session_id: "example-of-a-very-very-long-session-id-that-should-still-fit-the-packet".to_string(),
2234                ssa_index: SsaIndex::MAX,
2235                coefficient_index: hopr_protocol_pix::CoefficientIndex::MAX,
2236                commitment_proof: None,
2237                coefficient_commitments: (0..24).map(|i| (i as PolynomialIndex, [0u8; 33])).collect(),
2238            },
2239        );
2240        assert!(
2241            msg.encode()?.1.len() <= HoprPacket::PAYLOAD_SIZE,
2242            "SsaRequest must fit within {}",
2243            HoprPacket::PAYLOAD_SIZE
2244        );
2245
2246        // The same message as a constant-term one: it additionally carries the proof, so it must
2247        // still fit with fewer entries.
2248        let msg = StartProtocol::<String, String, u8, [u8; 33], [u8; 65], MinimalDeposit>::SsaCommit(
2249            SsaClientCommitmentMessage {
2250                session_id: "example-of-a-very-very-long-session-id-that-should-still-fit-the-packet".to_string(),
2251                ssa_index: SsaIndex::MAX,
2252                coefficient_index: 0,
2253                commitment_proof: Some([0u8; 65]),
2254                coefficient_commitments: (0..22).map(|i| (i as PolynomialIndex, [0u8; 33])).collect(),
2255            },
2256        );
2257        assert!(
2258            msg.encode()?.1.len() <= HoprPacket::PAYLOAD_SIZE,
2259            "SsaCommit carrying a proof must fit within {}",
2260            HoprPacket::PAYLOAD_SIZE
2261        );
2262
2263        let msg =
2264            StartProtocol::<String, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::KeepAlive(KeepAliveMessage {
2265                session_id: "example-of-a-very-very-long-session-id-that-should-still-fit-the-packet".to_string(),
2266                flags: None.into(),
2267                additional_data: 0,
2268            });
2269        assert!(
2270            msg.encode()?.1.len() <= HoprPacket::PAYLOAD_SIZE,
2271            "KeepAlive must fit within {}",
2272            HoprPacket::PAYLOAD_SIZE
2273        );
2274
2275        Ok(())
2276    }
2277
2278    #[test]
2279    fn start_protocol_message_keep_alive_surb_capacity_should_include_all_headers() -> anyhow::Result<()> {
2280        for id_len in [0, 9, 20, 500] {
2281            let keep_alive = KeepAliveMessage::from("x".repeat(id_len));
2282            let capacity = keep_alive.max_surbs()?;
2283            let msg = StartProtocol::<String, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::KeepAlive(keep_alive);
2284            let data = ApplicationData::try_from(msg)?;
2285            assert_eq!(capacity, HoprPacket::max_surbs_with_message(data.total_len()));
2286        }
2287
2288        Ok(())
2289    }
2290
2291    /// Session ID used by the hand-framed malformed-message tests below. Its concrete type is
2292    /// `u32`, matching the `I` parameter those tests decode with.
2293    const MALFORMED_SESSION_ID: u32 = 0xfeedbeef;
2294
2295    /// Type the hand-framed bodies are decoded as: 33-byte commitments and a 65-byte proof, the
2296    /// same shape the production instantiation uses.
2297    type Decoder = StartProtocol<u32, String, u8, [u8; 33], [u8; 65], MinimalDeposit>;
2298
2299    /// Wraps a raw body in the Start protocol envelope (version, discriminant, 16-bit body length)
2300    /// exactly as `encode` does. Malformed-input tests need bodies the encoder would refuse to
2301    /// produce, so they frame them by hand.
2302    fn frame(disc: StartProtocolDiscriminants, body: &[u8]) -> Vec<u8> {
2303        let mut out = vec![Decoder::START_PROTOCOL_VERSION, disc as u8];
2304        out.extend_from_slice(&(body.len() as u16).to_be_bytes());
2305        out.extend_from_slice(body);
2306        out
2307    }
2308
2309    /// Builds an `SsaCommit` body: fixed prefix, optional proof, entries, trailing CBOR session id.
2310    /// `declared_polys` is written to the wire as-is, so it can disagree with `entries` — which is
2311    /// the whole point of the tests that use it.
2312    fn ssa_commit_body(
2313        coefficient_index: u16,
2314        declared_polys: u16,
2315        proof: Option<&[u8]>,
2316        entries: &[(u16, [u8; 33])],
2317    ) -> Vec<u8> {
2318        let mut body = Vec::new();
2319        body.extend_from_slice(&1u32.to_be_bytes());
2320        body.extend_from_slice(&coefficient_index.to_be_bytes());
2321        body.extend_from_slice(&declared_polys.to_be_bytes());
2322        if let Some(proof) = proof {
2323            body.extend_from_slice(proof);
2324        }
2325        for (index, commitment) in entries {
2326            body.extend_from_slice(&index.to_be_bytes());
2327            body.extend_from_slice(commitment);
2328        }
2329        body.extend(serde_cbor_2::to_vec(&MALFORMED_SESSION_ID).expect("session id must serialize"));
2330        body
2331    }
2332
2333    /// The `SsaRequest` counterpart of [`ssa_commit_body`], whose entries are keyed by SSA index.
2334    fn ssa_request_body(declared_commitments: u16, entries: &[(u32, [u8; 33])]) -> Vec<u8> {
2335        // An empty CBOR map, which is the single byte 0xA0 — the smallest `deposit_data` there is,
2336        // so these bodies stay about the commitment entries that follow it.
2337        ssa_request_body_with_deposit_data(&[0xa0], declared_commitments, entries)
2338    }
2339
2340    /// [`ssa_request_body`] with the `deposit_data` bytes written out by the caller, for the tests
2341    /// that are about that map rather than about what follows it.
2342    fn ssa_request_body_with_deposit_data(
2343        deposit_data: &[u8],
2344        declared_commitments: u16,
2345        entries: &[(u32, [u8; 33])],
2346    ) -> Vec<u8> {
2347        ssa_request_body_with(deposit_data, declared_commitments, entries, 0, &[])
2348    }
2349
2350    /// The most general `SsaRequest` body: both tables written out as the caller asks, counts and
2351    /// all, so a count is free to disagree with the entries that follow it.
2352    fn ssa_request_body_with(
2353        deposit_data: &[u8],
2354        declared_commitments: u16,
2355        entries: &[(u32, [u8; 33])],
2356        declared_runs: u16,
2357        runs: &[(u32, u16, u16)],
2358    ) -> Vec<u8> {
2359        let mut body = Vec::new();
2360        body.extend_from_slice(&0u32.to_be_bytes());
2361        body.extend_from_slice(deposit_data);
2362        body.extend_from_slice(&declared_commitments.to_be_bytes());
2363        for (ssa_index, commitment) in entries {
2364            body.extend_from_slice(&ssa_index.to_be_bytes());
2365            body.extend_from_slice(commitment);
2366        }
2367        body.extend_from_slice(&declared_runs.to_be_bytes());
2368        for (ssa_index, first, last) in runs {
2369            body.extend_from_slice(&ssa_index.to_be_bytes());
2370            body.extend_from_slice(&first.to_be_bytes());
2371            body.extend_from_slice(&last.to_be_bytes());
2372        }
2373        body.extend(serde_cbor_2::to_vec(&MALFORMED_SESSION_ID).expect("session id must serialize"));
2374        body
2375    }
2376
2377    fn decode_framed(disc: StartProtocolDiscriminants, body: &[u8]) -> errors::Result<Decoder> {
2378        Decoder::decode(Decoder::START_PROTOCOL_MESSAGE_TAG, &frame(disc, body))
2379    }
2380
2381    /// A commitment or proof whose byte length is free to disagree with `size_of`, which is what
2382    /// the encoder's size guards compare against. A fixed-size array can never be the wrong length,
2383    /// so those guards are unreachable without a type like this.
2384    #[derive(Clone, Debug, PartialEq, Eq)]
2385    struct VarLenBytes(Vec<u8>);
2386
2387    impl AsRef<[u8]> for VarLenBytes {
2388        fn as_ref(&self) -> &[u8] {
2389            &self.0
2390        }
2391    }
2392
2393    fn is_parse_error(error: &StartProtocolError, what: &str) -> bool {
2394        matches!(error, StartProtocolError::ParseError(context) if context == what)
2395    }
2396
2397    /// The proof rides on constant-term messages only, and its presence is implied by the
2398    /// coefficient index rather than by a flag. An encoder that let the two disagree would
2399    /// desynchronise the decoder, so all three disagreements must be refused.
2400    #[test]
2401    fn start_protocol_encode_should_refuse_a_proof_that_disagrees_with_the_coefficient_index() {
2402        let missing = StartProtocol::<u32, String, u8, [u8; 33], [u8; 65], MinimalDeposit>::SsaCommit(
2403            SsaClientCommitmentMessage {
2404                session_id: MALFORMED_SESSION_ID,
2405                ssa_index: SsaIndex::MIN,
2406                coefficient_index: 0,
2407                commitment_proof: None,
2408                coefficient_commitments: [(0u16, [0u8; 33])].into_iter().collect(),
2409            },
2410        );
2411        assert!(
2412            matches!(missing.encode(), Err(ref e) if is_parse_error(e, "missing commitment_proof")),
2413            "a constant-term message without a proof must be refused"
2414        );
2415
2416        let unexpected = StartProtocol::<u32, String, u8, [u8; 33], [u8; 65], MinimalDeposit>::SsaCommit(
2417            SsaClientCommitmentMessage {
2418                session_id: MALFORMED_SESSION_ID,
2419                ssa_index: SsaIndex::MIN,
2420                coefficient_index: 1,
2421                commitment_proof: Some([0u8; 65]),
2422                coefficient_commitments: [(0u16, [0u8; 33])].into_iter().collect(),
2423            },
2424        );
2425        assert!(
2426            matches!(unexpected.encode(), Err(ref e) if is_parse_error(e, "commitment_proof on a non-constant term")),
2427            "a proof on a non-constant term must be refused"
2428        );
2429
2430        let wrong_size = StartProtocol::<u32, String, u8, VarLenBytes, VarLenBytes, MinimalDeposit>::SsaCommit(
2431            SsaClientCommitmentMessage {
2432                session_id: MALFORMED_SESSION_ID,
2433                ssa_index: SsaIndex::MIN,
2434                coefficient_index: 0,
2435                commitment_proof: Some(VarLenBytes(vec![0u8; 7])),
2436                coefficient_commitments: [(
2437                    0u16,
2438                    VarLenBytes(vec![
2439                        0u8;
2440                        StartProtocol::<
2441                            u32,
2442                            String,
2443                            u8,
2444                            VarLenBytes,
2445                            VarLenBytes,
2446                            MinimalDeposit,
2447                        >::PIX_COEFF_COMMITMENT_REPR_SIZE
2448                    ]),
2449                )]
2450                .into_iter()
2451                .collect(),
2452            },
2453        );
2454        assert!(
2455            matches!(wrong_size.encode(), Err(ref e) if is_parse_error(e, "commitment_proof_size")),
2456            "a proof of the wrong length must be refused"
2457        );
2458    }
2459
2460    /// Entries are read back at a fixed stride, so a commitment of the wrong length would shift
2461    /// every field after it. Both message kinds carry entries and both must reject it.
2462    #[test]
2463    fn start_protocol_encode_should_refuse_wrongly_sized_commitments() -> anyhow::Result<()> {
2464        let commit = StartProtocol::<u32, String, u8, VarLenBytes, VarLenBytes, MinimalDeposit>::SsaCommit(
2465            SsaClientCommitmentMessage {
2466                session_id: MALFORMED_SESSION_ID,
2467                ssa_index: SsaIndex::MIN,
2468                coefficient_index: 1,
2469                commitment_proof: None,
2470                coefficient_commitments: [(0u16, VarLenBytes(vec![0u8; 7]))].into_iter().collect(),
2471            },
2472        );
2473        assert!(
2474            matches!(commit.encode(), Err(ref e) if is_parse_error(e, "commitment_repr_size")),
2475            "SsaCommit must refuse a commitment of the wrong length"
2476        );
2477
2478        let request = StartProtocol::<u32, String, u8, VarLenBytes, VarLenBytes, MinimalDeposit>::SsaRequest(
2479            SsaServerCommitmentMessage {
2480                session_id: MALFORMED_SESSION_ID,
2481                params: 0,
2482                deposit_data: [(SsaIndex::MIN, MinimalDeposit::default())].into_iter().collect(),
2483                commitments: [(SsaIndex::MIN, VarLenBytes(vec![0u8; 7]))].into_iter().collect(),
2484                missing: Default::default(),
2485            },
2486        );
2487        assert!(
2488            matches!(request.encode(), Err(ref e) if is_parse_error(e, "commitment_repr_size")),
2489            "SsaRequest must refuse a commitment of the wrong length"
2490        );
2491
2492        Ok(())
2493    }
2494
2495    /// A commitment message with nothing to commit to is a wasted packet, and the decoder rejects
2496    /// `num_polys == 0` in any case — so the encoder must not emit one.
2497    #[test]
2498    fn start_protocol_encode_should_refuse_an_ssa_commit_without_commitments() {
2499        let msg = StartProtocol::<u32, String, u8, [u8; 33], [u8; 65], MinimalDeposit>::SsaCommit(
2500            SsaClientCommitmentMessage {
2501                session_id: MALFORMED_SESSION_ID,
2502                ssa_index: SsaIndex::MIN,
2503                coefficient_index: 1,
2504                commitment_proof: None,
2505                coefficient_commitments: Default::default(),
2506            },
2507        );
2508
2509        assert!(matches!(msg.encode(), Err(StartProtocolError::NumberOfCommitments)));
2510    }
2511
2512    /// Everything below decodes bodies a peer could send but the encoder would never produce. The
2513    /// codec has to stay total: each one is answered with an error, never a panic or a silent
2514    /// misparse of the fields that follow.
2515    #[test]
2516    fn start_protocol_decode_should_reject_truncated_session_errors() {
2517        // A `Challenge` identifier without room for the trailing reason byte.
2518        let mut body = vec![ErrorIdentifierDiscriminants::Challenge as u8];
2519        body.extend_from_slice(&[0u8; size_of::<StartChallenge>()]);
2520        assert!(matches!(
2521            decode_framed(StartProtocolDiscriminants::SessionError, &body),
2522            Err(StartProtocolError::InvalidLength)
2523        ));
2524
2525        // A `SessionId` identifier with nothing at all after the tag byte.
2526        assert!(matches!(
2527            decode_framed(
2528                StartProtocolDiscriminants::SessionError,
2529                &[ErrorIdentifierDiscriminants::SessionId as u8]
2530            ),
2531            Err(StartProtocolError::InvalidLength)
2532        ));
2533    }
2534
2535    #[test]
2536    fn start_protocol_decode_should_reject_an_ssa_commit_shorter_than_its_fixed_prefix() {
2537        assert!(matches!(
2538            decode_framed(StartProtocolDiscriminants::SsaCommit, &[0u8; 10]),
2539            Err(StartProtocolError::InvalidLength)
2540        ));
2541    }
2542
2543    /// `num_polys` is attacker-controlled and sizes an allocation, so it is bounded before it is
2544    /// used — both at zero and at `MAX_POLYS_PER_SSA`.
2545    #[test]
2546    fn start_protocol_decode_should_reject_an_out_of_range_polynomial_count() {
2547        for declared in [0, MAX_POLYS_PER_SSA + 1] {
2548            let body = ssa_commit_body(1, declared, None, &[(0, [0u8; 33])]);
2549            assert!(
2550                matches!(
2551                    decode_framed(StartProtocolDiscriminants::SsaCommit, &body),
2552                    Err(StartProtocolError::NumberOfCommitments)
2553                ),
2554                "num_polys={declared} must be rejected"
2555            );
2556        }
2557    }
2558
2559    /// A count that survives the `MAX_POLYS_PER_SSA` bound can still be more than the packet can
2560    /// physically hold; the wire limit is what catches it before the allocation.
2561    #[test]
2562    fn start_protocol_decode_should_reject_more_polynomials_than_the_body_can_hold() {
2563        let body = ssa_commit_body(1, 100, None, &[(0, [0u8; 33]), (1, [1u8; 33])]);
2564
2565        assert!(matches!(
2566            decode_framed(StartProtocolDiscriminants::SsaCommit, &body),
2567            Err(StartProtocolError::NumberOfCommitments)
2568        ));
2569    }
2570
2571    /// A constant-term message declares its proof by its coefficient index alone, so a body with no
2572    /// room for one after the fixed prefix is malformed rather than proof-less.
2573    #[test]
2574    fn start_protocol_decode_should_reject_a_constant_term_without_room_for_its_proof() {
2575        // Fixed prefix plus exactly the proof: nothing left for entries or the session id.
2576        let body = ssa_commit_body(0, 1, Some(&[0u8; 65]), &[]);
2577
2578        assert!(matches!(
2579            decode_framed(StartProtocolDiscriminants::SsaCommit, &body[..8 + 65]),
2580            Err(StartProtocolError::InvalidLength)
2581        ));
2582    }
2583
2584    /// Repeating a polynomial index would silently overwrite the earlier commitment, so the decoder
2585    /// refuses the message instead of picking a winner.
2586    #[test]
2587    fn start_protocol_decode_should_reject_duplicate_polynomial_commitments() {
2588        let body = ssa_commit_body(1, 2, None, &[(7, [0u8; 33]), (7, [1u8; 33])]);
2589
2590        assert!(matches!(
2591            decode_framed(StartProtocolDiscriminants::SsaCommit, &body),
2592            Err(StartProtocolError::DuplicateCommitment)
2593        ));
2594    }
2595
2596    #[test]
2597    fn start_protocol_decode_should_reject_an_ssa_request_shorter_than_its_fixed_prefix() {
2598        assert!(matches!(
2599            decode_framed(StartProtocolDiscriminants::SsaRequest, &[0u8; 5]),
2600            Err(StartProtocolError::InvalidLength)
2601        ));
2602    }
2603
2604    #[test]
2605    fn start_protocol_decode_should_reject_an_out_of_range_commitment_count() {
2606        for declared in [0, Decoder::MAX_SSAS_PER_REQUEST + 1] {
2607            let body = ssa_request_body(declared, &[(1, [0u8; 33])]);
2608            assert!(
2609                matches!(
2610                    decode_framed(StartProtocolDiscriminants::SsaRequest, &body),
2611                    Err(StartProtocolError::NumberOfCommitments)
2612                ),
2613                "num_commitments={declared} must be rejected"
2614            );
2615        }
2616    }
2617
2618    /// `SsaRequest` has no payload-derived bound on its count, so a body that promises more entries
2619    /// than it carries must be caught while walking them.
2620    #[test]
2621    fn start_protocol_decode_should_reject_an_ssa_request_that_promises_more_than_it_carries() {
2622        let body = ssa_request_body(3, &[(1, [0u8; 33])]);
2623
2624        assert!(matches!(
2625            decode_framed(StartProtocolDiscriminants::SsaRequest, &body),
2626            Err(StartProtocolError::InvalidLength)
2627        ));
2628    }
2629
2630    /// A map header is the peer's word for how many entries follow, and a packet of a few dozen
2631    /// bytes is free to claim billions. Sizing an allocation from that claim is the whole problem:
2632    /// the count a request can carry is bounded by its commitments, and a header above that bound is
2633    /// refused on the header, before it has been used to size anything.
2634    #[test]
2635    fn start_protocol_decode_should_reject_a_deposit_data_map_larger_than_a_request_can_carry() {
2636        let over_the_bound = |context: &str| context.starts_with("deposit_data") && context.contains("at most");
2637
2638        // A definite-length CBOR map (0xBB) announcing every entry the address space can hold, in a
2639        // body that carries none of them.
2640        let mut announced = vec![0xbb];
2641        announced.extend_from_slice(&u64::MAX.to_be_bytes());
2642        let body = ssa_request_body_with_deposit_data(&announced, 1, &[(1, [0u8; 33])]);
2643        assert!(
2644            matches!(decode_framed(StartProtocolDiscriminants::SsaRequest, &body), Err(StartProtocolError::ParseError(ref c)) if over_the_bound(c)),
2645            "a map header claiming {} entries must be refused on the claim: {:?}",
2646            u64::MAX,
2647            decode_framed(StartProtocolDiscriminants::SsaRequest, &body)
2648        );
2649
2650        // Complete and well-formed, one entry over the bound — the case a header check alone would
2651        // let through, and the only difference from the accepted body below.
2652        let cbor_map = |entries: u16| {
2653            serde_cbor_2::to_vec(
2654                &(1..=entries as u32)
2655                    .map(|i| (i, ()))
2656                    .collect::<std::collections::BTreeMap<_, _>>(),
2657            )
2658            .expect("deposit data map must serialize")
2659        };
2660
2661        let body =
2662            ssa_request_body_with_deposit_data(&cbor_map(Decoder::MAX_SSAS_PER_REQUEST + 1), 1, &[(1, [0u8; 33])]);
2663        assert!(
2664            matches!(decode_framed(StartProtocolDiscriminants::SsaRequest, &body), Err(StartProtocolError::ParseError(ref c)) if over_the_bound(c)),
2665            "a complete map one entry over the bound must be refused: {:?}",
2666            decode_framed(StartProtocolDiscriminants::SsaRequest, &body)
2667        );
2668
2669        // An indefinite-length map (0xbf … 0xff) announces no count at all, so the header check has
2670        // nothing to refuse and the per-entry one is the only bound left. Repeating a single key
2671        // makes the map's own size useless as a counter: every entry overwrites the last, so the
2672        // decoder holds one pair no matter how many went past it. Only the entries themselves are
2673        // hand-framed; the pairs come from the serializer.
2674        let mut repeated_key = vec![0xbf];
2675        for _ in 0..=Decoder::MAX_SSAS_PER_REQUEST {
2676            repeated_key.extend(serde_cbor_2::to_vec(&1u32).expect("an ssa index must serialize"));
2677            repeated_key.extend(serde_cbor_2::to_vec(&MinimalDeposit::default()).expect("deposit data must serialize"));
2678        }
2679        repeated_key.push(0xff);
2680
2681        let body = ssa_request_body_with_deposit_data(&repeated_key, 1, &[(1, [0u8; 33])]);
2682        assert!(
2683            matches!(decode_framed(StartProtocolDiscriminants::SsaRequest, &body), Err(StartProtocolError::ParseError(ref c)) if over_the_bound(c)),
2684            "an indefinite map must be bounded by the entries it carries, not the keys it keeps: {:?}",
2685            decode_framed(StartProtocolDiscriminants::SsaRequest, &body)
2686        );
2687
2688        // And the bound itself still parses, entries and all.
2689        let body = ssa_request_body_with_deposit_data(&cbor_map(Decoder::MAX_SSAS_PER_REQUEST), 1, &[(1, [0u8; 33])]);
2690        let decoded = decode_framed(StartProtocolDiscriminants::SsaRequest, &body);
2691        assert!(
2692            matches!(decoded, Ok(StartProtocol::SsaRequest(ref req)) if req.deposit_data.len() == Decoder::MAX_SSAS_PER_REQUEST as usize),
2693            "a map at the bound must decode with all of its entries: {decoded:?}"
2694        );
2695    }
2696
2697    #[test]
2698    fn start_protocol_decode_should_reject_duplicate_ssa_commitments() {
2699        let body = ssa_request_body(2, &[(1, [0u8; 33]), (1, [1u8; 33])]);
2700
2701        assert!(matches!(
2702            decode_framed(StartProtocolDiscriminants::SsaRequest, &body),
2703            Err(StartProtocolError::DuplicateCommitment)
2704        ));
2705    }
2706
2707    /// An SSA index of zero has no representation in `SsaIndex`, and it reaches the decoder as a
2708    /// plain `u32` — so both message kinds must turn it into an error rather than unwrap it.
2709    #[test]
2710    fn start_protocol_decode_should_reject_a_zero_ssa_index() {
2711        let mut body = ssa_commit_body(1, 1, None, &[(0, [0u8; 33])]);
2712        body[..4].copy_from_slice(&0u32.to_be_bytes());
2713        assert!(
2714            matches!(decode_framed(StartProtocolDiscriminants::SsaCommit, &body), Err(ref e) if is_parse_error(e, "ssa_index is 0")),
2715        );
2716
2717        let body = ssa_request_body(1, &[(0, [0u8; 33])]);
2718        assert!(
2719            matches!(decode_framed(StartProtocolDiscriminants::SsaRequest, &body), Err(ref e) if is_parse_error(e, "ssa_index is 0")),
2720        );
2721    }
2722
2723    #[test]
2724    fn start_protocol_new_multiple_messages_should_encode_and_decode() -> anyhow::Result<()> {
2725        // Generate a real SSA commitment using the same setup as the PIX
2726        // `test_generator_reconstructor`, but with 2048 polynomials per SSA and threshold 64.
2727        let generator = SsaShareGenerator::<HoprPixSpec>::new(SsaGeneratorConfig {
2728            polynomials_per_ssa: 2048,
2729            threshold: 64,
2730            surplus_shares: 0,
2731        });
2732
2733        let pseudonym = SimplePseudonym::random();
2734        let commitment = generator.new_ssa_commitment(&pseudonym, SsaIndex::MIN)?;
2735
2736        type DummySessionId = [u8; 20];
2737
2738        let session_id: DummySessionId = Default::default();
2739        let messages: Vec<SsaClientCommitmentMessage<DummySessionId, HoprPixGroupElement, HoprPixCommitmentProof>> =
2740            SsaClientCommitmentMessage::new_multiple::<HoprPixSpec>(session_id, commitment)?;
2741
2742        // PIX commits to constant terms only, so every message carries coefficient index 0 — the
2743        // wire format still admits others, nothing produces them. 2048 commitments do not fit in
2744        // one packet, so the pass spans many messages.
2745        assert!(messages.len() > 1);
2746        assert!(
2747            messages.iter().all(|m| m.coefficient_index == 0),
2748            "only constant-term commitments are ever emitted"
2749        );
2750
2751        // Between them they must carry exactly one commitment per polynomial.
2752        let total: usize = messages.iter().map(|m| m.coefficient_commitments.len()).sum();
2753        assert_eq!(2048, total);
2754        let distinct: std::collections::BTreeSet<_> = messages
2755            .iter()
2756            .flat_map(|m| m.coefficient_commitments.keys().copied())
2757            .collect();
2758        assert_eq!(2048, distinct.len(), "each polynomial must be committed exactly once");
2759
2760        // The proof of knowledge rides on every constant-term message: presence is implied by the
2761        // coefficient index rather than a flag, so the two must never disagree.
2762        assert!(
2763            messages.iter().all(|m| m.commitment_proof.is_some()),
2764            "the proof must accompany every constant-term message"
2765        );
2766
2767        let mut max_encoded_size = 0;
2768
2769        for message in messages {
2770            let msg_1 = StartProtocol::<
2771                DummySessionId,
2772                String,
2773                u8,
2774                HoprPixGroupElement,
2775                HoprPixCommitmentProof,
2776                MinimalDeposit,
2777            >::SsaCommit(message);
2778
2779            let (tag, encoded) = msg_1.clone().encode()?;
2780            let expected: Tag =
2781                StartProtocol::<(), (), (), HoprPixGroupElement, HoprPixCommitmentProof, MinimalDeposit>::START_PROTOCOL_MESSAGE_TAG;
2782            assert_eq!(tag, expected);
2783
2784            assert!(
2785                encoded.len() <= ApplicationData::PAYLOAD_SIZE,
2786                "encoded SsaCommit message ({} bytes) exceeds PAYLOAD_SIZE ({})",
2787                encoded.len(),
2788                ApplicationData::PAYLOAD_SIZE
2789            );
2790            max_encoded_size = max_encoded_size.max(encoded.len());
2791
2792            let msg_2 = StartProtocol::<
2793                DummySessionId,
2794                String,
2795                u8,
2796                HoprPixGroupElement,
2797                HoprPixCommitmentProof,
2798                MinimalDeposit,
2799            >::decode(tag, &encoded)?;
2800            assert_eq!(msg_1, msg_2);
2801        }
2802
2803        // The packing must be tight: the largest encoded message must leave less than one entry's
2804        // worth of headroom, or `new_multiple` is under-filling packets and emitting more of them
2805        // than the cycle needs.
2806        let per_entry = size_of::<hopr_protocol_pix::PolynomialIndex>()
2807            + StartProtocol::<DummySessionId, (), (), HoprPixGroupElement, HoprPixCommitmentProof, MinimalDeposit>::PIX_COEFF_COMMITMENT_REPR_SIZE;
2808        let headroom = ApplicationData::PAYLOAD_SIZE - max_encoded_size;
2809        assert!(
2810            headroom < per_entry,
2811            "largest encoded SsaCommit ({max_encoded_size} bytes) leaves {headroom} bytes of headroom, enough for \
2812             another {per_entry}-byte entry"
2813        );
2814
2815        Ok(())
2816    }
2817
2818    /// The whole commitment is `polys` constant terms, so the message count is decided purely by
2819    /// how many fit in a packet alongside the proof of knowledge. That bound is what
2820    /// `MIN_COMMITMENTS_PER_SSA_COMMIT_MSG` in `transport/session/src/manager.rs` mirrors to size
2821    /// the Start ingress channel, where an overflow silently kills a cycle — so it is worth
2822    /// pinning here rather than leaving it an implementation detail of `new_multiple`.
2823    #[test]
2824    fn start_protocol_ssa_commit_messages_should_cover_every_polynomial_exactly_once() -> anyhow::Result<()> {
2825        const POLYS: u16 = 2048;
2826        const THRESHOLD: u8 = 64;
2827
2828        let generator = SsaShareGenerator::<HoprPixSpec>::new(SsaGeneratorConfig {
2829            polynomials_per_ssa: POLYS,
2830            threshold: THRESHOLD,
2831            surplus_shares: 0,
2832        });
2833        let pseudonym = SimplePseudonym::random();
2834        let commitment = generator.new_ssa_commitment(&pseudonym, SsaIndex::MIN)?;
2835
2836        type DummySessionId = [u8; 20];
2837        let session_id: DummySessionId = Default::default();
2838        let messages: Vec<SsaClientCommitmentMessage<DummySessionId, HoprPixGroupElement, HoprPixCommitmentProof>> =
2839            SsaClientCommitmentMessage::new_multiple::<HoprPixSpec>(session_id, commitment)?;
2840
2841        // Every polynomial committed exactly once, no duplicates and no omissions.
2842        let mut seen = std::collections::BTreeMap::<hopr_protocol_pix::PolynomialIndex, usize>::new();
2843        for message in &messages {
2844            for poly_index in message.coefficient_commitments.keys() {
2845                *seen.entry(*poly_index).or_default() += 1;
2846            }
2847        }
2848        assert_eq!(POLYS as usize, seen.len(), "every polynomial must be committed");
2849        assert!(
2850            seen.values().all(|&count| count == 1),
2851            "no polynomial may be committed twice — the Exit rejects the second as a duplicate"
2852        );
2853
2854        // Every message but the last must be packed to the same width, and that width is the
2855        // per-message figure the channel sizing is derived from.
2856        let widths: Vec<usize> = messages.iter().map(|m| m.coefficient_commitments.len()).collect();
2857        let full = widths[0];
2858        assert!(
2859            widths[..widths.len() - 1].iter().all(|&w| w == full),
2860            "all but the trailing message must be full, got {widths:?}"
2861        );
2862        assert_eq!(
2863            messages.len(),
2864            (POLYS as usize).div_ceil(full),
2865            "the message count must be exactly what the packing implies"
2866        );
2867
2868        Ok(())
2869    }
2870
2871    #[test]
2872    fn start_protocol_keep_alive_truncated_lengths_should_not_panic() {
2873        let msg =
2874            StartProtocol::<String, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::KeepAlive(KeepAliveMessage {
2875                session_id: "test-session".to_string(),
2876                flags: None.into(),
2877                additional_data: 0,
2878            });
2879        let (tag, encoded) = msg.encode().expect("encode must succeed");
2880        let full_len = encoded.len();
2881
2882        for trunc_len in 4..full_len {
2883            let result = StartProtocol::<String, String, u8, Box<[u8]>, Box<[u8]>, MinimalDeposit>::decode(
2884                tag,
2885                &encoded[..trunc_len],
2886            );
2887            assert!(
2888                result.is_err(),
2889                "truncated keep-alive at length {trunc_len}/{full_len} should return error, got {result:?}"
2890            );
2891        }
2892    }
2893}