Skip to main content

rings_node/onion/
pipeline.rs

1//! Onion Kleisli pipelines: typed morphisms of the free category `Free(G_Σ)` over the static
2//! signature `Σ` (#834 D3, D4a, D4b, L1, L2, L3).
3//!
4//! ```text
5//! θ : X ↝ Y    ϑ : Y ↝ Z
6//! ────────────────────────
7//!    θ ⋙ ϑ : X ↝ Z
8//! ```
9//!
10//! Laws:
11//!
12//! - **Well-formedness** (D4a). A normal-form pipeline `P = (f₁, ā₁) ⋙ … ⋙ (fₙ, āₙ)` satisfies
13//!   `1 ≤ n ≤ MAX_ONION_LOOP_SYMBOLS = 4`, `∀ k < n: Out_{fₖ} = In_{fₖ₊₁}`,
14//!   `∀ k < n: pos(fₖ) = Intermediate`, and `fₙ ∈ Σ_W ⇒ n = 1`. Every normal-form pipeline is
15//!   therefore either one world-facing session symbol (`Session`) or `1 ..= 4` composable `invoke`
16//!   stages (`Invoke`). Empty pipelines, mismatched widths (`Out ≠ In`), world-facing symbols
17//!   before the end, `invoke ⋙ world-facing` compositions, and `> 4` symbols are rejected at
18//!   construction.
19//! - **Identity** (L1). `relay : X ↝ X` is the identity morphism; normal form `nf` removes every
20//!   `relay` step, so `nf(relay ⋙ P) = nf(P) = nf(P ⋙ relay)` and `LoopOf(relay ⋙ P) =_d LoopOf(P)`.
21//! - **Associativity** (L2). `(f ⋙ g) ⋙ h = f ⋙ (g ⋙ h)` as normal-form pipelines and on carried
22//!   values.
23//! - **Sealed backend arguments** (D3). An `invoke` application encodes `(ω, ā′)` inside the
24//!   fixed `A = 64` argument bytes of its hop's layer; the public symbol word `σ` exposes only
25//!   `OnionInvokeShape`s, never backend names `ω` or constants `ā′`.
26//! - **Width** (L3). For an `OnionInvokePipeline`, `loop_class` selects the least `OnionLoopClass`
27//!   `b` with `|enc(v₀)| < C₀` and `∀ k: W(fₖ) < C₀`.
28
29use std::time::Duration;
30
31use super::signature::OnionBackendName;
32use super::signature::OnionInputType;
33use super::signature::OnionInvokeShape;
34use super::signature::OnionServiceName;
35use super::signature::OnionShape;
36use super::signature::OnionWidthClass;
37use super::signature::ONION_BACKEND_NAME_MAX_BYTES;
38use super::sphinx::class::OnionLoopClass;
39use super::sphinx::layer::OnionApplication;
40use super::sphinx::layer::OnionArguments;
41use super::sphinx::layer::ONION_ARGUMENT_BYTES;
42use super::MAX_ONION_LOOP_SYMBOLS;
43use crate::error::Error;
44use crate::error::Result;
45
46/// Two-byte header `|ω|:u8 ‖ |ā′|:u8` of [`OnionInvokeArguments`].
47const ONION_INVOKE_ARG_HEADER_BYTES: usize = 2;
48
49/// Maximum inline constant bytes `|ā′|` when `|ω| = 1`: `64 − 2 − 1 = 61` bytes.
50pub const ONION_INVOKE_MAX_CONSTANTS_BYTES: usize =
51    ONION_ARGUMENT_BYTES - ONION_INVOKE_ARG_HEADER_BYTES - 1;
52
53// Every fixed width class in `𝒲` fits inside `KiB64`'s padded carry slot (#834 L3).
54const _: () = assert!(OnionWidthClass::KiB16.bytes() <= OnionLoopClass::KiB64.value_capacity());
55// Even a 32-byte backend name leaves 30 bytes of inline constants inside `A = 64` (#834 D3).
56const _: () =
57    assert!(ONION_INVOKE_ARG_HEADER_BYTES + ONION_BACKEND_NAME_MAX_BYTES < ONION_ARGUMENT_BYTES);
58
59/// Carried value types (vertices of `G_Σ`, #834 D1′, D4a).
60#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
61pub enum OnionValueType {
62    /// `()`, the empty value `ε` (`0` bytes, #834 D7).
63    Unit,
64    /// A fixed-width byte string of `W` bytes (#834 D1′, L3).
65    Fixed(OnionWidthClass),
66    /// A session stream frame (`tcp`, `https`, #834 D2′).
67    Frame,
68}
69
70impl From<OnionInputType> for OnionValueType {
71    fn from(input: OnionInputType) -> Self {
72        match input {
73            OnionInputType::Unit => Self::Unit,
74            OnionInputType::Fixed(width) => Self::Fixed(width),
75        }
76    }
77}
78
79impl From<OnionWidthClass> for OnionValueType {
80    fn from(width: OnionWidthClass) -> Self {
81        Self::Fixed(width)
82    }
83}
84
85/// Sealed layer arguments `ā = (ω, ā′)` of an `invoke` hop (#834 D3), encoded canonically in
86/// `A = 64` bytes as `|ω|:u8 ‖ |ā′|:u8 ‖ ω ‖ ā′ ‖ 0^{62 − |ω| − |ā′|}`.
87///
88/// Law (canonical): `decode(encode(args)) = Some(args)`, and `decode(w) = Some(args)` implies
89/// `encode(args) = w` (non-zero trailing padding, invalid `ω`, or out-of-range lengths return
90/// `None`).
91#[derive(Clone, Debug, Eq, PartialEq)]
92pub struct OnionInvokeArguments {
93    backend: OnionBackendName,
94    constants: Vec<u8>,
95}
96
97impl OnionInvokeArguments {
98    /// Validate `|enc(ω, ā′)| ≤ A = 64` and construct sealed `invoke` arguments.
99    pub fn new(
100        backend: OnionBackendName,
101        constants: impl Into<Vec<u8>>,
102    ) -> std::result::Result<Self, OnionPipelineError> {
103        let constants = constants.into();
104        let used = ONION_INVOKE_ARG_HEADER_BYTES
105            .saturating_add(backend.as_str().len())
106            .saturating_add(constants.len());
107        if used > ONION_ARGUMENT_BYTES {
108            return Err(OnionPipelineError::ArgumentsTooWide {
109                backend_bytes: backend.as_str().len(),
110                constants_bytes: constants.len(),
111                capacity: ONION_ARGUMENT_BYTES - ONION_INVOKE_ARG_HEADER_BYTES,
112            });
113        }
114        Ok(Self { backend, constants })
115    }
116
117    /// Return the backend name `ω`.
118    pub const fn backend(&self) -> &OnionBackendName {
119        &self.backend
120    }
121
122    /// Return the inline client constants `ā′`.
123    pub fn constants(&self) -> &[u8] {
124        self.constants.as_slice()
125    }
126
127    /// Destructure into `(backend, constants)`.
128    pub fn into_parts(self) -> (OnionBackendName, Vec<u8>) {
129        (self.backend, self.constants)
130    }
131
132    /// Encode `(ω, ā′)` into the fixed `A = 64`-byte layer argument slot.
133    pub(crate) fn encode(&self) -> OnionArguments {
134        let mut bytes = [0_u8; ONION_ARGUMENT_BYTES];
135        let name = self.backend.as_str().as_bytes();
136        let constants = self.constants.as_slice();
137        bytes[0] = name.len() as u8;
138        bytes[1] = constants.len() as u8;
139        bytes
140            .iter_mut()
141            .skip(ONION_INVOKE_ARG_HEADER_BYTES)
142            .zip(name.iter().chain(constants.iter()))
143            .for_each(|(slot, byte)| *slot = *byte);
144        OnionArguments::new(bytes)
145    }
146
147    /// Decode `(ω, ā′)` from `arguments`, rejecting any non-canonical 64-byte string.
148    pub(crate) fn decode(arguments: &OnionArguments) -> Option<Self> {
149        let bytes = arguments.as_bytes();
150        let name_len = usize::from(bytes[0]);
151        let const_len = usize::from(bytes[1]);
152        if name_len == 0 || name_len > ONION_BACKEND_NAME_MAX_BYTES {
153            return None;
154        }
155        let name_end = ONION_INVOKE_ARG_HEADER_BYTES.checked_add(name_len)?;
156        let end = name_end.checked_add(const_len)?;
157        if bytes.get(end..)?.iter().any(|byte| *byte != 0) {
158            return None;
159        }
160        let name_str =
161            std::str::from_utf8(bytes.get(ONION_INVOKE_ARG_HEADER_BYTES..name_end)?).ok()?;
162        let backend = OnionBackendName::parse(name_str).ok()?;
163        let constants = bytes.get(name_end..end)?.to_vec();
164        Some(Self { backend, constants })
165    }
166}
167
168/// Errors when constructing or composing an onion Kleisli pipeline (#834 D3, D4a).
169#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
170pub enum OnionPipelineError {
171    /// Empty normal-form pipeline (`n = 0`, e.g., `relay` alone with no symbol application).
172    #[error("onion pipeline must apply at least one non-relay symbol")]
173    Empty,
174    /// More than `MAX_ONION_LOOP_SYMBOLS` non-relay symbol applications.
175    #[error("onion pipeline has {symbols} symbols; maximum is {max_symbols}")]
176    TooManySymbols {
177        /// Requested non-relay symbol count.
178        symbols: usize,
179        /// Protocol bound `MAX_ONION_LOOP_SYMBOLS`.
180        max_symbols: usize,
181    },
182    /// Sequential composition `θ ⋙ ϑ` where `Out_θ ≠ In_ϑ` (#834 D4a).
183    #[error("onion pipeline type mismatch: {left_out:?} cannot feed {right_in:?}")]
184    TypeMismatch {
185        /// Output type of the left morphism.
186        left_out: OnionValueType,
187        /// Input type of the right morphism.
188        right_in: OnionValueType,
189    },
190    /// A world-facing symbol appeared before the end of the pipeline (#834 D4a).
191    #[error("world-facing onion symbol must be terminal")]
192    WorldFacingNotTerminal,
193    /// A world-facing session symbol was composed after an intermediate symbol (#834 D4a, Phase 2b).
194    #[error("world-facing session symbol must stand alone (n = 1)")]
195    SessionSymbolMustStandAlone,
196    /// Inline `(ω, ā′)` exceeds the 64-byte layer argument field (#834 D3).
197    #[error(
198        "onion invoke arguments ({backend_bytes}B backend + {constants_bytes}B constants) exceed {capacity}B inline capacity"
199    )]
200    ArgumentsTooWide {
201        /// Backend name length in bytes.
202        backend_bytes: usize,
203        /// Inline constant length in bytes.
204        constants_bytes: usize,
205        /// Combined payload byte capacity (`62` bytes).
206        capacity: usize,
207    },
208}
209
210impl From<OnionPipelineError> for Error {
211    fn from(error: OnionPipelineError) -> Self {
212        Self::InvalidConfig(error.to_string())
213    }
214}
215
216/// One placed-to-be `invoke` stage `(f, (ω, ā′))` of a Kleisli pipeline (#834 D3, D4a).
217#[derive(Clone, Debug, Eq, PartialEq)]
218pub struct OnionInvokeStage {
219    shape: OnionInvokeShape,
220    arguments: OnionInvokeArguments,
221}
222
223impl OnionInvokeStage {
224    /// Construct one `invoke` application `(shape, (backend, constants))`, validating `|enc(ω, ā′)| ≤ A`.
225    pub fn new(
226        shape: OnionInvokeShape,
227        backend: OnionBackendName,
228        constants: impl Into<Vec<u8>>,
229    ) -> std::result::Result<Self, OnionPipelineError> {
230        Ok(Self {
231            shape,
232            arguments: OnionInvokeArguments::new(backend, constants)?,
233        })
234    }
235
236    /// Return the shape `f ∈ Σ_I`.
237    pub const fn shape(&self) -> OnionInvokeShape {
238        self.shape
239    }
240
241    /// Return the backend name `ω ∈ Ω`.
242    pub const fn backend(&self) -> &OnionBackendName {
243        self.arguments.backend()
244    }
245
246    /// Return the inline constants `ā′`.
247    pub fn constants(&self) -> &[u8] {
248        self.arguments.constants()
249    }
250
251    /// Lift this single stage into a 1-stage [`OnionInvokePipeline`].
252    pub fn into_pipeline(self) -> OnionInvokePipeline {
253        OnionInvokePipeline { stages: vec![self] }
254    }
255
256    /// Kleisli-compose `self ⋙ next` into a 2-stage [`OnionInvokePipeline`] (#834 D4a).
257    pub fn then(
258        self,
259        next: OnionInvokeStage,
260    ) -> std::result::Result<OnionInvokePipeline, OnionPipelineError> {
261        self.into_pipeline().then_stage(next)
262    }
263
264    pub(crate) fn to_application(&self) -> OnionApplication {
265        OnionApplication {
266            symbol: OnionShape::Invoke(self.shape),
267            arguments: self.arguments.encode(),
268        }
269    }
270}
271
272/// Well-formed one-shot Kleisli pipeline `(f₁, ā₁) ⋙ … ⋙ (fₙ, āₙ)` over `Σ_I` (#834 D4a, D4b).
273///
274/// Invariants:
275/// - `1 ≤ stages.len() ≤ MAX_ONION_LOOP_SYMBOLS`;
276/// - `∀ k < n: OnionValueType::Fixed(stages[k - 1].shape.output()) == OnionValueType::from(stages[k].shape.input())`.
277#[derive(Clone, Debug, Eq, PartialEq)]
278pub struct OnionInvokePipeline {
279    stages: Vec<OnionInvokeStage>,
280}
281
282impl OnionInvokePipeline {
283    /// Build a pipeline from a non-empty sequence of stages, verifying `Out_{fₖ} = In_{fₖ₊₁}` and
284    /// `n ≤ MAX_ONION_LOOP_SYMBOLS`.
285    pub fn from_stages(
286        stages: impl IntoIterator<Item = OnionInvokeStage>,
287    ) -> std::result::Result<Self, OnionPipelineError> {
288        let mut iter = stages.into_iter();
289        let first = iter.next().ok_or(OnionPipelineError::Empty)?;
290        iter.try_fold(first.into_pipeline(), Self::then_stage)
291    }
292
293    /// Append one `invoke` stage (`self ⋙ next`).
294    pub fn then_stage(
295        mut self,
296        next: OnionInvokeStage,
297    ) -> std::result::Result<Self, OnionPipelineError> {
298        let left_out = OnionValueType::Fixed(self.output());
299        let right_in = OnionValueType::from(next.shape.input());
300        if left_out != right_in {
301            return Err(OnionPipelineError::TypeMismatch { left_out, right_in });
302        }
303        let symbols = self.stages.len() + 1;
304        if symbols > MAX_ONION_LOOP_SYMBOLS {
305            return Err(OnionPipelineError::TooManySymbols {
306                symbols,
307                max_symbols: MAX_ONION_LOOP_SYMBOLS,
308            });
309        }
310        self.stages.push(next);
311        Ok(self)
312    }
313
314    /// Kleisli-compose two pipelines (`self ⋙ other`), checking boundary types and total length.
315    pub fn then(self, other: Self) -> std::result::Result<Self, OnionPipelineError> {
316        other.stages.into_iter().try_fold(self, Self::then_stage)
317    }
318
319    /// Return the non-empty slice of stages in pipeline order.
320    pub fn stages(&self) -> &[OnionInvokeStage] {
321        self.stages.as_slice()
322    }
323
324    /// Return `n ∈ [1, MAX_ONION_LOOP_SYMBOLS]`, the number of `invoke` stages.
325    pub fn len(&self) -> usize {
326        self.stages.len()
327    }
328
329    /// Always `false`: a constructed [`OnionInvokePipeline`] has `n ≥ 1` stages.
330    pub fn is_empty(&self) -> bool {
331        self.stages.is_empty()
332    }
333
334    /// Input specification `In_{f₁}` consumed from the client.
335    pub fn input(&self) -> OnionInputType {
336        self.stages
337            .first()
338            .map_or(OnionInputType::Unit, |stage| stage.shape.input())
339    }
340
341    /// Exact byte length of the initial carried input `v₀` required from the client.
342    pub fn input_bytes(&self) -> usize {
343        self.input().bytes()
344    }
345
346    /// Output width class `Out_{fₙ}` returned to the client.
347    pub fn output(&self) -> OnionWidthClass {
348        self.stages
349            .last()
350            .map_or(OnionWidthClass::B32, |stage| stage.shape.output())
351    }
352
353    /// Exact byte length `W(fₙ)` of the result returned to the client.
354    pub fn output_bytes(&self) -> usize {
355        self.output().bytes()
356    }
357
358    /// Sum `Σ_{k=1..n} L(fₖ)` of per-hop computation delays along the pipeline (L4).
359    pub fn total_latency(&self) -> Duration {
360        self.stages.iter().fold(Duration::ZERO, |acc, stage| {
361            acc.saturating_add(stage.shape.latency().duration())
362        })
363    }
364
365    /// Public symbol word `σ` of shapes only, omitting backend names `ω` and constants `ā′` (#834 D3).
366    pub fn symbol_word(&self) -> Vec<OnionInvokeShape> {
367        self.stages.iter().map(OnionInvokeStage::shape).collect()
368    }
369
370    /// The `(shape, backend)` registration pairs required along the pipeline, in stage order (D2).
371    pub fn required_symbols(&self) -> Vec<(OnionInvokeShape, OnionBackendName)> {
372        self.stages
373            .iter()
374            .map(|stage| (stage.shape, stage.backend().clone()))
375            .collect()
376    }
377
378    /// Least loop class `b` satisfying `|v₀| < C₀` and `∀ k: W(fₖ) < C₀` (#834 L3).
379    pub fn loop_class(&self) -> OnionLoopClass {
380        let widest = self.stages.iter().fold(self.input_bytes(), |acc, stage| {
381            acc.max(stage.shape.output_bytes())
382        });
383        OnionLoopClass::least_for_value_bytes(widest).unwrap_or(OnionLoopClass::MiB12)
384    }
385
386    pub(crate) fn applications(&self) -> Vec<OnionApplication> {
387        self.stages
388            .iter()
389            .map(OnionInvokeStage::to_application)
390            .collect()
391    }
392}
393
394impl From<OnionInvokeStage> for OnionInvokePipeline {
395    fn from(stage: OnionInvokeStage) -> Self {
396        stage.into_pipeline()
397    }
398}
399
400/// Morphism in `Free(G_Σ)` before normal-form `relay` elimination (#834 D4a, L1, L2).
401#[derive(Clone, Debug, Eq, PartialEq)]
402pub struct OnionPipelineTerm {
403    input: OnionValueType,
404    output: OnionValueType,
405    non_relay: Vec<TermAtom>,
406}
407
408#[derive(Clone, Debug, Eq, PartialEq)]
409enum TermAtom {
410    Invoke(OnionInvokeStage),
411    WorldFacing(OnionServiceName),
412}
413
414impl OnionPipelineTerm {
415    /// Identity morphism `relay : ty ↝ ty` (`L(relay) = 0`, #834 L1).
416    pub const fn relay(ty: OnionValueType) -> Self {
417        Self {
418            input: ty,
419            output: ty,
420            non_relay: Vec::new(),
421        }
422    }
423
424    /// Atomic `invoke` morphism `In_f ↝ Out_f`.
425    pub fn invoke(stage: OnionInvokeStage) -> Self {
426        let input = OnionValueType::from(stage.shape.input());
427        let output = OnionValueType::Fixed(stage.shape.output());
428        Self {
429            input,
430            output,
431            non_relay: vec![TermAtom::Invoke(stage)],
432        }
433    }
434
435    /// Atomic world-facing session morphism `Frame ↝ Frame`.
436    pub fn world_facing(service: OnionServiceName) -> Self {
437        Self {
438            input: OnionValueType::Frame,
439            output: OnionValueType::Frame,
440            non_relay: vec![TermAtom::WorldFacing(service)],
441        }
442    }
443
444    /// Return the domain `In` of this morphism.
445    pub const fn input_type(&self) -> OnionValueType {
446        self.input
447    }
448
449    /// Return the codomain `Out` of this morphism.
450    pub const fn output_type(&self) -> OnionValueType {
451        self.output
452    }
453
454    /// Sequential composition `self ⋙ next` in `Free(G_Σ)` (#834 D4a, L1, L2).
455    pub fn then(mut self, next: Self) -> std::result::Result<Self, OnionPipelineError> {
456        if self.output != next.input {
457            return Err(OnionPipelineError::TypeMismatch {
458                left_out: self.output,
459                right_in: next.input,
460            });
461        }
462        if !next.non_relay.is_empty()
463            && self
464                .non_relay
465                .iter()
466                .any(|atom| matches!(atom, TermAtom::WorldFacing(_)))
467        {
468            return Err(OnionPipelineError::WorldFacingNotTerminal);
469        }
470        self.non_relay.extend(next.non_relay);
471        if self.non_relay.len() > 1
472            && matches!(self.non_relay.last(), Some(TermAtom::WorldFacing(_)))
473        {
474            return Err(OnionPipelineError::SessionSymbolMustStandAlone);
475        }
476        if self.non_relay.len() > MAX_ONION_LOOP_SYMBOLS {
477            return Err(OnionPipelineError::TooManySymbols {
478                symbols: self.non_relay.len(),
479                max_symbols: MAX_ONION_LOOP_SYMBOLS,
480            });
481        }
482        self.output = next.output;
483        Ok(self)
484    }
485
486    /// Normalize (`nf`, deleting `relay` identities) into a well-formed [`OnionPipeline`],
487    /// rejecting an empty normal form (`relay` alone).
488    pub fn into_pipeline(self) -> std::result::Result<OnionPipeline, OnionPipelineError> {
489        if self.non_relay.is_empty() {
490            return Err(OnionPipelineError::Empty);
491        }
492        if self.non_relay.len() == 1 {
493            if let Some(TermAtom::WorldFacing(service)) = self.non_relay.first() {
494                return Ok(OnionPipeline::Session(service.clone()));
495            }
496        }
497        let mut stages = Vec::with_capacity(self.non_relay.len());
498        for (index, atom) in self.non_relay.into_iter().enumerate() {
499            match atom {
500                TermAtom::Invoke(stage) => stages.push(stage),
501                TermAtom::WorldFacing(_) => {
502                    return Err(if index + 1 == stages.capacity() {
503                        OnionPipelineError::SessionSymbolMustStandAlone
504                    } else {
505                        OnionPipelineError::WorldFacingNotTerminal
506                    });
507                }
508            }
509        }
510        OnionInvokePipeline::from_stages(stages).map(OnionPipeline::Invoke)
511    }
512}
513
514/// Normal-form well-formed pipeline `nf(P)` (#834 D4a, L1): either one world-facing session
515/// symbol (`n = 1`) or a 1..=4 stage `invoke` Kleisli pipeline.
516#[derive(Clone, Debug, Eq, PartialEq)]
517pub enum OnionPipeline {
518    /// One-shot intermediate computation pipeline `(f₁, ā₁) ⋙ … ⋙ (fₙ, āₙ)`.
519    Invoke(OnionInvokePipeline),
520    /// Single world-facing session symbol (`tcp`, `https`).
521    Session(OnionServiceName),
522}
523
524impl OnionPipeline {
525    /// Public symbol word `σ` of shapes only (#834 D3).
526    pub fn symbol_word(&self) -> Vec<OnionShape> {
527        match self {
528            Self::Invoke(pipeline) => pipeline
529                .symbol_word()
530                .into_iter()
531                .map(OnionShape::Invoke)
532                .collect(),
533            Self::Session(service) => vec![OnionShape::WorldFacing(service.clone())],
534        }
535    }
536}
537
538/// Validate `route` and `pipeline` compatibility helper returning crate [`Result`].
539pub(crate) fn ensure_pipeline_input_width(
540    pipeline: &OnionInvokePipeline,
541    input: &[u8],
542) -> Result<()> {
543    let expected = pipeline.input_bytes();
544    if input.len() != expected {
545        return Err(Error::InvalidConfig(format!(
546            "onion pipeline expects {expected}-byte input, got {} bytes",
547            input.len()
548        )));
549    }
550    Ok(())
551}
552
553#[cfg(test)]
554mod tests {
555    use rand::SeedableRng;
556    use rand_chacha::ChaCha20Rng;
557    use rings_core::dht::Did;
558
559    use super::OnionInvokeArguments;
560    use super::OnionInvokePipeline;
561    use super::OnionInvokeStage;
562    use super::OnionPipeline;
563    use super::OnionPipelineError;
564    use super::OnionPipelineTerm;
565    use super::OnionValueType;
566    use crate::onion::signature::OnionBackendName;
567    use crate::onion::signature::OnionInputType;
568    use crate::onion::signature::OnionInvokeShape;
569    use crate::onion::signature::OnionLatencyClass;
570    use crate::onion::signature::OnionServiceName;
571    use crate::onion::signature::OnionShape;
572    use crate::onion::signature::OnionWidthClass;
573    use crate::onion::sphinx::builder::build_loop;
574    use crate::onion::sphinx::class::OnionLoopClass;
575    use crate::onion::sphinx::layer::OnionArguments;
576    use crate::onion::sphinx::layer::ONION_ARGUMENT_BYTES;
577    use crate::onion::tests::fixture::fixture_secret;
578    use crate::onion::tests::fixture::grid_expiry;
579    use crate::onion::tests::fixture::session_loop;
580    use crate::onion::OnionProcessEpoch;
581    use crate::onion::OnionRouteHop;
582
583    fn stage(
584        input: OnionInputType,
585        output: OnionWidthClass,
586        latency: OnionLatencyClass,
587        backend: &str,
588        constants: &[u8],
589    ) -> OnionInvokeStage {
590        OnionInvokeStage::new(
591            OnionInvokeShape::new(input, output, latency),
592            OnionBackendName::parse(backend).expect("backend"),
593            constants,
594        )
595        .expect("valid stage")
596    }
597
598    /// D3: `(ω, ā′)` round-trips canonically through `A = 64` bytes, rejects non-zero trailing
599    /// padding or invalid backend names, and `symbol_word` never exposes `ω`.
600    #[test]
601    fn test_invoke_arguments_are_canonical_and_hidden_from_symbol_word() {
602        let backend = OnionBackendName::parse("jev.typesafe").expect("backend");
603        let constants = vec![0x00, 0x11, 0x22, 0x00];
604        let args = OnionInvokeArguments::new(backend.clone(), constants.clone()).expect("fits");
605        let encoded = args.encode();
606        let decoded = OnionInvokeArguments::decode(&encoded).expect("decodes");
607        assert_eq!(decoded, args);
608        assert_eq!(decoded.encode(), encoded);
609
610        // Non-zero trailing padding is rejected so every application has one canonical encoding.
611        let mut non_canonical = *encoded.as_bytes();
612        non_canonical[ONION_ARGUMENT_BYTES - 1] = 1;
613        assert!(OnionInvokeArguments::decode(&OnionArguments::new(non_canonical)).is_none());
614
615        // Oversized inline constants fail closed at construction.
616        assert!(matches!(
617            OnionInvokeArguments::new(backend, vec![0xaa; 60]),
618            Err(OnionPipelineError::ArgumentsTooWide { .. })
619        ));
620
621        // Public symbol word `σ` exposes shapes only, never `ω`.
622        let p = stage(
623            OnionInputType::Fixed(OnionWidthClass::B32),
624            OnionWidthClass::B64,
625            OnionLatencyClass::Ms500,
626            "jev.typesafe",
627            b"secret-const",
628        )
629        .into_pipeline();
630        let word = OnionPipeline::Invoke(p).symbol_word();
631        assert_eq!(word.len(), 1);
632        assert!(matches!(word[0], OnionShape::Invoke(_)));
633        assert!(!word[0].to_string().contains("jev"));
634    }
635
636    /// D4a: `Out ≠ In`, `WorldFacing` before the last symbol, `invoke ⋙ WorldFacing`, empty
637    /// pipeline, and `> 4` symbols are all rejected at construction.
638    #[test]
639    fn test_pipeline_type_and_position_checking() {
640        // Empty normal form (`relay` alone) rejected.
641        let only_relay = OnionPipelineTerm::relay(OnionValueType::Fixed(OnionWidthClass::B32))
642            .then(OnionPipelineTerm::relay(OnionValueType::Fixed(
643                OnionWidthClass::B32,
644            )))
645            .expect("relay ⋙ relay composes as term");
646        assert_eq!(only_relay.into_pipeline(), Err(OnionPipelineError::Empty));
647        assert_eq!(
648            OnionInvokePipeline::from_stages(Vec::new()),
649            Err(OnionPipelineError::Empty)
650        );
651
652        // Out ≠ In rejected.
653        let f = stage(
654            OnionInputType::Fixed(OnionWidthClass::B32),
655            OnionWidthClass::B64,
656            OnionLatencyClass::Ms10,
657            "add",
658            b"1",
659        );
660        let g_bad = stage(
661            OnionInputType::Fixed(OnionWidthClass::B32),
662            OnionWidthClass::B32,
663            OnionLatencyClass::Ms10,
664            "mul",
665            b"2",
666        );
667        assert_eq!(
668            f.clone().then(g_bad),
669            Err(OnionPipelineError::TypeMismatch {
670                left_out: OnionValueType::Fixed(OnionWidthClass::B64),
671                right_in: OnionValueType::Fixed(OnionWidthClass::B32),
672            })
673        );
674
675        // WorldFacing before last symbol rejected.
676        let tcp = OnionPipelineTerm::world_facing(OnionServiceName::tcp());
677        let https = OnionPipelineTerm::world_facing(OnionServiceName::https());
678        assert_eq!(
679            tcp.then(https),
680            Err(OnionPipelineError::WorldFacingNotTerminal)
681        );
682
683        // > 4 symbols rejected.
684        let id_stage = || {
685            stage(
686                OnionInputType::Fixed(OnionWidthClass::B32),
687                OnionWidthClass::B32,
688                OnionLatencyClass::Ms10,
689                "step",
690                b"",
691            )
692        };
693        let four = OnionInvokePipeline::from_stages((0..4).map(|_| id_stage())).expect("4 fits");
694        assert_eq!(
695            four.then_stage(id_stage()),
696            Err(OnionPipelineError::TooManySymbols {
697                symbols: 5,
698                max_symbols: 4,
699            })
700        );
701    }
702
703    /// L1 & L2: `nf(relay ⋙ P) = P = nf(P ⋙ relay)`, `(f ⋙ g) ⋙ h = f ⋙ (g ⋙ h)`, and
704    /// `LoopOf(relay ⋙ P)` produces byte-identical loop cells to `LoopOf(P)` under the same seed.
705    #[test]
706    fn test_identity_normal_form_and_associativity_laws() {
707        let f = stage(
708            OnionInputType::Unit,
709            OnionWidthClass::B32,
710            OnionLatencyClass::Ms10,
711            "seed",
712            b"a",
713        );
714        let g = stage(
715            OnionInputType::Fixed(OnionWidthClass::B32),
716            OnionWidthClass::B64,
717            OnionLatencyClass::Ms100,
718            "expand",
719            b"b",
720        );
721        let h = stage(
722            OnionInputType::Fixed(OnionWidthClass::B64),
723            OnionWidthClass::B256,
724            OnionLatencyClass::Ms500,
725            "finalize",
726            b"c",
727        );
728
729        // L2: (f ⋙ g) ⋙ h == f ⋙ (g ⋙ h)
730        let left = f
731            .clone()
732            .then(g.clone())
733            .expect("f ⋙ g")
734            .then_stage(h.clone())
735            .expect("(f ⋙ g) ⋙ h");
736        let right = f
737            .clone()
738            .into_pipeline()
739            .then(g.clone().then(h).expect("g ⋙ h"))
740            .expect("f ⋙ (g ⋙ h)");
741        assert_eq!(left, right);
742
743        // L1: relay ⋙ f ⋙ relay normalizes to f, and builds identical loop bytes.
744        let plain = f.clone().into_pipeline();
745        let wrapped_term = OnionPipelineTerm::relay(OnionValueType::Unit)
746            .then(OnionPipelineTerm::invoke(f))
747            .expect("relay ⋙ f")
748            .then(OnionPipelineTerm::relay(OnionValueType::Fixed(
749                OnionWidthClass::B32,
750            )))
751            .expect("(relay ⋙ f) ⋙ relay");
752        let OnionPipeline::Invoke(normalized) = wrapped_term.into_pipeline().expect("nf") else {
753            panic!("invoke pipeline");
754        };
755        assert_eq!(normalized, plain);
756
757        let hops = session_loop([1_u8, 2, 3, 4].map(|seed| {
758            OnionRouteHop::new(
759                Did::from(u32::from(seed)),
760                fixture_secret(seed).pubkey(),
761                OnionProcessEpoch::new([0x31; 16]),
762            )
763        }));
764        let built_plain = build_loop(
765            &hops,
766            &plain.applications(),
767            Did::from(99_u32),
768            plain.loop_class(),
769            grid_expiry(5),
770            b"",
771            &mut ChaCha20Rng::from_seed([0x77; 32]),
772        )
773        .expect("build plain");
774        let built_normalized = build_loop(
775            &hops,
776            &normalized.applications(),
777            Did::from(99_u32),
778            normalized.loop_class(),
779            grid_expiry(5),
780            b"",
781            &mut ChaCha20Rng::from_seed([0x77; 32]),
782        )
783        .expect("build normalized");
784        assert_eq!(
785            built_plain.cell.into_bytes(),
786            built_normalized.cell.into_bytes()
787        );
788        assert_eq!(built_plain.reply.tag, built_normalized.reply.tag);
789    }
790
791    /// L3: `loop_class` selects `KiB16` while widths stay below `C₀(KiB16) = 13,449` and steps up
792    /// to `KiB64` once any stage or input uses `OnionWidthClass::KiB16` (`16,384` bytes).
793    #[test]
794    fn test_loop_class_selects_least_admissible_bucket() {
795        let small = stage(
796            OnionInputType::Fixed(OnionWidthClass::B32),
797            OnionWidthClass::KiB1,
798            OnionLatencyClass::Ms10,
799            "small",
800            b"",
801        )
802        .into_pipeline();
803        assert_eq!(small.loop_class(), OnionLoopClass::KiB16);
804
805        let wide = small
806            .then_stage(stage(
807                OnionInputType::Fixed(OnionWidthClass::KiB1),
808                OnionWidthClass::KiB16,
809                OnionLatencyClass::Ms100,
810                "wide",
811                b"",
812            ))
813            .expect("compose wide");
814        assert_eq!(wide.loop_class(), OnionLoopClass::KiB64);
815    }
816}