vc-shared 0.1.0

Canonical JSON, SHA256 hashing, and Merkle root utilities for Visual Compiler
Documentation
//! Deterministic canonical JSON serialization.
//!
//! This module provides a function to serialize any `Serialize` type
//! into a canonical JSON byte sequence that is deterministic
//! according to the Visual Compiler canonicalization rules.
//!
//! **Important**: This module defines the serialized representation only.
//! It does not validate, normalize, or modify domain semantics.

use serde::Serialize;
use serde_json::{Map, Value};
use std::collections::BTreeMap;

/// Errors that can occur during canonical serialization.
#[derive(Debug, thiserror::Error)]
pub enum CanonicalError {
    #[error("Serialization error")]
    Serialize(#[from] serde_json::Error),
}

/// Serializes a value to canonical JSON bytes.
///
/// This function produces deterministic JSON for values representable
/// by serde_json, according to the Visual Compiler canonicalization rules:
///
/// - Object keys are sorted in lexicographical byte order.
/// - Arrays preserve their original order.
/// - Numeric values are not intentionally transformed.
/// - Unicode is preserved as-is.
///
/// # Examples
/// ```
/// use serde_json::json;
/// use vc_shared::canonical::canonical_json;
///
/// let obj = json!({ "b": 2, "a": 1 });
/// let bytes = canonical_json(&obj).unwrap();
/// assert_eq!(bytes, br#"{"a":1,"b":2}"#.as_slice());
/// ```
pub fn canonical_json<T: Serialize>(value: &T) -> Result<Vec<u8>, CanonicalError> {
    let value = serde_json::to_value(value)?;
    let canonical = canonicalize_value(value);
    let json = serde_json::to_string(&canonical)?;
    Ok(json.into_bytes())
}

/// Recursively transforms a JSON value into canonical form.
///
/// - Objects: keys sorted alphabetically using BTreeMap.
/// - Arrays: order preserved.
fn canonicalize_value(value: Value) -> Value {
    match value {
        Value::Object(map) => {
            let mut sorted = BTreeMap::new();
            for (k, v) in map {
                sorted.insert(k, canonicalize_value(v));
            }
            Value::Object(Map::from_iter(sorted))
        }
        Value::Array(arr) => {
            let normalized = arr.into_iter().map(canonicalize_value).collect();
            Value::Array(normalized)
        }
        _ => value,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn canonical_sorts_object_keys() {
        let obj = json!({ "b": 2, "a": 1 });
        let bytes = canonical_json(&obj).unwrap();
        assert_eq!(bytes, br#"{"a":1,"b":2}"#.as_slice());
    }

    #[test]
    fn canonical_preserves_array_order() {
        let obj = json!({ "items": [3, 1, 2] });
        let bytes = canonical_json(&obj).unwrap();
        assert_eq!(bytes, br#"{"items":[3,1,2]}"#.as_slice());
    }

    #[test]
    fn canonical_nested_objects() {
        let obj = json!({
            "b": 2,
            "a": 1,
            "c": { "z": 26, "y": 25 }
        });
        let bytes = canonical_json(&obj).unwrap();
        assert_eq!(bytes, br#"{"a":1,"b":2,"c":{"y":25,"z":26}}"#.as_slice());
    }

    #[test]
    fn canonical_idempotent() {
        let obj = json!({
            "b": 2,
            "a": 1,
            "c": [3, 1, 2]
        });
        let bytes1 = canonical_json(&obj).unwrap();
        let json_str = String::from_utf8(bytes1.clone()).unwrap();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        let bytes2 = canonical_json(&parsed).unwrap();
        assert_eq!(bytes1, bytes2);
    }

    #[test]
    fn canonical_preserves_float_values() {
        let obj = json!({ "value": 0.123456789 });
        let bytes = canonical_json(&obj).unwrap();
        let parsed: Value = serde_json::from_slice(&bytes).unwrap();
        let value = parsed.get("value").and_then(|v| v.as_f64()).unwrap();
        assert!((value - 0.123456789).abs() < 1e-12);
    }

    #[test]
    fn canonical_preserves_scientific_notation() {
        let obj = json!({ "value": 1e20 });
        let bytes = canonical_json(&obj).unwrap();
        let parsed: Value = serde_json::from_slice(&bytes).unwrap();
        let value = parsed.get("value").and_then(|v| v.as_f64()).unwrap();
        assert_eq!(value, 1e20);
    }

    #[test]
    fn canonical_does_not_normalize_unicode() {
        let composed = json!({ "café": 1 });
        let decomposed = json!({ "cafe\u{0301}": 1 });

        let bytes_composed = canonical_json(&composed).unwrap();
        let bytes_decomposed = canonical_json(&decomposed).unwrap();

        assert_ne!(bytes_composed, bytes_decomposed);
        assert_eq!(canonical_json(&composed).unwrap(), bytes_composed);
        assert_eq!(canonical_json(&decomposed).unwrap(), bytes_decomposed);
    }
}