hopr_transport_session/types.rs
1use std::{
2 convert::Into,
3 fmt::Debug,
4 pin::Pin,
5 sync::Arc,
6 task::{Context, Poll},
7 time::Duration,
8};
9
10use futures::{SinkExt, StreamExt, TryStreamExt};
11use hopr_api::{
12 OffchainPublicKey,
13 node::PixDepositData,
14 types::{
15 internal::{prelude::HoprPseudonym, routing::DestinationRouting},
16 primitive::errors::GeneralError,
17 },
18};
19use hopr_crypto_packet::{
20 HoprPixSpec,
21 prelude::{HoprPixCommitmentProof, HoprPixGroupElement},
22};
23use hopr_protocol_app::prelude::{ApplicationData, ApplicationDataIn, ApplicationDataOut, ReservedTag, Tag};
24use hopr_protocol_pix::{PixParams, PixSpec, SsaId, SsaRecoveryProgress};
25#[cfg(feature = "telemetry")]
26use hopr_protocol_session::NoopTracker;
27use hopr_protocol_session::{
28 AcknowledgementMode, AcknowledgementState, AcknowledgementStateConfig, FrameLossSignal, ReliableSocket,
29 SegmentRequest, SeqIndicator, SessionSocketConfig, UnreliableSocket,
30 flow_control::{DeliveryClock, DeliveryMeter, DeliveryTap, FlowControlConfig},
31 session_frame_size,
32};
33use hopr_protocol_start::StartProtocol;
34use hopr_utils::network_types::utils::{AsyncWriteSink, DuplexIO};
35use tracing::{debug, warn};
36
37use crate::{
38 Capabilities, Capability, SESSION_MTU,
39 balancer::BalancerStateValues,
40 errors::{SessionManagerError, TransportSessionError},
41 flow_control::{PacedWriter, SurbSupply},
42};
43
44/// Wrapper for [`Capabilities`] that makes conversion to/from `u8` possible.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub struct HoprSessionCapabilities(pub Capabilities);
47
48impl HoprSessionCapabilities {
49 pub fn empty() -> Self {
50 Self(Capabilities::empty())
51 }
52}
53
54impl TryFrom<u8> for HoprSessionCapabilities {
55 type Error = GeneralError;
56
57 fn try_from(value: u8) -> Result<Self, Self::Error> {
58 Capabilities::new(value)
59 .map(Self)
60 .map_err(|_| GeneralError::ParseError("capabilities".into()))
61 }
62}
63
64impl From<HoprSessionCapabilities> for u8 {
65 fn from(value: HoprSessionCapabilities) -> Self {
66 *value.0.as_ref()
67 }
68}
69
70impl From<HoprSessionCapabilities> for Capabilities {
71 fn from(value: HoprSessionCapabilities) -> Self {
72 value.0
73 }
74}
75
76impl From<Capabilities> for HoprSessionCapabilities {
77 fn from(value: Capabilities) -> Self {
78 Self(value)
79 }
80}
81
82impl AsRef<Capabilities> for HoprSessionCapabilities {
83 fn as_ref(&self) -> &Capabilities {
84 &self.0
85 }
86}
87
88/// Start protocol instantiation for HOPR.
89pub type HoprStartProtocol = StartProtocol<
90 SessionId,
91 SessionTarget,
92 HoprSessionCapabilities,
93 HoprPixGroupElement,
94 HoprPixCommitmentProof,
95 HoprPixDepositPayload,
96>;
97
98/// The deposit data a [deposit pool](hopr_api::chain::DepositPool) produced for one batch of SSAs.
99///
100/// This is what the Exit *collects*, not what it sends: the pool answers a
101/// [`PixDepositDataRequest`](hopr_api::node::PixDepositDataRequest) with one
102/// [`PixDepositData`] per requested [`PixAddressId`](hopr_api::node::PixAddressId), delivered one at
103/// a time over the `deposit_data_created` channel, so a batch arrives as a flat list rather than as
104/// anything keyed. [`deposit_data_for_batch`] turns it into the per-SSA map an `SsaRequest` carries.
105pub type HoprPixDepositData = Vec<PixDepositData>;
106
107/// The deposit data for a *single* SSA, as it travels inside an `SsaRequest`.
108#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
109pub struct HoprPixDepositPayload(#[serde(with = "serde_bytes")] pub Box<[u8]>);
110
111/// Turns the deposit data a pool produced for a batch into the per-SSA map an `SsaRequest` carries.
112///
113/// Every SSA in the batch must come out of this with an entry, and the absence of one is fatal — see
114/// [`MissingDepositData`](crate::errors::SessionManagerError::MissingDepositData) for why the batch
115/// cannot simply travel short. An *empty* entry is not an absent one: a pool with nothing to attach
116/// says so by answering with empty data, which is a value
117/// ([`PixDepositData::is_empty`]) and travels fine.
118///
119/// Entries the batch has no place for — another Session's, an SSA outside this batch, a second answer
120/// for an index already answered — are dropped and reported. They are not themselves fatal: what they
121/// are evidence of is, and the gap they leave behind is what fails.
122pub(crate) fn deposit_data_for_batch(
123 session_id: &SessionId,
124 batch: &[hopr_protocol_pix::SsaIndex],
125 deposit_data: HoprPixDepositData,
126) -> Result<std::collections::HashMap<hopr_protocol_pix::SsaIndex, HoprPixDepositPayload>, SessionManagerError> {
127 let mut out = std::collections::HashMap::with_capacity(batch.len());
128 let (mut foreign, mut duplicate) = (0usize, 0usize);
129
130 for entry in deposit_data {
131 let ssa_index = entry.id.ssa_index();
132 if &entry.id.session_id() != session_id || !batch.contains(&ssa_index) {
133 foreign += 1;
134 continue;
135 }
136 if out.insert(ssa_index, HoprPixDepositPayload(entry.data)).is_some() {
137 duplicate += 1;
138 }
139 }
140
141 if foreign > 0 || duplicate > 0 {
142 warn!(
143 %session_id,
144 requested = batch.len(),
145 usable = out.len(),
146 foreign,
147 duplicate,
148 "deposit pool answered with entries this batch has no place for"
149 );
150 }
151
152 let missing = batch.iter().filter(|i| !out.contains_key(i)).collect::<Vec<_>>();
153 if !missing.is_empty() {
154 return Err(SessionManagerError::MissingDepositData(format!(
155 "session {session_id} is missing deposit data for {} of {} SSAs in the batch: {missing:?} ({foreign} \
156 entries were for other SSAs, {duplicate} were repeats)",
157 missing.len(),
158 batch.len(),
159 )));
160 }
161
162 Ok(out)
163}
164
165/// Quota per single SSA in bytes.
166///
167/// The quota in bytes has only informative value for the user - the volume of Exit -> Entry data
168/// one SSA cycle carries, which is what a single deposit pays for.
169///
170/// Not the volume at which the Exit *recovers* the SSA private key: recovery needs
171/// `polys × threshold` useful shares, and so happens before the cycle drains. The quota covers the
172/// whole cycle, surplus included — see [`pix_params_to_quota`].
173///
174/// The SessionManager always counts in packets, not in bytes, when it comes to quota management.
175/// [`PIX_QUOTA_BYTES_PER_SHARE`] is the one conversion between the two.
176pub type SsaQuota = u64;
177
178/// Bytes of quota one PIX share is priced at: the Session data the packet it rides on can carry.
179///
180/// [`SESSION_MTU`] rather than `HoprPacket::PAYLOAD_SIZE`, because a Session packet carries one
181/// segment and the rest of the HOPR payload is SURBs or padding. Every conversion between a quota
182/// and a packet count goes through this, so the two stay in step.
183pub const PIX_QUOTA_BYTES_PER_SHARE: SsaQuota = SESSION_MTU as SsaQuota;
184
185/// What a single SSA deposit buys: every Exit → Entry Session byte the cycle can carry.
186///
187/// Counts [`PixParams::emitted_shares_per_poly`], i.e. `threshold + surplus`, and not the threshold
188/// alone. A polynomial leaves the generator's queue only once it has emitted `threshold + surplus`
189/// shares (`SsaShareGenerator::next_share`), whether or not any were lost, and each share rides back
190/// on one Exit → Entry data packet — so this is exactly the traffic the Exit serves per cycle.
191/// Charging the threshold alone left the surplus unpaid, which at the deployed 3.47× factor is 71 %
192/// of all Exit → Entry traffic.
193///
194/// The surplus is insurance the Entry buys against share loss, and it is billed like insurance: on
195/// purchase, not on claim. One deposit per cycle at this rate is what makes paid-for equal served.
196///
197/// The other half of that equality lives in the generator's own tests
198/// (`drain_shares_by_polynomial` in `hopr-protocol-pix`), which pin a cycle's emission at
199/// `polys × (threshold + surplus)`. Change either expression and the other has to move with it.
200pub(crate) const fn pix_params_to_quota(params: &PixParams) -> SsaQuota {
201 params.polys_per_ssa() as SsaQuota * params.emitted_shares_per_poly() as SsaQuota * PIX_QUOTA_BYTES_PER_SHARE
202}
203
204/// Default number of polynomials ("SSA parts") a single SSA is split into.
205///
206/// This is the single source of truth for the Entry-side generator dimension
207/// (`PixGlobalConfig::num_ssa_parts`) and for the Exit-side acceptance policy
208/// ([`IncomingSessionPixConfig::quota_range`](crate::IncomingSessionPixConfig::quota_range)).
209/// Both must be derived from it so the two cannot drift apart: the Exit computes the
210/// offered quota as `polys × (shares + surplus) × SESSION_MTU` and rejects the Session if neither
211/// it nor an allowed dynamic batch brings the total inside the configured range. At the default
212/// batch ceiling of one, a hard-coded range that no longer matches the dimension defaults makes
213/// every PIX Session fail to establish.
214///
215/// ## Choosing the split
216///
217/// For a fixed useful-share count `U = polys × threshold` the *product* is pinned, so the split
218/// between the two is free — but the costs scale differently, and dropping the non-constant
219/// coefficient commitments (see [`hopr_protocol_pix::SsaPartCommitment`]) changed which way they
220/// pull:
221///
222/// * Commitment wire volume and Exit ingest are one commitment per polynomial — **linear in `polys`**, and formerly
223/// `polys × threshold`. Ingest is dominated by point decompression plus the cofactor-8 subgroup check.
224/// * Reconstructor commitment memory is likewise `polys`, no longer `U`.
225/// * Share verification is one scalar multiplication per *polynomial*, not `O(threshold)` per share. It used to be `U ×
226/// threshold` and is now simply `polys`.
227/// * Interpolating a polynomial is `O(threshold²)` field operations, and there are `polys` of them — `U × threshold`,
228/// **linear in `threshold`**, and it is field arithmetic rather than curve arithmetic.
229/// * Detection of a dishonest Entry takes `threshold` return packets, since a share set is only checked once it
230/// interpolates.
231/// * On the **Entry**, `SsaShareGenerator::next_share` evaluates a `threshold`-wide polynomial by Horner for every
232/// share it emits — `U × threshold` again. This is much the smaller of the two per-share terms, but it is not zero,
233/// and describing the Entry as threshold-free (as this list once did) is wrong.
234///
235/// So raising `threshold` (and lowering `polys`) buys a proportionally smaller commitment phase at
236/// the cost of more interpolation, later fault detection and more Entry evaluation.
237///
238/// Both sides have since been measured — see [`hopr_protocol_pix::DEFAULT_POLY_THRESHOLD`] for the
239/// tables. The objective is **Exit reconstruction capacity**, because the Exit serves 10–30 clients
240/// while an Entry serves only itself, and on that measure the Exit-only optimum sits around 54 and
241/// is flat within 0.5 % from 48 to 64. The deployed split has since moved below that, to 32, for a
242/// reason the cost model does not weigh: the surplus is a *ratio* of the threshold, so a lower
243/// threshold makes the 50 %-loss configuration cheaper in absolute quota even though it costs the
244/// Exit more per share. The tables there carry that reading.
245///
246/// The quota is fixed by `polys × (threshold + surplus)`, so the split can be re-tuned without
247/// touching session negotiation as long as that product holds.
248///
249/// ## Why this is an alias
250///
251/// The generator that produces the shares lives in `hopr-protocol-pix` and carries its own
252/// defaults, so the split existed as two independent literals — and they drifted: this side was
253/// re-tuned to `8192 × 64` while the pix crate stayed at a threshold of 128, which made
254/// [`hopr_protocol_pix::SsaGeneratorConfig::default`] imply a 1.01 GiB quota, outside the very
255/// range derived below. Four benchmarks had grown comments explaining which of the two to
256/// believe. Aliasing removes the choice.
257pub const DEFAULT_PIX_POLYS_PER_SSA: u16 = hopr_protocol_pix::DEFAULT_POLYS_PER_SSA;
258
259/// Default number of shares required to reconstruct a single SSA part.
260///
261/// See [`DEFAULT_PIX_POLYS_PER_SSA`] for why this is shared between both sides, why it is kept
262/// small relative to the polynomial count, and why it is an alias rather than a literal.
263pub const DEFAULT_PIX_SHARES_PER_POLY: u8 = hopr_protocol_pix::DEFAULT_POLY_THRESHOLD;
264
265/// Default number of shares emitted per SSA part beyond [`DEFAULT_PIX_SHARES_PER_POLY`].
266///
267/// An alias for the same reason as its two siblings, and with more riding on it than they have: the
268/// surplus is part of [`DEFAULT_PIX_SSA_QUOTA`], so a second, disagreeing default would not merely
269/// mis-describe a cycle — it would price one.
270pub const DEFAULT_PIX_SURPLUS_SHARES: u8 = hopr_protocol_pix::DEFAULT_SURPLUS_SHARES;
271
272/// The elliptic curve suite this build instantiates PIX over, as announced to peers.
273///
274/// A property of how the node was compiled — `pix-bjj` or `pix-secp256k1` on `hopr-crypto-packet`
275/// — not of its configuration, so it is read off the spec rather than named again here. Peers that
276/// disagree about it cannot exchange PIX commitments at all, because every curve-sized field on the
277/// wire changes width with it; announcing it is what turns that into a refused Session instead of
278/// undecodable traffic.
279pub const LOCAL_PIX_SUITE: hopr_protocol_pix::PixSuite = <HoprPixSpec as PixSpec>::PIX_SUITE;
280
281/// The three defaults and the local curve suite, as the single set both nodes must agree on.
282///
283/// The `match` is a compile-time range check: defaults that fall outside what
284/// [`PixParams::try_new`] accepts fail the build rather than every Session.
285pub(crate) const DEFAULT_PIX_PARAMS: PixParams = match PixParams::try_new(
286 DEFAULT_PIX_POLYS_PER_SSA,
287 DEFAULT_PIX_SHARES_PER_POLY,
288 DEFAULT_PIX_SURPLUS_SHARES,
289 LOCAL_PIX_SUITE,
290) {
291 Ok(params) => params,
292 Err(_) => panic!("default PIX dimensions must be within the protocol ranges"),
293};
294
295/// Nominal per-SSA data quota implied by the default PIX dimensions.
296///
297/// This is the amount of Exit → Entry data covered by a single SSA deposit when both
298/// nodes run the default PIX configuration.
299pub const DEFAULT_PIX_SSA_QUOTA: SsaQuota = pix_params_to_quota(&DEFAULT_PIX_PARAMS);
300
301/// Divisor applied to [`DEFAULT_PIX_SSA_QUOTA`] to obtain the lower bound of the default
302/// [`quota_range`](crate::IncomingSessionPixConfig::quota_range).
303///
304/// Preserves the 4× span the range had when its bounds were hard-coded.
305pub(crate) const DEFAULT_PIX_QUOTA_RANGE_SPAN: SsaQuota = 4;
306
307/// Representation of a data quota per SSA agreed upon during the Session establishment.
308///
309/// No longer `Copy`: [`deposit_data`](Self::deposit_data) owns its bytes.
310#[derive(Debug, Clone, PartialEq, Eq)]
311pub struct AgreedSsaQuota {
312 /// ID of the SSA.
313 pub ssa_id: SsaId<HoprPseudonym>,
314 /// Deposit address of the SSA.
315 pub deposit_address: <HoprPixSpec as PixSpec>::DepositAddress,
316 /// Quota of the SSA in bytes.
317 pub quota_per_ssa: SsaQuota,
318 /// Deposit data the pool produced for this SSA.
319 ///
320 /// Both nodes end up holding the same value by different routes: the Entry rebuilds it from the
321 /// `SsaRequest` it just decoded, the Exit recalls what it sent for this index. Empty when the pool
322 /// produced nothing for this SSA — the field is not optional, because a pool that has no deposit
323 /// data to attach and one that failed to attach it are the same thing to a reader, and
324 /// [`PixDepositData::is_empty`] already says which it is.
325 pub deposit_data: PixDepositData,
326}
327
328/// Events raised by the [`crate::manager::SessionManager`] in response to received PIX messages.
329#[derive(Debug)]
330pub enum HoprSessionOutPixEvent {
331 /// Event raised by the [`crate::manager::SessionManager`] of an Entry node can deposit funds to an SSA for the
332 /// agreed data quota.
333 ReadyToDeposit(AgreedSsaQuota),
334 /// Event raised by the [`crate::manager::SessionManager`] of an Exit node, whenever it knows a new SSA and expects
335 /// funds to be deposited.
336 ///
337 /// The attached sender is used to deliver updates once the deposit is completed.
338 DepositNeeded(AgreedSsaQuota, hopr_api::node::DepositUpdated),
339 /// Event raised by the [`crate::manager::SessionManager`] of an Exit node before it requests
340 /// commitments for a batch of SSAs, asking the deposit pool for the data to attach to them.
341 ///
342 /// The Exit waits [`DEPOSIT_DATA_REQUEST_TIMEOUT`](crate::DEPOSIT_DATA_REQUEST_TIMEOUT) for one
343 /// answer per requested id, and a shortfall is *fatal*: the SSA request fails with
344 /// [`MissingDepositData`](crate::errors::SessionManagerError::MissingDepositData) and the Session
345 /// is closed with [`ClosureReason::MissingDepositData`]. A pool with nothing to attach must
346 /// therefore answer with *empty* data rather than stay silent — empty is a value, silence is not.
347 ///
348 /// A listener that cannot answer at all should drop the attached sender: that ends the wait
349 /// immediately and fails the request now, whereas holding it costs every SSA request the full
350 /// timeout before failing anyway.
351 DepositDataRequest(hopr_api::node::PixDepositDataRequest),
352}
353
354/// Events received by the [`crate::manager::SessionManager`] in reaction to received shares from the packet pipeline.
355#[derive(Debug, Clone)]
356pub enum HoprSessionInPixEvent {
357 /// Informs the [`crate::manager::SessionManager`] that an SSA was fully recovered.
358 SsaRecovered(SsaId<HoprPseudonym>),
359 /// Informs the [`crate::manager::SessionManager`] that the early recovery threshold was reached
360 /// for an SSA — the next SSA request can be made.
361 SsaAlmostRecovered(SsaId<HoprPseudonym>),
362 /// Informs the [`crate::manager::SessionManager`] that unverifiable shares were encountered.
363 ///
364 /// Carries the reconstructor's running total for the SSA rather than a delta: shares for one
365 /// cycle reach the Exit over whichever return path is available, so no single relayer's count is
366 /// the whole story, and an absolute total makes a duplicated or reordered report harmless.
367 UnverifiableShares {
368 ssa_id: SsaId<HoprPseudonym>,
369 observed_total: u64,
370 /// Relayer that carried the offending share, for attribution in the close log.
371 peer: OffchainPublicKey,
372 },
373 /// Reports how far an SSA has got towards recovery.
374 ///
375 /// Unlike the others this is paced by traffic rather than by lifecycle transitions, and it is
376 /// what keeps a funded Session's egress flowing — the gate stops serving a cycle that shows no
377 /// progress. Delivered without backpressure for that reason; see
378 /// `SessionPixSupervisorHandle::try_send_progress`.
379 RecoveryProgress(SsaRecoveryProgress<HoprPseudonym>),
380}
381
382impl HoprSessionInPixEvent {
383 /// Extracts the pseudonym of the SSA that might map to an existing Session.
384 pub fn pseudonym(&self) -> &HoprPseudonym {
385 match self {
386 HoprSessionInPixEvent::SsaRecovered(ssa_id) => ssa_id.pseudonym(),
387 HoprSessionInPixEvent::SsaAlmostRecovered(ssa_id) => ssa_id.pseudonym(),
388 HoprSessionInPixEvent::UnverifiableShares { ssa_id, .. } => ssa_id.pseudonym(),
389 HoprSessionInPixEvent::RecoveryProgress(progress) => progress.ssa_id.pseudonym(),
390 }
391 }
392}
393
394/// Constant application tag used for all sessions.
395/// Previously tags were dynamically allocated per session.
396pub const SESSION_APPLICATION_TAG: Tag = Tag::Reserved(ReservedTag::Session as u64);
397
398/// [`SessionId`], [`ServiceId`], and [`SessionTarget`] are provided by `hopr-types` and
399/// re-exported here via `hopr-utils`, so they match the published `hopr-api` session types.
400///
401/// - `SessionId` is a type alias for `HoprPseudonym` (a constant application tag is used for all sessions instead
402/// of dynamically allocating tags).
403/// - `ServiceId` identifies a service local to the Exit node (e.g. Cover Traffic).
404/// - `SessionTarget` describes where data received over the session is forwarded.
405pub use hopr_utils::network_types::types::{ServiceId, SessionId, SessionTarget};
406
407pub(crate) fn caps_to_ack_mode(caps: Capabilities) -> AcknowledgementMode {
408 if caps.contains(Capability::RetransmissionAck | Capability::RetransmissionNack) {
409 AcknowledgementMode::Both
410 } else if caps.contains(Capability::RetransmissionAck) {
411 AcknowledgementMode::Full
412 } else {
413 AcknowledgementMode::Partial
414 }
415}
416
417/// Indicates the closure reason of a [`HoprSession`].
418///
419/// Delivered to the `on_close` callback a Session is constructed with — see
420/// [`HoprSession::new`] — and to the `SessionManager`'s closure notifier, so a caller has to be able
421/// to name this type to write either.
422#[derive(Clone, Copy, Debug, PartialEq, Eq, strum::Display)]
423pub enum ClosureReason {
424 /// Write-half of the Session has been closed.
425 WriteClosed,
426 /// Read-part of the Session has been closed (encountered empty read).
427 EmptyRead,
428 /// Session has been evicted from the cache due to inactivity or capacity reasons.
429 Eviction,
430 /// Deposit to an SSA has not been made on-time on a PIX-enabled Session.
431 UnrealizedDeposit,
432 /// The local deposit pool did not supply the deposit data an SSA batch needs.
433 ///
434 /// Exit-side and locally caused, unlike [`UnrealizedDeposit`](Self::UnrealizedDeposit) which is
435 /// the Entry failing to pay. Kept apart from it for exactly that reason: the two look alike from
436 /// the outside — a PIX Session that stopped — and point at opposite nodes.
437 MissingDepositData,
438 /// The PIX supervisor ended the Session — a recovery deadline elapsed, too many shares failed
439 /// verification, or the supervisor itself became unavailable.
440 ///
441 /// Distinct from [`UnrealizedDeposit`](Self::UnrealizedDeposit) and
442 /// [`MissingDepositData`](Self::MissingDepositData), which name the two PIX failures an operator
443 /// can act on directly; the rest are collapsed here and distinguished in telemetry by the
444 /// supervisor's own close reason.
445 PixFailure,
446}
447
448/// Helper trait to allow Box aliasing
449trait AsyncReadWrite: futures::AsyncWrite + futures::AsyncRead + Send + Unpin {}
450impl<T: futures::AsyncWrite + futures::AsyncRead + Send + Unpin> AsyncReadWrite for T {}
451
452/// Wrapper for an incoming [`HoprSession`] carrying the [`SessionId`] and [`SessionTarget`]
453/// extracted from the Start protocol during session establishment.
454///
455/// This is the published generic [`hopr_api::node::IncomingSession`] specialized to the
456/// concrete [`HoprSession`] byte-stream.
457pub type IncomingSession = hopr_api::node::IncomingSession<HoprSession>;
458
459/// Where a [`SessionAdmissionRequest`](hopr_api::node::SessionAdmissionRequest)'s answer is delivered.
460///
461/// The error is a string rather than the session server's own type because that type is chosen by
462/// whoever installs the server and is unnameable from here — the same erasure the session-server
463/// wiring already performs when it logs a processing failure. The message is for the Exit's own
464/// operator; the peer is told only [`StartErrorReason::TargetNotAdmitted`].
465///
466/// [`StartErrorReason::TargetNotAdmitted`]: hopr_protocol_start::StartErrorReason::TargetNotAdmitted
467pub type SessionAdmissionReply =
468 futures::channel::oneshot::Sender<Result<hopr_api::node::SessionAdmissionDecision, String>>;
469
470/// How the [`SessionManager`](crate::SessionManager) reaches whoever decides admission.
471///
472/// Bounded, and deliberately so: an unanswered request is a refused Session rather than an
473/// unbounded queue of peers waiting on a session server that has stopped keeping up.
474pub type SessionAdmissionSink =
475 futures::channel::mpsc::Sender<(hopr_api::node::SessionAdmissionRequest, SessionAdmissionReply)>;
476
477/// Names one admission of a pseudonym into the SURB store's admitted class.
478///
479/// A pseudonym is client-chosen and freely reusable, so successive Sessions can be established on
480/// the same one, and the store's admitted class holds at most one ring per pseudonym. The token is
481/// what lets a [`retire`](SurbAdmissionControl::retire) be matched to the admission it belongs to:
482/// [`admit`](SurbAdmissionControl::admit) returns a fresh token each time it is called, and a
483/// retire whose token no longer names the pseudonym's current admission is a no-op. Without that
484/// match, a teardown that deferred its retire past the packet pipeline's SURB-resolution window
485/// could invalidate a *successor* Session's already-admitted ring, silently degrading its return
486/// path (hoprnet#8515).
487///
488/// The value is opaque on purpose: callers thread it from `admit` to `retire` without reading it,
489/// so the store is free to change how admissions are numbered.
490#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
491pub struct AdmissionToken(u64);
492
493impl AdmissionToken {
494 /// The token of an admission that never happened.
495 ///
496 /// Stores must never issue this value, so a retire carrying it matches nothing: it is what a
497 /// teardown of a Session that was never committed — hence never admitted — passes through the
498 /// seam, keeping every teardown wired to the same path without inventing a retire that could
499 /// match a live admission.
500 pub const NONE: Self = Self(0);
501
502 /// Wraps the store's raw admission number back into a token.
503 ///
504 /// For the composition root bridging the two trait families: the store side deals in raw
505 /// numbers, this crate in opaque tokens.
506 pub const fn from_raw(raw: u64) -> Self {
507 Self(raw)
508 }
509
510 /// The store's raw admission number this token wraps.
511 pub const fn into_raw(self) -> u64 {
512 self.0
513 }
514}
515
516/// Hands a [`SessionId`] in and out of the SURB store's admission classes.
517///
518/// Without it every SURB that arrives for a `Final` packet — including the ones an established
519/// Session legitimately depends on — lands in the un-admitted quarantine class, which caps
520/// pseudonyms at a few SURBs each and expires them quickly (hoprnet#8515). The manager calls
521/// [`admit`](SurbAdmissionControl::admit) at the point a Session becomes established — the slot
522/// guard's `commit`, not slot allocation, so that no peer is admitted before the Start handshake has
523/// authenticated it — and [`retire`](SurbAdmissionControl::retire) at every teardown point.
524///
525/// Declared here rather than in the SURB store's own crate because the two crates depend on each
526/// other the wrong way round: the store cannot name the session crate, and this crate cannot name
527/// `hopr-protocol-hopr`. `hopr-transport` is the only crate that sees both, so it supplies the
528/// implementation bridging the two. Both methods are expected to be cheap and non-blocking; the
529/// store side is idempotent, so a retire for a pseudonym that was never admitted is a no-op.
530///
531/// [`retire`](SurbAdmissionControl::retire) may run some time after the teardown that asked for it
532/// — the closing Session's own return-routed notification still needs its ring while the packet
533/// pipeline resolves the route — and is therefore matched against the token `admit` returned: it
534/// must be a no-op once `token` no longer names the pseudonym's current admission, because a
535/// successor Session can have been admitted on the same pseudonym in the meantime.
536pub trait SurbAdmissionControl: Send + Sync + 'static {
537 /// Admits `pseudonym` into the store's admitted class, sized for `expected_surbs`, and returns
538 /// the token naming this admission.
539 ///
540 /// `expected_surbs` is the Session's announced SURB buffer target, or the largest the node allows
541 /// when the Entry announced none; the store owns the headroom arithmetic and the floor, so a value
542 /// of `0` (target unknown) still yields a usable ring.
543 /// Calling this twice for the same pseudonym must not discard what the admitted ring already
544 /// holds, and invalidates the token the earlier admission returned.
545 fn admit(&self, pseudonym: &SessionId, expected_surbs: usize) -> AdmissionToken;
546 /// Returns `pseudonym` to the un-admitted class, on behalf of the admission `token` names.
547 ///
548 /// A no-op when `token` no longer names `pseudonym`'s current admission — a successor Session
549 /// was admitted in the meantime, and its ring is not this retire's to release. Idempotent.
550 fn retire(&self, pseudonym: &SessionId, token: AdmissionToken);
551
552 /// Widens the ring of the admission `token` names to fit a target `expected_surbs` announced
553 /// *after* establishment.
554 ///
555 /// The counterpart of [`admit`](Self::admit) for a target that changes mid-Session. A peer may
556 /// raise its SURB balancer target and say so in a keep-alive; the gnosis_vpn client ramps from a
557 /// ping tier to a main tier seconds after the Session opens (gnosis/gnosis_vpn#739). Without
558 /// this, the ring keeps the target the Session was admitted with, and every SURB minted toward
559 /// the larger one is evicted on arrival — under PIX, together with the share it carried.
560 ///
561 /// Like [`retire`](Self::retire), a `token` that no longer names the pseudonym's current
562 /// admission is a no-op: a successor Session's ring is not this announcement's to widen. Widening
563 /// must keep the resident SURBs and the admission number, so that the token the Session holds
564 /// still names its admission and its teardown still releases it.
565 ///
566 /// Defaults to a no-op, for implementations that do not size a per-Session ring.
567 fn raise_target(&self, _pseudonym: &SessionId, _token: AdmissionToken, _expected_surbs: usize) {}
568}
569
570/// Configures the Session protocol socket over HOPR.
571#[derive(Copy, Clone, Debug, PartialEq, Eq, smart_default::SmartDefault, serde::Serialize)]
572pub struct HoprSessionConfig {
573 /// Capabilities of the Session protocol socket.
574 ///
575 /// Default is no capabilities.
576 #[default(Capabilities::empty())]
577 pub capabilities: Capabilities,
578 /// Expected frame size of the Session protocol socket.
579 ///
580 /// Clamped to the socket's supported frame size range — see
581 /// [`session_frame_size`].
582 ///
583 /// Default is [`SESSION_MTU`], i.e. exactly one segment per frame.
584 #[default(SESSION_MTU)]
585 pub frame_mtu: usize,
586 /// Maximum amount of time an incomplete frame can be kept in the buffer.
587 ///
588 /// Default is 800 ms
589 #[default(Duration::from_millis(800))]
590 #[serde(with = "humantime_serde")]
591 pub frame_timeout: Duration,
592 /// Maximum number of segments to buffer in the downstream transport.
593 /// If 0 is given, the transport is unbuffered.
594 ///
595 /// Default is 0.
596 #[default(0)]
597 pub max_buffered_segments: usize,
598 /// Abandon the frame due next once this many later frames are waiting behind it.
599 ///
600 /// Head-of-line bound, distinct from [`Self::frame_timeout`]: that one waits for a frame that
601 /// may still arrive, this bounds how much already-received data is held while it waits. `None`
602 /// keeps the timeout as the only rule.
603 pub max_frames_behind_gap: Option<usize>,
604}
605
606/// Represents the Session protocol socket over HOPR.
607///
608/// This is essentially a HOPR-specific wrapper for [`ReliableSocket`] and [`UnreliableSocket`]
609/// Session protocol sockets.
610#[pin_project::pin_project]
611pub struct HoprSession {
612 id: SessionId,
613 span: tracing::Span,
614 #[pin]
615 inner: Box<dyn AsyncReadWrite>,
616 routing: DestinationRouting,
617 cfg: HoprSessionConfig,
618 on_close: Option<Box<dyn FnOnce(SessionId, ClosureReason) + Send + Sync>>,
619}
620
621pub(crate) const SESSION_SOCKET_CAPACITY: usize = 16384;
622
623impl HoprSession {
624 /// Creates a new HOPR Session.
625 ///
626 /// It builds an [`futures::io::AsyncRead`] + [`futures::io::AsyncWrite`] transport
627 /// from the given `hopr` interface and passing it to the appropriate [`UnreliableSocket`] or [`ReliableSocket`]
628 /// based on the given `capabilities`.
629 ///
630 /// The `on_close` closure can be optionally called when the Session has been closed via `poll_close`.
631 pub fn new<Tx, Rx>(
632 id: SessionId,
633 routing: DestinationRouting,
634 cfg: HoprSessionConfig,
635 hopr: (Tx, Rx),
636 on_close: Option<Box<dyn FnOnce(SessionId, ClosureReason) + Send + Sync>>,
637 ) -> Result<Self, TransportSessionError>
638 where
639 Tx: futures::Sink<(DestinationRouting, ApplicationDataOut)> + Send + Unpin + 'static,
640 Rx: futures::Stream<Item = ApplicationDataIn> + Send + Unpin + 'static,
641 Tx::Error: std::error::Error + Send + Sync,
642 {
643 Self::new_with_surb_state(id, routing, cfg, hopr, on_close, None, None, None)
644 }
645
646 /// Like [`new`](Self::new) but threads the SURB balancer state and the opt-in client-side
647 /// flow-control config. `flow_control` = the client's [`FlowControlConfig`] for this session
648 /// (`None` leaves it unpaced); `surb_mgmt` gives the window its anti-grief down-only SURB ceiling.
649 /// The entry (sending) side passes `Some(..)` for it; sites without them pass `None`.
650 ///
651 /// `loss_signal` is the Exit's handle on the frames its socket fails to reassemble: the socket
652 /// stamps it at every loss, so the Exit can react within seconds. It reaches only the sockets of
653 /// Sessions with [`Capability::Segmentation`] (a raw Session has no frames to lose); `None`
654 /// records nothing.
655 #[allow(clippy::too_many_arguments)]
656 pub fn new_with_surb_state<Tx, Rx>(
657 id: SessionId,
658 routing: DestinationRouting,
659 mut cfg: HoprSessionConfig,
660 hopr: (Tx, Rx),
661 on_close: Option<Box<dyn FnOnce(SessionId, ClosureReason) + Send + Sync>>,
662 surb_mgmt: Option<Arc<BalancerStateValues>>,
663 flow_control: Option<FlowControlConfig>,
664 loss_signal: Option<Arc<FrameLossSignal>>,
665 ) -> Result<Self, TransportSessionError>
666 where
667 Tx: futures::Sink<(DestinationRouting, ApplicationDataOut)> + Send + Unpin + 'static,
668 Rx: futures::Stream<Item = ApplicationDataIn> + Send + Unpin + 'static,
669 Tx::Error: std::error::Error + Send + Sync,
670 {
671 // Keep the same parent for socket workers and every later IO poll.
672 let span = tracing::debug_span!("session", session_id = %id);
673 let _entered = span.enter();
674 if cfg.capabilities.contains(Capability::Segmentation) {
675 let mut max_segments = (SeqIndicator::MAX + 1) as usize;
676 if cfg.capabilities.contains(Capability::RetransmissionAck)
677 || cfg.capabilities.contains(Capability::RetransmissionNack)
678 {
679 max_segments = max_segments
680 .min(SegmentRequest::<{ ApplicationData::PAYLOAD_SIZE }>::MAX_MISSING_SEGMENTS_PER_FRAME);
681 }
682 // Use the same effective frame size for the socket and its delivery accounting.
683 cfg.frame_mtu = session_frame_size::<{ ApplicationData::PAYLOAD_SIZE }>(cfg.frame_mtu, max_segments);
684 }
685 let routing_clone = routing.clone();
686
687 #[cfg(feature = "telemetry")]
688 let (session_id_write, session_id_read) = (id, id);
689
690 // Wrap the HOPR transport so that it appears as regular transport to the SessionSocket
691 let transport = DuplexIO(
692 AsyncWriteSink::<{ ApplicationData::PAYLOAD_SIZE }, _>(hopr.0.sink_map_err(std::io::Error::other).with(
693 move |buf: Box<[u8]>| {
694 #[cfg(feature = "telemetry")]
695 crate::telemetry::record_session_write(&session_id_write, buf.len());
696 // The Session protocol does not set any packet info on outgoing packets.
697 // However, the SessionManager on top usually overrides this.
698 futures::future::ready(
699 ApplicationData::new(SESSION_APPLICATION_TAG, buf.into_vec())
700 .map(|data| (routing_clone.clone(), ApplicationDataOut::with_no_packet_info(data)))
701 .map_err(std::io::Error::other),
702 )
703 },
704 )),
705 // The Session protocol ignores the packet info on incoming packets.
706 // It is typically SessionManager's job to interpret those.
707 hopr.1
708 .map(move |data| {
709 #[cfg(feature = "telemetry")]
710 crate::telemetry::record_session_read(&session_id_read, data.data.plain_text.len());
711 Ok::<_, std::io::Error>(data.data.plain_text)
712 })
713 .into_async_read(),
714 );
715
716 // Based on the requested capabilities, see if we should use the Session protocol
717 let inner: Box<dyn AsyncReadWrite> = if cfg.capabilities.contains(Capability::Segmentation) {
718 let socket_cfg = SessionSocketConfig {
719 frame_size: cfg.frame_mtu,
720 frame_timeout: cfg.frame_timeout,
721 capacity: SESSION_SOCKET_CAPACITY,
722 flush_immediately: cfg.capabilities.contains(Capability::NoDelay),
723 // Datagram-boundary preservation is stateless-only: the stateless branch below turns
724 // it on for `NoDelay` sessions. The reliable socket must never run in datagram mode
725 // (its NACK missing-segment bitmap cannot address the segments of an oversized
726 // datagram frame), so it keeps `NoDelay`'s buffering behavior only.
727 datagram: false,
728 max_buffered_segments: cfg.max_buffered_segments,
729 // Anti-bufferbloat bound; only meaningful when flow control is enabled, which is
730 // also where the honest clock that observes the resulting loss lives.
731 max_frame_age: flow_control.and_then(|c| c.max_frame_age),
732 // Head-of-line bound, and deliberately *not* gated on flow control the way
733 // `max_frame_age` is. The reasoning there runs backwards for this one: a session
734 // that can retransmit may still recover a missing frame, so waiting is
735 // productive, while a session without retransmission is waiting for something
736 // that is never coming and holds everything already received behind it. The
737 // sessions that need this bound most are exactly the ones flow control excludes.
738 max_frames_behind_gap: cfg.max_frames_behind_gap,
739 ..Default::default()
740 };
741
742 // Need to test the capabilities separately, because any Retransmission capability
743 // implies Segmentation, and therefore `is_disjoint` would fail
744 if cfg.capabilities.contains(Capability::RetransmissionAck)
745 || cfg.capabilities.contains(Capability::RetransmissionNack)
746 {
747 let fc = flow_control;
748
749 // TODO: update config values
750 let ack_cfg = AcknowledgementStateConfig {
751 // This is a very coarse assumption, that a single 3-hop packet
752 // takes on average 200 ms to deliver.
753 // We can no longer base this timeout on the number of hops because
754 // it is not known for SURB-based routing.
755 expected_packet_latency: Duration::from_millis(200),
756 mode: caps_to_ack_mode(cfg.capabilities),
757 backoff_base: 0.2,
758 max_incoming_frame_retries: 1,
759 // Under flow control the sender is paced to the SURB drain rate, so an un-acked
760 // frame is usually just a *delayed* ack on a temporarily-starved return path, not
761 // a genuine loss. The retry budget is a flow-control config knob (`frame_retries`,
762 // default 2 = original); a robust profile raises it so delayed frames recover
763 // instead of being abandoned (an abandoned frame leaves a gap → stream corruption).
764 // `.max(1)`: never drop the retry budget to 0 — an abandoned frame under
765 // reliable-mode flow control leaves a gap and corrupts the stream.
766 max_outgoing_frame_retries: fc.map(|c| c.frame_retries.max(1) as usize).unwrap_or(2),
767 // Retire an outgoing frame that is already too stale to be worth delivering,
768 // rather than spending the remaining retry budget on it.
769 max_frame_age: fc.and_then(|c| c.max_frame_age),
770 ..Default::default()
771 };
772
773 debug!(
774 ?socket_cfg,
775 ?ack_cfg,
776 flow_control = fc.is_some(),
777 "opening new stateful session socket"
778 );
779
780 // Opt-in client-side flow control: when enabled, install the honest-clock tap on the
781 // ack state and keep the paired clock to drive the paced writer.
782 let (ack_state, flow_control) = match fc {
783 Some(fc_cfg) => {
784 let meter = DeliveryMeter::default();
785 let ack_state = AcknowledgementState::<{ ApplicationData::PAYLOAD_SIZE }>::new(id, ack_cfg)
786 .with_delivery_tap(DeliveryTap::new(meter.clone(), cfg.frame_mtu));
787 let clock = DeliveryClock::new(meter, Some(ack_cfg.expected_packet_latency));
788 (ack_state, Some((fc_cfg, clock)))
789 }
790 None => (
791 AcknowledgementState::<{ ApplicationData::PAYLOAD_SIZE }>::new(id, ack_cfg),
792 None,
793 ),
794 };
795
796 let socket = ReliableSocket::new(
797 transport,
798 ack_state,
799 socket_cfg,
800 loss_signal,
801 #[cfg(feature = "telemetry")]
802 NoopTracker,
803 )?;
804
805 match flow_control {
806 Some((fc_cfg, clock)) => {
807 let surb_state = surb_mgmt
808 .clone()
809 .unwrap_or_else(|| Arc::new(BalancerStateValues::default()));
810 let supply = SurbSupply::new(surb_state, cfg.frame_mtu);
811 debug!(?fc_cfg, "wrapping session socket with paced flow-control writer");
812 Box::new(PacedWriter::new(socket, fc_cfg, clock, supply))
813 }
814 None => Box::new(socket),
815 }
816 } else {
817 // Stateless (unreliable) sockets support datagram-boundary preservation, driven by
818 // `NoDelay` (UDP-like framing). See `Capability::NoDelay`.
819 let socket_cfg = SessionSocketConfig {
820 datagram: cfg.capabilities.contains(Capability::NoDelay),
821 ..socket_cfg
822 };
823 debug!(?socket_cfg, "opening new stateless session socket");
824
825 Box::new(UnreliableSocket::<{ ApplicationData::PAYLOAD_SIZE }>::new_stateless(
826 id,
827 transport,
828 socket_cfg,
829 loss_signal,
830 #[cfg(feature = "telemetry")]
831 NoopTracker,
832 )?)
833 }
834 } else {
835 debug!("opening raw session socket");
836 Box::new(transport)
837 };
838
839 drop(_entered);
840 Ok(Self {
841 id,
842 span,
843 inner,
844 routing,
845 cfg,
846 on_close,
847 })
848 }
849
850 /// ID of this Session.
851 pub fn id(&self) -> &SessionId {
852 &self.id
853 }
854
855 /// Routing options used to deliver data.
856 pub fn routing(&self) -> &DestinationRouting {
857 &self.routing
858 }
859
860 /// Configuration of this Session.
861 pub fn config(&self) -> &HoprSessionConfig {
862 &self.cfg
863 }
864}
865
866impl std::fmt::Debug for HoprSession {
867 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
868 f.debug_struct("Session")
869 .field("id", &self.id)
870 .field("routing", &self.routing)
871 .finish_non_exhaustive()
872 }
873}
874
875impl futures::AsyncRead for HoprSession {
876 fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<std::io::Result<usize>> {
877 let this = self.project();
878 let _entered = this.span.enter();
879 let _poll = tracing::trace_span!("Session::poll_read").entered();
880 let read = futures::ready!(this.inner.poll_read(cx, buf))?;
881 if read == 0 {
882 tracing::trace!("hopr session empty read");
883 // Empty read signals end of the socket, notify if needed
884 if let Some(notifier) = this.on_close.take() {
885 tracing::trace!("notifying read half closure of session");
886 notifier(*this.id, ClosureReason::EmptyRead);
887 }
888 }
889 Poll::Ready(Ok(read))
890 }
891}
892
893impl futures::AsyncWrite for HoprSession {
894 fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<std::io::Result<usize>> {
895 let this = self.project();
896 let _entered = this.span.enter();
897 let _poll = tracing::trace_span!("Session::poll_write").entered();
898 this.inner.poll_write(cx, buf)
899 }
900
901 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
902 let this = self.project();
903 let _entered = this.span.enter();
904 let _poll = tracing::trace_span!("Session::poll_flush").entered();
905 this.inner.poll_flush(cx)
906 }
907
908 fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
909 let this = self.project();
910 let _entered = this.span.enter();
911 let _poll = tracing::trace_span!("Session::poll_close").entered();
912 futures::ready!(this.inner.poll_close(cx))?;
913 tracing::trace!("hopr session closed");
914
915 #[cfg(feature = "telemetry")]
916 crate::telemetry::set_session_state(this.id, crate::telemetry::SessionLifecycleState::Closing);
917
918 if let Some(notifier) = this.on_close.take() {
919 tracing::trace!("notifying write half closure of session");
920 notifier(*this.id, ClosureReason::WriteClosed);
921 }
922
923 Poll::Ready(Ok(()))
924 }
925}
926
927#[cfg(feature = "runtime-tokio")]
928impl tokio::io::AsyncRead for HoprSession {
929 fn poll_read(
930 mut self: Pin<&mut Self>,
931 cx: &mut Context<'_>,
932 buf: &mut tokio::io::ReadBuf<'_>,
933 ) -> Poll<std::io::Result<()>> {
934 let slice = buf.initialize_unfilled();
935 let n = std::task::ready!(futures::AsyncRead::poll_read(self.as_mut(), cx, slice))?;
936 buf.advance(n);
937 Poll::Ready(Ok(()))
938 }
939}
940
941#[cfg(feature = "runtime-tokio")]
942impl tokio::io::AsyncWrite for HoprSession {
943 fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize, std::io::Error>> {
944 futures::AsyncWrite::poll_write(self.as_mut(), cx, buf)
945 }
946
947 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), std::io::Error>> {
948 futures::AsyncWrite::poll_flush(self.as_mut(), cx)
949 }
950
951 fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), std::io::Error>> {
952 futures::AsyncWrite::poll_close(self.as_mut(), cx)
953 }
954}
955
956#[cfg(test)]
957mod tests {
958 use anyhow::Context;
959 use futures::{AsyncReadExt, AsyncWriteExt, FutureExt};
960 use hopr_api::types::{
961 crypto::prelude::*,
962 crypto_random::Randomizable,
963 internal::{prelude::HoprPseudonym, routing::RoutingOptions},
964 primitive::prelude::*,
965 };
966 use hopr_utils::network_types::prelude::SealedHost;
967
968 use super::*;
969
970 fn deposit_entry(session_id: &SessionId, ssa_index: u32, data: &[u8]) -> PixDepositData {
971 PixDepositData {
972 id: hopr_api::node::PixAddressId::new(
973 session_id,
974 hopr_protocol_pix::SsaIndex::new(ssa_index).expect("non-zero"),
975 ),
976 data: data.into(),
977 }
978 }
979
980 /// The pool answers a batch as a flat list, in whatever order it produced the entries, so the
981 /// transform has to key them itself — and pair each payload with the index its own `id` names,
982 /// not with the position it arrived in.
983 #[test]
984 fn deposit_data_for_batch_should_key_payloads_by_their_own_ssa_index() -> anyhow::Result<()> {
985 let session_id: SessionId = HoprPseudonym::random();
986 let batch = [
987 hopr_protocol_pix::SsaIndex::new(7).expect("non-zero"),
988 hopr_protocol_pix::SsaIndex::new(8).expect("non-zero"),
989 ];
990
991 // Deliberately not in batch order: nothing promises the channel delivers them sorted.
992 let out = deposit_data_for_batch(
993 &session_id,
994 &batch,
995 vec![
996 deposit_entry(&session_id, 8, b"eight"),
997 deposit_entry(&session_id, 7, b"seven"),
998 ],
999 )?;
1000
1001 assert_eq!(2, out.len());
1002 assert_eq!(
1003 Some(&HoprPixDepositPayload(b"seven".as_slice().into())),
1004 out.get(&batch[0])
1005 );
1006 assert_eq!(
1007 Some(&HoprPixDepositPayload(b"eight".as_slice().into())),
1008 out.get(&batch[1])
1009 );
1010
1011 Ok(())
1012 }
1013
1014 /// An answer must not be credited to an SSA it does not name, even when the index alone matches:
1015 /// a `PixAddressId` is the pseudonym *and* the index, and only both together identify the SSA.
1016 #[test]
1017 fn deposit_data_for_batch_should_drop_entries_outside_the_batch() -> anyhow::Result<()> {
1018 let session_id: SessionId = HoprPseudonym::random();
1019 let other_session: SessionId = HoprPseudonym::random();
1020 let batch = [hopr_protocol_pix::SsaIndex::new(7).expect("non-zero")];
1021
1022 let out = deposit_data_for_batch(
1023 &session_id,
1024 &batch,
1025 vec![
1026 // Right Session, index the batch does not contain.
1027 deposit_entry(&session_id, 9, b"not in batch"),
1028 // Right index, but belonging to another Session.
1029 deposit_entry(&other_session, 7, b"wrong session"),
1030 deposit_entry(&session_id, 7, b"good"),
1031 ],
1032 )?;
1033
1034 assert_eq!(1, out.len());
1035 assert_eq!(
1036 Some(&HoprPixDepositPayload(b"good".as_slice().into())),
1037 out.get(&batch[0])
1038 );
1039
1040 Ok(())
1041 }
1042
1043 /// An SSA with no answer fails the batch: the data only ever travels in the `SsaRequest` that
1044 /// carries the commitments, so an Entry that needed it would have no way to obtain it later.
1045 #[test]
1046 fn deposit_data_for_batch_should_reject_a_short_answer() -> anyhow::Result<()> {
1047 let session_id: SessionId = HoprPseudonym::random();
1048 let batch = [
1049 hopr_protocol_pix::SsaIndex::new(1).expect("non-zero"),
1050 hopr_protocol_pix::SsaIndex::new(2).expect("non-zero"),
1051 ];
1052
1053 // One of two answered.
1054 assert!(matches!(
1055 deposit_data_for_batch(&session_id, &batch, vec![deposit_entry(&session_id, 2, b"only one")]),
1056 Err(SessionManagerError::MissingDepositData(_))
1057 ));
1058
1059 // Nothing answered at all — the no-pool case.
1060 assert!(matches!(
1061 deposit_data_for_batch(&session_id, &batch, Vec::new()),
1062 Err(SessionManagerError::MissingDepositData(_))
1063 ));
1064
1065 // An entry that is present but *empty* is an answer, not an absence: a pool with nothing to
1066 // attach says so this way, and the batch travels.
1067 let out = deposit_data_for_batch(
1068 &session_id,
1069 &batch,
1070 vec![deposit_entry(&session_id, 1, b""), deposit_entry(&session_id, 2, b"")],
1071 )?;
1072 assert_eq!(2, out.len());
1073 assert!(out.values().all(|payload| payload.0.is_empty()));
1074
1075 Ok(())
1076 }
1077
1078 // --- PIX quota tests ---
1079
1080 /// The quota must count what the generator emits, not what the Exit needs to recover.
1081 ///
1082 /// This is one half of "paid-for equals served". The other half is
1083 /// `drain_shares_by_polynomial` in `hopr-protocol-pix`, which pins a cycle's emission at
1084 /// `polys × (threshold + surplus)` — the same expression. If one moves without the other, the
1085 /// Exit is either serving unpaid traffic or charging for traffic it never sends.
1086 #[test]
1087 fn quota_must_price_every_share_a_cycle_emits() -> anyhow::Result<()> {
1088 for (polys, threshold, surplus) in [(1u16, 2u8, 0u8), (8, 2, 2), (8192, 64, 32), (16192, 255, 255)] {
1089 let params = PixParams::try_new(polys, threshold, surplus, LOCAL_PIX_SUITE)?;
1090 assert_eq!(
1091 polys as u64 * (threshold as u64 + surplus as u64) * SESSION_MTU as u64,
1092 pix_params_to_quota(¶ms),
1093 "the quota must cover every share the cycle emits"
1094 );
1095 }
1096 Ok(())
1097 }
1098
1099 /// A non-zero surplus must cost something. Before it was priced, these two were equal — which
1100 /// is exactly the state this guards against returning to.
1101 #[test]
1102 fn a_surplus_must_raise_the_quota_above_the_threshold_alone() -> anyhow::Result<()> {
1103 let threshold_only = pix_params_to_quota(&PixParams::try_new(8192, 64, 0, LOCAL_PIX_SUITE)?);
1104 let with_surplus = pix_params_to_quota(&PixParams::try_new(8192, 64, 32, LOCAL_PIX_SUITE)?);
1105
1106 assert!(
1107 with_surplus > threshold_only,
1108 "a surplus of 32 must be charged for, got {with_surplus} against {threshold_only}"
1109 );
1110 assert_eq!(
1111 threshold_only * 3 / 2,
1112 with_surplus,
1113 "a surplus of half the threshold must cost half the threshold's quota again"
1114 );
1115
1116 // And the same, at the surplus this node actually defaults to — sized for a 50 % share loss
1117 // rather than the `threshold / 4` it used to be; see `hopr_protocol_pix::default_surplus_for`.
1118 let deployed = pix_params_to_quota(&DEFAULT_PIX_PARAMS);
1119 let deployed_factor = (DEFAULT_PIX_SHARES_PER_POLY as u64 + DEFAULT_PIX_SURPLUS_SHARES as u64) as f64
1120 / DEFAULT_PIX_SHARES_PER_POLY as f64;
1121 assert!(
1122 (deployed_factor - 3.46875).abs() < 1e-9,
1123 "the deployed surplus factor is {deployed_factor}x, expected 3.46875x"
1124 );
1125 // Compared against the same dimensions with no surplus, which is the property that matters:
1126 // the deployed surplus is charged for. The absolute figure moves with the deployed split, so
1127 // this cannot be stated against the 8192 x 64 literals above.
1128 let deployed_threshold_only = pix_params_to_quota(&PixParams::try_new(
1129 DEFAULT_PIX_POLYS_PER_SSA,
1130 DEFAULT_PIX_SHARES_PER_POLY,
1131 0,
1132 LOCAL_PIX_SUITE,
1133 )?);
1134 assert!(
1135 deployed > deployed_threshold_only,
1136 "the deployed quota {deployed} must exceed the surplus-free quota {deployed_threshold_only} at the same \
1137 dimensions"
1138 );
1139 Ok(())
1140 }
1141
1142 /// The defaults the Exit's `quota_range` is anchored on are the ones an Entry actually runs.
1143 #[test]
1144 fn default_quota_must_follow_the_default_dimensions() {
1145 assert_eq!(
1146 DEFAULT_PIX_POLYS_PER_SSA as u64
1147 * (DEFAULT_PIX_SHARES_PER_POLY as u64 + DEFAULT_PIX_SURPLUS_SHARES as u64)
1148 * SESSION_MTU as u64,
1149 DEFAULT_PIX_SSA_QUOTA
1150 );
1151 // Anchored on the derivation rather than on a restatement of it: the surplus depends on both
1152 // dimensions, so it is the derivation at *these* two that the quota must price.
1153 assert_eq!(
1154 DEFAULT_PIX_SURPLUS_SHARES,
1155 hopr_protocol_pix::default_surplus_for(DEFAULT_PIX_POLYS_PER_SSA, DEFAULT_PIX_SHARES_PER_POLY)
1156 );
1157 }
1158
1159 // --- ByteCapabilities tests ---
1160
1161 #[test]
1162 fn byte_capabilities_roundtrip_via_u8() -> anyhow::Result<()> {
1163 let flags: Capabilities = Capability::Segmentation.into();
1164 let caps = HoprSessionCapabilities::from(flags);
1165 let byte_val: u8 = caps.into();
1166 let restored = HoprSessionCapabilities::try_from(byte_val)?;
1167 assert_eq!(caps, restored);
1168 Ok(())
1169 }
1170
1171 #[test]
1172 fn byte_capabilities_invalid_bits_are_rejected() {
1173 // 0xFF has bits set that don't correspond to any Capability
1174 assert!(HoprSessionCapabilities::try_from(0xFF_u8).is_err());
1175 }
1176
1177 #[test]
1178 fn byte_capabilities_empty_is_zero() {
1179 let caps = HoprSessionCapabilities::from(Capabilities::empty());
1180 let byte_val: u8 = caps.into();
1181 assert_eq!(byte_val, 0);
1182 }
1183
1184 #[test]
1185 fn byte_capabilities_combined_flags() -> anyhow::Result<()> {
1186 let caps: Capabilities = Capability::Segmentation | Capability::NoRateControl;
1187 let byte_caps = HoprSessionCapabilities::from(caps);
1188 let byte_val: u8 = byte_caps.into();
1189 let restored = HoprSessionCapabilities::try_from(byte_val)?;
1190 assert_eq!(*restored.as_ref(), caps);
1191 Ok(())
1192 }
1193
1194 // --- caps_to_ack_mode tests ---
1195
1196 #[test]
1197 fn caps_to_ack_mode_both_when_ack_and_nack() {
1198 let caps: Capabilities = Capability::RetransmissionAck | Capability::RetransmissionNack;
1199 assert_eq!(caps_to_ack_mode(caps), AcknowledgementMode::Both);
1200 }
1201
1202 #[test]
1203 fn caps_to_ack_mode_full_when_only_ack() {
1204 let caps: Capabilities = Capability::RetransmissionAck.into();
1205 assert_eq!(caps_to_ack_mode(caps), AcknowledgementMode::Full);
1206 }
1207
1208 #[test]
1209 fn caps_to_ack_mode_partial_when_no_retransmission() {
1210 let caps: Capabilities = Capability::Segmentation.into();
1211 assert_eq!(caps_to_ack_mode(caps), AcknowledgementMode::Partial);
1212 }
1213
1214 #[test]
1215 fn caps_to_ack_mode_partial_when_empty() {
1216 assert_eq!(caps_to_ack_mode(Capabilities::empty()), AcknowledgementMode::Partial);
1217 }
1218
1219 #[test]
1220 fn caps_to_ack_mode_should_be_partial_when_only_nack() {
1221 let caps: Capabilities = Capability::RetransmissionNack.into();
1222 assert_eq!(caps_to_ack_mode(caps), AcknowledgementMode::Partial);
1223 }
1224
1225 // --- ClosureReason tests ---
1226
1227 #[test]
1228 fn closure_reason_display_values_are_stable() {
1229 let reasons = [
1230 ClosureReason::WriteClosed,
1231 ClosureReason::EmptyRead,
1232 ClosureReason::Eviction,
1233 ClosureReason::UnrealizedDeposit,
1234 ClosureReason::MissingDepositData,
1235 ClosureReason::PixFailure,
1236 ];
1237
1238 // The array above is hand-maintained, and a snapshot that silently stops covering a variant
1239 // is worse than no snapshot: it reads as a guarantee it no longer gives. `PixFailure` was
1240 // missing for exactly that reason. This match is exhaustive and wildcard-free, so adding a
1241 // variant to `ClosureReason` fails to compile *here*, which is where the array is.
1242 for reason in reasons {
1243 match reason {
1244 ClosureReason::WriteClosed
1245 | ClosureReason::EmptyRead
1246 | ClosureReason::Eviction
1247 | ClosureReason::UnrealizedDeposit
1248 | ClosureReason::MissingDepositData
1249 | ClosureReason::PixFailure => {}
1250 }
1251 }
1252
1253 insta::assert_debug_snapshot!(reasons);
1254 }
1255
1256 // --- HoprSessionConfig tests ---
1257
1258 #[test]
1259 fn hopr_session_config_default_snapshot() {
1260 let cfg = HoprSessionConfig::default();
1261 insta::assert_yaml_snapshot!(cfg);
1262 }
1263
1264 // --- SessionTarget tests ---
1265
1266 #[test]
1267 fn session_target_variants_debug_snapshot() -> anyhow::Result<()> {
1268 let targets: Vec<SessionTarget> = vec![
1269 SessionTarget::UdpStream(SealedHost::Plain(
1270 "127.0.0.1:8080".parse().context("parsing UDP target")?,
1271 )),
1272 SessionTarget::TcpStream(SealedHost::Plain("10.0.0.1:443".parse().context("parsing TCP target")?)),
1273 SessionTarget::ExitNode(42),
1274 ];
1275 insta::assert_debug_snapshot!(targets);
1276 Ok(())
1277 }
1278
1279 // --- SessionId edge cases ---
1280
1281 #[test]
1282 fn session_id_display_and_debug_should_be_identical() {
1283 let id = HoprPseudonym::random();
1284 assert_eq!(format!("{id}"), format!("{id:?}"));
1285 }
1286
1287 #[test]
1288 fn session_id_hash_eq_consistency() {
1289 use std::collections::HashSet;
1290 let pseudonym = HoprPseudonym::random();
1291 let id1: SessionId = pseudonym;
1292 let id2: SessionId = pseudonym;
1293 let id3: SessionId = HoprPseudonym::random();
1294
1295 let mut set = HashSet::new();
1296 set.insert(id1);
1297 assert!(set.contains(&id2));
1298 assert!(!set.contains(&id3), "different pseudonym should not be in the set");
1299 }
1300
1301 #[test]
1302 fn session_should_restore_its_span_on_each_io_poll() -> anyhow::Result<()> {
1303 use test_log::tracing_subscriber::{filter::LevelFilter, layer::SubscriberExt};
1304
1305 let subscriber = test_log::tracing_subscriber::registry().with(LevelFilter::DEBUG);
1306 tracing::subscriber::with_default(subscriber, || -> anyhow::Result<()> {
1307 let observed = Arc::new(parking_lot::Mutex::new(Vec::new()));
1308 let mut sessions = Vec::new();
1309 for _ in 0..2 {
1310 let writes = observed.clone();
1311 let reads = observed.clone();
1312 let id = HoprPseudonym::random();
1313 let sink = futures::sink::drain().with(move |_: (DestinationRouting, ApplicationDataOut)| {
1314 writes.lock().push(tracing::Span::current().id());
1315 futures::future::ready(Ok::<_, std::convert::Infallible>(()))
1316 });
1317 let stream = futures::stream::poll_fn(move |_| {
1318 reads.lock().push(tracing::Span::current().id());
1319 Poll::<Option<ApplicationDataIn>>::Pending
1320 });
1321 sessions.push(HoprSession::new(
1322 id,
1323 DestinationRouting::Return(id.into()),
1324 HoprSessionConfig {
1325 capabilities: Default::default(),
1326 ..Default::default()
1327 },
1328 (sink, stream),
1329 None,
1330 )?);
1331 }
1332 let unrelated = tracing::debug_span!("unrelated_poller");
1333 let _entered = unrelated.enter();
1334 let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
1335 // Interleave sessions, then re-poll the first after a Pending read.
1336 for index in [0, 1, 0] {
1337 let session = &mut sessions[index];
1338 let expected = session.span.id();
1339 assert_ne!(expected, unrelated.id());
1340 let before = observed.lock().len();
1341 assert!(futures::AsyncRead::poll_read(Pin::new(&mut *session), &mut cx, &mut [0]).is_pending());
1342 futures::executor::block_on(async {
1343 session.write_all(b"payload").await?;
1344 session.flush().await
1345 })?;
1346 let observed = observed.lock();
1347 assert!(
1348 observed.len() >= before + 2,
1349 "both read and write must reach the transport"
1350 );
1351 assert!(observed[before..].iter().all(|span| span == &expected));
1352 assert_eq!(
1353 tracing::Span::current().id(),
1354 unrelated.id(),
1355 "poll guards must exit on Pending and Ready"
1356 );
1357 }
1358 Ok(())
1359 })
1360 }
1361
1362 #[test]
1363 fn session_io_should_restore_context_on_pending_errors_and_close() -> anyhow::Result<()> {
1364 use test_log::tracing_subscriber::{filter::LevelFilter, layer::SubscriberExt};
1365
1366 #[derive(Clone, Copy)]
1367 enum Outcome {
1368 Pending,
1369 BrokenPipe,
1370 Ready,
1371 }
1372
1373 struct Probe {
1374 outcome: Outcome,
1375 observed: Arc<parking_lot::Mutex<Vec<Option<tracing::span::Id>>>>,
1376 }
1377
1378 impl Probe {
1379 fn poll<T>(&self, value: T) -> Poll<std::io::Result<T>> {
1380 self.observed.lock().push(tracing::Span::current().id());
1381 match self.outcome {
1382 Outcome::Pending => Poll::Pending,
1383 Outcome::BrokenPipe => Poll::Ready(Err(std::io::Error::new(
1384 std::io::ErrorKind::BrokenPipe,
1385 "test I/O failure",
1386 ))),
1387 Outcome::Ready => Poll::Ready(Ok(value)),
1388 }
1389 }
1390 }
1391
1392 impl futures::AsyncRead for Probe {
1393 fn poll_read(
1394 self: Pin<&mut Self>,
1395 _: &mut std::task::Context<'_>,
1396 _: &mut [u8],
1397 ) -> Poll<std::io::Result<usize>> {
1398 self.poll(0)
1399 }
1400 }
1401
1402 impl futures::AsyncWrite for Probe {
1403 fn poll_write(
1404 self: Pin<&mut Self>,
1405 _: &mut std::task::Context<'_>,
1406 buf: &[u8],
1407 ) -> Poll<std::io::Result<usize>> {
1408 self.poll(buf.len())
1409 }
1410
1411 fn poll_flush(self: Pin<&mut Self>, _: &mut std::task::Context<'_>) -> Poll<std::io::Result<()>> {
1412 self.poll(())
1413 }
1414
1415 fn poll_close(self: Pin<&mut Self>, _: &mut std::task::Context<'_>) -> Poll<std::io::Result<()>> {
1416 self.poll(())
1417 }
1418 }
1419
1420 tracing::subscriber::with_default(
1421 test_log::tracing_subscriber::registry().with(LevelFilter::DEBUG),
1422 || -> anyhow::Result<()> {
1423 for outcome in [Outcome::Pending, Outcome::BrokenPipe, Outcome::Ready] {
1424 let id = HoprPseudonym::random();
1425 let closed = Arc::new(parking_lot::Mutex::new(Vec::new()));
1426 let notifications = closed.clone();
1427 let mut session = HoprSession::new(
1428 id,
1429 DestinationRouting::Return(id.into()),
1430 HoprSessionConfig {
1431 capabilities: Default::default(),
1432 ..Default::default()
1433 },
1434 (futures::sink::drain(), futures::stream::pending()),
1435 Some(Box::new(move |id, reason| notifications.lock().push((id, reason)))),
1436 )?;
1437 let observed = Arc::new(parking_lot::Mutex::new(Vec::new()));
1438 session.inner = Box::new(Probe {
1439 outcome,
1440 observed: observed.clone(),
1441 });
1442 let unrelated = tracing::debug_span!("unrelated_poller");
1443 let _entered = unrelated.enter();
1444 let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
1445 let results = [
1446 futures::AsyncWrite::poll_write(Pin::new(&mut session), &mut cx, b"payload").map_ok(|_| ()),
1447 futures::AsyncWrite::poll_flush(Pin::new(&mut session), &mut cx),
1448 futures::AsyncWrite::poll_close(Pin::new(&mut session), &mut cx),
1449 futures::AsyncRead::poll_read(Pin::new(&mut session), &mut cx, &mut [0]).map_ok(|_| ()),
1450 ];
1451 for result in results {
1452 match outcome {
1453 Outcome::Pending => assert!(result.is_pending()),
1454 Outcome::BrokenPipe => assert!(
1455 matches!(result, Poll::Ready(Err(e)) if e.kind() == std::io::ErrorKind::BrokenPipe)
1456 ),
1457 Outcome::Ready => assert!(matches!(result, Poll::Ready(Ok(())))),
1458 }
1459 }
1460 assert_eq!(*observed.lock(), vec![session.span.id(); 4]);
1461 assert_eq!(tracing::Span::current().id(), unrelated.id());
1462 if matches!(outcome, Outcome::Ready) {
1463 assert_eq!(*closed.lock(), [(id, ClosureReason::WriteClosed)]);
1464 assert!(matches!(
1465 futures::AsyncWrite::poll_close(Pin::new(&mut session), &mut cx),
1466 Poll::Ready(Ok(()))
1467 ));
1468 assert_eq!(
1469 closed.lock().len(),
1470 1,
1471 "read EOF and repeated close must not notify twice"
1472 );
1473 } else {
1474 assert!(
1475 closed.lock().is_empty(),
1476 "Pending and errors must not report successful closure"
1477 );
1478 }
1479 }
1480 Ok(())
1481 },
1482 )
1483 }
1484
1485 // --- Existing tests ---
1486
1487 #[test_log::test(tokio::test)]
1488 async fn session_flow_control_should_use_effective_frame_size() -> anyhow::Result<()> {
1489 use hopr_protocol_session::types::{FrameAcknowledgements, SessionMessage};
1490
1491 let id = HoprPseudonym::random();
1492 let (mut incoming, rx) = futures::channel::mpsc::channel(1);
1493 let mut session = HoprSession::new_with_surb_state(
1494 id,
1495 DestinationRouting::Return(id.into()),
1496 HoprSessionConfig {
1497 capabilities: Capability::RetransmissionAck.into(),
1498 frame_mtu: 1, // The socket clamps this up to one full segment.
1499 ..Default::default()
1500 },
1501 (futures::sink::drain(), rx),
1502 None,
1503 None,
1504 Some(FlowControlConfig {
1505 min_window_size: SESSION_MTU,
1506 max_window_size: SESSION_MTU,
1507 ..Default::default()
1508 }),
1509 None,
1510 )?;
1511 let frame = vec![7u8; SESSION_MTU];
1512 session.write_all(&frame).await?;
1513 session.flush().await?;
1514
1515 let ack =
1516 SessionMessage::<{ ApplicationData::PAYLOAD_SIZE }>::Acknowledge(FrameAcknowledgements::try_from(vec![1])?);
1517 incoming
1518 .send(ApplicationDataIn {
1519 data: ApplicationData::new(SESSION_APPLICATION_TAG, ack.into_encoded().into_vec())?,
1520 packet_info: Default::default(),
1521 })
1522 .await?;
1523 // Process the acknowledgement; no application payload is available to read.
1524 assert!(session.read(&mut [0u8; 1]).now_or_never().is_none());
1525
1526 tokio::time::timeout(Duration::from_millis(100), session.write_all(&frame))
1527 .await
1528 .context("one frame acknowledgement must release a full frame's send window")??;
1529 assert_eq!(session.config().frame_mtu, SESSION_MTU);
1530 Ok(())
1531 }
1532
1533 #[test_log::test(tokio::test)]
1534 async fn test_session_bidirectional_flow_without_segmentation() -> anyhow::Result<()> {
1535 let dst: Address = (&ChainKeypair::random()).into();
1536 let id: SessionId = HoprPseudonym::random();
1537 const DATA_LEN: usize = 5000;
1538
1539 let (alice_tx, bob_rx) = futures::channel::mpsc::unbounded::<(DestinationRouting, ApplicationDataOut)>();
1540 let (bob_tx, alice_rx) = futures::channel::mpsc::unbounded::<(DestinationRouting, ApplicationDataOut)>();
1541
1542 let mut alice_session = HoprSession::new(
1543 id,
1544 DestinationRouting::forward_only(dst, RoutingOptions::Hops(0.try_into()?)),
1545 Default::default(),
1546 (
1547 alice_tx,
1548 alice_rx
1549 .map(|(_, data)| ApplicationDataIn {
1550 data: data.data,
1551 packet_info: Default::default(),
1552 })
1553 .inspect(|d| debug!("alice rcvd: {}", d.data.total_len())),
1554 ),
1555 None,
1556 )?;
1557
1558 let mut bob_session = HoprSession::new(
1559 id,
1560 DestinationRouting::Return(id.into()),
1561 Default::default(),
1562 (
1563 bob_tx,
1564 bob_rx
1565 .map(|(_, data)| ApplicationDataIn {
1566 data: data.data,
1567 packet_info: Default::default(),
1568 })
1569 .inspect(|d| debug!("bob rcvd: {}", d.data.total_len())),
1570 ),
1571 None,
1572 )?;
1573
1574 let alice_sent = hopr_api::types::crypto_random::random_bytes::<DATA_LEN>();
1575 let bob_sent = hopr_api::types::crypto_random::random_bytes::<DATA_LEN>();
1576
1577 let mut bob_recv = [0u8; DATA_LEN];
1578 let mut alice_recv = [0u8; DATA_LEN];
1579
1580 tokio::time::timeout(Duration::from_secs(1), alice_session.write_all(&alice_sent))
1581 .await
1582 .context("alice write failed")?
1583 .context("alice write timed out")?;
1584 alice_session.flush().await?;
1585
1586 tokio::time::timeout(Duration::from_secs(1), bob_session.write_all(&bob_sent))
1587 .await
1588 .context("bob write failed")?
1589 .context("bob write timed out")?;
1590 bob_session.flush().await?;
1591
1592 tokio::time::timeout(Duration::from_secs(1), bob_session.read_exact(&mut bob_recv))
1593 .await
1594 .context("bob read failed")?
1595 .context("bob read timed out")?;
1596
1597 tokio::time::timeout(Duration::from_secs(1), alice_session.read_exact(&mut alice_recv))
1598 .await
1599 .context("alice read failed")?
1600 .context("alice read timed out")?;
1601
1602 assert_eq!(&alice_sent, bob_recv.as_slice());
1603 assert_eq!(bob_sent, alice_recv);
1604
1605 Ok(())
1606 }
1607
1608 /// A loss signal passed to `new_with_surb_state` reaches the socket, and the socket records into it.
1609 ///
1610 /// This is the seam the Exit relies on: the manager creates the signal per Exit Session, hands it
1611 /// to the Session constructor, and the socket stamps it on every frame it fails to reassemble. A segment
1612 /// whose frame never completes is exactly that — the frame expires incomplete.
1613 #[test_log::test(tokio::test)]
1614 async fn a_passed_loss_signal_records_the_frames_the_socket_fails_to_reassemble() -> anyhow::Result<()> {
1615 use hopr_protocol_session::types::{Segment, SeqIndicator, SessionMessage};
1616
1617 let id: SessionId = HoprPseudonym::random();
1618 let signal = Arc::new(FrameLossSignal::new());
1619 let (mut incoming, rx) = futures::channel::mpsc::channel(4);
1620 let session = HoprSession::new_with_surb_state(
1621 id,
1622 DestinationRouting::Return(id.into()),
1623 HoprSessionConfig {
1624 capabilities: Capability::Segmentation.into(),
1625 // Three segments per frame, of which only the first ever arrives.
1626 frame_mtu: 3 * SESSION_MTU,
1627 frame_timeout: Duration::from_millis(100),
1628 ..Default::default()
1629 },
1630 (futures::sink::drain(), rx),
1631 None,
1632 None,
1633 None,
1634 Some(signal.clone()),
1635 )?;
1636
1637 assert_eq!(0, signal.lost_total(), "nothing lost before anything arrived");
1638 incoming
1639 .send(ApplicationDataIn {
1640 data: ApplicationData::new(
1641 SESSION_APPLICATION_TAG,
1642 SessionMessage::<{ ApplicationData::PAYLOAD_SIZE }>::Segment(Segment {
1643 frame_id: 1,
1644 seq_idx: 0,
1645 // One segment of a three-segment frame: the other two never arrive.
1646 seq_flags: SeqIndicator::new_with_flags(3, false),
1647 data: vec![0u8; SESSION_MTU].into_boxed_slice(),
1648 })
1649 .into_encoded()
1650 .into_vec(),
1651 )?,
1652 packet_info: Default::default(),
1653 })
1654 .await?;
1655
1656 // The frame expires incomplete, which is the loss the signal exists to carry.
1657 let mut buf = [0u8; SESSION_MTU];
1658 let mut session = session;
1659 let _ = tokio::time::timeout(Duration::from_secs(2), session.read(&mut buf)).await;
1660 assert!(
1661 signal.lost_total() > 0,
1662 "a frame that expired incomplete must be recorded in the signal passed to the socket"
1663 );
1664 assert!(signal.lost_within(Duration::from_secs(5)));
1665 Ok(())
1666 }
1667
1668 #[test_log::test(tokio::test)]
1669 async fn test_session_bidirectional_flow_with_segmentation() -> anyhow::Result<()> {
1670 let dst: Address = (&ChainKeypair::random()).into();
1671 let id: SessionId = HoprPseudonym::random();
1672 const DATA_LEN: usize = 5000;
1673
1674 let (alice_tx, bob_rx) = futures::channel::mpsc::unbounded::<(DestinationRouting, ApplicationDataOut)>();
1675 let (bob_tx, alice_rx) = futures::channel::mpsc::unbounded::<(DestinationRouting, ApplicationDataOut)>();
1676
1677 let mut alice_session = HoprSession::new(
1678 id,
1679 DestinationRouting::forward_only(dst, RoutingOptions::Hops(0.try_into()?)),
1680 HoprSessionConfig {
1681 capabilities: Capability::Segmentation.into(),
1682 ..Default::default()
1683 },
1684 (
1685 alice_tx,
1686 alice_rx
1687 .map(|(_, data)| ApplicationDataIn {
1688 data: data.data,
1689 packet_info: Default::default(),
1690 })
1691 .inspect(|d| debug!("alice rcvd: {}", d.data.total_len())),
1692 ),
1693 None,
1694 )?;
1695
1696 let mut bob_session = HoprSession::new(
1697 id,
1698 DestinationRouting::Return(id.into()),
1699 HoprSessionConfig {
1700 capabilities: Capability::Segmentation.into(),
1701 ..Default::default()
1702 },
1703 (
1704 bob_tx,
1705 bob_rx
1706 .map(|(_, data)| ApplicationDataIn {
1707 data: data.data,
1708 packet_info: Default::default(),
1709 })
1710 .inspect(|d| debug!("bob rcvd: {}", d.data.total_len())),
1711 ),
1712 None,
1713 )?;
1714
1715 let alice_sent = hopr_api::types::crypto_random::random_bytes::<DATA_LEN>();
1716 let bob_sent = hopr_api::types::crypto_random::random_bytes::<DATA_LEN>();
1717
1718 let mut bob_recv = [0u8; DATA_LEN];
1719 let mut alice_recv = [0u8; DATA_LEN];
1720
1721 tokio::time::timeout(Duration::from_secs(1), alice_session.write_all(&alice_sent))
1722 .await
1723 .context("alice write failed")?
1724 .context("alice write timed out")?;
1725 alice_session.flush().await?;
1726
1727 tokio::time::timeout(Duration::from_secs(1), bob_session.write_all(&bob_sent))
1728 .await
1729 .context("bob write failed")?
1730 .context("bob write timed out")?;
1731 bob_session.flush().await?;
1732
1733 tokio::time::timeout(Duration::from_secs(1), bob_session.read_exact(&mut bob_recv))
1734 .await
1735 .context("bob read failed")?
1736 .context("bob read timed out")?;
1737
1738 tokio::time::timeout(Duration::from_secs(1), alice_session.read_exact(&mut alice_recv))
1739 .await
1740 .context("alice read failed")?
1741 .context("alice read timed out")?;
1742
1743 assert_eq!(alice_sent, bob_recv);
1744 assert_eq!(bob_sent, alice_recv);
1745
1746 Ok(())
1747 }
1748}