Skip to main content

hopr_transport/
config.rs

1use std::{
2    fmt::{Display, Formatter},
3    net::ToSocketAddrs,
4    num::ParseIntError,
5    str::FromStr,
6    time::Duration,
7};
8
9use hopr_api::Multiaddr;
10pub use hopr_protocol_hopr::{
11    HoprCodecConfig, HoprUnacknowledgedTicketProcessorConfig, ReplayFilterConfig, SurbPopOrder, SurbStoreConfig,
12};
13use hopr_protocol_pix::SsaReconstructorConfig;
14pub use hopr_transport_mixer::config::MixerConfig;
15pub use hopr_transport_probe::config::ProbeConfig;
16use hopr_transport_session::{
17    DEFAULT_MAX_SSAS_PER_SSA_REQUEST, DEFAULT_PIX_POLYS_PER_SSA, DEFAULT_PIX_SHARES_PER_POLY, IncomingSessionPixConfig,
18    MAX_ASSUMED_SESSION_PACKET_RATE, MIN_BALANCER_SAMPLING_INTERVAL, MIN_REFUSAL_REPLY_REFILL_PERIOD,
19    MIN_SURB_BUFFER_DURATION, RefusalReplyBudget,
20};
21use proc_macro_regex::regex;
22use validator::{Validate, ValidationError, ValidationErrors};
23
24use crate::{errors::HoprTransportError, protocol::PacketPipelineConfig};
25
26const DEFAULT_COUNTER_FLUSH_INTERVAL: Duration = Duration::from_secs(15);
27
28const DEFAULT_PER_PEER_CHANNEL_CAPACITY: usize = 5_000;
29const DEFAULT_STREAM_OPEN_TIMEOUT: Duration = Duration::from_secs(2);
30const DEFAULT_FRAME_WRITER_BACKPRESSURE_BYTES: usize = 131_072;
31const DEFAULT_EGRESS_BACKPRESSURE_TIMEOUT: Duration = Duration::from_secs(2);
32
33/// Minimum accepted value for [`StreamProtocolConfig::stream_open_timeout`].
34pub const MIN_STREAM_OPEN_TIMEOUT: Duration = Duration::from_millis(1);
35
36/// Minimum accepted value for [`StreamProtocolConfig::egress_backpressure_timeout`].
37pub const MIN_EGRESS_BACKPRESSURE_TIMEOUT: Duration = Duration::from_millis(1);
38
39fn default_per_peer_channel_capacity() -> usize {
40    DEFAULT_PER_PEER_CHANNEL_CAPACITY
41}
42
43fn default_stream_open_timeout() -> Duration {
44    DEFAULT_STREAM_OPEN_TIMEOUT
45}
46
47fn default_frame_writer_backpressure_bytes() -> usize {
48    DEFAULT_FRAME_WRITER_BACKPRESSURE_BYTES
49}
50
51#[inline]
52fn default_egress_backpressure_timeout() -> Duration {
53    DEFAULT_EGRESS_BACKPRESSURE_TIMEOUT
54}
55
56fn validate_stream_open_timeout(value: &Duration) -> Result<(), ValidationError> {
57    if MIN_STREAM_OPEN_TIMEOUT <= *value {
58        Ok(())
59    } else {
60        Err(ValidationError::new("stream open timeout must be at least 1 ms"))
61    }
62}
63
64fn validate_egress_backpressure_timeout(value: &Duration) -> Result<(), ValidationError> {
65    if MIN_EGRESS_BACKPRESSURE_TIMEOUT <= *value {
66        Ok(())
67    } else {
68        // A zero (or sub-millisecond) timeout would make every full channel fall straight into
69        // drop-newest, silently defeating the backpressure feature — reject it at config time.
70        Err(ValidationError::new(
71            "egress backpressure timeout must be at least 1 ms",
72        ))
73    }
74}
75
76/// Configuration of the per-peer egress stream layer.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Validate, smart_default::SmartDefault)]
78#[cfg_attr(
79    feature = "serde",
80    derive(serde::Serialize, serde::Deserialize),
81    serde(deny_unknown_fields)
82)]
83pub struct StreamProtocolConfig {
84    /// Capacity of the per-peer egress channel (in packets).
85    ///
86    /// The egress drain enqueues each outgoing packet via `try_send`. When the
87    /// channel is full the behaviour depends on the stream state: while the stream
88    /// is still opening it drops the newest packet (a slow open for one peer must
89    /// not head-of-line-block others); once the stream is open and its write pump
90    /// is draining, it instead applies bounded backpressure — waiting up to
91    /// `EGRESS_BACKPRESSURE_TIMEOUT` for space so wire-rate backpressure propagates
92    /// upstream — and only drops the newest packet if the peer stays full past that
93    /// timeout. The channel absorbs bursts while a stream is being opened; once open
94    /// the write pump continuously drains it, so it stays near-empty under normal load.
95    ///
96    /// Sized to absorb a typical SURB pre-fill burst (default SurbBalancer:
97    /// target 7 000 / max 5 000/s).
98    ///
99    /// When the per-peer channel is full, the egress drain drops the newest
100    /// packet (drop-newest) for both open and still-opening streams. The mixer's
101    /// hard capacity bound (`MixerConfig::capacity`) provides the upstream
102    /// backpressure layer, so this drop is a rate-limiting measure that prevents
103    /// one congested peer from head-of-line-blocking the shared drain loop.
104    ///
105    /// Defaults to 5 000.
106    #[validate(range(min = 1))]
107    #[default(default_per_peer_channel_capacity())]
108    #[cfg_attr(feature = "serde", serde(default = "default_per_peer_channel_capacity"))]
109    pub per_peer_channel_capacity: usize,
110
111    /// Timeout for the `NetworkStreamControl::open` call when opening a new
112    /// outgoing stream to a peer.
113    ///
114    /// A timeout is mandatory: without it a permanently-unreachable peer would park
115    /// the opener task indefinitely. When the open attempt fails or times out the
116    /// buffered packets for that peer are dropped and a debug-level log entry is
117    /// emitted. The cache entry is then invalidated so the next send triggers a
118    /// fresh open attempt.
119    ///
120    /// Must be at least 1 ms. Defaults to 2 seconds.
121    #[validate(custom(function = "validate_stream_open_timeout"))]
122    #[default(default_stream_open_timeout())]
123    #[cfg_attr(
124        feature = "serde",
125        serde(default = "default_stream_open_timeout", with = "humantime_serde")
126    )]
127    pub stream_open_timeout: Duration,
128
129    /// Pending-write-buffer byte threshold on the framed writer before a flush is forced.
130    ///
131    /// A value of `1` flushes on every encoded frame (one syscall per message).
132    /// Larger values coalesce adjacent small frames into a single quinn write call,
133    /// reducing connection-mutex acquisitions and driver wake-ups on the hot path.
134    /// A HOPR packet is ~1 440 bytes; at the default 128 KiB threshold roughly 91
135    /// packets are coalesced per write, cutting driver wake frequency ~30×.
136    ///
137    /// Defaults to 131 072 bytes (128 KiB).
138    #[validate(range(min = 1))]
139    #[default(default_frame_writer_backpressure_bytes())]
140    #[cfg_attr(feature = "serde", serde(default = "default_frame_writer_backpressure_bytes"))]
141    pub frame_writer_backpressure_bytes: usize,
142
143    /// Write-pump stall timeout for a per-peer egress channel.
144    ///
145    /// If the pump feeding a peer's QUIC stream makes no write progress for this long (the remote
146    /// stopped reading, parking quinn's `poll_write` forever), the pump fails and its cache entry
147    /// is evicted so the next send reopens the stream rather than parking the shared drain loop.
148    /// This prevents one stalled peer from head-of-line-blocking other peers indefinitely.
149    /// Previously this timeout also governed an inline backpressure wait in the shared egress
150    /// drain (replaced by drop-newest at the egress, with upstream backpressure from the mixer's
151    /// hard capacity bound).
152    ///
153    /// Defaults to 2 seconds. Must be at least 1 ms.
154    #[validate(custom(function = "validate_egress_backpressure_timeout"))]
155    #[default(default_egress_backpressure_timeout())]
156    #[cfg_attr(feature = "serde", serde(default = "default_egress_backpressure_timeout"))]
157    pub egress_backpressure_timeout: Duration,
158}
159
160fn default_counter_flush_interval() -> Duration {
161    DEFAULT_COUNTER_FLUSH_INTERVAL
162}
163
164/// How often SURB round-trip counts reach the network graph.
165///
166/// Much shorter than the protocol counter flush, which is the same order as the recovery window
167/// this signal exists to shorten -- evidence about a dead relayer sitting unreported for 15 s would
168/// defeat the point. Still well inside the graph's own bucket width, so batching adds no
169/// distortion while cutting graph write locks by orders of magnitude.
170const DEFAULT_SURB_FLUSH_INTERVAL: Duration = Duration::from_secs(1);
171
172fn default_surb_flush_interval() -> Duration {
173    DEFAULT_SURB_FLUSH_INTERVAL
174}
175
176/// Simulated per-packet transit latency inserted between the mixer and the wire.
177///
178/// When set on a node's config, every packet emitted by the mixer is held for a
179/// Gaussian-jittered delay before being forwarded to the transport layer.  The delay
180/// is **FIFO** (packets are never reordered): the release deadline is `max(prev_deadline,
181/// now) + sample`, so back-to-back bursts accumulate a monotonically non-decreasing
182/// offset rather than reordering.
183///
184/// **Intended for testing only** — simulates WAN-link transit latency (e.g. ~50 ms) in
185/// a local cluster.  Defaults to `None` (disabled; zero production overhead).
186#[derive(Debug, Clone, Copy, PartialEq, Eq, smart_default::SmartDefault)]
187#[cfg_attr(
188    feature = "serde",
189    derive(serde::Serialize, serde::Deserialize),
190    serde(deny_unknown_fields)
191)]
192pub struct TransitLatencyConfig {
193    /// Mean transit latency per packet.
194    #[default(Duration::from_millis(50))]
195    #[cfg_attr(feature = "serde", serde(with = "humantime_serde"))]
196    pub mean: Duration,
197    /// Standard deviation of the transit latency.
198    ///
199    /// Set to zero for a deterministic (fixed) delay equal to `mean`.
200    #[default(Duration::from_millis(5))]
201    #[cfg_attr(feature = "serde", serde(with = "humantime_serde"))]
202    pub std_dev: Duration,
203}
204
205/// Complete configuration of the HOPR protocol stack.
206#[derive(Debug, smart_default::SmartDefault, Validate, Clone, PartialEq)]
207#[cfg_attr(
208    feature = "serde",
209    derive(serde::Serialize, serde::Deserialize),
210    serde(deny_unknown_fields)
211)]
212#[validate(schema(function = "validate_pix_supervision_pairing", skip_on_field_errors = false))]
213pub struct HoprProtocolConfig {
214    /// Libp2p-related transport configuration
215    #[validate(nested)]
216    #[cfg_attr(feature = "serde", serde(default))]
217    pub transport: TransportConfig,
218    /// HOPR packet pipeline configuration
219    #[validate(nested)]
220    #[cfg_attr(feature = "serde", serde(default))]
221    pub packet: HoprPacketPipelineConfig,
222    /// Probing protocol configuration
223    #[validate(nested)]
224    #[cfg_attr(feature = "serde", serde(default))]
225    pub probe: ProbeConfig,
226    /// Session protocol global configuration
227    #[validate(nested)]
228    #[cfg_attr(feature = "serde", serde(default))]
229    pub session: SessionGlobalConfig,
230    /// Global configuration for the PIX.
231    #[validate(nested)]
232    #[cfg_attr(feature = "serde", serde(default))]
233    pub pix: PixGlobalConfig,
234    /// Per-node PIX session configuration for incoming sessions.
235    #[validate(custom(function = "validate_incoming_session_pix_config"))]
236    #[cfg_attr(feature = "serde", serde(default))]
237    pub incoming_session_pix_config: IncomingSessionPixConfig,
238    /// Mixer configuration.
239    #[validate(nested)]
240    #[cfg_attr(feature = "serde", serde(default))]
241    pub mixer: MixerConfig,
242    /// Simulated transit latency shim between the mixer output and the wire.
243    ///
244    /// When `Some`, a Gaussian-jittered FIFO delay is inserted before every forwarded
245    /// packet — simulating WAN-link transit time in a local cluster test run.
246    /// Set `None` (the default) in production: zero overhead.
247    #[cfg_attr(feature = "serde", serde(default))]
248    pub transit_latency: Option<TransitLatencyConfig>,
249    /// Per-peer egress stream configuration
250    #[validate(nested)]
251    #[cfg_attr(feature = "serde", serde(default))]
252    pub stream: StreamProtocolConfig,
253    /// Path planner configuration
254    #[validate(nested)]
255    #[cfg_attr(feature = "serde", serde(default))]
256    pub path_planner: crate::path::PathPlannerConfig,
257    /// Interval at which per-peer protocol conformance counters are flushed
258    /// into the network graph.
259    ///
260    /// Default is 15 seconds.
261    #[default(default_counter_flush_interval())]
262    #[cfg_attr(
263        feature = "serde",
264        serde(default = "default_counter_flush_interval", with = "humantime_serde")
265    )]
266    pub counter_flush_interval: Duration,
267    /// Interval at which SURB round-trip counts are flushed into the network graph.
268    ///
269    /// Default is 1 second.
270    #[default(default_surb_flush_interval())]
271    #[cfg_attr(
272        feature = "serde",
273        serde(default = "default_surb_flush_interval", with = "humantime_serde")
274    )]
275    pub surb_flush_interval: Duration,
276    /// How long a relayer's SURB reply races are remembered when judging its health, in multiples of
277    /// its own typical margin plus spread. Longer is steadier but slower to notice a stall and to
278    /// forgive a recovery. `0` judges dead or healthy only.
279    #[default(default_latency_race_memory())]
280    #[cfg_attr(feature = "serde", serde(default = "default_latency_race_memory"))]
281    pub latency_race_memory: u32,
282    /// How hard relayer health bites in path selection: the graph gets `health^weight`. `1` as judged,
283    /// above `1` harsher, `0` switches the mitigation off, dead relayers included: nothing is written off
284    /// and no SURB generation is advanced either. Must be finite.
285    #[default(default_relayer_health_weight())]
286    #[validate(custom(function = "validate_relayer_health_weight"))]
287    #[cfg_attr(feature = "serde", serde(default = "default_relayer_health_weight"))]
288    pub relayer_health_weight: f64,
289}
290
291fn default_latency_race_memory() -> u32 {
292    4
293}
294
295fn default_relayer_health_weight() -> f64 {
296    1.0
297}
298
299/// Rejects a negative or non-finite `relayer_health_weight`. A minimum alone lets NaN and `+inf` through:
300/// `health^NaN` is NaN, and `health^inf` zeroes every health below one, either way dropping valid paths
301/// from weighted selection.
302fn validate_relayer_health_weight(value: f64) -> Result<(), ValidationError> {
303    if value.is_finite() && value >= 0.0 {
304        Ok(())
305    } else {
306        Err(ValidationError::new(
307            "relayer health weight must be finite and non-negative",
308        ))
309    }
310}
311
312/// Rejects a supervisor whose deadlines its own node's reconstructor cannot honour.
313///
314/// The deadlines the Exit-side supervisor derives from `incoming_session_pix_config` have to agree
315/// with the reconstructor's lifetimes: a supervisor that waits longer than the reconstructor keeps
316/// state is waiting on an SSA that can no longer be completed.
317///
318/// It lives on [`HoprProtocolConfig`] rather than beside the other `incoming_session_pix_config`
319/// checks because the two halves are *siblings*, and a field validator sees only its own field. The
320/// reconstructor became operator-settable under `pix.reconstructor`, and validating the supervisor
321/// against `SsaReconstructorConfig::default()` from inside the sibling would then certify a pairing
322/// the node does not run — passing for every operator who changed `unused_verifier_lifetime` or
323/// `max_ack_await_time`, which are precisely the values this check is about. Reaching both is the
324/// whole point, so the check has to sit where both are in scope.
325///
326/// [`ssa_reconstructor`](crate::ssa_reconstructor) builds from the same field, so what is validated
327/// here is what the node installs.
328fn validate_pix_supervision_pairing(cfg: &HoprProtocolConfig) -> Result<(), ValidationError> {
329    hopr_transport_session::validate_pix_supervision(
330        &cfg.incoming_session_pix_config.supervisor_config(),
331        &cfg.pix.reconstructor.into(),
332    )
333    .map_err(|error| {
334        let mut e = ValidationError::new("pix supervision deadlines conflict with the reconstructor's lifetimes");
335        e.message = Some(error.to_string().into());
336        e
337    })
338}
339
340/// Rejects an [`IncomingSessionPixConfig`] that cannot work.
341///
342/// Three independent failures, all of which would otherwise only show up at runtime:
343///
344/// `quota_range` is operator-settable, and an empty (inverted) range silently makes
345/// `check_pix_params` reject every offered PIX parameter set, which surfaces only as
346/// `UnacceptablePixParams` errors at Session establishment time.
347///
348/// `max_recovery_time` has to leave a whole cycle at the widest dimensions this Exit will *accept*
349/// time to complete, or it closes honest Sessions partway through one. With fill enabled that is
350/// judged at `fill.max_rate`, counted up to [`MAX_ASSUMED_SESSION_PACKET_RATE`]; without it, at that
351/// rate itself, so only a deadline no Session could meet is refused. The check is possible at all only because the
352/// quota counts the surplus: `quota_range.end()` prices every share a cycle emits, so the packet count follows by
353/// division with nothing left to guess.
354///
355/// And `max_live_cycle_bytes` has to admit at least one Session at those same widest dimensions,
356/// or the Exit advertises a `quota_range` whose top it will always refuse for want of budget —
357/// again as a Start error the operator cannot attribute. Deliberately *one* Session and not
358/// `maximum_managed_sessions` of them: this budget exists precisely because that product is a
359/// number no node holds, so checking it here would only ever reject the shipping defaults.
360fn validate_incoming_session_pix_config(cfg: &IncomingSessionPixConfig) -> Result<(), ValidationError> {
361    hopr_transport_session::validate_incoming_session_pix_config(cfg, MAX_ASSUMED_SESSION_PACKET_RATE).map_err(
362        |error| {
363            let mut e = ValidationError::new("invalid incoming PIX configuration");
364            e.message = Some(error.to_string().into());
365            e
366        },
367    )
368}
369
370/// Global configuration for the Protocol for Incentivization of eXits (PIX).
371#[derive(Clone, Copy, Debug, PartialEq, Validate, smart_default::SmartDefault)]
372#[cfg_attr(
373    feature = "serde",
374    derive(serde::Serialize, serde::Deserialize),
375    serde(default, deny_unknown_fields)
376)]
377pub struct PixGlobalConfig {
378    /// Number of parts an SSA is split into.
379    ///
380    /// This scales will with the CPU parallelism.
381    ///
382    /// Defaults to [`DEFAULT_PIX_POLYS_PER_SSA`], which is also what
383    /// [`IncomingSessionPixConfig::quota_range`] is derived from — changing this without
384    /// widening the peer Exit's `quota_range` accordingly will get the Session rejected.
385    ///
386    /// The range below bounds this field alone, and nothing bounds its product with
387    /// [`ssa_part_size`](Self::ssa_part_size) beyond the two ranges. The product is this node's own
388    /// generation cost and the quota it pays for, and the peer Exit bounds the quota it will serve with
389    /// its `quota_range` when the Session is initiated — before this node has generated anything,
390    /// since polynomials are built only once the Exit asks for a cycle with an `SsaRequest`. An
391    /// oversized offer therefore costs one refused initiation. A local ceiling on the product used to
392    /// sit here on the premise that the refusal arrived after generation, which it does not.
393    #[validate(range(min = 8, max = 16192))]
394    #[default(DEFAULT_PIX_POLYS_PER_SSA as usize)]
395    pub num_ssa_parts: usize,
396
397    /// Number of shares required to reconstruct an SSA part.
398    ///
399    /// This does not scale well with CPU parallelism.
400    ///
401    /// Defaults to [`DEFAULT_PIX_SHARES_PER_POLY`]. See [`num_ssa_parts`](Self::num_ssa_parts)
402    /// for the interaction with the Exit's accepted quota range, and for why the two are not bounded
403    /// together. Capped at 255 because the threshold is one byte of the negotiated
404    /// [`PixParams`](hopr_protocol_pix::PixParams) word — see
405    /// [`MAX_POLY_THRESHOLD`](hopr_protocol_pix::MAX_POLY_THRESHOLD).
406    #[validate(range(min = 2, max = 255))]
407    #[default(DEFAULT_PIX_SHARES_PER_POLY as usize)]
408    pub ssa_part_size: usize,
409
410    /// Number of shares sent in addition to `ssa_part_size` to reconstruct an SSA part.
411    ///
412    /// This is used to account for potential packet loss but makes it take longer for the
413    /// other side to reconstruct the entire SSA from all its parts. This is because if
414    /// no packet loss is present, the other side can reconstruct the SSA from fewer shares.
415    ///
416    /// **Leave unset unless you have measured your return-path loss.** `None` derives the surplus
417    /// from [`num_ssa_parts`](Self::num_ssa_parts) and [`ssa_part_size`](Self::ssa_part_size) via
418    /// [`default_surplus_for`](hopr_protocol_pix::default_surplus_for), which sizes it so that a
419    /// cycle still recovers at 99 % when half of all shares go missing — 79 at the deployed
420    /// `4096 × 32`. Read [`surplus_shares`](Self::surplus_shares) for the resolved value.
421    ///
422    /// It depends on both dimensions because a cycle recovers only if *every* polynomial does: one
423    /// polynomial survives with probability `P(Binom(ssa_part_size + surplus, 1 − loss) >=
424    /// ssa_part_size)`, and the cycle with that raised to the power `num_ssa_parts`. Setting an
425    /// absolute count therefore means a different loss tolerance at every split.
426    ///
427    /// The factor is what matters, because it is what this costs. A polynomial leaves the
428    /// generator's queue at `ssa_part_size + surplus` shares whether or not any were
429    /// lost, so this is service the Exit performs in every case — and since the surplus travels to
430    /// the peer as part of the negotiated [`PixParams`](hopr_protocol_pix::PixParams), the per-SSA
431    /// quota counts it and the deposit pays for it. It buys loss tolerance, and it is charged for
432    /// like any other insurance: on purchase, not on claim.
433    ///
434    /// Raising it therefore costs money rather than earning free service, which is the way round it
435    /// should be. It used to be the other way: the surplus was excluded from the quota, so the
436    /// rational Entry raised this dial to take traffic it was not billed for.
437    ///
438    /// Capped at 255 because it is the other byte of that word, and at nothing tighter: how much
439    /// insurance a path needs is a property of its loss rate, and the surplus that a 50 % loss needs
440    /// exceeds the threshold at every split in the deployed range.
441    #[validate(range(min = 0, max = 255))]
442    pub additional_shares: Option<usize>,
443
444    /// Maximum number of SSA commitments this node, acting as an Entry, accepts in a single
445    /// `SsaRequest` from an Exit.
446    ///
447    /// This is a protection against a misbehaving Exit rather than a preference: each accepted entry
448    /// costs a full client commitment, its own burst of `SsaCommit` packets and its own on-chain
449    /// deposit, so an uncapped request would let one inbound packet amplify into minutes of CPU and
450    /// as many simultaneous deposits as the wire format admits (27). An over-cap request is rejected
451    /// in full before any of that work starts.
452    ///
453    /// **Must be at least the `ssas_per_request` of every Exit this node uses.** The batch size is not
454    /// negotiated — the Exit cannot learn this value — so an Exit batching above it has every request
455    /// rejected, and every such Session is lost. The refusal is reported to the Exit as an
456    /// `UnacceptablePixParams` `SessionError` so it fails in about a round trip rather than as a
457    /// deposit timeout minutes later, but raising the Exit side still requires raising this in step.
458    ///
459    /// Defaults to 2, minimum 1, maximum 9 (`MAX_SSA_BATCH_SIZE`).
460    #[validate(range(min = 1, max = 9))]
461    #[default(DEFAULT_MAX_SSAS_PER_SSA_REQUEST)]
462    pub max_ssas_per_request: usize,
463
464    /// Exit-side SSA reconstructor configuration.
465    ///
466    /// Nested rather than flattened so the whole PIX surface stays under one key, and so that
467    /// Exit-side capacity does not intermix with the Entry-side dimensions above.
468    #[validate(nested)]
469    #[cfg_attr(feature = "serde", serde(default))]
470    pub reconstructor: PixReconstructorConfig,
471}
472
473impl PixGlobalConfig {
474    /// Surplus shares per polynomial: the operator's value if set, otherwise derived from
475    /// [`num_ssa_parts`](Self::num_ssa_parts) and [`ssa_part_size`](Self::ssa_part_size).
476    ///
477    /// Every reader must go through this rather than the field. The field is `Option` precisely
478    /// because serde cannot express "default to a function of a sibling", so the field alone is not
479    /// the configuration — reading it directly is how the unset case would silently become zero
480    /// surplus, i.e. no loss tolerance at all.
481    pub fn surplus_shares(&self) -> usize {
482        self.additional_shares.unwrap_or_else(|| {
483            hopr_protocol_pix::default_surplus_for(
484                self.num_ssa_parts.min(u16::MAX as usize) as u16,
485                self.ssa_part_size.min(u8::MAX as usize) as u8,
486            ) as usize
487        })
488    }
489}
490
491/// Rejects a reconstructor configuration that [`SsaReconstructorConfig`] itself would reject.
492///
493/// The mirror below deliberately carries no `range` attributes of its own. Every bound on those
494/// seven fields is a property of the reconstructor, not of this crate, so the protocol type stays
495/// the single source of truth for them and this delegates rather than restating. A restated range
496/// is simply a second place to forget when the first one moves.
497///
498/// `validator` schema functions return one [`ValidationError`], so the inner [`ValidationErrors`]
499/// is folded into its message — [`validate_incoming_session_pix_config`] above is the existing
500/// precedent in this file for a hand-written check that reaches into another crate.
501fn validate_pix_reconstructor_config(cfg: &PixReconstructorConfig) -> Result<(), ValidationError> {
502    SsaReconstructorConfig::from(*cfg).validate().map_err(|errors| {
503        let mut error = ValidationError::new("pix reconstructor configuration is out of range");
504        error.message = Some(errors.to_string().into());
505        error
506    })
507}
508
509/// Operator-facing mirror of [`SsaReconstructorConfig`], the Exit-side share reconstructor.
510///
511/// Stands in the same relationship to the protocol type that the fields of [`PixGlobalConfig`]
512/// stand in to `SsaGeneratorConfig`: `hopr-protocol-pix` owns the type the reconstructor is built
513/// from, and this crate owns the shape an operator writes. It exists because none of these seven
514/// values was reachable from a config file at all — both production constructors took
515/// `SsaReconstructorConfig::default()`, so the Exit side of PIX was unconfigurable while the Entry
516/// side was not.
517///
518/// Duplicating seven fields is the price of the mirror, and two guards pay it. The [`From`] impl
519/// below is written exhaustively, so a field added to [`SsaReconstructorConfig`] fails to compile
520/// until it is mirrored here; and `pix_reconstructor_mirror_matches_the_protocol_defaults` asserts
521/// the two default sets still agree. Validation is not duplicated at all — see
522// `validate_pix_reconstructor_config` is deliberately unlinked: it is module-private, so an
523// intra-doc link from this public type trips `rustdoc::private_intra_doc_links`, which the
524// `nix build .#docs` job builds as an error.
525/// `validate_pix_reconstructor_config`.
526///
527/// Each field's rationale lives on the protocol type and is linked rather than copied, since a
528/// third copy of the same prose is a third thing to keep true.
529#[derive(Clone, Copy, Debug, PartialEq, Validate, smart_default::SmartDefault)]
530#[cfg_attr(
531    feature = "serde",
532    derive(serde::Serialize, serde::Deserialize),
533    serde(default, deny_unknown_fields)
534)]
535#[validate(schema(function = "validate_pix_reconstructor_config", skip_on_field_errors = false))]
536pub struct PixReconstructorConfig {
537    /// Time until the complete commitment to an SSA must be received.
538    ///
539    /// Defaults to 2 minutes. See
540    /// [`SsaReconstructorConfig::incomplete_commitment_lifetime`].
541    #[default(SsaReconstructorConfig::DEFAULT_INCOMPLETE_COMMITMENT_LIFETIME)]
542    #[cfg_attr(feature = "serde", serde(with = "humantime_serde"))]
543    pub incomplete_commitment_lifetime: Duration,
544
545    /// Maximum time an SSA cycle can go without progress before it is discarded.
546    ///
547    /// Defaults to 30 minutes. See [`SsaReconstructorConfig::unused_verifier_lifetime`].
548    #[default(SsaReconstructorConfig::DEFAULT_UNUSED_VERIFIER_LIFETIME)]
549    #[cfg_attr(feature = "serde", serde(with = "humantime_serde"))]
550    pub unused_verifier_lifetime: Duration,
551
552    /// Maximum number of peers tracked simultaneously with unacknowledged shares.
553    ///
554    /// Defaults to 2000, minimum 10. See [`SsaReconstructorConfig::max_tracked_peers`].
555    #[default(SsaReconstructorConfig::DEFAULT_MAX_TRACKED_PEERS)]
556    pub max_tracked_peers: usize,
557
558    /// Maximum number of awaited acknowledgements held **per peer**.
559    ///
560    /// Defaults to 1 000 000, minimum 10 000. See [`SsaReconstructorConfig::max_awaiting_acks`].
561    #[default(SsaReconstructorConfig::DEFAULT_MAX_AWAITING_ACKS)]
562    pub max_awaiting_acks: usize,
563
564    /// Maximum time an acknowledgement is awaited before its share is discarded.
565    ///
566    /// Defaults to 30 seconds. See [`SsaReconstructorConfig::max_ack_await_time`].
567    #[default(SsaReconstructorConfig::DEFAULT_MAX_ACK_AWAIT_TIME)]
568    #[cfg_attr(feature = "serde", serde(with = "humantime_serde"))]
569    pub max_ack_await_time: Duration,
570
571    /// Whether to use the batch verification algorithm for acknowledgements.
572    ///
573    /// Defaults to `false`. See [`SsaReconstructorConfig::use_batch_verification`], which records
574    /// the measurements behind that default and why the knob was kept rather than removed.
575    #[default(SsaReconstructorConfig::DEFAULT_USE_BATCH_VERIFICATION)]
576    pub use_batch_verification: bool,
577
578    /// Fraction of reconstructed polynomials at which an early recovery notification is emitted.
579    ///
580    /// Defaults to 0.85, range 0.0..=1.0. See
581    /// [`SsaReconstructorConfig::early_recovery_threshold`].
582    #[default(SsaReconstructorConfig::DEFAULT_EARLY_RECOVERY_THRESHOLD)]
583    pub early_recovery_threshold: f64,
584
585    /// Ceiling on the total awaiting-acknowledgement state held across every peer, in bytes.
586    ///
587    /// Defaults to 1 GiB, minimum 25 600 B — 64 entries at the measured per-entry cost. That floor
588    /// is a sanity check rather than a sizing recommendation; see
589    /// [`SsaReconstructorConfig::max_ack_buffer_bytes`], which is where it is enforced and why it is
590    /// deliberately low.
591    ///
592    /// This — not the product of [`max_tracked_peers`](Self::max_tracked_peers) and
593    /// [`max_awaiting_acks`](Self::max_awaiting_acks) — is what bounds the reconstructor's
594    /// acknowledgement buffer, and the reconstructor enforces it as shares arrive rather than
595    /// checking a workload model here. A model would have to assume a Session count and a packet
596    /// rate; `maximum_managed_sessions` validates to 100 000 and `SessionCapability::NoRateControl`
597    /// removes the rate limiter, so neither assumption survives contact with a legal configuration.
598    #[default(SsaReconstructorConfig::DEFAULT_MAX_ACK_BUFFER_BYTES)]
599    pub max_ack_buffer_bytes: usize,
600}
601
602impl From<PixReconstructorConfig> for SsaReconstructorConfig {
603    /// Both sides are written out exhaustively, with no `..Default::default()` on either.
604    ///
605    /// That is the guard the mirror rests on: a field added to [`SsaReconstructorConfig`] leaves
606    /// this initialiser incomplete and a field added to [`PixReconstructorConfig`] leaves the
607    /// pattern incomplete, so either one fails to compile until it is mirrored. Struct update
608    /// syntax would compile in both directions and silently pin the new knob to its default.
609    fn from(cfg: PixReconstructorConfig) -> Self {
610        let PixReconstructorConfig {
611            incomplete_commitment_lifetime,
612            unused_verifier_lifetime,
613            max_tracked_peers,
614            max_awaiting_acks,
615            max_ack_await_time,
616            use_batch_verification,
617            early_recovery_threshold,
618            max_ack_buffer_bytes,
619        } = cfg;
620
621        Self {
622            incomplete_commitment_lifetime,
623            unused_verifier_lifetime,
624            max_tracked_peers,
625            max_awaiting_acks,
626            max_ack_await_time,
627            use_batch_verification,
628            early_recovery_threshold,
629            max_ack_buffer_bytes,
630        }
631    }
632}
633
634/// Configuration of the HOPR packet pipeline.
635#[derive(Clone, Copy, Debug, PartialEq, Validate, smart_default::SmartDefault)]
636#[cfg_attr(
637    feature = "serde",
638    derive(serde::Serialize, serde::Deserialize),
639    serde(deny_unknown_fields)
640)]
641pub struct HoprPacketPipelineConfig {
642    /// HOPR packet codec configuration
643    #[validate(nested)]
644    #[cfg_attr(feature = "serde", serde(default))]
645    pub codec: HoprCodecConfig,
646    /// Configuration of unacknowledged tickets processing.
647    #[validate(nested)]
648    #[cfg_attr(feature = "serde", serde(default))]
649    pub ack_processor: HoprUnacknowledgedTicketProcessorConfig,
650    /// Single Use Reply Block (SURB) handling configuration
651    #[validate(nested)]
652    #[cfg_attr(feature = "serde", serde(default))]
653    pub surb_store: SurbStoreConfig,
654    /// Packet pipeline configuration controlling output/input concurrency and acknowledgement processing
655    #[validate(nested)]
656    #[cfg_attr(feature = "serde", serde(default))]
657    pub pipeline: PacketPipelineConfig,
658}
659
660regex!(is_dns_address_regex "^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)*[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$");
661
662/// Check whether the string looks like a valid domain.
663#[inline]
664pub fn looks_like_domain(s: &str) -> bool {
665    is_dns_address_regex(s)
666}
667
668/// Check whether the string is an actual reachable domain.
669pub fn is_reachable_domain(host: &str) -> bool {
670    host.to_socket_addrs().is_ok_and(|i| i.into_iter().next().is_some())
671}
672
673/// Enumeration of possible host types.
674#[derive(Debug, Clone, PartialEq)]
675#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
676pub enum HostType {
677    /// IPv4 based host
678    IPv4(String),
679    /// DNS based host
680    Domain(String),
681}
682
683impl validator::Validate for HostType {
684    fn validate(&self) -> Result<(), ValidationErrors> {
685        match &self {
686            HostType::IPv4(ip4) => validate_ipv4_address(ip4).map_err(|e| {
687                let mut errs = ValidationErrors::new();
688                errs.add("ipv4", e);
689                errs
690            }),
691            HostType::Domain(domain) => validate_dns_address(domain).map_err(|e| {
692                let mut errs = ValidationErrors::new();
693                errs.add("domain", e);
694                errs
695            }),
696        }
697    }
698}
699
700impl Default for HostType {
701    fn default() -> Self {
702        HostType::IPv4("127.0.0.1".to_owned())
703    }
704}
705
706/// Configuration of the listening host.
707///
708/// This is used for the P2P and REST API listeners.
709///
710/// Intentionally has no default because it depends on the use case.
711#[derive(Debug, Validate, Clone, PartialEq)]
712#[cfg_attr(
713    feature = "serde",
714    derive(serde::Serialize, serde::Deserialize),
715    serde(deny_unknown_fields)
716)]
717pub struct HostConfig {
718    /// Host on which to listen
719    #[cfg_attr(feature = "serde", serde(default))]
720    pub address: HostType,
721    /// Listening TCP or UDP port (mandatory).
722    #[validate(range(min = 1u16))]
723    #[cfg_attr(feature = "serde", serde(default))]
724    pub port: u16,
725}
726
727impl FromStr for HostConfig {
728    type Err = String;
729
730    fn from_str(s: &str) -> Result<Self, Self::Err> {
731        let (ip_or_dns, str_port) = match s.split_once(':') {
732            None => return Err("Invalid host, is not in the '<host>:<port>' format".into()),
733            Some(split) => split,
734        };
735
736        let port = str_port.parse().map_err(|e: ParseIntError| e.to_string())?;
737
738        if validator::ValidateIp::validate_ipv4(&ip_or_dns) {
739            Ok(Self {
740                address: HostType::IPv4(ip_or_dns.to_owned()),
741                port,
742            })
743        } else if looks_like_domain(ip_or_dns) {
744            Ok(Self {
745                address: HostType::Domain(ip_or_dns.to_owned()),
746                port,
747            })
748        } else {
749            Err("Not a valid IPv4 or domain host".into())
750        }
751    }
752}
753
754impl Display for HostConfig {
755    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
756        write!(f, "{:?}:{}", self.address, self.port)
757    }
758}
759
760fn default_multiaddr_transport(port: u16) -> String {
761    cfg_if::cfg_if! {
762        if #[cfg(feature = "p2p-announce-quic")] {
763            // In case we run on a Dappnode-like device, presumably behind NAT, we fall back to TCP
764            // to circumvent issues with QUIC in such environments. To make this work reliably,
765            // we would need proper NAT traversal support.
766            let on_dappnode = std::env::var("DAPPNODE")
767                .map(|v| v.to_lowercase() == "true")
768                .unwrap_or(false);
769
770            // Using HOPRD_NAT a user can overwrite the default behaviour even on a Dappnode-like device
771            let uses_nat = std::env::var("HOPRD_NAT")
772                .map(|v| v.to_lowercase() == "true")
773                .unwrap_or(on_dappnode);
774
775            if uses_nat {
776                format!("tcp/{port}")
777            } else {
778                format!("udp/{port}/quic-v1")
779            }
780        } else {
781            format!("tcp/{port}")
782        }
783    }
784}
785
786impl TryFrom<&HostConfig> for Multiaddr {
787    type Error = HoprTransportError;
788
789    fn try_from(value: &HostConfig) -> Result<Self, Self::Error> {
790        match &value.address {
791            HostType::IPv4(ip) => Multiaddr::from_str(
792                format!("/ip4/{}/{}", ip.as_str(), default_multiaddr_transport(value.port)).as_str(),
793            )
794            .map_err(|e| HoprTransportError::Api(e.to_string())),
795            HostType::Domain(domain) => Multiaddr::from_str(
796                format!("/dns4/{}/{}", domain.as_str(), default_multiaddr_transport(value.port)).as_str(),
797            )
798            .map_err(|e| HoprTransportError::Api(e.to_string())),
799        }
800    }
801}
802
803fn validate_ipv4_address(s: &str) -> Result<(), ValidationError> {
804    if validator::ValidateIp::validate_ipv4(&s) {
805        let ipv4 = std::net::Ipv4Addr::from_str(s)
806            .map_err(|_| ValidationError::new("Failed to deserialize the string into an ipv4 address"))?;
807
808        if ipv4.is_private() || ipv4.is_multicast() || ipv4.is_unspecified() {
809            return Err(ValidationError::new(
810                "IPv4 cannot be private, multicast or unspecified (0.0.0.0)",
811            ))?;
812        }
813        Ok(())
814    } else {
815        Err(ValidationError::new("Invalid IPv4 address provided"))
816    }
817}
818
819fn validate_dns_address(s: &str) -> Result<(), ValidationError> {
820    if looks_like_domain(s) || is_reachable_domain(s) {
821        Ok(())
822    } else {
823        Err(ValidationError::new("Invalid DNS address provided"))
824    }
825}
826
827/// Configuration of the physical transport mechanism.
828#[derive(Debug, Default, Validate, Clone, Copy, PartialEq)]
829#[cfg_attr(
830    feature = "serde",
831    derive(serde::Serialize, serde::Deserialize),
832    serde(deny_unknown_fields)
833)]
834pub struct TransportConfig {
835    /// When true, assume that the node is running in an isolated network and does
836    /// not need any connection to nodes outside the subnet
837    #[cfg_attr(feature = "serde", serde(default))]
838    pub announce_local_addresses: bool,
839    /// When true, assume a testnet with multiple nodes running on the same machine
840    /// or in the same private IPv4 network
841    #[cfg_attr(feature = "serde", serde(default))]
842    pub prefer_local_addresses: bool,
843}
844
845const DEFAULT_SESSION_IDLE_TIMEOUT: Duration = Duration::from_mins(3);
846
847const SESSION_IDLE_MIN_TIMEOUT: Duration = Duration::from_secs(2);
848
849const DEFAULT_SESSION_ESTABLISH_RETRY_DELAY: Duration = Duration::from_secs(2);
850
851const DEFAULT_SESSION_ESTABLISH_MAX_RETRIES: usize = 3;
852
853const DEFAULT_SESSION_BALANCER_SAMPLING: Duration = Duration::from_millis(100);
854
855const DEFAULT_SESSION_BALANCER_BUFFER_DURATION: Duration = Duration::from_secs(5);
856
857const DEFAULT_MAXIMUM_MANAGED_SESSIONS: usize = 100;
858
859fn default_session_balancer_buffer_duration() -> Duration {
860    DEFAULT_SESSION_BALANCER_BUFFER_DURATION
861}
862
863fn default_session_establish_max_retries() -> usize {
864    DEFAULT_SESSION_ESTABLISH_MAX_RETRIES
865}
866
867fn default_session_idle_timeout() -> Duration {
868    DEFAULT_SESSION_IDLE_TIMEOUT
869}
870
871fn default_session_establish_retry_delay() -> Duration {
872    DEFAULT_SESSION_ESTABLISH_RETRY_DELAY
873}
874
875fn default_session_balancer_sampling() -> Duration {
876    DEFAULT_SESSION_BALANCER_SAMPLING
877}
878
879fn default_max_managed_sessions() -> usize {
880    DEFAULT_MAXIMUM_MANAGED_SESSIONS
881}
882
883/// Transport-layer default for the SURB balance notification period; this is the effective default
884/// for [`SessionGlobalConfig::surb_balance_notify_period`] (15s). It deliberately overrides the
885/// lower-level fallback in `SessionManagerConfig` (whose own field default is `None`) with a 15s
886/// cadence, so the Entry's dead-reckoned estimate of the Exit's SURB buffer is corrected often
887/// enough to keep the SURB balancer from under-producing (and starving the Exit) under drift,
888/// without the per-session keep-alive overhead of the previous 2s cadence. The 1s floor is enforced
889/// downstream by `SessionManager::new` (`MIN_SURB_BUFFER_NOTIFICATION_PERIOD`).
890fn default_session_surb_balance_notify_period() -> Option<Duration> {
891    Some(Duration::from_secs(15))
892}
893
894/// Transport-layer default for the Exit's degraded notification period: 1s.
895///
896/// Fast enough to corroborate a dead-relayer verdict inside the 15s test gate from a 15s base
897/// cadence, and no faster than the floor `SessionManager::new` enforces anyway.
898fn default_session_surb_degraded_notify_period() -> Option<Duration> {
899    Some(Duration::from_secs(1))
900}
901
902/// Transport-layer default for [`SessionGlobalConfig::surb_idle_notify_period`]: 45s.
903fn default_session_surb_idle_notify_period() -> Option<Duration> {
904    Some(Duration::from_secs(45))
905}
906
907/// Transport-layer default for the Exit's refusal reply budget: a burst of 32, then one reply a second.
908fn default_session_refusal_reply_budget() -> Option<RefusalReplyBudget> {
909    Some(RefusalReplyBudget::default())
910}
911
912fn default_session_max_frames_behind_gap() -> Option<usize> {
913    Some(256)
914}
915
916fn default_session_surb_target_notify() -> bool {
917    true
918}
919
920fn validate_session_idle_timeout(value: &Duration) -> Result<(), ValidationError> {
921    if SESSION_IDLE_MIN_TIMEOUT <= *value {
922        Ok(())
923    } else {
924        Err(ValidationError::new("session idle timeout is too low"))
925    }
926}
927
928fn validate_balancer_sampling(value: &Duration) -> Result<(), ValidationError> {
929    if MIN_BALANCER_SAMPLING_INTERVAL <= *value {
930        Ok(())
931    } else {
932        Err(ValidationError::new("balancer sampling interval is too low"))
933    }
934}
935
936fn validate_balancer_buffer_duration(value: &Duration) -> Result<(), ValidationError> {
937    if MIN_SURB_BUFFER_DURATION <= *value {
938        Ok(())
939    } else {
940        Err(ValidationError::new("minmum SURB buffer duration is too low"))
941    }
942}
943
944fn validate_surb_balance_notify_period(value: &Duration) -> Result<(), ValidationError> {
945    // `custom` on an `Option` field skips `None` and passes the inner value on `Some`.
946    if *value >= Duration::from_secs(1) {
947        Ok(())
948    } else {
949        Err(ValidationError::new(
950            "SURB balance notify period must be at least 1 second",
951        ))
952    }
953}
954
955fn validate_surb_degraded_notify_period(value: &Duration) -> Result<(), ValidationError> {
956    if *value >= Duration::from_secs(1) {
957        Ok(())
958    } else {
959        Err(ValidationError::new(
960            "SURB degraded notify period must be at least 1 second",
961        ))
962    }
963}
964
965fn validate_surb_idle_notify_period(value: &Duration) -> Result<(), ValidationError> {
966    if *value >= Duration::from_secs(1) {
967        Ok(())
968    } else {
969        Err(ValidationError::new(
970            "SURB idle notify period must be at least 1 second",
971        ))
972    }
973}
974
975fn validate_refusal_reply_budget(value: &RefusalReplyBudget) -> Result<(), ValidationError> {
976    if value.refill_period >= MIN_REFUSAL_REPLY_REFILL_PERIOD {
977        Ok(())
978    } else {
979        Err(ValidationError::new(
980            "refusal reply budget refill period must be at least 1 millisecond",
981        ))
982    }
983}
984
985/// Global configuration of Sessions and the Session manager.
986#[derive(Clone, Copy, Debug, PartialEq, Eq, Validate, smart_default::SmartDefault)]
987#[cfg_attr(
988    feature = "serde",
989    derive(serde::Serialize, serde::Deserialize),
990    serde(deny_unknown_fields)
991)]
992pub struct SessionGlobalConfig {
993    /// Maximum time before an idle Session is closed.
994    ///
995    /// Defaults to 3 minutes.
996    #[validate(custom(function = "validate_session_idle_timeout"))]
997    #[default(default_session_idle_timeout())]
998    #[cfg_attr(
999        feature = "serde",
1000        serde(default = "default_session_idle_timeout", with = "humantime_serde")
1001    )]
1002    pub idle_timeout: Duration,
1003
1004    /// Maximum number of Sessions that can be managed by the Session manager.
1005    ///
1006    /// Default is 100, minimum is 2, maximum is 100 000.
1007    #[validate(range(min = 2, max = 100_000))]
1008    #[default(default_max_managed_sessions())]
1009    #[cfg_attr(feature = "serde", serde(default = "default_max_managed_sessions"))]
1010    pub maximum_managed_sessions: usize,
1011
1012    /// Maximum retries to attempt to establish the Session
1013    /// Set 0 for no retries.
1014    ///
1015    /// Defaults to 3, maximum is 20.
1016    #[validate(range(min = 0, max = 20))]
1017    #[default(default_session_establish_max_retries())]
1018    #[cfg_attr(feature = "serde", serde(default = "default_session_establish_max_retries"))]
1019    pub establish_max_retries: usize,
1020
1021    /// Delay between Session establishment retries.
1022    ///
1023    /// Default is 2 seconds.
1024    #[default(default_session_establish_retry_delay())]
1025    #[cfg_attr(
1026        feature = "serde",
1027        serde(default = "default_session_establish_retry_delay", with = "humantime_serde")
1028    )]
1029    pub establish_retry_timeout: Duration,
1030
1031    /// Sampling interval for SURB balancer in milliseconds.
1032    ///
1033    /// Default is 100 milliseconds.
1034    #[validate(custom(function = "validate_balancer_sampling"))]
1035    #[default(default_session_balancer_sampling())]
1036    #[cfg_attr(
1037        feature = "serde",
1038        serde(default = "default_session_balancer_sampling", with = "humantime_serde")
1039    )]
1040    pub balancer_sampling_interval: Duration,
1041
1042    /// Minimum runway of received SURBs in seconds.
1043    ///
1044    /// This applies to incoming Sessions on Exit nodes only and is the main indicator of how
1045    /// the egress traffic will be shaped, unless the `NoRateControl` Session
1046    /// capability is specified during initiation.
1047    ///
1048    /// Default is 5 seconds, minimum is 1 second.
1049    #[validate(custom(function = "validate_balancer_buffer_duration"))]
1050    #[default(default_session_balancer_buffer_duration())]
1051    #[cfg_attr(
1052        feature = "serde",
1053        serde(default = "default_session_balancer_buffer_duration", with = "humantime_serde")
1054    )]
1055    pub balancer_minimum_surb_buffer_duration: Duration,
1056
1057    /// How often the Exit reports its true SURB buffer level to the Entry, as an absolute
1058    /// correction of the Entry's dead-reckoned estimate. Without it, cumulative packet loss
1059    /// silently inflates the estimate until the Exit runs out of SURBs and can no longer
1060    /// send reply data.
1061    ///
1062    /// A report costs the Exit one SURB, so it is sent only to an Entry that has shown it runs a SURB
1063    /// balancer, by having sent a keep-alive (whether or not that keep-alive announces a target, but not a manual
1064    /// ping), and only while the Exit's own estimate of the SURBs it holds for the Session is above 0.
1065    ///
1066    /// Default is 15 seconds. Set to `null` to disable; minimum effective period is 1 second.
1067    #[validate(custom(function = "validate_surb_balance_notify_period"))]
1068    #[default(default_session_surb_balance_notify_period())]
1069    #[cfg_attr(
1070        feature = "serde",
1071        serde(
1072            default = "default_session_surb_balance_notify_period",
1073            with = "humantime_serde::option"
1074        )
1075    )]
1076    pub surb_balance_notify_period: Option<Duration>,
1077
1078    /// How often the Exit reports its SURB buffer level while the Session's forward path is degraded.
1079    ///
1080    /// The Entry's dead-relayer verdict is corroborated by replies coming home after the relayer went
1081    /// quiet. When the forward path is dark, the data frames never reassemble at the Exit, so no echo
1082    /// reply goes out and the Exit's SURB-level report is the only reply left — at
1083    /// [`surb_balance_notify_period`](Self::surb_balance_notify_period), 15 s by default, the verdict
1084    /// waits 12 to 28 s for it instead of the ~11 s an intact path gives.
1085    ///
1086    /// While the Session has lost a frame within the last three seconds, or its frames stalled within
1087    /// them (segments of two frames arriving and neither completing for a second, which shows a dark
1088    /// forward path seconds before its first frame times out), its Entry has shown it reads the
1089    /// reports, and its SURB stock is above the keep-alive reserve, the Exit reports this often
1090    /// instead. The extra traffic is bounded by both: at most one SURB per report, never into the
1091    /// reserve, and the normal period resumes within three seconds and one poll of the last loss or stall. A
1092    /// Session that loses frames only occasionally therefore spends a few extra SURBs of its buffer
1093    /// around each loss and nothing otherwise.
1094    ///
1095    /// While the frames stall, the forward path is dark: the reports are all the Entry hears, and the Exit
1096    /// sends one every 100 ms, as long as this period is set (a fixed cadence, bounded by the same reserve).
1097    /// A Session of single-segment frames never stalls, so it only ever reports at this period.
1098    ///
1099    /// A Session for which the Exit has no announced SURB target (a `NoRateControl` Session, which runs no
1100    /// balancer on the Exit) never reports at this period; it keeps the normal one.
1101    ///
1102    /// The same holds on a PIX Session: its degraded reports stop at the keep-alive reserve too. PIX
1103    /// fill itself is unaffected by degradation and keeps its own reserve.
1104    ///
1105    /// Default is 1 second. Set to `null` to disable; minimum is 1 second, and a value at or above
1106    /// [`surb_balance_notify_period`](Self::surb_balance_notify_period) reports no faster, so it is
1107    /// treated as disabled.
1108    #[validate(custom(function = "validate_surb_degraded_notify_period"))]
1109    #[default(default_session_surb_degraded_notify_period())]
1110    #[cfg_attr(
1111        feature = "serde",
1112        serde(
1113            default = "default_session_surb_degraded_notify_period",
1114            with = "humantime_serde::option"
1115        )
1116    )]
1117    pub surb_degraded_notify_period: Option<Duration>,
1118
1119    /// The longest period the Exit's SURB-level report backs off to on an idle Session.
1120    ///
1121    /// Each report costs the Exit a SURB, and a ticket on a multi-hop return path. While no data moves, PIX
1122    /// fill is off and the Session is not degraded, the period doubles from
1123    /// [`surb_balance_notify_period`](Self::surb_balance_notify_period) up to this value, after the first minute.
1124    /// Data in either direction resets it. Clamped to a quarter of [`idle_timeout`](Self::idle_timeout), because
1125    /// on an idle Session these reports keep the Entry's slot alive, and per Session to a quarter of the idle
1126    /// timeout the Entry announces. An Entry that announces none is assumed to use this node's.
1127    ///
1128    /// Default is 45 seconds. Set to `null` to disable; minimum is 1 second.
1129    #[validate(custom(function = "validate_surb_idle_notify_period"))]
1130    #[default(default_session_surb_idle_notify_period())]
1131    #[cfg_attr(
1132        feature = "serde",
1133        serde(
1134            default = "default_session_surb_idle_notify_period",
1135            with = "humantime_serde::option"
1136        )
1137    )]
1138    pub surb_idle_notify_period: Option<Duration>,
1139
1140    /// Whether the Entry's SURB balancer tells the Exit its buffer target on its keep-alives.
1141    ///
1142    /// For a Session that announced a target, the Exit sizes the SURB ring from it, and widens the ring
1143    /// when a raised one arrives. A rate-controlled Exit also takes its balancer's set-point, its egress
1144    /// cap (`max_surbs_per_sec`) and the SURB reserve it holds back for its keep-alives from the target,
1145    /// and follows every change the Entry announces, lowered as well as raised.
1146    ///
1147    /// With this off, the Exit only knows the target announced at establishment, and no change to it
1148    /// is seen, lower or higher. A rate-controlled Exit then keeps its ring, balancer, egress cap and
1149    /// keep-alive reserve at the establishment target: an Entry that raises its target does not lift
1150    /// the Exit's egress cap or widen its ring, and one that lowers it to that reserve or below may
1151    /// leave the Exit holding its data back for good, waiting for a stock the Entry no longer keeps. A
1152    /// Session that announces no target at establishment, as an Entry without a SURB balancer or any
1153    /// `NoRateControl` Entry does, gets the full ring from the start, so turning this off costs it
1154    /// nothing. The Exit's SURB-level reports are unaffected: it recognises a balancing Entry by its
1155    /// balancer's keep-alives, flagged or not.
1156    ///
1157    /// Default is true.
1158    #[default(default_session_surb_target_notify())]
1159    #[cfg_attr(feature = "serde", serde(default = "default_session_surb_target_notify"))]
1160    pub surb_target_notify: bool,
1161
1162    /// How many later frames may queue behind a missing one before the reassembler gives up on it
1163    /// and releases what it already has.
1164    ///
1165    /// Only applies to Sessions without retransmission, where a missing frame is never coming and
1166    /// waiting out the frame timeout cannot change the outcome — it only holds everything behind
1167    /// it. The right value tracks reordering depth (throughput × latency spread ÷ frame size), so
1168    /// a bulk-data Session and a control Session on the same node differ by orders of magnitude;
1169    /// an individual Session may override it.
1170    ///
1171    /// Default is 256. Set to `null` to disable the bound and wait out the frame timeout instead.
1172    #[default(default_session_max_frames_behind_gap())]
1173    #[cfg_attr(feature = "serde", serde(default = "default_session_max_frames_behind_gap"))]
1174    pub max_frames_behind_gap: Option<usize>,
1175
1176    /// How many refusal replies the Exit sends to refused `StartSession`s, across all reasons.
1177    ///
1178    /// Each reply can cost the Exit a ticket while the request is free, so a flood of refused requests
1179    /// would otherwise drain its funds. A refusal that finds the budget spent gets no reply and the
1180    /// requester times out.
1181    ///
1182    /// Default is `{ burst: 32, refill_period: 1s }`; a `burst` of 0 never answers. Set to `null` to
1183    /// answer every refusal. The refill period must be at least 1 millisecond.
1184    #[validate(custom(function = "validate_refusal_reply_budget"))]
1185    #[default(default_session_refusal_reply_budget())]
1186    #[cfg_attr(feature = "serde", serde(default = "default_session_refusal_reply_budget"))]
1187    pub refusal_reply_budget: Option<RefusalReplyBudget>,
1188
1189    /// Tag allocator partition configuration.
1190    #[validate(nested)]
1191    #[cfg_attr(feature = "serde", serde(default))]
1192    pub tag_allocator: hopr_transport_tag_allocator::TagAllocatorConfig,
1193}
1194
1195#[cfg(test)]
1196mod tests {
1197    use anyhow::Context;
1198    use hopr_protocol_pix::SHARE_EMISSION_WINDOW;
1199    use hopr_transport_session::{MAX_SSA_BATCH_SIZE, PIX_QUOTA_BYTES_PER_SHARE, SupervisorConfig};
1200
1201    use super::*;
1202
1203    /// The Exit computes the offered quota as `polys × (shares + surplus) × PIX_QUOTA_BYTES_PER_SHARE`
1204    /// and rejects the Session when neither that quota nor an allowed dynamic batch falls inside
1205    /// `quota_range`. The default batch ceiling is one, so an Entry running the default
1206    /// `PixGlobalConfig` must itself be acceptable to an Exit running the default
1207    /// `IncomingSessionPixConfig`, otherwise PIX cannot be used at all out of the box — and before
1208    /// both structs became `serde(default)` there was no way for an operator to fix it.
1209    ///
1210    /// The surplus is in that product, so this also guards the alias that gives the two crates one
1211    /// default surplus: if `additional_shares` and `hopr-protocol-pix`'s own default drift apart
1212    /// again, the quota computed here stops matching the one the range is anchored on.
1213    #[test]
1214    fn default_pix_dimensions_must_be_inside_default_incoming_quota_range() {
1215        let pix = PixGlobalConfig::default();
1216        let incoming = IncomingSessionPixConfig::default();
1217
1218        let quota =
1219            pix.num_ssa_parts as u64 * (pix.ssa_part_size + pix.surplus_shares()) as u64 * PIX_QUOTA_BYTES_PER_SHARE;
1220
1221        assert!(
1222            incoming.quota_range.contains(&quota),
1223            "default PIX quota {quota} is outside the default accepted range {:?} — every PIX session would be \
1224             rejected with UnacceptablePixParams",
1225            incoming.quota_range
1226        );
1227
1228        // Both sides are derived from the same constants, so the range must be anchored exactly
1229        // at the nominal quota. Asserting the relationship rather than a literal keeps this test
1230        // correct if `PIX_QUOTA_BYTES_PER_SHARE` ever changes, while still failing loudly if the
1231        // range or the dimensions stop being derived from a shared source.
1232        assert_eq!(
1233            quota,
1234            *incoming.quota_range.end(),
1235            "the accepted range must be anchored at the nominal default quota"
1236        );
1237    }
1238
1239    #[test]
1240    fn relayer_health_weight_must_be_finite_and_non_negative() {
1241        for weight in [0.0, 1.0, 2.5] {
1242            let config = HoprProtocolConfig {
1243                relayer_health_weight: weight,
1244                ..Default::default()
1245            };
1246            assert!(config.validate().is_ok(), "a weight of {weight} must be accepted");
1247        }
1248        for weight in [-1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
1249            let config = HoprProtocolConfig {
1250                relayer_health_weight: weight,
1251                ..Default::default()
1252            };
1253            assert!(config.validate().is_err(), "a weight of {weight} must be rejected");
1254        }
1255    }
1256
1257    #[test]
1258    fn default_pix_configs_must_validate() {
1259        PixGlobalConfig::default()
1260            .validate()
1261            .expect("default PixGlobalConfig must be valid");
1262        validate_incoming_session_pix_config(&IncomingSessionPixConfig::default())
1263            .expect("default IncomingSessionPixConfig must be valid");
1264        HoprProtocolConfig::default()
1265            .validate()
1266            .expect("default HoprProtocolConfig must be valid");
1267    }
1268
1269    /// At the end of each emission-window block, every polynomial emits all of its surplus shares
1270    /// after it has already reached the reconstruction threshold.  None of those packets advances
1271    /// `useful_shares`, so the funded service gate must admit that whole run plus the first useful
1272    /// share of the next block.  Otherwise the gate parks the writer waiting for progress that only
1273    /// the parked writer can create.
1274    ///
1275    /// **The gate no longer counts `useful_shares`.** It counts every share the cycle accepts, via
1276    /// `SsaRecoveryProgress::shares_seen`, so the surplus run resets it exactly like the useful
1277    /// shares around it and the inequality this test used to assert — ceiling above
1278    /// `additional_shares × min(polys, window)` — constrains nothing. Sizing a static ceiling
1279    /// against the run was never sound anyway: the run's length comes from the dimensions negotiated
1280    /// per Session, and this value is fixed at config load.
1281    ///
1282    /// What is asserted instead is the shipping-default property the deferral path relies on: a
1283    /// polynomial's whole emission fits one peer deferral bucket, so no acknowledgement for it can
1284    /// ever be dropped for want of room. This is a *sufficient* condition for "never dropped", not a
1285    /// requirement — the bucket only holds shares that arrive before the cycle's commitments
1286    /// install, which is a prefix, so larger dimensions merely lose the guarantee rather than break.
1287    /// That is why it is asserted on the defaults here and not enforced in `validate`, where it
1288    /// would reject legitimate splits such as `4096 x 128`.
1289    ///
1290    /// The behavioural half of the original concern is pinned where it can actually be exercised:
1291    /// `a_surplus_only_snapshot_is_liveness_without_payment` in the supervisor, which drives a
1292    /// surplus-only run through the gate and the idle deadline.
1293    #[test]
1294    fn default_pix_emission_fits_one_deferral_bucket() {
1295        let cfg = HoprProtocolConfig::default();
1296
1297        let emitted_per_poly = cfg.pix.ssa_part_size + cfg.pix.surplus_shares();
1298        assert!(
1299            emitted_per_poly <= hopr_protocol_pix::MAX_DEFERRED_ACKS_PER_POLYNOMIAL,
1300            "default emission of {emitted_per_poly} shares per polynomial should fit one deferral bucket ({}), so \
1301             that no acknowledgement can be dropped for want of room",
1302            hopr_protocol_pix::MAX_DEFERRED_ACKS_PER_POLYNOMIAL
1303        );
1304
1305        // The ceiling still has to bound *something* — it is what stops an Entry consuming service
1306        // while returning nothing at all — so a zero would disable the anti-drip rule outright.
1307        assert!(
1308            cfg.incoming_session_pix_config.supervision.max_served_without_progress > 0,
1309            "the gate ceiling still bounds silence, and zero would disable it"
1310        );
1311
1312        // The surplus run is quoted rather than bounded: it is what the block-structured emission
1313        // produces, and the liveness counter is what absorbs it.
1314        let surplus_run = cfg.pix.surplus_shares() as u64 * cfg.pix.num_ssa_parts.min(SHARE_EMISSION_WINDOW) as u64;
1315        assert_eq!(
1316            40_448, surplus_run,
1317            "the shipped dimensions produce a 40 448-packet run of non-useful shares (79 x a window of 512; it was 20 \
1318             224 at a window of 256). This is a tripwire on the product of three values rather than an invariant: if \
1319             it moves, one of `PixGlobalConfig::ssa_part_size` (or the surplus: `additional_shares`, or the default \
1320             an unset one resolves to), `PixGlobalConfig::num_ssa_parts`, or \
1321             `hopr_protocol_pix::SHARE_EMISSION_WINDOW` has changed. Re-derive the run, then re-check that nothing \
1322             has started keying liveness on useful shares again"
1323        );
1324    }
1325
1326    /// The operator-facing mirror must round-trip to the protocol type it stands for.
1327    ///
1328    /// Both sides now read the same `SsaReconstructorConfig::DEFAULT_*` constants, so this is
1329    /// structurally true rather than merely observed — which is the point of asserting it. What the
1330    /// test actually guards is a future edit that replaces one of those references with a literal:
1331    /// the mirror would still compile, still validate, and quietly install a different Exit.
1332    ///
1333    /// The field *set* is guarded by the compiler instead — `From` is written exhaustively in both
1334    /// directions, so neither struct can grow a field the other lacks.
1335    #[test]
1336    fn pix_reconstructor_mirror_matches_the_protocol_defaults() {
1337        assert_eq!(
1338            SsaReconstructorConfig::default(),
1339            SsaReconstructorConfig::from(PixReconstructorConfig::default()),
1340            "the operator-facing mirror and the reconstructor it configures have drifted apart"
1341        );
1342    }
1343
1344    /// The acknowledgement-budget floor named in this crate's operator documentation must be the
1345    /// one the protocol crate actually enforces.
1346    ///
1347    /// The doc comment above once said 16 MiB against a validated 25 600 B, from a floor lowered on
1348    /// one side only. A number written in prose cannot be checked by the compiler, so it gets
1349    /// checked here instead — the same lesson L20 recorded about a `SAFETY` comment quoting a
1350    /// constant it did not reference.
1351    #[test]
1352    fn the_documented_ack_budget_floor_is_the_enforced_one() {
1353        const DOCUMENTED_FLOOR: usize = 25_600;
1354
1355        PixReconstructorConfig {
1356            max_ack_buffer_bytes: DOCUMENTED_FLOOR,
1357            ..Default::default()
1358        }
1359        .validate()
1360        .expect("the documented floor itself must be accepted");
1361
1362        assert!(
1363            PixReconstructorConfig {
1364                max_ack_buffer_bytes: DOCUMENTED_FLOOR - 1,
1365                ..Default::default()
1366            }
1367            .validate()
1368            .is_err(),
1369            "one byte below the documented floor must be rejected — the prose and the validator have drifted"
1370        );
1371    }
1372
1373    /// The dimensions are bounded field by field and by nothing else, so every corner of the box the
1374    /// ranges describe must validate.
1375    ///
1376    /// The product used to be capped as well, at 4× the profiled operating point, on the premise
1377    /// that the peer Exit's `quota_range` refusal arrives after this node has generated the cycle. It
1378    /// arrives at Session initiation, and this node generates a cycle only when the Exit asks for one,
1379    /// so the product is this node's own cost and price and the Exit is where it is bounded.
1380    #[test]
1381    fn every_corner_of_the_pix_dimension_ranges_validates() -> anyhow::Result<()> {
1382        for num_ssa_parts in [8usize, 16192] {
1383            for ssa_part_size in [2usize, 255] {
1384                for additional_shares in [None, Some(0usize), Some(255)] {
1385                    PixGlobalConfig {
1386                        num_ssa_parts,
1387                        ssa_part_size,
1388                        additional_shares,
1389                        ..Default::default()
1390                    }
1391                    .validate()
1392                    .with_context(|| {
1393                        format!("{num_ssa_parts} x ({ssa_part_size} + {additional_shares:?}) must be accepted")
1394                    })?;
1395                }
1396            }
1397        }
1398        Ok(())
1399    }
1400
1401    /// The fill-off deadline floor is a figure in packets, so no packet or segment size can move it.
1402    /// Changing it is a policy decision, and this is where that decision shows up.
1403    #[test]
1404    fn the_assumed_session_rate_is_stated_in_packets() {
1405        assert_eq!(MAX_ASSUMED_SESSION_PACKET_RATE, 5000);
1406    }
1407
1408    /// The default recovery deadline must leave a cycle at the widest accepted quota time to
1409    /// complete, both with fill and without it.
1410    ///
1411    /// Full emission is the right count here because it is what `quota_range` prices.
1412    #[test]
1413    fn default_recovery_deadline_must_cover_a_whole_cycle_at_the_accepted_quota() -> anyhow::Result<()> {
1414        let cfg = IncomingSessionPixConfig::default();
1415        validate_incoming_session_pix_config(&cfg).context("the shipping default must validate")?;
1416
1417        let without_fill = IncomingSessionPixConfig {
1418            supervision: SupervisorConfig {
1419                fill: hopr_transport_session::PixFillConfig {
1420                    enabled: false,
1421                    ..cfg.supervision.fill.clone()
1422                },
1423                ..cfg.supervision.clone()
1424            },
1425            ..cfg
1426        };
1427        validate_incoming_session_pix_config(&without_fill)
1428            .context("the shipping deadline must also clear the fill-off floor")?;
1429        Ok(())
1430    }
1431
1432    /// Without fill, a deadline is refused only when even a Session at the fastest assumed rate
1433    /// could not finish a cycle of the widest accepted quota inside it.
1434    #[test]
1435    fn without_fill_a_deadline_below_one_cycle_at_the_assumed_rate_is_rejected() -> anyhow::Result<()> {
1436        let with_deadline = |max_recovery_time: Duration| IncomingSessionPixConfig {
1437            supervision: SupervisorConfig {
1438                max_recovery_time,
1439                fill: hopr_transport_session::PixFillConfig {
1440                    enabled: false,
1441                    ..Default::default()
1442                },
1443                ..Default::default()
1444            },
1445            ..Default::default()
1446        };
1447        let packets = *IncomingSessionPixConfig::default().quota_range.end() / PIX_QUOTA_BYTES_PER_SHARE;
1448        let needed = Duration::from_secs(packets.div_ceil(MAX_ASSUMED_SESSION_PACKET_RATE));
1449
1450        validate_incoming_session_pix_config(&with_deadline(needed))
1451            .context("a deadline of exactly one cycle at the assumed rate must be accepted")?;
1452        assert!(
1453            validate_incoming_session_pix_config(&with_deadline(needed - Duration::from_nanos(1))).is_err(),
1454            "a deadline a nanosecond short of {needed:?} must be refused"
1455        );
1456        Ok(())
1457    }
1458
1459    /// The fill rate a cycle of the widest default quota needs to finish inside `max_recovery_time`,
1460    /// by the planner's own arithmetic at the default fractions.
1461    fn default_fill_rate_needed_within(max_recovery_time: Duration) -> u64 {
1462        let packets = *IncomingSessionPixConfig::default().quota_range.end() / PIX_QUOTA_BYTES_PER_SHARE;
1463        let fill = hopr_transport_session::PixFillConfig::default();
1464        let horizon = max_recovery_time.mul_f64(fill.finish_fraction);
1465        (packets as f64 * (1.0 + fill.loss_margin) / horizon.as_secs_f64()).ceil() as u64
1466    }
1467
1468    /// The deadline below which no Session could finish a cycle of the widest default quota.
1469    fn default_fill_off_floor() -> Duration {
1470        let packets = *IncomingSessionPixConfig::default().quota_range.end() / PIX_QUOTA_BYTES_PER_SHARE;
1471        Duration::from_secs(packets.div_ceil(MAX_ASSUMED_SESSION_PACKET_RATE))
1472    }
1473
1474    /// With fill enabled, the deadline is judged at `fill.max_rate`: it is the fill ceiling, not the
1475    /// fill-off floor, that decides.
1476    #[test]
1477    fn with_fill_the_deadline_is_judged_at_the_fill_ceiling() -> anyhow::Result<()> {
1478        let max_recovery_time = default_fill_off_floor() * 4;
1479        let needed_rate = default_fill_rate_needed_within(max_recovery_time);
1480        assert!(
1481            needed_rate <= MAX_ASSUMED_SESSION_PACKET_RATE,
1482            "test case must need no more than the assumed Session rate, needs {needed_rate}"
1483        );
1484
1485        let with_ceiling = |max_rate: u64| -> anyhow::Result<IncomingSessionPixConfig> {
1486            Ok(IncomingSessionPixConfig {
1487                supervision: SupervisorConfig {
1488                    max_recovery_time,
1489                    fill: hopr_transport_session::PixFillConfig {
1490                        max_rate: u32::try_from(max_rate)?,
1491                        ..Default::default()
1492                    },
1493                    ..Default::default()
1494                },
1495                ..Default::default()
1496            })
1497        };
1498
1499        validate_incoming_session_pix_config(&with_ceiling(needed_rate)?)
1500            .context("a ceiling that finishes the cycle in time must be accepted")?;
1501        assert!(
1502            validate_incoming_session_pix_config(&with_ceiling(needed_rate - 1)?).is_err(),
1503            "a ceiling one packet/s short of {needed_rate} must be refused"
1504        );
1505        Ok(())
1506    }
1507
1508    /// But a fill ceiling above the fastest rate a Session is assumed to carry buys no shorter
1509    /// deadline, because fill that fast could not finish a cycle any sooner.
1510    #[test]
1511    fn a_fill_ceiling_above_the_assumed_session_rate_buys_no_shorter_deadline() -> anyhow::Result<()> {
1512        // `MAX_FILL_RATE`, the largest ceiling `validate_pix_supervision` accepts.
1513        const LARGEST_LEGAL_FILL_RATE: u32 = 10_000;
1514        let with_deadline = |max_recovery_time: Duration| IncomingSessionPixConfig {
1515            supervision: SupervisorConfig {
1516                max_recovery_time,
1517                fill: hopr_transport_session::PixFillConfig {
1518                    max_rate: LARGEST_LEGAL_FILL_RATE,
1519                    ..Default::default()
1520                },
1521                ..Default::default()
1522            },
1523            ..Default::default()
1524        };
1525
1526        let too_short = default_fill_off_floor();
1527        let needed_rate = default_fill_rate_needed_within(too_short);
1528        assert!(
1529            needed_rate > MAX_ASSUMED_SESSION_PACKET_RATE && needed_rate <= u64::from(LARGEST_LEGAL_FILL_RATE),
1530            "test case must need more than the assumed Session rate but no more than the ceiling, needs {needed_rate}"
1531        );
1532        assert!(
1533            validate_incoming_session_pix_config(&with_deadline(too_short)).is_err(),
1534            "a deadline that needs {needed_rate} packets/s of fill must be refused despite the ceiling allowing it"
1535        );
1536
1537        let long_enough = too_short * 2;
1538        assert!(
1539            default_fill_rate_needed_within(long_enough) <= MAX_ASSUMED_SESSION_PACKET_RATE,
1540            "test case must need no more than the assumed Session rate"
1541        );
1542        validate_incoming_session_pix_config(&with_deadline(long_enough))
1543            .context("a deadline within the assumed Session rate must be accepted")?;
1544        Ok(())
1545    }
1546
1547    /// The fill ceiling must clear the rate the widest accepted quota actually needs.
1548    ///
1549    /// Fill exists to complete funded cycles that the application will not, and a ceiling below the
1550    /// requirement is a filler that runs flat out and still strands the deposit. The failure is
1551    /// invisible without this check: every individual value validates, the rate gauge sits pinned at
1552    /// the cap, and the only symptom is a cycle closing on `RecoveryDeadline` four hours later.
1553    ///
1554    /// The floor is the planner's own arithmetic taken at the moment fill starts — the whole cycle
1555    /// remaining, spread over `finish_fraction` of `max_recovery_time`, plus the loss margin —
1556    /// recomputed here rather than shared with the validator, so a change to either has to be
1557    /// restated.
1558    #[test]
1559    fn a_fill_ceiling_below_the_widest_accepted_quota_is_rejected() {
1560        let cfg = IncomingSessionPixConfig::default();
1561        let packets = *cfg.quota_range.end() / PIX_QUOTA_BYTES_PER_SHARE;
1562        let horizon = cfg
1563            .supervision
1564            .max_recovery_time
1565            .mul_f64(cfg.supervision.fill.finish_fraction);
1566        let floor = (packets as f64 * (1.0 + cfg.supervision.fill.loss_margin) / horizon.as_secs_f64()).ceil() as u32;
1567
1568        assert!(
1569            cfg.supervision.fill.max_rate >= floor,
1570            "the shipping default ceiling ({}) must clear the {floor} packets/s its own quota range needs",
1571            cfg.supervision.fill.max_rate
1572        );
1573        validate_incoming_session_pix_config(&cfg).expect("the shipping default must validate");
1574
1575        let starved = IncomingSessionPixConfig {
1576            supervision: SupervisorConfig {
1577                fill: hopr_transport_session::PixFillConfig {
1578                    max_rate: floor - 1,
1579                    ..Default::default()
1580                },
1581                ..Default::default()
1582            },
1583            ..Default::default()
1584        };
1585        assert!(
1586            validate_incoming_session_pix_config(&starved).is_err(),
1587            "a ceiling one packet/s short of the requirement must be refused"
1588        );
1589
1590        // And an Exit that has turned fill off is not held to a bound nothing reads: it has chosen
1591        // the pre-fill behaviour, where an idle cycle simply strands.
1592        let disabled = IncomingSessionPixConfig {
1593            supervision: SupervisorConfig {
1594                fill: hopr_transport_session::PixFillConfig {
1595                    enabled: false,
1596                    max_rate: 1,
1597                    ..Default::default()
1598                },
1599                ..Default::default()
1600            },
1601            ..Default::default()
1602        };
1603        validate_incoming_session_pix_config(&disabled)
1604            .expect("a disabled filler must not be judged against a rate it will never use");
1605    }
1606
1607    /// The live-cycle budget must admit at least one Session at the widest quota this Exit accepts.
1608    ///
1609    /// Otherwise the Exit advertises a `quota_range` whose top it will always refuse for want of
1610    /// memory, and the peer sees only a `NoSlotsAvailable` it cannot attribute to a dimension it
1611    /// chose. Deliberately *one* Session: the whole reason this budget exists is that the product
1612    /// with `maximum_managed_sessions` is a number no node holds, so checking that product here
1613    /// would only ever reject the shipping defaults.
1614    #[test]
1615    fn a_live_cycle_budget_too_small_for_the_accepted_quota_is_rejected() {
1616        let cfg = IncomingSessionPixConfig::default();
1617        let widest = hopr_transport_session::max_cycle_budget_for_quota(
1618            *cfg.quota_range.end(),
1619            cfg.supervision.ssas_per_request,
1620        );
1621
1622        assert!(
1623            cfg.max_live_cycle_bytes >= widest,
1624            "the shipping default budget ({}) must admit one session at the top of its own quota range ({widest})",
1625            cfg.max_live_cycle_bytes
1626        );
1627        validate_incoming_session_pix_config(&cfg).expect("the shipping default must validate");
1628
1629        let starved = IncomingSessionPixConfig {
1630            max_live_cycle_bytes: widest - 1,
1631            ..Default::default()
1632        };
1633        assert!(
1634            validate_incoming_session_pix_config(&starved).is_err(),
1635            "a budget one byte short of a single session must be refused"
1636        );
1637
1638        // The other way round: the operator asked for more cycles per request. This rather than a
1639        // widened `quota_range`, because widening the quota does *not* scale the reservation without
1640        // limit — `MAX_POLYS_PER_SSA` caps the polynomial count, so past a point a larger quota only
1641        // buys a bigger threshold. The batch size has no such ceiling below `MAX_SSA_BATCH_SIZE`,
1642        // and it multiplies the whole figure.
1643        //
1644        // Measured against the single-cycle figure rather than the shipping default, because the
1645        // multiplication is the invariant and whether 3 GiB happens to be exceeded is not: at
1646        // `MAX_SSA_BATCH_SIZE` the default budget covers the whole legal range, so a batched config
1647        // left on the default would validate and prove nothing.
1648        let batched = IncomingSessionPixConfig {
1649            max_live_cycle_bytes: widest,
1650            supervision: SupervisorConfig {
1651                ssas_per_request: hopr_transport_session::MAX_SSA_BATCH_SIZE,
1652                ..cfg.supervision.clone()
1653            },
1654            ..cfg.clone()
1655        };
1656        assert!(
1657            validate_incoming_session_pix_config(&batched).is_err(),
1658            "a batch of {} live cycles per session needs a budget raised past the {widest} one cycle needs",
1659            hopr_transport_session::MAX_SSA_BATCH_SIZE
1660        );
1661    }
1662
1663    // The reversed range is the point of the test: `quota_range` is operator-settable, so an
1664    // inverted range is reachable from a config file and must be rejected by validation rather
1665    // than silently matching nothing.
1666    #[allow(clippy::reversed_empty_ranges)]
1667    #[test]
1668    fn empty_pix_quota_range_is_rejected() {
1669        let cfg = IncomingSessionPixConfig {
1670            quota_range: 100..=10,
1671            ..Default::default()
1672        };
1673        assert!(validate_incoming_session_pix_config(&cfg).is_err());
1674
1675        let cfg = HoprProtocolConfig {
1676            incoming_session_pix_config: IncomingSessionPixConfig {
1677                quota_range: 100..=10,
1678                ..Default::default()
1679            },
1680            ..Default::default()
1681        };
1682        assert!(cfg.validate().is_err());
1683    }
1684
1685    /// The Entry's `surb_target_notify` is reachable from a node's configuration file, and a file that
1686    /// predates it keeps the behaviour the Entry always had.
1687    #[cfg(feature = "serde")]
1688    #[test]
1689    fn surb_target_notify_is_configurable_and_on_by_default() -> anyhow::Result<()> {
1690        assert!(SessionGlobalConfig::default().surb_target_notify);
1691
1692        let omitted: SessionGlobalConfig =
1693            serde_saphyr::from_str("idle_timeout: 3m\n").context("config without the setting must parse")?;
1694        assert!(
1695            omitted.surb_target_notify,
1696            "a configuration that does not name the setting must announce the target, as it always did"
1697        );
1698
1699        let off: SessionGlobalConfig =
1700            serde_saphyr::from_str("surb_target_notify: false\n").context("config turning it off must parse")?;
1701        assert!(!off.surb_target_notify);
1702
1703        let on: SessionGlobalConfig =
1704            serde_saphyr::from_str("surb_target_notify: true\n").context("config turning it on must parse")?;
1705        assert!(on.surb_target_notify);
1706        Ok(())
1707    }
1708
1709    #[cfg(feature = "serde")]
1710    #[test]
1711    fn path_planner_weights_are_reachable_from_serialized_config() {
1712        let json = r#"{
1713            "path_planner": {
1714                "latency_halflife": "250ms",
1715                "capacity_reference": 5000,
1716                "edge_penalty": 0.8,
1717                "return_path_weight_temper": 0.25
1718            }
1719        }"#;
1720        let cfg: HoprProtocolConfig = serde_json::from_str(json).expect("path planner weights must deserialize");
1721        let planner = cfg.path_planner;
1722        let defaults = crate::path::PathPlannerConfig::default();
1723
1724        assert_eq!(Duration::from_millis(250), planner.latency_halflife);
1725        assert_eq!(5000, planner.capacity_reference);
1726        assert_eq!(0.8, planner.edge_penalty);
1727        assert_eq!(0.25, planner.return_path_weight_temper);
1728        assert_eq!(
1729            defaults.min_ack_rate, planner.min_ack_rate,
1730            "unspecified planner fields must keep their defaults"
1731        );
1732        assert_eq!(defaults.cache_ttl, planner.cache_ttl);
1733        assert!(cfg.validate().is_ok());
1734
1735        let bad_temper = r#"{ "path_planner": { "return_path_weight_temper": 1.5 } }"#;
1736        let cfg: HoprProtocolConfig = serde_json::from_str(bad_temper).expect("it parses; validation rejects it");
1737        assert!(cfg.validate().is_err(), "an out-of-range temper must fail validation");
1738
1739        let typo = r#"{ "path_planner": { "latency_halflif": "250ms" } }"#;
1740        assert!(
1741            serde_json::from_str::<HoprProtocolConfig>(typo).is_err(),
1742            "a misspelled planner key must be rejected, not silently ignored"
1743        );
1744
1745        let round_trip: HoprProtocolConfig =
1746            serde_json::from_str(&serde_json::to_string(&cfg).expect("serialize")).expect("round trip");
1747        assert_eq!(cfg, round_trip);
1748    }
1749
1750    #[cfg(feature = "serde")]
1751    #[test]
1752    fn pix_configs_are_reachable_from_serialized_config() {
1753        // Regression guard: these fields used to be `serde(skip)`, which pinned them to their
1754        // defaults and made PIX unconfigurable. The supervision block is checked here too, since
1755        // `deny_unknown_fields` on both levels means a rename on either side fails this loudly
1756        // rather than silently ignoring an operator's setting.
1757        let json = r#"{
1758            "pix": { "num_ssa_parts": 2048 },
1759            "incoming_session_pix_config": {
1760                "enforce_pix": true,
1761                "supervision": { "max_deposit_wait": "90s" }
1762            }
1763        }"#;
1764        let cfg: HoprProtocolConfig = serde_json::from_str(json).expect("PIX config must deserialize");
1765
1766        assert_eq!(2048, cfg.pix.num_ssa_parts);
1767        // Container-level `serde(default)` keeps unspecified fields at their defaults.
1768        assert_eq!(
1769            PixGlobalConfig::default().ssa_part_size,
1770            cfg.pix.ssa_part_size,
1771            "unspecified PIX fields must fall back to their defaults"
1772        );
1773        assert!(cfg.incoming_session_pix_config.enforce_pix);
1774        assert_eq!(
1775            Duration::from_secs(90),
1776            cfg.incoming_session_pix_config.supervision.max_deposit_wait
1777        );
1778        assert_eq!(
1779            hopr_transport_session::SupervisorConfig::default().max_recovery_time,
1780            cfg.incoming_session_pix_config.supervision.max_recovery_time,
1781            "unspecified supervision fields must fall back to their defaults"
1782        );
1783        assert!(
1784            cfg.incoming_session_pix_config.supervision.allow_dynamic_ssa_batches,
1785            "omitting allow_dynamic_ssa_batches must retain its true default"
1786        );
1787        assert_eq!(
1788            IncomingSessionPixConfig::default().quota_range,
1789            cfg.incoming_session_pix_config.quota_range
1790        );
1791
1792        // The fill block is nested inside a `deny_unknown_fields` struct, so it has to carry its own
1793        // `serde(default)` for a node configuration written before fill existed to keep loading —
1794        // and partial specification must work, or an operator raising the ceiling would have to
1795        // restate the heartbeat, the fractions and the reserve alongside it.
1796        assert_eq!(
1797            hopr_transport_session::PixFillConfig::default(),
1798            cfg.incoming_session_pix_config.supervision.fill,
1799            "a config that names no fill block must get the shipped one"
1800        );
1801        let json = r#"{
1802            "incoming_session_pix_config": {
1803                "supervision": { "fill": { "max_rate": 500 } }
1804            }
1805        }"#;
1806        let cfg: HoprProtocolConfig = serde_json::from_str(json).expect("a partial fill block must deserialize");
1807        let fill = &cfg.incoming_session_pix_config.supervision.fill;
1808        assert_eq!(500, fill.max_rate);
1809        assert_eq!(
1810            hopr_transport_session::PixFillConfig::default().heartbeat,
1811            fill.heartbeat,
1812            "unspecified fill fields must fall back to their defaults"
1813        );
1814        assert!(fill.enabled, "omitting `enabled` must retain its true default");
1815
1816        // Both SSA batch knobs and the fixed-mode opt-out must be settable from a config file too.
1817        // Raising the Exit's ceiling past the Entry's is a silently fatal misconfiguration, and an
1818        // operator who needs the old exact-batch policy must be able to select it explicitly.
1819        let json = r#"{
1820            "pix": { "max_ssas_per_request": 5 },
1821            "incoming_session_pix_config": {
1822                "supervision": {
1823                    "ssas_per_request": 5,
1824                    "allow_dynamic_ssa_batches": false
1825                }
1826            }
1827        }"#;
1828        let cfg: HoprProtocolConfig = serde_json::from_str(json).expect("SSA batch config must deserialize");
1829        assert_eq!(5, cfg.pix.max_ssas_per_request);
1830        assert_eq!(5, cfg.incoming_session_pix_config.supervision.ssas_per_request);
1831        assert!(!cfg.incoming_session_pix_config.supervision.allow_dynamic_ssa_batches);
1832        cfg.validate().expect("a matched pair of batch knobs must validate");
1833
1834        // Same defect one struct down: every Exit-side reconstructor dial used to be unreachable
1835        // because both production constructors took `SsaReconstructorConfig::default()`. The
1836        // durations must come through `humantime_serde` rather than as a struct of secs/nanos.
1837        //
1838        // `tombstone_retention_window` is raised in the same document because it has to be: the
1839        // supervisor must outlive the reconstructor's ack window, and 45 s of ack window against the
1840        // default 30 s tombstone is the conflict `validate_pix_supervision_pairing` exists to
1841        // reject. Setting one without the other is what an operator must not be able to do quietly,
1842        // so this doubles as the round trip proving both halves are reachable from one file.
1843        let json = r#"{
1844            "pix": { "reconstructor": { "max_ack_await_time": "45s", "max_tracked_peers": 500 } },
1845            "incoming_session_pix_config": { "supervision": { "tombstone_retention_window": "60s" } }
1846        }"#;
1847        let cfg: HoprProtocolConfig = serde_json::from_str(json).expect("reconstructor config must deserialize");
1848        assert_eq!(Duration::from_secs(45), cfg.pix.reconstructor.max_ack_await_time);
1849        assert_eq!(500, cfg.pix.reconstructor.max_tracked_peers);
1850        assert_eq!(
1851            PixReconstructorConfig::default().unused_verifier_lifetime,
1852            cfg.pix.reconstructor.unused_verifier_lifetime,
1853            "unspecified reconstructor fields must fall back to their defaults"
1854        );
1855        cfg.validate().expect("a narrowed reconstructor must validate");
1856
1857        // And the pairing is enforced, not merely satisfiable: the same reconstructor without the
1858        // matching supervision key is rejected.
1859        let unpaired = r#"{ "pix": { "reconstructor": { "max_ack_await_time": "45s" } } }"#;
1860        let unpaired: HoprProtocolConfig = serde_json::from_str(unpaired).expect("must deserialize");
1861        assert!(
1862            unpaired.validate().is_err(),
1863            "a 45 s ack window against the default 30 s tombstone must be rejected, not silently accepted against the \
1864             reconstructor defaults the node no longer uses"
1865        );
1866
1867        // And it must reach the reconstructor, not merely parse: the conversion is what the two
1868        // production constructors consume.
1869        assert_eq!(
1870            Duration::from_secs(45),
1871            SsaReconstructorConfig::from(cfg.pix.reconstructor).max_ack_await_time
1872        );
1873
1874        // An unset surplus must derive from the configured dimensions, not fall to zero. This is the
1875        // one field whose `serde(default)` cannot express its own default, so "absent" and "zero"
1876        // are the two readings that must not be confused — zero surplus is legal and means no loss
1877        // tolerance at all. 48 rather than the deployed 32, so that a derivation that only ever
1878        // returned the deployed default would be caught.
1879        let json = r#"{ "pix": { "ssa_part_size": 48 } }"#;
1880        let cfg: HoprProtocolConfig = serde_json::from_str(json).expect("PIX dimensions must deserialize");
1881        assert_eq!(None, cfg.pix.additional_shares, "the field itself stays unset");
1882        assert_eq!(
1883            103,
1884            cfg.pix.surplus_shares(),
1885            "and resolves to the derivation at 4096 x 48"
1886        );
1887
1888        let json = r#"{ "pix": { "ssa_part_size": 32, "additional_shares": 30 } }"#;
1889        let cfg: HoprProtocolConfig = serde_json::from_str(json).expect("an explicit surplus must deserialize");
1890        assert_eq!(30, cfg.pix.surplus_shares(), "an explicit surplus is passed through");
1891
1892        // A surplus above the threshold is legal now: the ratio a path needs falls as the threshold
1893        // rises, so the old `surplus <= threshold` rule was tightest where the requirement was
1894        // largest. 65 against 16 is a real choice, not a typo, and only the wire byte bounds it.
1895        let json = r#"{ "pix": { "ssa_part_size": 16, "additional_shares": 65 } }"#;
1896        let cfg: HoprProtocolConfig = serde_json::from_str(json).expect("it parses; validation is what rejects it");
1897        assert!(
1898            cfg.validate().is_ok(),
1899            "a surplus above the threshold must be accepted — only the wire byte bounds it"
1900        );
1901    }
1902
1903    /// The surplus has exactly one upper bound: the byte the wire gives it.
1904    ///
1905    /// `range(max = 255)` is that byte. It used to be joined by a schema check capping the surplus
1906    /// at the threshold — "insurance must not cost more than the payload it insures" — and that rule
1907    /// was wrong, because the ratio a path needs *falls* as the threshold rises. See the note above
1908    /// `SsaGeneratorConfig` in `hopr-protocol-pix` for the derivation.
1909    ///
1910    /// The `range` attribute is asserted because one on an `Option` is not obviously live: the crate
1911    /// has no other instance of one, and an attribute that silently validated nothing would look
1912    /// exactly like this one. It does fire — validator 0.21 unwraps the `Option` — and this is what
1913    /// would notice if that changed.
1914    #[test]
1915    fn the_surplus_is_bounded_only_by_the_wire_byte() {
1916        // A surplus that covers a 50 % share loss at a low threshold, which the previous
1917        // `surplus <= threshold` rule rejected outright. At threshold 32 a cycle needs 81 surplus
1918        // shares to survive half its shares going missing, and the old bound refused anything above
1919        // 32.
1920        for (ssa_part_size, additional_shares) in [(32usize, 81usize), (16, 54), (64, 128), (64, 255)] {
1921            let cfg = PixGlobalConfig {
1922                ssa_part_size,
1923                additional_shares: Some(additional_shares),
1924                ..Default::default()
1925            };
1926            cfg.validate().unwrap_or_else(|e| {
1927                panic!("threshold {ssa_part_size} with surplus {additional_shares} must be admissible: {e}")
1928            });
1929        }
1930
1931        // The field's own byte range: a value that cannot fit the `PixParams` byte must be refused
1932        // by the field range, which fires through the `Option` rather than only via a schema check.
1933        let past_the_wire_byte = PixGlobalConfig {
1934            ssa_part_size: 64,
1935            additional_shares: Some(256),
1936            ..Default::default()
1937        };
1938        let errors = past_the_wire_byte
1939            .validate()
1940            .expect_err("a surplus that cannot fit the PixParams byte must be rejected");
1941        assert!(
1942            errors.field_errors().contains_key("additional_shares"),
1943            "the field range must fire through the Option, not only a schema check"
1944        );
1945    }
1946
1947    /// The derived surplus tracks the configured split, which is the whole point of deriving it.
1948    ///
1949    /// It depends on both dimensions — the cycle recovers only if every one of `num_ssa_parts`
1950    /// polynomials does — so both have to reach `default_surplus_for`, and the deployed split has to
1951    /// land on the deployed constant rather than be special-cased onto it. A special case is what
1952    /// this used to be, and it made the derived value a cliff: 50 % loss tolerance at
1953    /// `ssa_part_size` 32 and ~3 % one share either side of it.
1954    #[test]
1955    fn the_derived_surplus_follows_the_configured_split() {
1956        for ssa_part_size in 2usize..=255 {
1957            let cfg = PixGlobalConfig {
1958                num_ssa_parts: 8,
1959                ssa_part_size,
1960                ..Default::default()
1961            };
1962            let surplus = cfg.surplus_shares();
1963            assert_eq!(
1964                hopr_protocol_pix::default_surplus_for(8, ssa_part_size as u8) as usize,
1965                surplus
1966            );
1967            assert!(
1968                surplus > 0,
1969                "ssa_part_size {ssa_part_size} derives no surplus, i.e. no loss tolerance at all"
1970            );
1971            assert!(
1972                cfg.validate().is_ok(),
1973                "a derived surplus must never fail the bound it is derived under"
1974            );
1975        }
1976
1977        // No cliff: at the deployed polynomial count the surplus never falls as the threshold rises,
1978        // and in particular not either side of the deployed threshold.
1979        let at = |num_ssa_parts: usize, ssa_part_size: usize| {
1980            PixGlobalConfig {
1981                num_ssa_parts,
1982                ssa_part_size,
1983                ..Default::default()
1984            }
1985            .surplus_shares()
1986        };
1987        let polys = DEFAULT_PIX_POLYS_PER_SSA as usize;
1988        for ssa_part_size in 3usize..=255 {
1989            assert!(
1990                at(polys, ssa_part_size) >= at(polys, ssa_part_size - 1),
1991                "the derived surplus falls from ssa_part_size {} to {ssa_part_size}",
1992                ssa_part_size - 1
1993            );
1994        }
1995
1996        // The polynomial count reaches the derivation too: more polynomials, more for every one of
1997        // them to survive.
1998        assert!(at(8192, 32) > at(4096, 32), "the surplus must grow with num_ssa_parts");
1999
2000        // And the deployed split resolves to the deployed constant by derivation, not by fiat.
2001        assert_eq!(
2002            hopr_protocol_pix::DEFAULT_SURPLUS_SHARES as usize,
2003            PixGlobalConfig::default().surplus_shares(),
2004            "the deployed split must derive the deployed surplus"
2005        );
2006    }
2007
2008    /// Both SSA batch knobs are bounded by [`MAX_SSA_BATCH_SIZE`], and the `range` attribute on
2009    /// `max_ssas_per_request` has to spell that ceiling out as a literal — so assert the two agree.
2010    ///
2011    /// Zero is rejected on both sides for different reasons: an Exit asking for zero SSAs would never
2012    /// send an `SsaRequest` at all, and an Entry accepting zero would reject every request it ever
2013    /// receives. Either way PIX silently stops working.
2014    #[test]
2015    fn ssa_batch_knobs_are_bounded_by_the_shared_ceiling() {
2016        // The literal in the `range` attribute must track the constant it stands for.
2017        let at_ceiling = PixGlobalConfig {
2018            max_ssas_per_request: MAX_SSA_BATCH_SIZE,
2019            ..Default::default()
2020        };
2021        assert!(
2022            at_ceiling.validate().is_ok(),
2023            "MAX_SSA_BATCH_SIZE itself must be accepted — the range literal has drifted below it"
2024        );
2025        let past_ceiling = PixGlobalConfig {
2026            max_ssas_per_request: MAX_SSA_BATCH_SIZE + 1,
2027            ..Default::default()
2028        };
2029        assert!(
2030            past_ceiling.validate().is_err(),
2031            "above MAX_SSA_BATCH_SIZE must be rejected — the range literal has drifted above it"
2032        );
2033
2034        assert!(
2035            PixGlobalConfig {
2036                max_ssas_per_request: 0,
2037                ..Default::default()
2038            }
2039            .validate()
2040            .is_err(),
2041            "an Entry accepting zero SSAs per request would reject every request"
2042        );
2043
2044        // The Exit-side knob now lives on `SupervisorConfig`, so it is `validate_pix_supervision`
2045        // that has to reject an out-of-range batch — reached through `HoprProtocolConfig`'s schema
2046        // validator rather than the incoming-config one, because the pairing needs the sibling
2047        // `pix.reconstructor` field that only the parent can see.
2048        // The budget is raised with the batch size, because the two are coupled: a batch of `n`
2049        // holds `n` live reconstructor cycles, and `validate_incoming_session_pix_config` refuses a
2050        // configuration whose declared memory cannot hold the batch it asks for. Leaving the default
2051        // 2 GiB here would make every case below fail on memory rather than on the batch range this
2052        // test is about.
2053        let with_supervision = |supervision: SupervisorConfig| HoprProtocolConfig {
2054            incoming_session_pix_config: IncomingSessionPixConfig {
2055                max_live_cycle_bytes: u64::MAX,
2056                supervision,
2057                ..Default::default()
2058            },
2059            ..Default::default()
2060        };
2061
2062        for ssas_per_request in [0, MAX_SSA_BATCH_SIZE + 1] {
2063            assert!(
2064                with_supervision(SupervisorConfig {
2065                    ssas_per_request,
2066                    ..Default::default()
2067                })
2068                .validate()
2069                .is_err(),
2070                "ssas_per_request of {ssas_per_request} is outside 1..={MAX_SSA_BATCH_SIZE} and must be rejected"
2071            );
2072        }
2073
2074        assert!(
2075            with_supervision(SupervisorConfig {
2076                ssas_per_request: MAX_SSA_BATCH_SIZE,
2077                ..Default::default()
2078            })
2079            .validate()
2080            .is_ok(),
2081            "the ceiling itself must be accepted"
2082        );
2083
2084        // The scaled deadlines are what the supervisor actually arms, so the 24 h cap has to be
2085        // applied to the product. A per-cycle duration that is fine alone must be rejected once the
2086        // batch multiplies it past the cap.
2087        //
2088        // Derived from the ceiling rather than written out, so this keeps testing the multiplication
2089        // if `MAX_SSA_BATCH_SIZE` moves again: just over `cap / n` is legal on its own at any `n`,
2090        // and always over the cap once `n` of them are chained.
2091        const SUPERVISOR_DURATION_CAP: Duration = Duration::from_secs(24 * 3600);
2092        let per_cycle = SUPERVISOR_DURATION_CAP / MAX_SSA_BATCH_SIZE as u32 + Duration::from_secs(1);
2093        assert!(
2094            with_supervision(SupervisorConfig {
2095                ssas_per_request: MAX_SSA_BATCH_SIZE,
2096                max_deposit_wait: per_cycle,
2097                ..Default::default()
2098            })
2099            .validate()
2100            .is_err(),
2101            "{MAX_SSA_BATCH_SIZE} x {per_cycle:?} of deposit wait exceeds the supervisor duration cap and must be \
2102             rejected"
2103        );
2104    }
2105
2106    /// The supervisor must be validated against the reconstructor this node will actually build.
2107    ///
2108    /// The pairing check used to read `SsaReconstructorConfig::default()` from inside a validator
2109    /// that could see only `incoming_session_pix_config`. Once `pix.reconstructor` became
2110    /// operator-settable that made the check certify a pairing the node does not run: the two halves
2111    /// are siblings, and the one doing the checking could not see the other.
2112    ///
2113    /// `max_recovery_idle` must not exceed the reconstructor's `unused_verifier_lifetime` — a
2114    /// supervisor waiting past the point where reconstructor state is dropped is waiting on a cycle
2115    /// that can no longer complete. Shortening the *reconstructor* is therefore enough to invalidate
2116    /// a supervisor that was valid at the defaults, and that is exactly what a validator reading the
2117    /// default cannot notice.
2118    #[test]
2119    fn supervision_is_validated_against_the_configured_reconstructor_not_the_default() {
2120        let shortened = HoprProtocolConfig {
2121            pix: PixGlobalConfig {
2122                reconstructor: PixReconstructorConfig {
2123                    unused_verifier_lifetime: Duration::from_secs(30),
2124                    ..Default::default()
2125                },
2126                ..Default::default()
2127            },
2128            ..Default::default()
2129        };
2130
2131        assert!(
2132            shortened.pix.validate().is_ok(),
2133            "the shortened lifetime is valid on its own — the conflict is with its sibling"
2134        );
2135        assert!(
2136            validate_incoming_session_pix_config(&shortened.incoming_session_pix_config).is_ok(),
2137            "and the supervisor is valid on its own too, which is why neither field validator catches this"
2138        );
2139        assert!(
2140            shortened.validate().is_err(),
2141            "a 30 s verifier lifetime cannot support the default 60 s max_recovery_idle, and only the parent-level \
2142             check can see both"
2143        );
2144
2145        assert!(
2146            HoprProtocolConfig::default().validate().is_ok(),
2147            "the shipping defaults must still pair"
2148        );
2149    }
2150
2151    #[test]
2152    fn egress_backpressure_timeout_rejects_sub_minimum_values() {
2153        assert!(validate_egress_backpressure_timeout(&Duration::ZERO).is_err());
2154        assert!(validate_egress_backpressure_timeout(&Duration::from_micros(500)).is_err());
2155        assert!(validate_egress_backpressure_timeout(&MIN_EGRESS_BACKPRESSURE_TIMEOUT).is_ok());
2156        assert!(validate_egress_backpressure_timeout(&DEFAULT_EGRESS_BACKPRESSURE_TIMEOUT).is_ok());
2157    }
2158
2159    #[test]
2160    fn stream_protocol_config_default_is_valid() {
2161        assert!(StreamProtocolConfig::default().validate().is_ok());
2162    }
2163
2164    #[test]
2165    fn test_valid_domains_for_looks_like_a_domain() {
2166        assert!(looks_like_domain("localhost"));
2167        assert!(looks_like_domain("hoprnet.org"));
2168        assert!(looks_like_domain("hub.hoprnet.org"));
2169    }
2170
2171    #[test]
2172    fn test_valid_domains_for_does_not_look_like_a_domain() {
2173        assert!(!looks_like_domain(".org"));
2174        assert!(!looks_like_domain("-hoprnet-.org"));
2175    }
2176
2177    #[test]
2178    fn test_valid_domains_should_be_reachable() {
2179        assert!(!is_reachable_domain("google.com"));
2180    }
2181
2182    #[test]
2183    fn test_verify_valid_ip4_addresses() {
2184        assert!(validate_ipv4_address("1.1.1.1").is_ok());
2185        assert!(validate_ipv4_address("1.255.1.1").is_ok());
2186        assert!(validate_ipv4_address("187.1.1.255").is_ok());
2187        assert!(validate_ipv4_address("127.0.0.1").is_ok());
2188    }
2189
2190    #[test]
2191    fn test_verify_invalid_ip4_addresses() {
2192        assert!(validate_ipv4_address("1.256.1.1").is_err());
2193        assert!(validate_ipv4_address("-1.1.1.255").is_err());
2194        assert!(validate_ipv4_address("127.0.0.256").is_err());
2195        assert!(validate_ipv4_address("1").is_err());
2196        assert!(validate_ipv4_address("1.1").is_err());
2197        assert!(validate_ipv4_address("1.1.1").is_err());
2198        assert!(validate_ipv4_address("1.1.1.1.1").is_err());
2199    }
2200
2201    #[test]
2202    fn test_verify_valid_dns_addresses() {
2203        assert!(validate_dns_address("localhost").is_ok());
2204        assert!(validate_dns_address("google.com").is_ok());
2205        assert!(validate_dns_address("hub.hoprnet.org").is_ok());
2206    }
2207
2208    #[test]
2209    fn test_verify_invalid_dns_addresses() {
2210        assert!(validate_dns_address("-hoprnet-.org").is_err());
2211    }
2212
2213    #[test]
2214    fn test_multiaddress_on_dappnode_default() {
2215        temp_env::with_var("DAPPNODE", Some("true"), || {
2216            assert_eq!(default_multiaddr_transport(1234), "tcp/1234");
2217        });
2218    }
2219
2220    #[cfg(feature = "p2p-announce-quic")]
2221    #[test]
2222    fn test_multiaddress_on_non_dappnode_default() {
2223        temp_env::with_vars([("DAPPNODE", Some("false")), ("HOPRD_NAT", Some("false"))], || {
2224            assert_eq!(default_multiaddr_transport(1234), "udp/1234/quic-v1");
2225        });
2226    }
2227
2228    #[cfg(not(feature = "p2p-announce-quic"))]
2229    #[test]
2230    fn test_multiaddress_on_non_dappnode_default() {
2231        assert_eq!(default_multiaddr_transport(1234), "tcp/1234");
2232    }
2233
2234    #[test]
2235    fn test_multiaddress_on_non_dappnode_uses_nat() {
2236        temp_env::with_var("HOPRD_NAT", Some("true"), || {
2237            assert_eq!(default_multiaddr_transport(1234), "tcp/1234");
2238        });
2239    }
2240
2241    #[cfg(feature = "p2p-announce-quic")]
2242    #[test]
2243    fn test_multiaddress_on_non_dappnode_not_uses_nat() {
2244        temp_env::with_var("HOPRD_NAT", Some("false"), || {
2245            assert_eq!(default_multiaddr_transport(1234), "udp/1234/quic-v1");
2246        });
2247    }
2248
2249    #[cfg(not(feature = "p2p-announce-quic"))]
2250    #[test]
2251    fn test_multiaddress_on_non_dappnode_not_uses_nat() {
2252        temp_env::with_var("HOPRD_NAT", Some("false"), || {
2253            assert_eq!(default_multiaddr_transport(1234), "tcp/1234");
2254        });
2255    }
2256
2257    #[cfg(feature = "p2p-announce-quic")]
2258    #[test]
2259    fn test_multiaddress_on_dappnode_not_uses_nat() {
2260        temp_env::with_vars([("DAPPNODE", Some("true")), ("HOPRD_NAT", Some("false"))], || {
2261            assert_eq!(default_multiaddr_transport(1234), "udp/1234/quic-v1");
2262        });
2263    }
2264
2265    #[cfg(not(feature = "p2p-announce-quic"))]
2266    #[test]
2267    fn test_multiaddress_on_dappnode_not_uses_nat() {
2268        temp_env::with_vars([("DAPPNODE", Some("true")), ("HOPRD_NAT", Some("false"))], || {
2269            assert_eq!(default_multiaddr_transport(1234), "tcp/1234");
2270        });
2271    }
2272
2273    // --- HostConfig::FromStr tests ---
2274
2275    #[test]
2276    fn host_config_parses_ipv4_address() {
2277        let cfg = HostConfig::from_str("1.2.3.4:9091").unwrap();
2278        insta::assert_debug_snapshot!(cfg);
2279    }
2280
2281    #[test]
2282    fn host_config_parses_domain() {
2283        let cfg = HostConfig::from_str("example.com:443").unwrap();
2284        insta::assert_debug_snapshot!(cfg);
2285    }
2286
2287    #[test]
2288    fn host_config_rejects_missing_port() {
2289        assert!(HostConfig::from_str("1.2.3.4").is_err());
2290    }
2291
2292    #[test]
2293    fn host_config_rejects_invalid_port() {
2294        assert!(HostConfig::from_str("1.2.3.4:abc").is_err());
2295    }
2296
2297    #[test]
2298    fn host_config_rejects_invalid_host() {
2299        assert!(HostConfig::from_str("-invalid-.com:80").is_err());
2300    }
2301
2302    #[test]
2303    fn host_config_display_roundtrip() {
2304        let cfg = HostConfig {
2305            address: HostType::IPv4("10.0.0.1".into()),
2306            port: 8080,
2307        };
2308        insta::assert_yaml_snapshot!(cfg.to_string());
2309    }
2310
2311    // --- TryFrom<&HostConfig> for Multiaddr tests ---
2312
2313    #[test]
2314    fn multiaddr_from_ipv4_host_config() {
2315        let cfg = HostConfig {
2316            address: HostType::IPv4("1.2.3.4".into()),
2317            port: 9091,
2318        };
2319        let addr = Multiaddr::try_from(&cfg).unwrap();
2320        insta::assert_yaml_snapshot!(addr.to_string());
2321    }
2322
2323    #[test]
2324    fn multiaddr_from_domain_host_config() {
2325        let cfg = HostConfig {
2326            address: HostType::Domain("example.com".into()),
2327            port: 443,
2328        };
2329        let addr = Multiaddr::try_from(&cfg).unwrap();
2330        insta::assert_yaml_snapshot!(addr.to_string());
2331    }
2332
2333    // --- SessionGlobalConfig validation tests ---
2334
2335    #[test]
2336    fn session_global_config_default_is_valid() {
2337        let cfg = SessionGlobalConfig::default();
2338        assert!(cfg.validate().is_ok());
2339    }
2340
2341    #[test]
2342    fn session_global_config_too_low_idle_timeout_is_rejected() {
2343        let cfg = SessionGlobalConfig {
2344            idle_timeout: Duration::from_millis(100),
2345            ..Default::default()
2346        };
2347        assert!(cfg.validate().is_err());
2348    }
2349
2350    #[test]
2351    fn session_global_config_too_many_retries_is_rejected() {
2352        let cfg = SessionGlobalConfig {
2353            establish_max_retries: 21,
2354            ..Default::default()
2355        };
2356        assert!(cfg.validate().is_err());
2357    }
2358
2359    // --- surb_degraded_notify_period tests ---
2360
2361    #[test]
2362    fn surb_degraded_notify_period_defaults_to_one_second() {
2363        let cfg = SessionGlobalConfig::default();
2364        assert_eq!(
2365            Some(Duration::from_secs(1)),
2366            cfg.surb_degraded_notify_period,
2367            "the fast cadence must be on by default, or a dark forward path keeps the 15 s wait"
2368        );
2369        // And it is faster than the normal period it degrades from, which is what makes it useful.
2370        assert!(
2371            cfg.surb_degraded_notify_period < cfg.surb_balance_notify_period,
2372            "the degraded period must report faster than the normal one"
2373        );
2374    }
2375
2376    #[cfg(feature = "serde")]
2377    #[test]
2378    fn surb_degraded_notify_period_null_disables_it() -> anyhow::Result<()> {
2379        let cfg: SessionGlobalConfig =
2380            serde_saphyr::from_str("surb_degraded_notify_period: null").context("null must parse")?;
2381        assert_eq!(None, cfg.surb_degraded_notify_period);
2382        assert!(cfg.validate().is_ok(), "disabling the degraded period is valid");
2383        Ok(())
2384    }
2385
2386    #[test]
2387    fn surb_degraded_notify_period_below_the_floor_is_rejected() {
2388        let cfg = SessionGlobalConfig {
2389            surb_degraded_notify_period: Some(Duration::from_millis(999)),
2390            ..Default::default()
2391        };
2392        assert!(
2393            cfg.validate().is_err(),
2394            "the same 1 s floor as the normal period applies"
2395        );
2396
2397        let at_floor = SessionGlobalConfig {
2398            surb_degraded_notify_period: Some(Duration::from_secs(1)),
2399            ..Default::default()
2400        };
2401        assert!(at_floor.validate().is_ok());
2402    }
2403
2404    #[cfg(feature = "serde")]
2405    #[test]
2406    fn surb_degraded_notify_period_parses_humantime() -> anyhow::Result<()> {
2407        let cfg: SessionGlobalConfig =
2408            serde_saphyr::from_str("surb_degraded_notify_period: 2s").context("a humantime period must parse")?;
2409        assert_eq!(Some(Duration::from_secs(2)), cfg.surb_degraded_notify_period);
2410        Ok(())
2411    }
2412
2413    // --- surb_idle_notify_period tests ---
2414
2415    #[test]
2416    fn surb_idle_notify_period_defaults_to_45_seconds() {
2417        let cfg = SessionGlobalConfig::default();
2418        assert_eq!(Some(Duration::from_secs(45)), cfg.surb_idle_notify_period);
2419        assert!(
2420            cfg.surb_idle_notify_period <= Some(cfg.idle_timeout / 4),
2421            "the default must not trigger the clamp warning"
2422        );
2423        assert!(
2424            cfg.surb_idle_notify_period > cfg.surb_balance_notify_period,
2425            "the idle period must report slower than the normal one, or it backs nothing off"
2426        );
2427        assert!(cfg.validate().is_ok());
2428    }
2429
2430    #[cfg(feature = "serde")]
2431    #[test]
2432    fn surb_idle_notify_period_null_disables_it() -> anyhow::Result<()> {
2433        let cfg: SessionGlobalConfig =
2434            serde_saphyr::from_str("surb_idle_notify_period: null").context("null must parse")?;
2435        assert_eq!(None, cfg.surb_idle_notify_period);
2436        assert!(cfg.validate().is_ok(), "disabling the idle backoff is valid");
2437        Ok(())
2438    }
2439
2440    #[test]
2441    fn surb_idle_notify_period_below_the_floor_is_rejected() {
2442        let cfg = SessionGlobalConfig {
2443            surb_idle_notify_period: Some(Duration::from_millis(999)),
2444            ..Default::default()
2445        };
2446        assert!(cfg.validate().is_err());
2447
2448        let at_floor = SessionGlobalConfig {
2449            surb_idle_notify_period: Some(Duration::from_secs(1)),
2450            ..Default::default()
2451        };
2452        assert!(at_floor.validate().is_ok());
2453    }
2454
2455    #[cfg(feature = "serde")]
2456    #[test]
2457    fn surb_idle_notify_period_parses_humantime() -> anyhow::Result<()> {
2458        let cfg: SessionGlobalConfig =
2459            serde_saphyr::from_str("surb_idle_notify_period: 45s").context("a humantime period must parse")?;
2460        assert_eq!(Some(Duration::from_secs(45)), cfg.surb_idle_notify_period);
2461        Ok(())
2462    }
2463
2464    // --- refusal_reply_budget tests ---
2465
2466    #[test]
2467    fn refusal_reply_budget_defaults_to_a_burst_of_32_and_one_reply_a_second() {
2468        let cfg = SessionGlobalConfig::default();
2469        assert_eq!(
2470            Some(RefusalReplyBudget {
2471                burst: 32,
2472                refill_period: Duration::from_secs(1),
2473            }),
2474            cfg.refusal_reply_budget
2475        );
2476        assert!(cfg.validate().is_ok());
2477    }
2478
2479    #[cfg(feature = "serde")]
2480    #[test]
2481    fn refusal_reply_budget_defaults_when_omitted_from_the_config_file() -> anyhow::Result<()> {
2482        let cfg: SessionGlobalConfig = serde_saphyr::from_str("idle_timeout: 3m").context("must parse")?;
2483        assert_eq!(
2484            SessionGlobalConfig::default().refusal_reply_budget,
2485            cfg.refusal_reply_budget
2486        );
2487        Ok(())
2488    }
2489
2490    #[cfg(feature = "serde")]
2491    #[test]
2492    fn refusal_reply_budget_null_means_unlimited() -> anyhow::Result<()> {
2493        let cfg: SessionGlobalConfig =
2494            serde_saphyr::from_str("refusal_reply_budget: null").context("null must parse")?;
2495        assert_eq!(None, cfg.refusal_reply_budget);
2496        assert!(cfg.validate().is_ok(), "an unbounded budget is valid");
2497        Ok(())
2498    }
2499
2500    #[cfg(feature = "serde")]
2501    #[test]
2502    fn refusal_reply_budget_parses_humantime() -> anyhow::Result<()> {
2503        let cfg: SessionGlobalConfig =
2504            serde_saphyr::from_str("refusal_reply_budget: { burst: 5, refill_period: 250ms }")
2505                .context("a humantime refill period must parse")?;
2506        assert_eq!(
2507            Some(RefusalReplyBudget {
2508                burst: 5,
2509                refill_period: Duration::from_millis(250),
2510            }),
2511            cfg.refusal_reply_budget
2512        );
2513        Ok(())
2514    }
2515
2516    #[test]
2517    fn refusal_reply_budget_with_a_zero_refill_period_is_rejected() {
2518        let cfg = SessionGlobalConfig {
2519            refusal_reply_budget: Some(RefusalReplyBudget {
2520                burst: 1,
2521                refill_period: Duration::ZERO,
2522            }),
2523            ..Default::default()
2524        };
2525        assert!(cfg.validate().is_err());
2526
2527        let at_floor = SessionGlobalConfig {
2528            refusal_reply_budget: Some(RefusalReplyBudget {
2529                burst: 0,
2530                refill_period: MIN_REFUSAL_REPLY_REFILL_PERIOD,
2531            }),
2532            ..Default::default()
2533        };
2534        assert!(
2535            at_floor.validate().is_ok(),
2536            "a zero burst is a valid way to never answer"
2537        );
2538    }
2539
2540    #[cfg(feature = "serde")]
2541    #[test]
2542    fn refusal_reply_budget_rejects_unknown_fields() {
2543        assert!(serde_saphyr::from_str::<SessionGlobalConfig>("refusal_reply_budget: { burts: 5 }").is_err());
2544    }
2545
2546    #[test]
2547    fn stream_protocol_config_default_has_expected_values() {
2548        let cfg = StreamProtocolConfig::default();
2549        assert_eq!(cfg.per_peer_channel_capacity, DEFAULT_PER_PEER_CHANNEL_CAPACITY);
2550        assert_eq!(cfg.stream_open_timeout, DEFAULT_STREAM_OPEN_TIMEOUT);
2551        assert_eq!(
2552            cfg.frame_writer_backpressure_bytes,
2553            DEFAULT_FRAME_WRITER_BACKPRESSURE_BYTES
2554        );
2555        cfg.validate().expect("default StreamProtocolConfig must be valid");
2556    }
2557
2558    #[test]
2559    fn stream_protocol_config_zero_capacity_is_rejected() {
2560        let cfg = StreamProtocolConfig {
2561            per_peer_channel_capacity: 0,
2562            ..Default::default()
2563        };
2564        assert!(cfg.validate().is_err());
2565    }
2566
2567    #[test]
2568    fn stream_protocol_config_zero_backpressure_bytes_is_rejected() {
2569        let cfg = StreamProtocolConfig {
2570            frame_writer_backpressure_bytes: 0,
2571            ..Default::default()
2572        };
2573        assert!(cfg.validate().is_err());
2574    }
2575
2576    #[test]
2577    fn stream_protocol_config_zero_stream_open_timeout_is_rejected() {
2578        let cfg = StreamProtocolConfig {
2579            stream_open_timeout: Duration::ZERO,
2580            ..Default::default()
2581        };
2582        assert!(cfg.validate().is_err());
2583    }
2584
2585    #[test]
2586    fn stream_protocol_config_zero_backpressure_timeout_is_rejected() {
2587        // Proves the field `#[validate(custom)]` attribute is actually wired into the derived
2588        // `StreamProtocolConfig::validate()` — which the parent `HoprProtocolConfig`/`HoprLibConfig`
2589        // invoke via `#[validate(nested)]` at node build time (builder.rs `cfg.validate()?`).
2590        let cfg = StreamProtocolConfig {
2591            egress_backpressure_timeout: Duration::ZERO,
2592            ..Default::default()
2593        };
2594        assert!(cfg.validate().is_err());
2595    }
2596}