use std::array;
use rand::CryptoRng;
use rand::Rng;
use rand::RngCore;
use rings_aez::KeyError;
use rings_core::dht::Did;
use super::cell::OnionCell;
use super::cell::OnionClientError;
use super::cell::OnionSurb;
use super::class::OnionLoopClass;
use super::header::OnionHeader;
use super::header::OnionHeaderHop;
use super::header::OnionHeaderRoute;
use super::header::OnionHeaderRouteError;
use super::header::OnionLoopTag;
use super::layer::OnionApplication;
use super::layer::OnionLayer;
use super::layer::OnionLayerApplication;
use super::layer::OnionLayerHead;
use super::seed::OnionCarryKey;
use super::seed::OnionCarrySeed;
use super::seed::OnionSegmentSeed;
use crate::onion::circuit::OnionExpiry;
use crate::onion::circuit::OnionReplayNonce;
use crate::onion::OnionLoop;
use crate::onion::OnionLoopRole;
use crate::onion::OnionRouteHop;
use crate::onion::ONION_SEGMENT_RELAYS;
pub(crate) struct OnionReplyKey {
pub(crate) tag: OnionLoopTag,
pub(crate) key: OnionCarryKey,
pub(crate) expiry: OnionExpiry,
}
pub(crate) struct OnionBuiltLoop {
pub(crate) guard: Did,
pub(crate) cell: OnionCell,
pub(crate) reply: OnionReplyKey,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub(crate) enum OnionBuildError {
#[error(transparent)]
Key(#[from] KeyError),
#[error(transparent)]
Route(#[from] OnionHeaderRouteError),
#[error(transparent)]
Client(#[from] OnionClientError),
#[error("the applications do not match the loop's symbol positions")]
Shape,
}
struct OnionOpenSegment {
relays: array::IntoIter<OnionCarrySeed, ONION_SEGMENT_RELAYS>,
consumer: OnionCarrySeed,
}
impl OnionOpenSegment {
fn of(seed: &OnionSegmentSeed) -> Self {
let seeds = seed.seeds();
Self {
relays: seeds.relays.into_iter(),
consumer: seeds.consumer,
}
}
}
pub(crate) fn build_loop(
hops: &OnionLoop<OnionRouteHop>,
applications: &[OnionApplication],
client: Did,
class: OnionLoopClass,
expiry: OnionExpiry,
value: &[u8],
rng: &mut (impl CryptoRng + RngCore),
) -> Result<OnionBuiltLoop, OnionBuildError> {
let (first, first_keys) = OnionSegmentSeed::draw(rng)?;
let mut segment = OnionOpenSegment::of(&first);
let mut last = first;
let roles = hops.roles().collect::<Vec<_>>();
let nexts = roles
.iter()
.skip(1)
.map(|(_, hop)| hop.did)
.chain(core::iter::once(client));
let mut positions = Vec::with_capacity(roles.len());
for ((role, hop), next) in roles.iter().zip(nexts) {
let (application, inbound, outbound) = match role {
OnionLoopRole::Relay => (
OnionLayerApplication::Relay,
segment.relays.next().ok_or(OnionBuildError::Shape)?,
OnionSegmentSeed::random(rng),
),
OnionLoopRole::Symbol(k) => {
let application = k
.checked_sub(1)
.and_then(|index| applications.get(index))
.ok_or(OnionBuildError::Shape)?;
let (produced, _) = OnionSegmentSeed::draw(rng)?;
let inbound = core::mem::replace(&mut segment, OnionOpenSegment::of(&produced));
let outbound = OnionSegmentSeed::new(*produced.as_bytes());
last = produced;
(
OnionLayerApplication::Apply(application.clone()),
inbound.consumer,
outbound,
)
}
};
positions.push(OnionHeaderHop {
public_key: hop.delegatee_public_key,
layer: layer(application, next, hop, expiry, inbound, outbound, rng),
});
}
if hops.shape().symbols() != applications.len() {
return Err(OnionBuildError::Shape);
}
let route = OnionHeaderRoute::new(positions)?;
let (cell, tag) = OnionCell::client(&route, class, &first_keys, value, rng)?;
Ok(OnionBuiltLoop {
guard: hops.guard().did,
cell,
reply: OnionReplyKey {
tag,
key: last.seeds().consumer.key()?,
expiry,
},
})
}
pub(crate) fn build_surb<'h>(
path: impl IntoIterator<Item = &'h OnionRouteHop>,
client: Did,
class: OnionLoopClass,
expiry: OnionExpiry,
rng: &mut (impl CryptoRng + RngCore),
) -> Result<(OnionSurb, OnionReplyKey), OnionBuildError> {
let path = path.into_iter().collect::<Vec<_>>();
let (seed, _) = OnionSegmentSeed::draw(rng)?;
let mut segment = OnionOpenSegment::of(&seed);
let first = path
.first()
.map(|hop| hop.did)
.ok_or(OnionBuildError::Shape)?;
let nexts = path
.iter()
.skip(1)
.map(|hop| hop.did)
.chain(core::iter::once(client));
let positions = path
.iter()
.zip(nexts)
.map(|(hop, next)| {
let inbound = segment.relays.next().ok_or(OnionBuildError::Shape)?;
Ok(OnionHeaderHop {
public_key: hop.delegatee_public_key,
layer: layer(
OnionLayerApplication::Relay,
next,
hop,
expiry,
inbound,
OnionSegmentSeed::random(rng),
rng,
),
})
})
.collect::<Result<Vec<_>, OnionBuildError>>()?;
let (header, tag) = OnionHeader::build(&OnionHeaderRoute::new(positions)?, class, rng)
.map_err(OnionClientError::from)?;
let key = seed.seeds().consumer.key()?;
Ok((
OnionSurb::new(class, first, header, seed, expiry),
OnionReplyKey { tag, key, expiry },
))
}
fn layer(
application: OnionLayerApplication,
next: Did,
hop: &OnionRouteHop,
expiry: OnionExpiry,
inbound: OnionCarrySeed,
outbound: OnionSegmentSeed,
rng: &mut (impl CryptoRng + RngCore),
) -> OnionLayer {
OnionLayer {
head: OnionLayerHead {
application,
next,
epoch: hop.process_epoch,
expiry,
nonce: OnionReplayNonce::new(rng.gen()),
},
inbound,
outbound,
}
}