Skip to main content

gitiverse_git/
canonical.rs

1use serde::Serialize;
2use serde_json::Value;
3use sha2::{Digest, Sha256};
4use thiserror::Error;
5use wire_mesh_wire::minicbor::{Decode, Encode};
6use wire_mesh_wire::{DecodeError, decode_exact, to_vec};
7
8/// Failure returned by canonical serialisation helpers.
9#[derive(Debug, Error)]
10pub enum CanonicalError {
11    #[error("JSON serialisation failed: {0}")]
12    Json(#[from] serde_json::Error),
13    #[error("CBOR decode failed: {0}")]
14    Cbor(#[from] DecodeError),
15}
16
17fn canonicalise_json_value(value: Value) -> Value {
18    match value {
19        Value::Array(items) => {
20            Value::Array(items.into_iter().map(canonicalise_json_value).collect())
21        }
22        Value::Object(map) => {
23            let mut entries: Vec<(String, Value)> = map
24                .into_iter()
25                .map(|(k, v)| (k, canonicalise_json_value(v)))
26                .collect();
27            entries.sort_by(|(a, _), (b, _)| a.cmp(b));
28            let mut sorted = serde_json::Map::new();
29            for (k, v) in entries {
30                sorted.insert(k, v);
31            }
32            Value::Object(sorted)
33        }
34        other => other,
35    }
36}
37
38/// Serialises any `Serialize` value to deterministic compact JSON with lexicographically sorted object keys at every nesting depth.
39pub fn canonical_json_bytes<T: Serialize>(value: &T) -> Result<Vec<u8>, CanonicalError> {
40    let json_val = serde_json::to_value(value)?;
41    let canonical = canonicalise_json_value(json_val);
42    Ok(serde_json::to_vec(&canonical)?)
43}
44
45/// Serialises any `minicbor::Encode<()>` value into canonical CBOR bytes.
46#[must_use]
47pub fn to_canonical_cbor<T: Encode<()>>(value: &T) -> Vec<u8> {
48    to_vec(value)
49}
50
51/// Strictly decodes a `minicbor::Decode<()>` value from complete canonical CBOR bytes without trailing bytes.
52pub fn from_canonical_cbor<'b, T: Decode<'b, ()>>(bytes: &'b [u8]) -> Result<T, CanonicalError> {
53    Ok(decode_exact(bytes)?)
54}
55
56/// Computes the raw 32-byte SHA-256 digest of `bytes`.
57#[must_use]
58pub fn sha256_digest(bytes: &[u8]) -> [u8; 32] {
59    Sha256::digest(bytes).into()
60}
61
62/// Computes the 64-character lowercase hex SHA-256 digest of `bytes`.
63#[must_use]
64pub fn sha256_hex(bytes: &[u8]) -> String {
65    hex::encode(sha256_digest(bytes))
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71    use std::collections::HashMap;
72
73    #[test]
74    fn canonical_json_produces_identical_bytes_regardless_of_map_insertion_order() {
75        let mut m1 = HashMap::new();
76        m1.insert("z", 1);
77        m1.insert("a", 2);
78        m1.insert("m", 3);
79
80        let mut m2 = HashMap::new();
81        m2.insert("m", 3);
82        m2.insert("a", 2);
83        m2.insert("z", 1);
84
85        let b1 = canonical_json_bytes(&m1).unwrap();
86        let b2 = canonical_json_bytes(&m2).unwrap();
87        assert_eq!(b1, b2);
88        assert_eq!(String::from_utf8(b1).unwrap(), r#"{"a":2,"m":3,"z":1}"#);
89    }
90
91    #[test]
92    fn sha256_helpers_match_expected_digest() {
93        let digest = sha256_digest(b"gitiverse");
94        assert_eq!(hex::encode(digest), sha256_hex(b"gitiverse"));
95        assert_eq!(sha256_hex(b"gitiverse").len(), 64);
96    }
97}