use oxabl_cache_format::{CacheId, SealedTelemetry, TelemetryReport};
use crate::aead::Cipher;
use crate::domain::{AD_TELEMETRY, CTX_TELEMETRY, prefixed};
use crate::error::{Error, Result};
use crate::keys::RootKey;
use crate::random;
fn cipher(root: &RootKey) -> Result<Cipher> {
Cipher::new(&blake3::derive_key(CTX_TELEMETRY, root.bytes()))
}
fn associated(cache: &CacheId, header: &[u8]) -> Vec<u8> {
let mut bound = prefixed(AD_TELEMETRY, &cache.0);
bound.extend_from_slice(header);
bound
}
pub fn seal_telemetry(
root: &RootKey,
cache: &CacheId,
epoch: u32,
report: &TelemetryReport,
) -> Result<Vec<u8>> {
let nonce = random::array()?;
let header = SealedTelemetry::header(epoch, &nonce);
let mut body = report.encode();
cipher(root)?.seal(nonce, &associated(cache, &header), &mut body)?;
let mut frame = header;
frame.extend_from_slice(&body);
Ok(frame)
}
pub fn telemetry_epoch(frame: &[u8]) -> Result<u32> {
Ok(SealedTelemetry::decode(frame)?.epoch)
}
pub fn open_telemetry(
root: &RootKey,
cache: &CacheId,
epoch: u32,
frame: &[u8],
) -> Result<TelemetryReport> {
let sealed = SealedTelemetry::decode(frame)?;
if sealed.epoch != epoch {
return Err(Error::Mismatch("telemetry of another epoch"));
}
let header = SealedTelemetry::header(sealed.epoch, &sealed.nonce);
let mut body = sealed.sealed.to_vec();
let plain = cipher(root)?.open(sealed.nonce, &associated(cache, &header), &mut body)?;
Ok(TelemetryReport::decode(plain)?)
}