Skip to main content

vc_shared/
canonical.rs

1//! Deterministic canonical JSON serialization.
2//!
3//! This module provides a function to serialize any `Serialize` type
4//! into a canonical JSON byte sequence that is deterministic
5//! according to the Visual Compiler canonicalization rules.
6//!
7//! **Important**: This module defines the serialized representation only.
8//! It does not validate, normalize, or modify domain semantics.
9
10use serde::Serialize;
11use serde_json::{Map, Value};
12use std::collections::BTreeMap;
13
14/// Errors that can occur during canonical serialization.
15#[derive(Debug, thiserror::Error)]
16pub enum CanonicalError {
17    #[error("Serialization error")]
18    Serialize(#[from] serde_json::Error),
19}
20
21/// Serializes a value to canonical JSON bytes.
22///
23/// This function produces deterministic JSON for values representable
24/// by serde_json, according to the Visual Compiler canonicalization rules:
25///
26/// - Object keys are sorted in lexicographical byte order.
27/// - Arrays preserve their original order.
28/// - Numeric values are not intentionally transformed.
29/// - Unicode is preserved as-is.
30///
31/// # Examples
32/// ```
33/// use serde_json::json;
34/// use vc_shared::canonical::canonical_json;
35///
36/// let obj = json!({ "b": 2, "a": 1 });
37/// let bytes = canonical_json(&obj).unwrap();
38/// assert_eq!(bytes, br#"{"a":1,"b":2}"#.as_slice());
39/// ```
40pub fn canonical_json<T: Serialize>(value: &T) -> Result<Vec<u8>, CanonicalError> {
41    let value = serde_json::to_value(value)?;
42    let canonical = canonicalize_value(value);
43    let json = serde_json::to_string(&canonical)?;
44    Ok(json.into_bytes())
45}
46
47/// Recursively transforms a JSON value into canonical form.
48///
49/// - Objects: keys sorted alphabetically using BTreeMap.
50/// - Arrays: order preserved.
51fn canonicalize_value(value: Value) -> Value {
52    match value {
53        Value::Object(map) => {
54            let mut sorted = BTreeMap::new();
55            for (k, v) in map {
56                sorted.insert(k, canonicalize_value(v));
57            }
58            Value::Object(Map::from_iter(sorted))
59        }
60        Value::Array(arr) => {
61            let normalized = arr.into_iter().map(canonicalize_value).collect();
62            Value::Array(normalized)
63        }
64        _ => value,
65    }
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71    use serde_json::json;
72
73    #[test]
74    fn canonical_sorts_object_keys() {
75        let obj = json!({ "b": 2, "a": 1 });
76        let bytes = canonical_json(&obj).unwrap();
77        assert_eq!(bytes, br#"{"a":1,"b":2}"#.as_slice());
78    }
79
80    #[test]
81    fn canonical_preserves_array_order() {
82        let obj = json!({ "items": [3, 1, 2] });
83        let bytes = canonical_json(&obj).unwrap();
84        assert_eq!(bytes, br#"{"items":[3,1,2]}"#.as_slice());
85    }
86
87    #[test]
88    fn canonical_nested_objects() {
89        let obj = json!({
90            "b": 2,
91            "a": 1,
92            "c": { "z": 26, "y": 25 }
93        });
94        let bytes = canonical_json(&obj).unwrap();
95        assert_eq!(bytes, br#"{"a":1,"b":2,"c":{"y":25,"z":26}}"#.as_slice());
96    }
97
98    #[test]
99    fn canonical_idempotent() {
100        let obj = json!({
101            "b": 2,
102            "a": 1,
103            "c": [3, 1, 2]
104        });
105        let bytes1 = canonical_json(&obj).unwrap();
106        let json_str = String::from_utf8(bytes1.clone()).unwrap();
107        let parsed: Value = serde_json::from_str(&json_str).unwrap();
108        let bytes2 = canonical_json(&parsed).unwrap();
109        assert_eq!(bytes1, bytes2);
110    }
111
112    #[test]
113    fn canonical_preserves_float_values() {
114        let obj = json!({ "value": 0.123456789 });
115        let bytes = canonical_json(&obj).unwrap();
116        let parsed: Value = serde_json::from_slice(&bytes).unwrap();
117        let value = parsed.get("value").and_then(|v| v.as_f64()).unwrap();
118        assert!((value - 0.123456789).abs() < 1e-12);
119    }
120
121    #[test]
122    fn canonical_preserves_scientific_notation() {
123        let obj = json!({ "value": 1e20 });
124        let bytes = canonical_json(&obj).unwrap();
125        let parsed: Value = serde_json::from_slice(&bytes).unwrap();
126        let value = parsed.get("value").and_then(|v| v.as_f64()).unwrap();
127        assert_eq!(value, 1e20);
128    }
129
130    #[test]
131    fn canonical_does_not_normalize_unicode() {
132        let composed = json!({ "café": 1 });
133        let decomposed = json!({ "cafe\u{0301}": 1 });
134
135        let bytes_composed = canonical_json(&composed).unwrap();
136        let bytes_decomposed = canonical_json(&decomposed).unwrap();
137
138        assert_ne!(bytes_composed, bytes_decomposed);
139        assert_eq!(canonical_json(&composed).unwrap(), bytes_composed);
140        assert_eq!(canonical_json(&decomposed).unwrap(), bytes_decomposed);
141    }
142}