use crate::backend::api::{MaybeSend, MaybeSync};
use crate::error::{Error, Result};
pub const MAGIC: [u8; 4] = *b"CBNK";
pub const VERSION: u8 = 1;
pub const HEADER_LEN: usize = 6;
const fn header(chain_id: u8) -> [u8; HEADER_LEN] {
[MAGIC[0], MAGIC[1], MAGIC[2], MAGIC[3], VERSION, chain_id]
}
pub const MAX_DECODED_BYTES: usize = 256 * 1024 * 1024;
pub trait Filter: MaybeSend + MaybeSync + 'static {
fn name(&self) -> &'static str;
fn forward(&self, input: &[u8]) -> Result<Vec<u8>>;
fn reverse(&self, input: &[u8]) -> Result<Vec<u8>>;
fn forward_owned(&self, input: Vec<u8>) -> Result<Vec<u8>> {
self.forward(&input)
}
fn reverse_owned(&self, input: Vec<u8>) -> Result<Vec<u8>> {
self.reverse(&input)
}
}
impl std::fmt::Debug for dyn Filter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Filter")
.field("name", &self.name())
.finish()
}
}
pub struct FilterChain {
id: u8,
filters: Vec<Box<dyn Filter>>,
}
impl std::fmt::Debug for FilterChain {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FilterChain")
.field("id", &self.id)
.field(
"filters",
&self.filters.iter().map(|x| x.name()).collect::<Vec<_>>(),
)
.finish()
}
}
impl FilterChain {
pub fn new(id: u8, filters: Vec<Box<dyn Filter>>) -> Self {
Self { id, filters }
}
pub fn raw() -> Self {
Self::new(0, Vec::new())
}
pub fn checksum_only() -> Self {
Self::new(
crate::codec::CHECKSUM_ONLY_CHAIN_ID,
vec![Box::new(super::filters::Crc32)],
)
}
pub fn id(&self) -> u8 {
self.id
}
pub fn describe(&self) -> String {
if self.filters.is_empty() {
return format!("chain {} (raw)", self.id);
}
format!(
"chain {} ({})",
self.id,
self.filters
.iter()
.map(|f| f.name())
.collect::<Vec<_>>()
.join(" -> ")
)
}
pub fn seal(&self, payload: Vec<u8>) -> Result<Vec<u8>> {
let mut body = payload;
for filter in &self.filters {
body = filter.forward_owned(body)?;
}
body.splice(0..0, header(self.id));
Ok(body)
}
pub fn seal_slice(&self, payload: &[u8]) -> Result<Vec<u8>> {
self.seal(payload.to_vec())
}
pub fn open(&self, stored: &[u8]) -> Result<Vec<u8>> {
if stored.len() < HEADER_LEN {
return Err(Error::Corrupt(format!(
"value is {} bytes, shorter than the {HEADER_LEN} byte header",
stored.len()
)));
}
if stored[0..4] != MAGIC {
return Err(Error::Corrupt(
"value does not carry the crossbank magic".into(),
));
}
let version = stored[4];
if version != VERSION {
return Err(Error::UnsupportedVersion {
found: version,
supported: VERSION,
});
}
let chain = stored[5];
if chain != self.id {
return Err(Error::SchemaMismatch {
stored: format!("chain {chain}"),
requested: self.describe(),
});
}
let mut body = stored[HEADER_LEN..].to_vec();
for filter in self.filters.iter().rev() {
body = filter.reverse_owned(body)?;
}
Ok(body)
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Xor(u8);
impl Filter for Xor {
fn name(&self) -> &'static str {
"xor"
}
fn forward(&self, input: &[u8]) -> Result<Vec<u8>> {
Ok(input.iter().map(|b| b ^ self.0).collect())
}
fn reverse(&self, input: &[u8]) -> Result<Vec<u8>> {
self.forward(input)
}
}
struct Tag(u8);
impl Filter for Tag {
fn name(&self) -> &'static str {
"tag"
}
fn forward(&self, input: &[u8]) -> Result<Vec<u8>> {
let mut v = input.to_vec();
v.push(self.0);
Ok(v)
}
fn reverse(&self, input: &[u8]) -> Result<Vec<u8>> {
let mut v = input.to_vec();
match v.pop() {
Some(b) if b == self.0 => Ok(v),
other => Err(Error::Corrupt(format!("tag mismatch: {other:?}"))),
}
}
}
#[test]
fn seal_owned_and_seal_slice_produce_identical_bytes() {
for chain in [FilterChain::raw(), crate::codec::default_chain()] {
for len in [0usize, 1, 6, 7, 1000] {
let payload: Vec<u8> = (0..len).map(|i| (i * 17 % 253) as u8).collect();
assert_eq!(
chain.seal(payload.clone()).unwrap(),
chain.seal_slice(&payload).unwrap(),
"{} disagreed at {len} bytes",
chain.describe()
);
let sealed = chain.seal(payload.clone()).unwrap();
assert_eq!(&sealed[0..4], &MAGIC, "the header must survive splicing");
assert_eq!(sealed[4], VERSION);
assert_eq!(sealed[5], chain.id());
assert_eq!(chain.open(&sealed).unwrap(), payload);
}
}
}
#[test]
fn raw_chain_round_trips() {
let c = FilterChain::raw();
let sealed = c.seal_slice(b"hello").unwrap();
assert_eq!(&sealed[0..4], &MAGIC);
assert_eq!(c.open(&sealed).unwrap(), b"hello");
}
#[test]
fn an_empty_payload_round_trips() {
let c = FilterChain::raw();
let sealed = c.seal_slice(b"").unwrap();
assert_eq!(sealed.len(), HEADER_LEN);
assert_eq!(c.open(&sealed).unwrap(), b"");
}
#[test]
fn filters_reverse_in_the_opposite_order() {
let c = FilterChain::new(1, vec![Box::new(Tag(1)), Box::new(Tag(2))]);
let sealed = c.seal_slice(b"x").unwrap();
assert_eq!(&sealed[HEADER_LEN..], &[b'x', 1, 2]);
assert_eq!(c.open(&sealed).unwrap(), b"x");
}
#[test]
fn a_foreign_blob_is_rejected() {
let c = FilterChain::raw();
assert!(matches!(
c.open(b"not a crossbank value"),
Err(Error::Corrupt(_))
));
}
#[test]
fn a_truncated_value_is_an_error_not_a_panic() {
let c = FilterChain::raw();
assert!(matches!(c.open(b"CB"), Err(Error::Corrupt(_))));
}
#[test]
fn a_future_version_is_refused_by_version_not_misread() {
let c = FilterChain::raw();
let mut sealed = c.seal_slice(b"payload").unwrap();
sealed[4] = VERSION + 1;
assert!(matches!(
c.open(&sealed),
Err(Error::UnsupportedVersion { .. })
));
}
#[test]
fn a_different_chain_is_refused_rather_than_misdecoded() {
let writer = FilterChain::new(1, vec![Box::new(Xor(0xAA))]);
let reader = FilterChain::new(2, vec![Box::new(Xor(0x55))]);
let sealed = writer.seal_slice(b"secret").unwrap();
match reader.open(&sealed) {
Err(Error::SchemaMismatch { .. }) => {}
other => panic!("expected a schema mismatch, got {other:?}"),
}
}
#[test]
fn describe_names_the_filters_in_order() {
let c = FilterChain::new(7, vec![Box::new(Tag(1)), Box::new(Xor(2))]);
assert_eq!(c.describe(), "chain 7 (tag -> xor)");
assert_eq!(FilterChain::raw().describe(), "chain 0 (raw)");
}
}