use super::envelope::Row;
use serde_json::Value;
use sha2::{Digest, Sha256};
const NAME_END: u8 = 0x1f;
const FIELD_END: u8 = 0x1e;
const ROW_END: u8 = 0x1d;
const ALGORITHM: &str = "sha256";
#[derive(Debug, Default)]
pub struct Signature {
digest: Sha256,
rows: u64,
}
impl Signature {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn absorb(&mut self, row: &Row) {
for (name, value) in row {
self.digest.update(name.as_bytes());
self.digest.update([NAME_END]);
self.digest.update(canonical(value).as_bytes());
self.digest.update([FIELD_END]);
}
self.digest.update([ROW_END]);
self.rows += 1;
}
#[must_use]
pub const fn rows(&self) -> u64 {
self.rows
}
#[must_use]
pub fn finish(mut self) -> String {
self.digest.update(self.rows.to_be_bytes());
format!("{ALGORITHM}:{}", hex::encode(self.digest.finalize()))
}
}
#[must_use]
pub fn of_bytes(bytes: &[u8]) -> String {
let mut digest = Sha256::new();
digest.update(bytes);
format!("{ALGORITHM}:{}", hex::encode(digest.finalize()))
}
#[derive(Debug, Default)]
pub struct ByteSignature {
digest: Sha256,
}
impl ByteSignature {
pub fn absorb(&mut self, bytes: &[u8]) {
self.digest.update(bytes);
}
#[must_use]
pub fn finish(self) -> String {
format!("{ALGORITHM}:{}", hex::encode(self.digest.finalize()))
}
}
#[must_use]
pub fn of_rows(rows: &[Row]) -> String {
let mut signature = Signature::new();
for row in rows {
signature.absorb(row);
}
signature.finish()
}
fn canonical(value: &Value) -> String {
match value {
Value::Null => "\u{0}absent".to_owned(),
Value::String(text) => text.clone(),
other => serde_json::to_string(other).unwrap_or_else(|_| other.to_string()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use indexmap::IndexMap;
use serde_json::json;
fn row(name: &str, size: i64) -> Row {
let mut row = IndexMap::new();
row.insert("name".to_owned(), json!(name));
row.insert("size".to_owned(), json!(size));
row
}
#[test]
fn the_same_input_always_produces_the_same_signature() {
let rows = vec![row("alpha", 1), row("beta", 2)];
assert_eq!(of_rows(&rows), of_rows(&rows));
let again = vec![row("alpha", 1), row("beta", 2)];
assert_eq!(
of_rows(&rows),
of_rows(&again),
"a rebuilt result signs the same"
);
}
#[test]
fn the_signature_names_its_own_algorithm() {
let signature = of_rows(&[row("alpha", 1)]);
assert!(signature.starts_with("sha256:"), "{signature}");
assert_eq!(signature.len(), "sha256:".len() + 64);
}
#[test]
fn changing_one_cell_changes_the_signature() {
assert_ne!(of_rows(&[row("alpha", 1)]), of_rows(&[row("alpha", 2)]));
assert_ne!(of_rows(&[row("alpha", 1)]), of_rows(&[row("alphb", 1)]));
}
#[test]
fn feeding_rows_one_at_a_time_matches_signing_them_together() {
let rows = vec![row("alpha", 1), row("beta", 2), row("gamma", 3)];
let mut streamed = Signature::new();
for one in &rows {
streamed.absorb(one);
}
assert_eq!(streamed.rows(), 3);
assert_eq!(streamed.finish(), of_rows(&rows));
}
#[test]
fn a_field_boundary_cannot_be_forged_from_content() {
let mut joined = IndexMap::new();
joined.insert("name".to_owned(), json!("alpha\u{1f}1"));
let mut split = IndexMap::new();
split.insert("name".to_owned(), json!("alpha"));
split.insert("1".to_owned(), json!(""));
assert_ne!(of_rows(&[joined]), of_rows(&[split]));
}
#[test]
fn absence_signs_differently_from_empty_text() {
let mut absent = IndexMap::new();
absent.insert("name".to_owned(), Value::Null);
let mut empty = IndexMap::new();
empty.insert("name".to_owned(), json!(""));
assert_ne!(of_rows(&[absent]), of_rows(&[empty]));
}
#[test]
fn a_trailing_empty_row_changes_the_signature() {
let one = vec![row("alpha", 1)];
let two = vec![row("alpha", 1), IndexMap::new()];
assert_ne!(of_rows(&one), of_rows(&two));
}
#[test]
fn column_order_is_part_of_the_result_and_part_of_the_signature() {
let mut reversed = IndexMap::new();
reversed.insert("size".to_owned(), json!(1));
reversed.insert("name".to_owned(), json!("alpha"));
assert_ne!(of_rows(&[row("alpha", 1)]), of_rows(&[reversed]));
}
}