use thiserror::Error;
use crate::primitives::NONCE_SIZE;
pub use crate::OreCipher;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WireHeader {
pub version: u8,
pub scheme_id: u8,
}
pub(crate) const WIRE_HEADER_LEN: usize = 4;
impl WireHeader {
pub(crate) fn write(&self, num_blocks: u16, out: &mut Vec<u8>) {
out.push(self.version);
out.push(self.scheme_id);
out.extend_from_slice(&num_blocks.to_be_bytes());
}
pub(crate) fn strip<'a>(
&self,
num_blocks: usize,
data: &'a [u8],
) -> Result<&'a [u8], ParseError> {
let (header, body) = parse_header(data)?;
if header != (self.version, self.scheme_id, num_blocks) {
return Err(ParseError);
}
Ok(body)
}
}
struct WireCount<const N: usize>;
impl<const N: usize> WireCount<N> {
const FITS: () = assert!(
N <= u16::MAX as usize,
"WireCount: too many blocks for the wire header"
);
#[inline]
#[allow(clippy::let_unit_value)]
fn get() -> u16 {
let () = Self::FITS;
N as u16
}
}
pub(crate) type ParsedHeader = (u8, u8, usize);
pub(crate) fn parse_header(data: &[u8]) -> Result<(ParsedHeader, &[u8]), ParseError> {
if data.len() < WIRE_HEADER_LEN {
return Err(ParseError);
}
let count = u16::from_be_bytes([data[2], data[3]]) as usize;
Ok(((data[0], data[1], count), &data[WIRE_HEADER_LEN..]))
}
fn header_len<S: OreCipher>() -> usize {
if S::WIRE_HEADER.is_some() {
WIRE_HEADER_LEN
} else {
0
}
}
pub trait OreOutput: Sized {
fn size() -> usize;
fn to_bytes(&self) -> Vec<u8>;
fn from_slice(data: &[u8]) -> Result<Self, ParseError>;
#[deprecated(since = "0.8.0", note = "please use `from_slice` instead")]
fn from_bytes(data: &[u8]) -> Result<Self, ParseError> {
Self::from_slice(data)
}
}
#[derive(Debug, Copy, Clone)]
pub struct Left<S: OreCipher, const N: usize> {
pub f: [S::LeftBlockType; N],
pub xt: [u8; N],
}
#[derive(Debug, Copy, Clone)]
pub struct Right<S: OreCipher, const N: usize> {
pub nonce: [u8; NONCE_SIZE],
pub data: [S::RightBlockType; N],
}
#[derive(Debug, Copy, Clone)]
pub struct CipherText<S: OreCipher, const N: usize> {
pub left: Left<S, N>,
pub right: Right<S, N>,
}
pub trait CipherTextBlock: Default + Copy + std::fmt::Debug {
const BLOCK_SIZE: usize;
fn to_bytes(self) -> Vec<u8>;
fn from_bytes(data: &[u8]) -> Result<Self, ParseError>;
fn default_in_place(&mut self);
}
#[derive(Debug, Error)]
#[error("Unable to parse ORE Ciphertext")]
pub struct ParseError;
impl<S: OreCipher, const N: usize> Left<S, N> {
pub(crate) fn init() -> Self {
Self {
xt: [0; N],
f: [S::LeftBlockType::default(); N],
}
}
pub(crate) fn body_size() -> usize {
N * (S::LeftBlockType::BLOCK_SIZE + 1)
}
fn write_body(&self, vec: &mut Vec<u8>) {
vec.extend_from_slice(&self.xt);
self.f
.iter()
.for_each(|&block| vec.append(&mut block.to_bytes()));
}
fn from_body(data: &[u8]) -> Result<Self, ParseError> {
if data.len() != Self::body_size() {
return Err(ParseError);
}
let mut out = Self::init();
out.xt.copy_from_slice(&data[0..N]);
if out.xt.iter().any(|&s| usize::from(s) >= S::SYMBOL_DOMAIN) {
return Err(ParseError);
}
for i in 0..N {
let block_start_index = N + (i * S::LeftBlockType::BLOCK_SIZE);
out.f[i] = S::LeftBlockType::from_bytes(
&data[block_start_index..(block_start_index + S::LeftBlockType::BLOCK_SIZE)],
)?;
}
Ok(out)
}
}
impl<S: OreCipher, const N: usize> OreOutput for Left<S, N> {
fn size() -> usize {
header_len::<S>() + Self::body_size()
}
fn to_bytes(&self) -> Vec<u8> {
let mut vec = Vec::with_capacity(Self::size());
if let Some(header) = S::WIRE_HEADER {
header.write(WireCount::<N>::get(), &mut vec);
}
self.write_body(&mut vec);
vec
}
fn from_slice(data: &[u8]) -> Result<Self, ParseError> {
let body = match S::WIRE_HEADER {
Some(header) => header.strip(N, data)?,
None => data,
};
Self::from_body(body)
}
}
impl<S: OreCipher, const N: usize> Right<S, N> {
pub(crate) fn init() -> Self {
Self {
nonce: Default::default(),
data: [Default::default(); N],
}
}
pub(crate) fn body_size() -> usize {
(N * S::RightBlockType::BLOCK_SIZE) + NONCE_SIZE
}
fn write_body(&self, vec: &mut Vec<u8>) {
vec.extend_from_slice(&self.nonce);
self.data
.iter()
.for_each(|&block| vec.append(&mut block.to_bytes()));
}
fn from_body(data: &[u8]) -> Result<Self, ParseError> {
if data.len() != Self::body_size() {
return Err(ParseError);
}
let mut out = Self::init();
out.nonce.copy_from_slice(&data[0..NONCE_SIZE]);
for i in 0..N {
let block_start_index = NONCE_SIZE + (i * S::RightBlockType::BLOCK_SIZE);
out.data[i] = S::RightBlockType::from_bytes(
&data[block_start_index..(block_start_index + S::RightBlockType::BLOCK_SIZE)],
)?;
}
Ok(out)
}
}
impl<S: OreCipher, const N: usize> OreOutput for Right<S, N> {
fn size() -> usize {
header_len::<S>() + Self::body_size()
}
fn to_bytes(&self) -> Vec<u8> {
let mut vec = Vec::with_capacity(Self::size());
if let Some(header) = S::WIRE_HEADER {
header.write(WireCount::<N>::get(), &mut vec);
}
self.write_body(&mut vec);
vec
}
fn from_slice(data: &[u8]) -> Result<Self, ParseError> {
let body = match S::WIRE_HEADER {
Some(header) => header.strip(N, data)?,
None => data,
};
Self::from_body(body)
}
}
impl<S: OreCipher, const N: usize> OreOutput for CipherText<S, N> {
fn size() -> usize {
header_len::<S>() + Left::<S, N>::body_size() + Right::<S, N>::body_size()
}
fn to_bytes(&self) -> Vec<u8> {
let mut vec = Vec::with_capacity(Self::size());
if let Some(header) = S::WIRE_HEADER {
header.write(WireCount::<N>::get(), &mut vec);
}
self.left.write_body(&mut vec);
self.right.write_body(&mut vec);
vec
}
fn from_slice(data: &[u8]) -> Result<Self, ParseError> {
let body = match S::WIRE_HEADER {
Some(header) => header.strip(N, data)?,
None => data,
};
if body.len() != Left::<S, N>::body_size() + Right::<S, N>::body_size() {
return Err(ParseError);
}
let (left, right) = body.split_at(Left::<S, N>::body_size());
let left = Left::<S, N>::from_body(left)?;
let right = Right::<S, N>::from_body(right)?;
Ok(Self { left, right })
}
}