Skip to main content

rings_node/onion/
loop_shape.rs

1//! Onion loops: the closed hop sequence a pipeline is evaluated on (#834 D4c, D5, L7).
2//!
3//! A pipeline `P = (f₁, ā₁) ⋙ … ⋙ (fₙ, āₙ)` is evaluated on the client-sealed loop
4//!
5//! ```text
6//! LoopOf(P):  cl → r₀,₁ … r₀,ₛ → h₁ → r₁,₁ … r₁,ₛ → ⋯ → hₙ → rₙ,₁ … rₙ,ₛ → cl
7//! ```
8//!
9//! of `n + 1` segments of `s = ONION_SEGMENT_RELAYS` relays, closed by the client's entry guard
10//! `g = r₀,₁ = rₙ,ₛ`: the guard is relay `1` of the first segment and relay `s` of the last, and
11//! the symbol hop `hₖ` stands at position `(s + 1)·k` of `[1, H]`.
12//!
13//! Laws, for every shape `n ∈ [1, n_max]`:
14//!
15//! - **Size.** `H(n, s) = (s + 1)·n + s` positions and `H − 1` distinct hops, bounded by
16//!   `MAX_ONION_LOOP_HOPS = H(n_max, s) = 14` with `n_max = MAX_ONION_LOOP_SYMBOLS = 4`.
17//! - **Segment** (D5). Exactly `s` relay positions, the guard counted, precede `h₁`, separate
18//!   `hₖ` from `hₖ₊₁` and follow `hₙ`; the only constructor emits no other segment length.
19//! - **Guard closure** (L7). An [`OnionLoop`] stores the guard once and places it at positions `1`
20//!   and `H` and nowhere else, so the guard is the only hop adjacent to the client. The remaining
21//!   `H − 2` positions are pairwise distinct and distinct from `g` for every loop a route draws
22//!   (`select_loop` in the route module).
23//!
24//! The only constructor is [`OnionLoop::try_unfold`], an unfold of the non-empty, already
25//! labelled pipeline `f₁ … fₙ₋₁ ⋙ fₙ` in the failure monad: it places each symbol and labels the
26//! relay positions around them,
27//!
28//! ```text
29//! unfold [f₁ … fₙ] = Guard · Relay^{s−1} · Π_{k=1..n} (Symbol fₖ · Relay^{s − [k = n]})
30//! ```
31//!
32//! and closes the loop with the guard's label. Relay positions are labelled `P` and symbol
33//! positions `T`; the terminal `hₙ` is a field, not an index, so a caller labelling it with the
34//! drawn registrant reads it back totally. The unfold fixes the position order only: route
35//! selection draws the symbols first, then the guard, then the relays (#834 L7).
36
37use std::iter;
38
39use super::OnionRouteError;
40use crate::error::Error;
41use crate::error::Result;
42
43/// Number `s` of relays in every segment of a loop, the guard counted in both end segments (D5).
44///
45/// `s = 2` is the least value at which no single node is adjacent to both the client and a symbol
46/// hop: at `s = 1` the guard alone would neighbour the client, `h₁` and `hₙ`.
47pub const ONION_SEGMENT_RELAYS: usize = 2;
48
49/// Largest number `n_max` of symbol applications in one pipeline (#834 D4a).
50pub const MAX_ONION_LOOP_SYMBOLS: usize = 4;
51
52/// Largest number of positions of one loop, `H(n_max, s) = (s + 1)·n_max + s = 14`, derived from
53/// [`ONION_SEGMENT_RELAYS`] and [`MAX_ONION_LOOP_SYMBOLS`].
54pub const MAX_ONION_LOOP_HOPS: usize = loop_hops(MAX_ONION_LOOP_SYMBOLS);
55
56/// Period `s + 1` of the loop: each symbol hop `hₖ` together with the `s` relay positions before
57/// it, so `hₖ` stands at position `(s + 1)·k`.
58const SYMBOL_PERIOD: usize = ONION_SEGMENT_RELAYS + 1;
59
60/// Number of positions `H(n, s) = n + (n + 1)·s = (s + 1)·n + s` of a loop over `n` symbols.
61const fn loop_hops(symbols: usize) -> usize {
62    SYMBOL_PERIOD * symbols + ONION_SEGMENT_RELAYS
63}
64
65/// The shape of a loop over `n ∈ [1, n_max]` symbol applications.
66///
67/// Invariant: `1 ≤ symbols ≤ MAX_ONION_LOOP_SYMBOLS`, so `hop_count() ≤ MAX_ONION_LOOP_HOPS`.
68#[derive(Clone, Copy, Debug, Eq, PartialEq)]
69pub struct OnionLoopShape {
70    symbols: usize,
71}
72
73impl OnionLoopShape {
74    /// Shape of a pipeline ending in a world-facing session symbol, which stands alone (`n = 1`,
75    /// #834 D4a): `g, r₀,₂, h₁, r₁,₁, g`.
76    pub const SESSION: Self = Self { symbols: 1 };
77
78    /// Build the shape of a pipeline of `symbols` applications, rejecting `n = 0` and `n > n_max`.
79    pub fn new(symbols: usize) -> Result<Self> {
80        if symbols == 0 || symbols > MAX_ONION_LOOP_SYMBOLS {
81            return Err(Error::OnionRouteError(
82                OnionRouteError::LoopSymbolsOutOfBounds {
83                    symbols,
84                    max_symbols: MAX_ONION_LOOP_SYMBOLS,
85                },
86            ));
87        }
88        Ok(Self { symbols })
89    }
90
91    /// Return the number `n` of symbol applications.
92    pub const fn symbols(self) -> usize {
93        self.symbols
94    }
95
96    /// Return the number of positions `H(n, s) = (s + 1)·n + s`.
97    pub const fn hop_count(self) -> usize {
98        loop_hops(self.symbols)
99    }
100
101    /// Return the number `H − 1` of pairwise distinct hops: every position once, the guard once.
102    pub const fn distinct_hops(self) -> usize {
103        self.hop_count() - 1
104    }
105}
106
107/// A non-empty pipeline of symbols `f₁ … fₙ` (#834 D4a): every constructor proves `n ≥ 1`, so
108/// the terminal symbol `fₙ` is total.
109#[derive(Debug)]
110pub(crate) struct OnionPipelineSymbols<'s, S> {
111    all: &'s [S],
112    intermediate: &'s [S],
113    terminal: &'s S,
114}
115
116impl<'s, S> OnionPipelineSymbols<'s, S> {
117    /// The pipeline of one symbol.
118    pub(crate) const fn single(symbol: &'s S) -> Self {
119        Self {
120            all: std::slice::from_ref(symbol),
121            intermediate: &[],
122            terminal: symbol,
123        }
124    }
125
126    /// The pipeline `symbols`, or `None` when it is empty.
127    pub(crate) fn new(symbols: &'s [S]) -> Option<Self> {
128        symbols.split_last().map(|(terminal, intermediate)| Self {
129            all: symbols,
130            intermediate,
131            terminal,
132        })
133    }
134
135    /// Return the number `n ≥ 1` of symbols.
136    pub(crate) const fn symbol_count(&self) -> usize {
137        self.all.len()
138    }
139
140    /// Return the symbols in pipeline order.
141    pub(crate) const fn as_slice(&self) -> &'s [S] {
142        self.all
143    }
144
145    /// Label every symbol in pipeline order, handing each the symbols after it, and stop at the
146    /// first failure: `fₖ ↦ label(fₖ, [fₖ₊₁ … fₙ])`, split into the intermediate labels and the
147    /// terminal's.
148    pub(crate) fn try_map_with_later<T>(
149        &self,
150        mut label: impl FnMut(&'s S, &'s [S]) -> Result<T>,
151    ) -> Result<(Vec<T>, T)> {
152        let laters = iter::successors(self.all.split_first().map(|(_, later)| later), |later| {
153            later.split_first().map(|(_, rest)| rest)
154        });
155        let intermediate = self
156            .intermediate
157            .iter()
158            .zip(laters)
159            .map(|(symbol, later)| label(symbol, later))
160            .collect::<Result<Vec<_>>>()?;
161        Ok((intermediate, label(self.terminal, &[])?))
162    }
163}
164
165/// The kind of a relay position of the open path: the entry guard at position `1`, or another
166/// relay. Both evaluate `relay`.
167#[derive(Clone, Copy, Debug, Eq, PartialEq)]
168pub(crate) enum OnionLoopRelay {
169    /// Position `1`, the entry guard `g`.
170    Guard,
171    /// A relay position other than the guard.
172    Relay,
173}
174
175/// The role of one position of a loop: a relay position (the guard included), or the symbol hop
176/// `hₖ` with its index `k ∈ [1, n]`.
177#[derive(Clone, Copy, Debug, Eq, PartialEq)]
178pub enum OnionLoopRole {
179    /// A position evaluating `relay`.
180    Relay,
181    /// The symbol hop `hₖ`.
182    Symbol(usize),
183}
184
185/// A loop whose relay positions carry a label `P` and whose symbol positions carry a label `T`,
186/// the guard's label stored once.
187///
188/// The fields follow the unfold grammar of the module documentation: `lead` holds the relays
189/// after the guard, `stages` each intermediate symbol with the relays after it, `terminal` the
190/// last symbol `hₙ`, and `tail` the relays before the closing guard. The guard and the terminal
191/// are total, and the shape is derived from `stages`. The segment lengths `s − 1`, `s`, `s − 1`
192/// are established by `OnionLoop::try_unfold`, the only constructor.
193#[derive(Clone, Debug, Eq, PartialEq)]
194pub struct OnionLoop<P, T = P> {
195    guard: P,
196    lead: Vec<P>,
197    stages: Vec<(T, Vec<P>)>,
198    terminal: T,
199    tail: Vec<P>,
200}
201
202impl<P, T> OnionLoop<P, T> {
203    /// Unfold the loop of the labelled symbols `intermediate ⋙ terminal`, placing each symbol at
204    /// its position and labelling every relay position of the open path `1 … H − 1` in order,
205    /// stopping at the first failure.
206    ///
207    /// The guard is labelled exactly once, and position `H` repeats its label (L7). A pipeline
208    /// of more than `n_max` symbols is rejected before any relay is labelled.
209    pub(crate) fn try_unfold(
210        intermediate: Vec<T>,
211        terminal: T,
212        mut label_relay: impl FnMut(OnionLoopRelay) -> Result<P>,
213    ) -> Result<Self> {
214        OnionLoopShape::new(intermediate.len() + 1)?;
215        let guard = label_relay(OnionLoopRelay::Guard)?;
216        let lead = (1..ONION_SEGMENT_RELAYS)
217            .map(|_| label_relay(OnionLoopRelay::Relay))
218            .collect::<Result<Vec<_>>>()?;
219        let stages = intermediate
220            .into_iter()
221            .map(|symbol| {
222                let relays = (0..ONION_SEGMENT_RELAYS)
223                    .map(|_| label_relay(OnionLoopRelay::Relay))
224                    .collect::<Result<Vec<_>>>()?;
225                Ok((symbol, relays))
226            })
227            .collect::<Result<Vec<_>>>()?;
228        let tail = (1..ONION_SEGMENT_RELAYS)
229            .map(|_| label_relay(OnionLoopRelay::Relay))
230            .collect::<Result<Vec<_>>>()?;
231        Ok(Self {
232            guard,
233            lead,
234            stages,
235            terminal,
236            tail,
237        })
238    }
239
240    /// Return the shape of this loop: `n = |stages| + 1` symbols, bounded by construction.
241    pub fn shape(&self) -> OnionLoopShape {
242        OnionLoopShape {
243            symbols: self.stages.len() + 1,
244        }
245    }
246
247    /// Return the guard's label, the label of positions `1` and `H`.
248    pub const fn guard(&self) -> &P {
249        &self.guard
250    }
251
252    /// Return the label of the terminal symbol hop `hₙ`.
253    pub const fn terminal(&self) -> &T {
254        &self.terminal
255    }
256
257    /// Return the labels of the relay positions before `h₁`: the guard, then `r₀,₂ … r₀,ₛ`.
258    pub fn forward_prefix(&self) -> impl Iterator<Item = &P> {
259        iter::once(&self.guard).chain(self.lead.iter())
260    }
261
262    /// Relabel every symbol position by `project` and return the terminal's label beside the
263    /// relabelled loop: `OnionLoop<P, T> → OnionLoop<P> × T`.
264    pub(crate) fn project_symbols(self, project: impl Fn(&T) -> P) -> (OnionLoop<P>, T) {
265        let stages = self
266            .stages
267            .into_iter()
268            .map(|(symbol, relays)| (project(&symbol), relays))
269            .collect();
270        (
271            OnionLoop {
272                guard: self.guard,
273                lead: self.lead,
274                stages,
275                terminal: project(&self.terminal),
276                tail: self.tail,
277            },
278            self.terminal,
279        )
280    }
281    /// Relabel every symbol position by `project` and return all `n` symbol labels in pipeline
282    /// order beside the relabelled loop: `OnionLoop<P, T> → OnionLoop<P> × Vec<T>`.
283    pub(crate) fn project_all_symbols(self, project: impl Fn(&T) -> P) -> (OnionLoop<P>, Vec<T>) {
284        let mut symbols = Vec::with_capacity(self.stages.len() + 1);
285        let stages = self
286            .stages
287            .into_iter()
288            .map(|(symbol, relays)| {
289                let mapped = project(&symbol);
290                symbols.push(symbol);
291                (mapped, relays)
292            })
293            .collect();
294        let terminal = project(&self.terminal);
295        symbols.push(self.terminal);
296        (
297            OnionLoop {
298                guard: self.guard,
299                lead: self.lead,
300                stages,
301                terminal,
302                tail: self.tail,
303            },
304            symbols,
305        )
306    }
307}
308
309impl<P> OnionLoop<P> {
310    /// Return the labels of the open path `1 … H − 1`, the guard once: the `H − 1` hops a route
311    /// requires pairwise distinct.
312    pub fn open_path(&self) -> impl Iterator<Item = &P> {
313        self.forward_prefix()
314            .chain(
315                self.stages
316                    .iter()
317                    .flat_map(|(symbol, relays)| iter::once(symbol).chain(relays.iter())),
318            )
319            .chain(iter::once(&self.terminal))
320            .chain(self.tail.iter())
321    }
322
323    /// Return the labels of all `H` positions in order, the guard at `1` and `H`.
324    pub fn positions(&self) -> impl Iterator<Item = &P> {
325        self.open_path().chain(iter::once(&self.guard))
326    }
327
328    /// Return every position `1 … H` in order with its role: the relay positions, the guard at
329    /// `1` and `H` included, and each symbol hop `hₖ` with its index `k` (`1 ≤ k ≤ n`).
330    ///
331    /// Law: the projection to labels is [`Self::positions`], and the roles read
332    /// `Relay^s · Π_{k=1..n} (Symbol k · Relay^s)`, the unfold grammar with the guard counted in
333    /// both end segments.
334    pub fn roles(&self) -> impl Iterator<Item = (OnionLoopRole, &P)> {
335        let symbols = self.shape().symbols();
336        iter::once(&self.guard)
337            .chain(self.lead.iter())
338            .map(|relay| (OnionLoopRole::Relay, relay))
339            .chain(
340                self.stages
341                    .iter()
342                    .zip(1..)
343                    .flat_map(|((symbol, relays), k)| {
344                        iter::once((OnionLoopRole::Symbol(k), symbol))
345                            .chain(relays.iter().map(|relay| (OnionLoopRole::Relay, relay)))
346                    }),
347            )
348            .chain(iter::once((OnionLoopRole::Symbol(symbols), &self.terminal)))
349            .chain(
350                self.tail
351                    .iter()
352                    .chain(iter::once(&self.guard))
353                    .map(|relay| (OnionLoopRole::Relay, relay)),
354            )
355    }
356
357    /// Return the return path: the positions after the terminal `hₙ`, `rₙ,₁ … rₙ,ₛ = g`, which a
358    /// reply block of `hₙ` travels.
359    pub fn return_path(&self) -> impl Iterator<Item = &P> {
360        self.tail.iter().chain(iter::once(&self.guard))
361    }
362
363    /// Return the label of the symbol hop `hₖ`, `1 ≤ k ≤ n`, or `None` for any other `k`.
364    pub fn symbol(&self, k: usize) -> Option<&P> {
365        if k == self.shape().symbols() {
366            return Some(&self.terminal);
367        }
368        self.stages.get(k.checked_sub(1)?).map(|(symbol, _)| symbol)
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use super::OnionLoop;
375    use super::OnionLoopRelay;
376    use super::OnionLoopRole;
377    use super::OnionLoopShape;
378    use super::OnionPipelineSymbols;
379    use super::MAX_ONION_LOOP_HOPS;
380    use super::MAX_ONION_LOOP_SYMBOLS;
381    use super::ONION_SEGMENT_RELAYS;
382    use crate::error::Error;
383    use crate::error::Result;
384    use crate::onion::OnionRouteError;
385
386    /// The kind of one position, read off the unfolded loop: the guard, a relay, or the symbol
387    /// `k` of the pipeline `[1 … n]`.
388    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
389    enum Kind {
390        Guard,
391        Relay,
392        Symbol(usize),
393    }
394
395    /// Unfold the pipeline `[1 … n]` with each position labelled by its kind, and count the relay
396    /// labels asked for.
397    fn unfold_kinds(symbols: usize) -> Result<(OnionLoop<Kind>, usize)> {
398        let mut asked = 0;
399        let unfolded = OnionLoop::try_unfold(
400            (1..symbols).map(Kind::Symbol).collect(),
401            Kind::Symbol(symbols),
402            |relay| {
403                asked += 1;
404                Ok(match relay {
405                    OnionLoopRelay::Guard => Kind::Guard,
406                    OnionLoopRelay::Relay => Kind::Relay,
407                })
408            },
409        )?;
410        Ok((unfolded, asked))
411    }
412
413    /// Size (D5): `H = (s + 1)·n + s` for every admitted `n`, `H − 1` distinct hops asked for once
414    /// each, and the derived bound `MAX_ONION_LOOP_HOPS = 14`.
415    #[test]
416    fn test_loop_size_is_derived_from_segments() -> Result<()> {
417        assert_eq!(ONION_SEGMENT_RELAYS, 2);
418        assert_eq!(MAX_ONION_LOOP_SYMBOLS, 4);
419        assert_eq!(MAX_ONION_LOOP_HOPS, 14);
420        for (symbols, hops) in [(1, 5), (2, 8), (3, 11), (4, 14)] {
421            let shape = OnionLoopShape::new(symbols)?;
422            let (unfolded, asked) = unfold_kinds(symbols)?;
423            assert_eq!(shape.hop_count(), hops);
424            assert_eq!(
425                shape.hop_count(),
426                symbols + (symbols + 1) * ONION_SEGMENT_RELAYS
427            );
428            assert_eq!(shape.distinct_hops(), hops - 1);
429            assert!(shape.hop_count() <= MAX_ONION_LOOP_HOPS);
430            assert_eq!(unfolded.shape(), shape);
431            assert_eq!(unfolded.positions().count(), hops);
432            assert_eq!(unfolded.open_path().count(), hops - 1);
433            assert_eq!(asked + symbols, hops - 1);
434        }
435        assert_eq!(OnionLoopShape::SESSION, OnionLoopShape::new(1)?);
436        Ok(())
437    }
438
439    /// `n = 0` and `n > n_max` are rejected, the latter before any label is asked.
440    #[test]
441    fn test_loop_symbols_are_bounded() {
442        let mut asked = 0;
443        let unfolded =
444            OnionLoop::<(), ()>::try_unfold(vec![(); MAX_ONION_LOOP_SYMBOLS], (), |_| {
445                asked += 1;
446                Ok(())
447            });
448
449        assert!(matches!(
450            unfolded,
451            Err(Error::OnionRouteError(
452                OnionRouteError::LoopSymbolsOutOfBounds {
453                    symbols: 5,
454                    max_symbols: MAX_ONION_LOOP_SYMBOLS,
455                }
456            ))
457        ));
458        assert_eq!(asked, 0);
459        for symbols in [0, usize::MAX] {
460            assert!(OnionLoopShape::new(symbols).is_err());
461        }
462    }
463
464    /// Segment (D5) and guard closure (L7): the guard is at `1` and `H` only, the `k`-th symbol at
465    /// `(s + 1)·k`, exactly `s` relay positions, the guard counted, lie before `h₁`, between
466    /// consecutive symbols and after `hₙ`.
467    #[test]
468    fn test_unfold_interleaves_segments_of_s_relays() -> Result<()> {
469        for symbols in 1..=MAX_ONION_LOOP_SYMBOLS {
470            let (unfolded, _) = unfold_kinds(symbols)?;
471            let kinds = unfolded.positions().copied().collect::<Vec<_>>();
472            let guards = (1..=kinds.len())
473                .filter(|position| kinds.get(position - 1) == Some(&Kind::Guard))
474                .collect::<Vec<_>>();
475            let segments = kinds
476                .split(|kind| matches!(kind, Kind::Symbol(_)))
477                .map(<[Kind]>::len)
478                .collect::<Vec<_>>();
479
480            assert_eq!(guards, vec![1, kinds.len()]);
481            for k in 1..=symbols {
482                assert_eq!(
483                    kinds.get((ONION_SEGMENT_RELAYS + 1) * k - 1),
484                    Some(&Kind::Symbol(k))
485                );
486                assert_eq!(
487                    unfolded.symbol(k),
488                    kinds.get((ONION_SEGMENT_RELAYS + 1) * k - 1)
489                );
490            }
491            assert_eq!(segments, vec![ONION_SEGMENT_RELAYS; symbols + 1]);
492            assert_eq!(unfolded.guard(), &Kind::Guard);
493            assert_eq!(unfolded.terminal(), &Kind::Symbol(symbols));
494            assert_eq!(unfolded.symbol(0), None);
495            assert_eq!(unfolded.symbol(symbols + 1), None);
496            assert_eq!(
497                unfolded.forward_prefix().copied().collect::<Vec<_>>(),
498                kinds
499                    .get(..ONION_SEGMENT_RELAYS)
500                    .map(<[Kind]>::to_vec)
501                    .unwrap_or_default()
502            );
503        }
504        Ok(())
505    }
506
507    /// `roles` labels exactly the positions `positions` lists, the `k`-th symbol at `(s + 1)·k`
508    /// and every other position a relay, and the return path is the last `s` positions.
509    #[test]
510    fn test_roles_label_every_position_by_the_unfold_grammar() -> Result<()> {
511        for symbols in 1..=MAX_ONION_LOOP_SYMBOLS {
512            let (unfolded, _) = unfold_kinds(symbols)?;
513            let roles = unfolded.roles().collect::<Vec<_>>();
514
515            assert_eq!(
516                roles.iter().map(|(_, kind)| **kind).collect::<Vec<_>>(),
517                unfolded.positions().copied().collect::<Vec<_>>()
518            );
519            for (index, (role, kind)) in roles.iter().enumerate() {
520                match role {
521                    OnionLoopRole::Symbol(k) => {
522                        assert_eq!(**kind, Kind::Symbol(*k));
523                        assert_eq!(index + 1, (ONION_SEGMENT_RELAYS + 1) * k);
524                    }
525                    OnionLoopRole::Relay => assert!(!matches!(kind, Kind::Symbol(_))),
526                }
527            }
528            let tail = roles
529                .get(roles.len() - ONION_SEGMENT_RELAYS..)
530                .map(|tail| tail.iter().map(|(_, kind)| **kind).collect::<Vec<_>>());
531            assert_eq!(
532                tail,
533                Some(unfolded.return_path().copied().collect::<Vec<_>>())
534            );
535        }
536        Ok(())
537    }
538
539    /// Projecting the symbol labels keeps every position and hands back the terminal's label.
540    #[test]
541    fn test_project_symbols_returns_the_terminal_label() -> Result<()> {
542        let unfolded = OnionLoop::<u64, u64>::try_unfold(vec![1000], 2000, |relay| {
543            Ok(match relay {
544                OnionLoopRelay::Guard => 1,
545                OnionLoopRelay::Relay => 2,
546            })
547        })?;
548
549        let (projected, terminal) = unfolded.project_symbols(|label| label / 100 + 5);
550
551        assert_eq!(terminal, 2000);
552        assert_eq!(projected.positions().copied().collect::<Vec<_>>(), vec![
553            1, 2, 15, 2, 2, 25, 2, 1
554        ]);
555        Ok(())
556    }
557
558    /// Unfolding stops at the first failure.
559    #[test]
560    fn test_unfold_propagates_the_first_failure() {
561        let mut asked = 0;
562        let unfolded = OnionLoop::<(), ()>::try_unfold(Vec::new(), (), |_| {
563            asked += 1;
564            if asked > ONION_SEGMENT_RELAYS {
565                Err(Error::InvalidData)
566            } else {
567                Ok(())
568            }
569        });
570
571        assert!(matches!(unfolded, Err(Error::InvalidData)));
572        assert_eq!(asked, ONION_SEGMENT_RELAYS + 1);
573    }
574
575    /// Each symbol is labelled with the symbols after it, in pipeline order, the terminal with
576    /// none.
577    #[test]
578    fn test_symbols_are_labelled_with_the_symbols_after_them() -> Result<()> {
579        let pipeline = [1, 2, 3];
580        let symbols = OnionPipelineSymbols::new(&pipeline).ok_or(Error::InvalidData)?;
581
582        let labelled = symbols.try_map_with_later(|symbol, later| Ok((*symbol, later.to_vec())))?;
583
584        assert_eq!(
585            labelled,
586            (vec![(1, vec![2, 3]), (2, vec![3])], (3, Vec::new()))
587        );
588        assert_eq!(symbols.symbol_count(), 3);
589        assert!(OnionPipelineSymbols::<u8>::new(&[]).is_none());
590        assert_eq!(OnionPipelineSymbols::single(&7).symbol_count(), 1);
591        Ok(())
592    }
593}