use std::collections::BTreeMap;
use serde_json::Value;
use sha2::{Digest, Sha256};
use unicode_normalization::UnicodeNormalization;
pub const CANON_DOMAIN: &[u8] = b"vela.canonical-json-subset.v1\x00";
fn normalize(value: &Value, path: &str) -> Result<Value, String> {
match value {
Value::Null | Value::Bool(_) => Ok(value.clone()),
Value::Number(n) => {
if n.is_f64() {
return Err(format!("floating-point value forbidden at {path}"));
}
Ok(value.clone())
}
Value::String(s) => Ok(Value::String(s.nfc().collect::<String>())),
Value::Array(items) => {
let mut out = Vec::with_capacity(items.len());
for (i, item) in items.iter().enumerate() {
out.push(normalize(item, &format!("{path}[{i}]"))?);
}
Ok(Value::Array(out))
}
Value::Object(map) => {
let mut sorted: BTreeMap<String, Value> = BTreeMap::new();
for (key, child) in map {
let nkey: String = key.nfc().collect();
let nchild = normalize(child, &format!("{path}.{nkey}"))?;
if sorted.insert(nkey.clone(), nchild).is_some() {
return Err(format!(
"duplicate key after NFC normalization at {path}: {nkey:?}"
));
}
}
let mut obj = serde_json::Map::with_capacity(sorted.len());
for (key, child) in sorted {
obj.insert(key, child);
}
Ok(Value::Object(obj))
}
}
}
pub fn canonical_bytes(value: &Value) -> Result<Vec<u8>, String> {
let normalized = normalize(value, "$")?;
serde_json::to_vec(&normalized).map_err(|e| format!("sidon canonical: serialize failed: {e}"))
}
pub fn sha256_value(value: &Value) -> Result<String, String> {
let mut hasher = Sha256::new();
hasher.update(CANON_DOMAIN);
hasher.update(canonical_bytes(value)?);
Ok(hex::encode(hasher.finalize()))
}
pub fn digest(value: &Value) -> Result<String, String> {
Ok(format!("sha256:{}", sha256_value(value)?))
}
pub fn content_id(prefix: &str, value: &Value) -> Result<String, String> {
if !prefix.ends_with('_') {
return Err("content-id prefix must end with '_'".to_string());
}
Ok(format!("{prefix}{}", sha256_value(value)?))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn keys_sort_at_every_depth_compact() {
let v = json!({"z": 1, "a": {"y": 2, "b": 3}, "m": [{"q": 4, "p": 5}]});
let bytes = canonical_bytes(&v).unwrap();
assert_eq!(
String::from_utf8(bytes).unwrap(),
r#"{"a":{"b":3,"y":2},"m":[{"p":5,"q":4}],"z":1}"#
);
}
#[test]
fn floats_are_rejected() {
let v = json!({"x": 1.5});
assert!(canonical_bytes(&v).is_err());
}
#[test]
fn integers_pass_through() {
assert_eq!(
String::from_utf8(canonical_bytes(&json!({"k": 6})).unwrap()).unwrap(),
r#"{"k":6}"#
);
}
#[test]
fn nul_in_string_escapes_to_six_chars() {
let v = json!({ "domain": "x\u{0}" });
let s = String::from_utf8(canonical_bytes(&v).unwrap()).unwrap();
assert_eq!(s, "{\"domain\":\"x\\u0000\"}");
}
#[test]
fn content_id_requires_trailing_underscore() {
assert!(content_id("vop", &json!({})).is_err());
assert!(content_id("vop_", &json!({})).is_ok());
}
#[test]
fn non_ascii_is_raw_not_escaped() {
let v = json!({"t": "amyloid-beta-\u{03b2}"});
let s = String::from_utf8(canonical_bytes(&v).unwrap()).unwrap();
assert!(s.contains('\u{03b2}'));
assert!(!s.contains("\\u"));
}
}