use rings_core::dht::Did;
use rings_core::ecc::PublicKeyAddress;
use zeroize::Zeroize;
use zeroize::ZeroizeOnDrop;
use zeroize::Zeroizing;
use super::header::OnionHeaderMac;
use super::header::ONION_HEADER_MAC_BYTES;
use super::seed::OnionCarrySeed;
use super::seed::OnionSegmentSeed;
use super::seed::ONION_CARRY_SEED_BYTES;
use crate::onion::circuit::OnionExpiry;
use crate::onion::circuit::OnionReplayNonce;
use crate::onion::signature::OnionShape;
use crate::onion::signature::OnionSymbol;
use crate::onion::OnionProcessEpoch;
pub(crate) const ONION_DID_BYTES: usize = 20;
pub(crate) const ONION_EXPIRY_BYTES: usize = 8;
pub(crate) fn encode_next(next: Did) -> [u8; ONION_DID_BYTES] {
PublicKeyAddress::from(next).to_fixed_bytes()
}
pub(crate) fn decode_next(bytes: [u8; ONION_DID_BYTES]) -> Did {
Did::from(PublicKeyAddress::from(bytes))
}
pub(crate) fn encode_expiry(expiry: OnionExpiry) -> [u8; ONION_EXPIRY_BYTES] {
expiry.to_wire_ms().to_be_bytes()
}
pub(crate) fn decode_expiry(bytes: [u8; ONION_EXPIRY_BYTES]) -> Option<OnionExpiry> {
OnionExpiry::from_wire_ms(u64::from_be_bytes(bytes))
}
pub(crate) const ONION_ARGUMENT_BYTES: usize = 64;
macro_rules! layer_record {
($($(#[doc = $doc:literal])* $field:ident: $width:expr,)*) => {
#[derive(Zeroize, ZeroizeOnDrop)]
struct LayerRecord {
$($(#[doc = $doc])* $field: [u8; $width],)*
}
impl LayerRecord {
const WIDTH: usize = 0 $(+ $width)*;
fn encode(&self) -> Zeroizing<[u8; Self::WIDTH]> {
let mut bytes = Zeroizing::new([0; Self::WIDTH]);
bytes
.iter_mut()
.zip(core::iter::empty()$(.chain(self.$field.iter()))*)
.for_each(|(slot, byte)| *slot = *byte);
bytes
}
fn decode(mut bytes: &[u8]) -> Option<Self> {
let record = Self { $($field: take_field(&mut bytes)?,)* };
bytes.is_empty().then_some(record)
}
}
};
}
layer_record! {
code: 1,
arguments: ONION_ARGUMENT_BYTES,
next: ONION_DID_BYTES,
epoch: 16,
expiry: ONION_EXPIRY_BYTES,
nonce: 16,
inbound: ONION_CARRY_SEED_BYTES,
outbound: ONION_CARRY_SEED_BYTES,
next_mac: ONION_HEADER_MAC_BYTES,
}
pub(crate) const ONION_LAYER_BYTES: usize = LayerRecord::WIDTH;
fn take_field<const N: usize>(bytes: &mut &[u8]) -> Option<[u8; N]> {
let (field, rest) = bytes.split_first_chunk::<N>()?;
*bytes = rest;
Some(*field)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct OnionArguments([u8; ONION_ARGUMENT_BYTES]);
impl OnionArguments {
pub(crate) const fn new(bytes: [u8; ONION_ARGUMENT_BYTES]) -> Self {
Self(bytes)
}
pub(crate) const fn as_bytes(&self) -> &[u8; ONION_ARGUMENT_BYTES] {
&self.0
}
}
#[derive(Debug, Eq, PartialEq)]
pub(crate) enum OnionLayerApplication {
Relay,
Apply(OnionApplication),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct OnionApplication {
pub(crate) symbol: OnionShape,
pub(crate) arguments: OnionArguments,
}
#[derive(Debug, Eq, PartialEq)]
pub(crate) struct OnionLayer {
pub(crate) head: OnionLayerHead,
pub(crate) inbound: OnionCarrySeed,
pub(crate) outbound: OnionSegmentSeed,
}
#[derive(Debug, Eq, PartialEq)]
pub(crate) struct OnionLayerHead {
pub(crate) application: OnionLayerApplication,
pub(crate) next: Did,
pub(crate) epoch: OnionProcessEpoch,
pub(crate) expiry: OnionExpiry,
pub(crate) nonce: OnionReplayNonce,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub(crate) enum OnionLayerError {
#[error("layer of {0} bytes is not {ONION_LAYER_BYTES} bytes long")]
Width(usize),
#[error("layer symbol code {0} names no symbol of the onion signature")]
UnknownSymbol(u8),
#[error("relay layer carries arguments")]
RelayArguments,
#[error("layer expiry {0} ms is off the expiry grid")]
OffGridExpiry(u64),
}
impl OnionLayer {
pub(crate) fn encode(&self, next_mac: &OnionHeaderMac) -> Zeroizing<[u8; ONION_LAYER_BYTES]> {
let (symbol, arguments) = match &self.head.application {
OnionLayerApplication::Relay => (OnionSymbol::Relay, [0; ONION_ARGUMENT_BYTES]),
OnionLayerApplication::Apply(application) => (
OnionSymbol::Shape(application.symbol.clone()),
application.arguments.0,
),
};
LayerRecord {
code: [symbol.code()],
arguments,
next: encode_next(self.head.next),
epoch: self.head.epoch.to_bytes(),
expiry: encode_expiry(self.head.expiry),
nonce: self.head.nonce.to_bytes(),
inbound: *self.inbound.as_bytes(),
outbound: *self.outbound.as_bytes(),
next_mac: next_mac.to_bytes(),
}
.encode()
}
pub(crate) fn decode(bytes: &[u8]) -> Result<(Self, OnionHeaderMac), OnionLayerError> {
let record = LayerRecord::decode(bytes).ok_or(OnionLayerError::Width(bytes.len()))?;
let [code] = record.code;
let application =
match OnionSymbol::from_code(code).ok_or(OnionLayerError::UnknownSymbol(code))? {
OnionSymbol::Relay => (record.arguments == [0; ONION_ARGUMENT_BYTES])
.then_some(OnionLayerApplication::Relay)
.ok_or(OnionLayerError::RelayArguments)?,
OnionSymbol::Shape(symbol) => OnionLayerApplication::Apply(OnionApplication {
symbol,
arguments: OnionArguments(record.arguments),
}),
};
Ok((
Self {
head: OnionLayerHead {
application,
next: decode_next(record.next),
epoch: OnionProcessEpoch::new(record.epoch),
expiry: decode_expiry(record.expiry).ok_or(OnionLayerError::OffGridExpiry(
u64::from_be_bytes(record.expiry),
))?,
nonce: OnionReplayNonce::new(record.nonce),
},
inbound: OnionCarrySeed::new(record.inbound),
outbound: OnionSegmentSeed::new(record.outbound),
},
OnionHeaderMac::new(record.next_mac),
))
}
}