1use std::iter;
38
39use super::OnionRouteError;
40use crate::error::Error;
41use crate::error::Result;
42
43pub const ONION_SEGMENT_RELAYS: usize = 2;
48
49pub const MAX_ONION_LOOP_SYMBOLS: usize = 4;
51
52pub const MAX_ONION_LOOP_HOPS: usize = loop_hops(MAX_ONION_LOOP_SYMBOLS);
55
56const SYMBOL_PERIOD: usize = ONION_SEGMENT_RELAYS + 1;
59
60const fn loop_hops(symbols: usize) -> usize {
62 SYMBOL_PERIOD * symbols + ONION_SEGMENT_RELAYS
63}
64
65#[derive(Clone, Copy, Debug, Eq, PartialEq)]
69pub struct OnionLoopShape {
70 symbols: usize,
71}
72
73impl OnionLoopShape {
74 pub const SESSION: Self = Self { symbols: 1 };
77
78 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 pub const fn symbols(self) -> usize {
93 self.symbols
94 }
95
96 pub const fn hop_count(self) -> usize {
98 loop_hops(self.symbols)
99 }
100
101 pub const fn distinct_hops(self) -> usize {
103 self.hop_count() - 1
104 }
105}
106
107#[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 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 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 pub(crate) const fn symbol_count(&self) -> usize {
137 self.all.len()
138 }
139
140 pub(crate) const fn as_slice(&self) -> &'s [S] {
142 self.all
143 }
144
145 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
168pub(crate) enum OnionLoopRelay {
169 Guard,
171 Relay,
173}
174
175#[derive(Clone, Copy, Debug, Eq, PartialEq)]
178pub enum OnionLoopRole {
179 Relay,
181 Symbol(usize),
183}
184
185#[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 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 pub fn shape(&self) -> OnionLoopShape {
242 OnionLoopShape {
243 symbols: self.stages.len() + 1,
244 }
245 }
246
247 pub const fn guard(&self) -> &P {
249 &self.guard
250 }
251
252 pub const fn terminal(&self) -> &T {
254 &self.terminal
255 }
256
257 pub fn forward_prefix(&self) -> impl Iterator<Item = &P> {
259 iter::once(&self.guard).chain(self.lead.iter())
260 }
261
262 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 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 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 pub fn positions(&self) -> impl Iterator<Item = &P> {
325 self.open_path().chain(iter::once(&self.guard))
326 }
327
328 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 pub fn return_path(&self) -> impl Iterator<Item = &P> {
360 self.tail.iter().chain(iter::once(&self.guard))
361 }
362
363 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 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
389 enum Kind {
390 Guard,
391 Relay,
392 Symbol(usize),
393 }
394
395 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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}