use bytes::Bytes;
use zeroize::Zeroizing;
use crate::onion::sphinx::cell::OnionSurb;
use crate::onion::sphinx::cell::ONION_SURB_BYTES;
use crate::onion::sphinx::class::OnionLoopClass;
const DATA_TAG: u8 = 0x00;
const FIN_TAG: u8 = 0x01;
const CREDIT_TAG: u8 = 0x02;
const ABORT_TAG: u8 = 0x03;
const TARGET_FLAG: u8 = 0x01;
const DATA_OVERHEAD_BYTES: usize = 1 + 4 + 1;
const CREDIT_OVERHEAD_BYTES: usize = 1 + 4;
const TARGET_LENGTH_BYTES: usize = 2;
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub(crate) struct OnionSequence(u32);
impl OnionSequence {
pub(crate) const FIRST: Self = Self(0);
#[cfg(test)]
pub(crate) const fn new(value: u32) -> Self {
Self(value)
}
pub(crate) const fn value(self) -> u32 {
self.0
}
pub(crate) fn next(self) -> Option<Self> {
self.0.checked_add(1).map(Self)
}
}
#[derive(Debug)]
pub(crate) enum OnionFrame {
Data {
sequence: OnionSequence,
target: Option<Bytes>,
payload: Bytes,
},
Fin {
sequence: OnionSequence,
target: Option<Bytes>,
},
Credit {
mark: OnionSequence,
surbs: Vec<OnionSurb>,
},
Abort {
sequence: OnionSequence,
},
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub(crate) enum OnionFrameUnencodable {
#[error("session frame of {length} bytes exceeds the {capacity}-byte carry of its class")]
TooWide {
length: usize,
capacity: usize,
},
#[error("credit frame of no reply block")]
EmptyCredit,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub(crate) enum OnionFrameError {
#[error("unknown session frame tag")]
Tag,
#[error("reserved session flags {0:#04x}")]
Flags(u8),
#[error("malformed session frame")]
Malformed,
#[error("malformed reply block in a credit frame")]
Surb,
}
impl OnionFrame {
pub(crate) const fn carries_target(&self) -> bool {
matches!(
self,
Self::Data {
target: Some(_),
..
} | Self::Fin {
target: Some(_),
..
}
)
}
pub(crate) const fn is_sequenced(&self) -> bool {
!matches!(self, Self::Credit { .. })
}
pub(crate) const fn data_capacity(class: OnionLoopClass) -> usize {
class.value_capacity() - DATA_OVERHEAD_BYTES
}
pub(crate) fn data_capacity_with_target(class: OnionLoopClass, target: &[u8]) -> Option<usize> {
Self::data_capacity(class).checked_sub(TARGET_LENGTH_BYTES + target.len())
}
pub(crate) const fn credit_capacity(class: OnionLoopClass) -> usize {
(class.value_capacity() - CREDIT_OVERHEAD_BYTES) / ONION_SURB_BYTES
}
pub(crate) fn encode(
&self,
class: OnionLoopClass,
) -> Result<Zeroizing<Vec<u8>>, OnionFrameUnencodable> {
let capacity = class.value_capacity();
let mut bytes = Zeroizing::new(Vec::with_capacity(capacity));
match self {
Self::Data {
sequence,
target,
payload,
} => {
bytes.push(DATA_TAG);
bytes.extend_from_slice(&sequence.value().to_be_bytes());
encode_target(&mut bytes, target.as_ref(), capacity)?;
bytes.extend_from_slice(payload);
}
Self::Fin { sequence, target } => {
bytes.push(FIN_TAG);
bytes.extend_from_slice(&sequence.value().to_be_bytes());
encode_target(&mut bytes, target.as_ref(), capacity)?;
}
Self::Abort { sequence } => {
bytes.push(ABORT_TAG);
bytes.extend_from_slice(&sequence.value().to_be_bytes());
}
Self::Credit { surbs, .. } if surbs.is_empty() => {
return Err(OnionFrameUnencodable::EmptyCredit);
}
Self::Credit { mark, surbs } => {
bytes.push(CREDIT_TAG);
bytes.extend_from_slice(&mark.value().to_be_bytes());
surbs.iter().for_each(|surb| surb.encode_into(&mut bytes));
}
}
if bytes.len() > capacity {
return Err(OnionFrameUnencodable::TooWide {
length: bytes.len(),
capacity,
});
}
Ok(bytes)
}
pub(crate) fn decode(class: OnionLoopClass, bytes: &[u8]) -> Result<Self, OnionFrameError> {
let (tag, rest) = bytes.split_first().ok_or(OnionFrameError::Tag)?;
match *tag {
DATA_TAG => {
let (sequence, rest) = split_sequence(rest)?;
let (target, payload) = split_target(rest)?;
Ok(Self::Data {
sequence,
target,
payload: Bytes::copy_from_slice(payload),
})
}
FIN_TAG => {
let (sequence, rest) = split_sequence(rest)?;
match split_target(rest)? {
(target, []) => Ok(Self::Fin { sequence, target }),
_ => Err(OnionFrameError::Malformed),
}
}
ABORT_TAG => match split_sequence(rest)? {
(sequence, []) => Ok(Self::Abort { sequence }),
_ => Err(OnionFrameError::Malformed),
},
CREDIT_TAG => {
let (mark, rest) = split_sequence(rest)?;
let (blocks, []) = rest.as_chunks::<ONION_SURB_BYTES>() else {
return Err(OnionFrameError::Malformed);
};
if blocks.is_empty() {
return Err(OnionFrameError::Malformed);
}
blocks
.iter()
.map(|block| OnionSurb::decode(class, block).ok_or(OnionFrameError::Surb))
.collect::<Result<Vec<_>, _>>()
.map(|surbs| Self::Credit { mark, surbs })
}
_ => Err(OnionFrameError::Tag),
}
}
}
fn encode_target(
bytes: &mut Vec<u8>,
target: Option<&Bytes>,
capacity: usize,
) -> Result<(), OnionFrameUnencodable> {
match target {
Some(target) => {
let length =
u16::try_from(target.len()).map_err(|_| OnionFrameUnencodable::TooWide {
length: target.len(),
capacity,
})?;
bytes.push(TARGET_FLAG);
bytes.extend_from_slice(&length.to_be_bytes());
bytes.extend_from_slice(target);
}
None => bytes.push(0),
}
Ok(())
}
fn split_target(bytes: &[u8]) -> Result<(Option<Bytes>, &[u8]), OnionFrameError> {
let (flags, rest) = bytes.split_first().ok_or(OnionFrameError::Malformed)?;
match *flags {
0 => Ok((None, rest)),
TARGET_FLAG => {
let (length, rest) = rest
.split_first_chunk::<TARGET_LENGTH_BYTES>()
.ok_or(OnionFrameError::Malformed)?;
let (target, rest) = rest
.split_at_checked(usize::from(u16::from_be_bytes(*length)))
.ok_or(OnionFrameError::Malformed)?;
Ok((Some(Bytes::copy_from_slice(target)), rest))
}
reserved => Err(OnionFrameError::Flags(reserved)),
}
}
fn split_sequence(bytes: &[u8]) -> Result<(OnionSequence, &[u8]), OnionFrameError> {
bytes
.split_first_chunk::<4>()
.map(|(sequence, rest)| (OnionSequence(u32::from_be_bytes(*sequence)), rest))
.ok_or(OnionFrameError::Malformed)
}
const _: () = assert!(
DATA_TAG != FIN_TAG
&& DATA_TAG != CREDIT_TAG
&& DATA_TAG != ABORT_TAG
&& FIN_TAG != CREDIT_TAG
&& FIN_TAG != ABORT_TAG
&& CREDIT_TAG != ABORT_TAG
);
const _: () = assert!(
OnionFrame::credit_capacity(OnionLoopClass::DEFAULT) == 4
&& OnionFrame::data_capacity(OnionLoopClass::DEFAULT) == 13_442
);