use core::ops::Range;
use rings_aez::Tweak;
use zeroize::Zeroizing;
use super::class::OnionLoopClass;
use super::seed::OnionCarryKey;
use super::seed::OnionSegmentKeys;
pub(crate) const ONION_CARRY_AUTHENTICATOR_BYTES: usize = 16;
const PADDING_MARKER: u8 = 0x80;
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
#[error("carry value of {length} bytes exceeds the {capacity}-byte capacity of its class")]
pub(crate) struct OnionValueTooWide {
pub(crate) length: usize,
pub(crate) capacity: usize,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub(crate) enum OnionOpenError {
#[error("carry authenticator does not verify")]
Inauthentic,
#[error("carry value has no padding marker")]
Padding,
}
pub(crate) struct OnionCarryValue {
buffer: Zeroizing<Vec<u8>>,
range: Range<usize>,
}
impl OnionCarryValue {
pub(crate) fn as_slice(&self) -> &[u8] {
self.buffer.get(self.range.clone()).unwrap_or_default()
}
}
impl core::fmt::Debug for OnionCarryValue {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(formatter, "OnionCarryValue({} bytes)", self.range.len())
}
}
pub(crate) fn seal(
class: OnionLoopClass,
keys: &OnionSegmentKeys,
value: &[u8],
slot: &mut [u8],
) -> Result<(), OnionValueTooWide> {
let capacity = class.value_capacity();
if value.len() > capacity {
return Err(OnionValueTooWide {
length: value.len(),
capacity,
});
}
slot.iter_mut()
.zip(
value
.iter()
.copied()
.chain(core::iter::once(PADDING_MARKER))
.chain(core::iter::repeat(0)),
)
.for_each(|(byte, padded)| *byte = padded);
let _ = keys
.consumer()
.aez()
.encrypt(Tweak::EMPTY, ONION_CARRY_AUTHENTICATOR_BYTES, slot);
keys.relays()
.iter()
.rev()
.for_each(|relay| relay.aez().encipher(Tweak::EMPTY, slot));
Ok(())
}
pub(super) fn peel(key: &OnionCarryKey, slot: &mut [u8]) {
key.aez().decipher(Tweak::EMPTY, slot);
}
pub(super) fn open(
key: &OnionCarryKey,
buffer: Vec<u8>,
slot: Range<usize>,
) -> Result<OnionCarryValue, OnionOpenError> {
let mut buffer = Zeroizing::new(buffer);
let start = slot.start;
let message = buffer
.get_mut(slot)
.ok_or(OnionOpenError::Inauthentic)
.and_then(|slot| {
key.aez()
.decrypt(Tweak::EMPTY, ONION_CARRY_AUTHENTICATOR_BYTES, slot)
.map_err(|_| OnionOpenError::Inauthentic)
})?;
let length = message
.iter()
.rposition(|byte| *byte != 0)
.filter(|end| message.get(*end) == Some(&PADDING_MARKER))
.ok_or(OnionOpenError::Padding)?;
Ok(OnionCarryValue {
buffer,
range: start..start + length,
})
}