use std::iter;
use super::OnionRouteError;
use crate::error::Error;
use crate::error::Result;
pub const ONION_SEGMENT_RELAYS: usize = 2;
pub const MAX_ONION_LOOP_SYMBOLS: usize = 4;
pub const MAX_ONION_LOOP_HOPS: usize = loop_hops(MAX_ONION_LOOP_SYMBOLS);
const SYMBOL_PERIOD: usize = ONION_SEGMENT_RELAYS + 1;
const fn loop_hops(symbols: usize) -> usize {
SYMBOL_PERIOD * symbols + ONION_SEGMENT_RELAYS
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct OnionLoopShape {
symbols: usize,
}
impl OnionLoopShape {
pub const SESSION: Self = Self { symbols: 1 };
pub fn new(symbols: usize) -> Result<Self> {
if symbols == 0 || symbols > MAX_ONION_LOOP_SYMBOLS {
return Err(Error::OnionRouteError(
OnionRouteError::LoopSymbolsOutOfBounds {
symbols,
max_symbols: MAX_ONION_LOOP_SYMBOLS,
},
));
}
Ok(Self { symbols })
}
pub const fn symbols(self) -> usize {
self.symbols
}
pub const fn hop_count(self) -> usize {
loop_hops(self.symbols)
}
pub const fn distinct_hops(self) -> usize {
self.hop_count() - 1
}
}
#[derive(Debug)]
pub(crate) struct OnionPipelineSymbols<'s, S> {
all: &'s [S],
intermediate: &'s [S],
terminal: &'s S,
}
impl<'s, S> OnionPipelineSymbols<'s, S> {
pub(crate) const fn single(symbol: &'s S) -> Self {
Self {
all: std::slice::from_ref(symbol),
intermediate: &[],
terminal: symbol,
}
}
#[cfg(test)]
pub(crate) fn new(symbols: &'s [S]) -> Option<Self> {
symbols.split_last().map(|(terminal, intermediate)| Self {
all: symbols,
intermediate,
terminal,
})
}
pub(crate) const fn symbol_count(&self) -> usize {
self.all.len()
}
pub(crate) const fn as_slice(&self) -> &'s [S] {
self.all
}
pub(crate) fn try_map_with_later<T>(
&self,
mut label: impl FnMut(&'s S, &'s [S]) -> Result<T>,
) -> Result<(Vec<T>, T)> {
let laters = iter::successors(self.all.split_first().map(|(_, later)| later), |later| {
later.split_first().map(|(_, rest)| rest)
});
let intermediate = self
.intermediate
.iter()
.zip(laters)
.map(|(symbol, later)| label(symbol, later))
.collect::<Result<Vec<_>>>()?;
Ok((intermediate, label(self.terminal, &[])?))
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum OnionLoopRelay {
Guard,
Relay,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OnionLoopRole {
Relay,
Symbol(usize),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OnionLoop<P, T = P> {
guard: P,
lead: Vec<P>,
stages: Vec<(T, Vec<P>)>,
terminal: T,
tail: Vec<P>,
}
impl<P, T> OnionLoop<P, T> {
pub(crate) fn try_unfold(
intermediate: Vec<T>,
terminal: T,
mut label_relay: impl FnMut(OnionLoopRelay) -> Result<P>,
) -> Result<Self> {
OnionLoopShape::new(intermediate.len() + 1)?;
let guard = label_relay(OnionLoopRelay::Guard)?;
let lead = (1..ONION_SEGMENT_RELAYS)
.map(|_| label_relay(OnionLoopRelay::Relay))
.collect::<Result<Vec<_>>>()?;
let stages = intermediate
.into_iter()
.map(|symbol| {
let relays = (0..ONION_SEGMENT_RELAYS)
.map(|_| label_relay(OnionLoopRelay::Relay))
.collect::<Result<Vec<_>>>()?;
Ok((symbol, relays))
})
.collect::<Result<Vec<_>>>()?;
let tail = (1..ONION_SEGMENT_RELAYS)
.map(|_| label_relay(OnionLoopRelay::Relay))
.collect::<Result<Vec<_>>>()?;
Ok(Self {
guard,
lead,
stages,
terminal,
tail,
})
}
pub fn shape(&self) -> OnionLoopShape {
OnionLoopShape {
symbols: self.stages.len() + 1,
}
}
pub const fn guard(&self) -> &P {
&self.guard
}
pub const fn terminal(&self) -> &T {
&self.terminal
}
pub fn forward_prefix(&self) -> impl Iterator<Item = &P> {
iter::once(&self.guard).chain(self.lead.iter())
}
pub(crate) fn project_symbols(self, project: impl Fn(&T) -> P) -> (OnionLoop<P>, T) {
let stages = self
.stages
.into_iter()
.map(|(symbol, relays)| (project(&symbol), relays))
.collect();
(
OnionLoop {
guard: self.guard,
lead: self.lead,
stages,
terminal: project(&self.terminal),
tail: self.tail,
},
self.terminal,
)
}
}
impl<P> OnionLoop<P> {
pub fn open_path(&self) -> impl Iterator<Item = &P> {
self.forward_prefix()
.chain(
self.stages
.iter()
.flat_map(|(symbol, relays)| iter::once(symbol).chain(relays.iter())),
)
.chain(iter::once(&self.terminal))
.chain(self.tail.iter())
}
pub fn positions(&self) -> impl Iterator<Item = &P> {
self.open_path().chain(iter::once(&self.guard))
}
pub fn roles(&self) -> impl Iterator<Item = (OnionLoopRole, &P)> {
let symbols = self.shape().symbols();
iter::once(&self.guard)
.chain(self.lead.iter())
.map(|relay| (OnionLoopRole::Relay, relay))
.chain(
self.stages
.iter()
.zip(1..)
.flat_map(|((symbol, relays), k)| {
iter::once((OnionLoopRole::Symbol(k), symbol))
.chain(relays.iter().map(|relay| (OnionLoopRole::Relay, relay)))
}),
)
.chain(iter::once((OnionLoopRole::Symbol(symbols), &self.terminal)))
.chain(
self.tail
.iter()
.chain(iter::once(&self.guard))
.map(|relay| (OnionLoopRole::Relay, relay)),
)
}
pub fn return_path(&self) -> impl Iterator<Item = &P> {
self.tail.iter().chain(iter::once(&self.guard))
}
pub fn symbol(&self, k: usize) -> Option<&P> {
if k == self.shape().symbols() {
return Some(&self.terminal);
}
self.stages.get(k.checked_sub(1)?).map(|(symbol, _)| symbol)
}
}
#[cfg(test)]
mod tests {
use super::OnionLoop;
use super::OnionLoopRelay;
use super::OnionLoopRole;
use super::OnionLoopShape;
use super::OnionPipelineSymbols;
use super::MAX_ONION_LOOP_HOPS;
use super::MAX_ONION_LOOP_SYMBOLS;
use super::ONION_SEGMENT_RELAYS;
use crate::error::Error;
use crate::error::Result;
use crate::onion::OnionRouteError;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Kind {
Guard,
Relay,
Symbol(usize),
}
fn unfold_kinds(symbols: usize) -> Result<(OnionLoop<Kind>, usize)> {
let mut asked = 0;
let unfolded = OnionLoop::try_unfold(
(1..symbols).map(Kind::Symbol).collect(),
Kind::Symbol(symbols),
|relay| {
asked += 1;
Ok(match relay {
OnionLoopRelay::Guard => Kind::Guard,
OnionLoopRelay::Relay => Kind::Relay,
})
},
)?;
Ok((unfolded, asked))
}
#[test]
fn test_loop_size_is_derived_from_segments() -> Result<()> {
assert_eq!(ONION_SEGMENT_RELAYS, 2);
assert_eq!(MAX_ONION_LOOP_SYMBOLS, 4);
assert_eq!(MAX_ONION_LOOP_HOPS, 14);
for (symbols, hops) in [(1, 5), (2, 8), (3, 11), (4, 14)] {
let shape = OnionLoopShape::new(symbols)?;
let (unfolded, asked) = unfold_kinds(symbols)?;
assert_eq!(shape.hop_count(), hops);
assert_eq!(
shape.hop_count(),
symbols + (symbols + 1) * ONION_SEGMENT_RELAYS
);
assert_eq!(shape.distinct_hops(), hops - 1);
assert!(shape.hop_count() <= MAX_ONION_LOOP_HOPS);
assert_eq!(unfolded.shape(), shape);
assert_eq!(unfolded.positions().count(), hops);
assert_eq!(unfolded.open_path().count(), hops - 1);
assert_eq!(asked + symbols, hops - 1);
}
assert_eq!(OnionLoopShape::SESSION, OnionLoopShape::new(1)?);
Ok(())
}
#[test]
fn test_loop_symbols_are_bounded() {
let mut asked = 0;
let unfolded =
OnionLoop::<(), ()>::try_unfold(vec![(); MAX_ONION_LOOP_SYMBOLS], (), |_| {
asked += 1;
Ok(())
});
assert!(matches!(
unfolded,
Err(Error::OnionRouteError(
OnionRouteError::LoopSymbolsOutOfBounds {
symbols: 5,
max_symbols: MAX_ONION_LOOP_SYMBOLS,
}
))
));
assert_eq!(asked, 0);
for symbols in [0, usize::MAX] {
assert!(OnionLoopShape::new(symbols).is_err());
}
}
#[test]
fn test_unfold_interleaves_segments_of_s_relays() -> Result<()> {
for symbols in 1..=MAX_ONION_LOOP_SYMBOLS {
let (unfolded, _) = unfold_kinds(symbols)?;
let kinds = unfolded.positions().copied().collect::<Vec<_>>();
let guards = (1..=kinds.len())
.filter(|position| kinds.get(position - 1) == Some(&Kind::Guard))
.collect::<Vec<_>>();
let segments = kinds
.split(|kind| matches!(kind, Kind::Symbol(_)))
.map(<[Kind]>::len)
.collect::<Vec<_>>();
assert_eq!(guards, vec![1, kinds.len()]);
for k in 1..=symbols {
assert_eq!(
kinds.get((ONION_SEGMENT_RELAYS + 1) * k - 1),
Some(&Kind::Symbol(k))
);
assert_eq!(
unfolded.symbol(k),
kinds.get((ONION_SEGMENT_RELAYS + 1) * k - 1)
);
}
assert_eq!(segments, vec![ONION_SEGMENT_RELAYS; symbols + 1]);
assert_eq!(unfolded.guard(), &Kind::Guard);
assert_eq!(unfolded.terminal(), &Kind::Symbol(symbols));
assert_eq!(unfolded.symbol(0), None);
assert_eq!(unfolded.symbol(symbols + 1), None);
assert_eq!(
unfolded.forward_prefix().copied().collect::<Vec<_>>(),
kinds
.get(..ONION_SEGMENT_RELAYS)
.map(<[Kind]>::to_vec)
.unwrap_or_default()
);
}
Ok(())
}
#[test]
fn test_roles_label_every_position_by_the_unfold_grammar() -> Result<()> {
for symbols in 1..=MAX_ONION_LOOP_SYMBOLS {
let (unfolded, _) = unfold_kinds(symbols)?;
let roles = unfolded.roles().collect::<Vec<_>>();
assert_eq!(
roles.iter().map(|(_, kind)| **kind).collect::<Vec<_>>(),
unfolded.positions().copied().collect::<Vec<_>>()
);
for (index, (role, kind)) in roles.iter().enumerate() {
match role {
OnionLoopRole::Symbol(k) => {
assert_eq!(**kind, Kind::Symbol(*k));
assert_eq!(index + 1, (ONION_SEGMENT_RELAYS + 1) * k);
}
OnionLoopRole::Relay => assert!(!matches!(kind, Kind::Symbol(_))),
}
}
let tail = roles
.get(roles.len() - ONION_SEGMENT_RELAYS..)
.map(|tail| tail.iter().map(|(_, kind)| **kind).collect::<Vec<_>>());
assert_eq!(
tail,
Some(unfolded.return_path().copied().collect::<Vec<_>>())
);
}
Ok(())
}
#[test]
fn test_project_symbols_returns_the_terminal_label() -> Result<()> {
let unfolded = OnionLoop::<u64, u64>::try_unfold(vec![1000], 2000, |relay| {
Ok(match relay {
OnionLoopRelay::Guard => 1,
OnionLoopRelay::Relay => 2,
})
})?;
let (projected, terminal) = unfolded.project_symbols(|label| label / 100 + 5);
assert_eq!(terminal, 2000);
assert_eq!(projected.positions().copied().collect::<Vec<_>>(), vec![
1, 2, 15, 2, 2, 25, 2, 1
]);
Ok(())
}
#[test]
fn test_unfold_propagates_the_first_failure() {
let mut asked = 0;
let unfolded = OnionLoop::<(), ()>::try_unfold(Vec::new(), (), |_| {
asked += 1;
if asked > ONION_SEGMENT_RELAYS {
Err(Error::InvalidData)
} else {
Ok(())
}
});
assert!(matches!(unfolded, Err(Error::InvalidData)));
assert_eq!(asked, ONION_SEGMENT_RELAYS + 1);
}
#[test]
fn test_symbols_are_labelled_with_the_symbols_after_them() -> Result<()> {
let pipeline = [1, 2, 3];
let symbols = OnionPipelineSymbols::new(&pipeline).ok_or(Error::InvalidData)?;
let labelled = symbols.try_map_with_later(|symbol, later| Ok((*symbol, later.to_vec())))?;
assert_eq!(
labelled,
(vec![(1, vec![2, 3]), (2, vec![3])], (3, Vec::new()))
);
assert_eq!(symbols.symbol_count(), 3);
assert!(OnionPipelineSymbols::<u8>::new(&[]).is_none());
assert_eq!(OnionPipelineSymbols::single(&7).symbol_count(), 1);
Ok(())
}
}