use core::fmt;
use rand::CryptoRng;
use rand::RngCore;
use rings_aez::KeyError;
use rings_core::delegation::DelegateeKey;
use rings_core::dht::Did;
use super::carry;
use super::carry::OnionCarryValue;
use super::carry::OnionOpenError;
use super::carry::OnionValueTooWide;
use super::class::OnionLoopClass;
use super::header::peel_in_place;
use super::header::OnionBlindingError;
use super::header::OnionHeader;
use super::header::OnionHeaderRoute;
use super::header::OnionLoopTag;
use super::header::OnionPeelError;
use super::header::ONION_HEADER_BYTES;
use super::header::ONION_HEADER_MAC_BYTES;
use super::layer::decode_expiry;
use super::layer::decode_next;
use super::layer::encode_expiry;
use super::layer::encode_next;
use super::layer::OnionApplication;
use super::layer::OnionArguments;
use super::layer::OnionLayer;
use super::layer::OnionLayerApplication;
use super::layer::OnionLayerHead;
use super::layer::ONION_DID_BYTES;
use super::layer::ONION_EXPIRY_BYTES;
use super::seed::OnionCarryKey;
use super::seed::OnionSegmentKeys;
use super::seed::OnionSegmentSeed;
use super::seed::ONION_CARRY_SEED_BYTES;
use crate::onion::circuit::OnionAdmissionCharge;
use crate::onion::circuit::OnionAdmissionLayer;
use crate::onion::circuit::OnionAdmissionRejection;
use crate::onion::circuit::OnionAdmissionState;
use crate::onion::circuit::OnionExpiry;
use crate::onion::signature::OnionShape;
pub(crate) const ONION_SURB_BYTES: usize =
ONION_DID_BYTES + ONION_HEADER_BYTES + ONION_CARRY_SEED_BYTES + ONION_EXPIRY_BYTES;
const _: () = assert!(ONION_SURB_BYTES == 2979);
pub(crate) struct OnionCell {
class: OnionLoopClass,
bytes: Vec<u8>,
}
pub(crate) struct Charged<C> {
value: C,
charge: OnionAdmissionCharge,
}
pub(crate) struct OnionPeeledCell {
class: OnionLoopClass,
layer: OnionLayer,
bytes: Vec<u8>,
}
pub(crate) struct OnionAdmittedCell(OnionPeeledCell);
#[derive(Debug)]
pub(crate) enum OnionStep {
Relayed {
next: Did,
cell: OnionCell,
},
Consumed {
symbol: OnionShape,
arguments: OnionArguments,
value: OnionCarryValue,
surb: Box<OnionSurb>,
},
}
pub(crate) struct OnionSurb {
class: OnionLoopClass,
next: Did,
header: OnionHeader,
outbound: OnionSegmentSeed,
expiry: OnionExpiry,
}
const _: () = assert!(size_of::<OnionSurb>() <= 3 * 1024);
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
#[error("{0} bytes is not the length of any onion loop class")]
pub(crate) struct OnionCellWidth(pub(crate) usize);
#[derive(Debug, thiserror::Error)]
pub(crate) enum OnionProduceError {
#[error(transparent)]
Key(#[from] KeyError),
#[error("{width}")]
ValueTooWide {
surb: Box<OnionSurb>,
width: OnionValueTooWide,
},
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub(crate) enum OnionStepError {
#[error(transparent)]
Key(#[from] KeyError),
#[error(transparent)]
Open(#[from] OnionOpenError),
#[error("onion cell narrower than its header")]
Width,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub(crate) enum OnionClientError {
#[error(transparent)]
Blinding(#[from] OnionBlindingError),
#[error(transparent)]
ValueTooWide(#[from] OnionValueTooWide),
}
impl OnionCell {
pub(crate) fn parse(payload: &[u8]) -> Result<Self, OnionCellWidth> {
let class = Self::class_of(payload.len())?;
Ok(Self {
class,
bytes: payload.to_vec(),
})
}
fn class_of(width: usize) -> Result<OnionLoopClass, OnionCellWidth> {
OnionLoopClass::from_cell_bytes(width).ok_or(OnionCellWidth(width))
}
pub(crate) fn into_bytes(self) -> Vec<u8> {
self.bytes
}
pub(crate) const fn class(&self) -> OnionLoopClass {
self.class
}
fn seal(
class: OnionLoopClass,
header: &OnionHeader,
keys: &OnionSegmentKeys,
value: &[u8],
) -> Result<Self, OnionValueTooWide> {
let mut bytes = Vec::with_capacity(class.cell_bytes());
header.encode_into(&mut bytes);
bytes.resize(class.cell_bytes(), 0);
let slot = bytes.get_mut(ONION_HEADER_BYTES..).unwrap_or_default();
carry::seal(class, keys, value, slot)?;
Ok(Self { class, bytes })
}
pub(crate) fn client(
route: &OnionHeaderRoute,
class: OnionLoopClass,
keys: &OnionSegmentKeys,
value: &[u8],
rng: &mut (impl CryptoRng + RngCore),
) -> Result<(Self, OnionLoopTag), OnionClientError> {
let (header, tag) = OnionHeader::build(route, class, rng)?;
Ok((Self::seal(class, &header, keys, value)?, tag))
}
pub(crate) fn loop_tag(&self) -> OnionLoopTag {
let mut tag = [0; ONION_HEADER_MAC_BYTES];
tag.iter_mut()
.zip(
self.bytes
.get(ONION_HEADER_BYTES - ONION_HEADER_MAC_BYTES..ONION_HEADER_BYTES)
.unwrap_or_default(),
)
.for_each(|(slot, byte)| *slot = *byte);
OnionLoopTag::new(tag)
}
pub(crate) fn open(self, key: &OnionCarryKey) -> Result<OnionCarryValue, OnionOpenError> {
let end = self.bytes.len();
carry::open(key, self.bytes, ONION_HEADER_BYTES..end)
}
fn peel(mut self, keys: &[DelegateeKey]) -> Result<OnionPeeledCell, OnionPeelError> {
let header = self
.bytes
.first_chunk_mut::<ONION_HEADER_BYTES>()
.ok_or(OnionPeelError::Invalid)?;
let layer = peel_in_place(header, self.class, keys)?;
Ok(OnionPeeledCell {
class: self.class,
layer,
bytes: self.bytes,
})
}
}
impl fmt::Debug for OnionCell {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("OnionCell")
.field("class", &self.class)
.finish_non_exhaustive()
}
}
impl<C> Charged<C> {
pub(in crate::onion) const fn new(value: C, charge: OnionAdmissionCharge) -> Self {
Self { value, charge }
}
pub(crate) const fn value(&self) -> &C {
&self.value
}
}
impl Charged<OnionCell> {
pub(crate) fn settle(self) -> OnionCell {
self.value
}
pub(crate) fn peel(
self,
keys: &[DelegateeKey],
) -> Result<Charged<OnionPeeledCell>, OnionPeelError> {
let Self { value, charge } = self;
value.peel(keys).map(|peeled| Charged::new(peeled, charge))
}
}
impl OnionPeeledCell {
pub(crate) const fn head(&self) -> &OnionLayerHead {
&self.layer.head
}
}
impl Charged<OnionPeeledCell> {
pub(crate) fn admit(
self,
admission: &mut OnionAdmissionState,
now_ms: u128,
) -> Result<OnionAdmittedCell, OnionAdmissionRejection> {
let Self { value, charge } = self;
let head = &value.layer.head;
admission.admit(now_ms, charge, OnionAdmissionLayer {
epoch: head.epoch,
expiry: head.expiry,
tag: head.nonce,
})?;
Ok(OnionAdmittedCell(value))
}
}
impl OnionAdmittedCell {
#[cfg(test)]
pub(crate) const fn head(&self) -> &OnionLayerHead {
&self.0.layer.head
}
#[cfg(test)]
pub(crate) const fn layer(&self) -> &OnionLayer {
&self.0.layer
}
pub(crate) fn step(self) -> Result<OnionStep, OnionStepError> {
let OnionPeeledCell {
class,
layer,
mut bytes,
} = self.0;
let OnionLayer {
head,
inbound,
outbound,
} = layer;
let key = inbound.key()?;
match head.application {
OnionLayerApplication::Relay => {
carry::peel(
&key,
bytes.get_mut(ONION_HEADER_BYTES..).unwrap_or_default(),
);
Ok(OnionStep::Relayed {
next: head.next,
cell: OnionCell { class, bytes },
})
}
OnionLayerApplication::Apply(OnionApplication { symbol, arguments }) => {
let header = bytes
.first_chunk::<ONION_HEADER_BYTES>()
.map(OnionHeader::of)
.ok_or(OnionStepError::Width)?;
let surb = Box::new(OnionSurb {
class,
next: head.next,
header,
outbound,
expiry: head.expiry,
});
let end = bytes.len();
let value = carry::open(&key, bytes, ONION_HEADER_BYTES..end)?;
Ok(OnionStep::Consumed {
symbol,
arguments,
value,
surb,
})
}
}
}
}
impl OnionSurb {
pub(crate) const fn new(
class: OnionLoopClass,
next: Did,
header: OnionHeader,
outbound: OnionSegmentSeed,
expiry: OnionExpiry,
) -> Self {
Self {
class,
next,
header,
outbound,
expiry,
}
}
pub(crate) const fn expiry(&self) -> OnionExpiry {
self.expiry
}
pub(crate) const fn class(&self) -> OnionLoopClass {
self.class
}
pub(crate) const fn next(&self) -> Did {
self.next
}
#[cfg(test)]
pub(crate) const fn outbound(&self) -> &OnionSegmentSeed {
&self.outbound
}
#[cfg(test)]
pub(crate) const fn capacity(&self) -> usize {
self.class.value_capacity()
}
pub(crate) fn encode_into(&self, bytes: &mut Vec<u8>) {
bytes.extend_from_slice(&encode_next(self.next));
self.header.encode_into(bytes);
bytes.extend_from_slice(self.outbound.as_bytes());
bytes.extend_from_slice(&encode_expiry(self.expiry));
}
pub(crate) fn decode(class: OnionLoopClass, bytes: &[u8]) -> Option<Self> {
let (next, rest) = bytes.split_first_chunk::<ONION_DID_BYTES>()?;
let (header, rest) = rest.split_first_chunk::<ONION_HEADER_BYTES>()?;
let (outbound, rest) = rest.split_first_chunk::<ONION_CARRY_SEED_BYTES>()?;
let expiry = <[u8; ONION_EXPIRY_BYTES]>::try_from(rest).ok()?;
Some(Self {
class,
next: decode_next(*next),
header: OnionHeader::of(header),
outbound: OnionSegmentSeed::new(*outbound),
expiry: decode_expiry(expiry)?,
})
}
pub(crate) fn produce(self, value: &[u8]) -> Result<(Did, OnionCell), OnionProduceError> {
let keys = self.outbound.keys()?;
match OnionCell::seal(self.class, &self.header, &keys, value) {
Ok(cell) => Ok((self.next, cell)),
Err(width) => Err(OnionProduceError::ValueTooWide {
surb: Box::new(self),
width,
}),
}
}
}
impl fmt::Debug for OnionSurb {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("OnionSurb")
.field("class", &self.class)
.field("next", &self.next)
.field("expiry", &self.expiry)
.finish_non_exhaustive()
}
}