Skip to main content

phytrace_sdk/core/
canonical.rs

1//! Canonical JSON and the event signing payload.
2//!
3//! A provenance signature covers [`signing_payload`]: the event exactly as it
4//! is sent, with `provenance.signature` removed (and the block itself if
5//! nothing else is in it) and `null` object members dropped, rendered as canonical JSON.  Signing the transmitted JSON (rather
6//! than a hand-picked field list) means every field is covered, including
7//! the rest of the provenance block (key id, algorithm, signing time, device
8//! attestation), and any receiver can verify without knowing this SDK's
9//! types.
10//!
11//! The canonical form is byte-identical to Python's
12//! `json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True)`
13//! and to PhyCloud's `canonical_json`, so the Python SDK, the Rust SDK and
14//! PhyCloud all derive the same bytes from the same JSON.  The shared test
15//! vectors in `PhyTrace/test-vectors/provenance-signing.json` pin this down.
16
17use serde_json::{Map, Value};
18
19use crate::error::{PhyTraceError, PhyTraceResult};
20use crate::models::event::UdmEvent;
21
22/// The text an event's provenance signature is computed over.
23pub fn signing_payload(event: &UdmEvent) -> PhyTraceResult<String> {
24    let value = serde_json::to_value(event)
25        .map_err(|e| PhyTraceError::Serialization(format!("serialise event for signing: {e}")))?;
26    Ok(signing_payload_from_value(&value))
27}
28
29/// [`signing_payload`] for an event already in JSON form, e.g. as received
30/// over the wire.
31pub fn signing_payload_from_value(event: &Value) -> String {
32    let mut value = strip_nulls(event);
33    if let Value::Object(map) = &mut value {
34        if let Some(Value::Object(provenance)) = map.get_mut("provenance") {
35            provenance.remove("signature");
36            if provenance.is_empty() {
37                map.remove("provenance");
38            }
39        }
40    }
41    canonical_json(&value)
42}
43
44/// The payload a batch-signed event's Merkle leaf is computed over:
45/// [`signing_payload_from_value`] with `provenance.batch` also removed
46/// (issue #392).
47pub fn leaf_payload_from_value(event: &Value) -> String {
48    let mut value = event.clone();
49    if let Some(Value::Object(provenance)) = value.get_mut("provenance") {
50        provenance.remove("batch");
51    }
52    signing_payload_from_value(&value)
53}
54
55/// Recursively drop object members whose value is `null`.  Array elements
56/// are kept as-is, matching PhyCloud's ingest normalisation.
57pub fn strip_nulls(value: &Value) -> Value {
58    match value {
59        Value::Object(map) => Value::Object(
60            map.iter()
61                .filter(|(_, v)| !v.is_null())
62                .map(|(k, v)| (k.clone(), strip_nulls(v)))
63                .collect(),
64        ),
65        Value::Array(items) => Value::Array(items.iter().map(strip_nulls).collect()),
66        other => other.clone(),
67    }
68}
69
70/// Render `value` as canonical JSON: keys sorted, no whitespace, non-ASCII
71/// escaped as `\uXXXX`.
72pub fn canonical_json(value: &Value) -> String {
73    let mut out = String::new();
74    write_value(&mut out, value);
75    out
76}
77
78fn write_value(out: &mut String, v: &Value) {
79    match v {
80        Value::Null => out.push_str("null"),
81        Value::Bool(true) => out.push_str("true"),
82        Value::Bool(false) => out.push_str("false"),
83        Value::Number(n) => match n.as_f64() {
84            Some(f) if n.is_f64() => out.push_str(&python_float_repr(f)),
85            _ => out.push_str(&n.to_string()),
86        },
87        Value::String(s) => write_string(out, s),
88        Value::Array(arr) => {
89            out.push('[');
90            for (i, item) in arr.iter().enumerate() {
91                if i > 0 {
92                    out.push(',');
93                }
94                write_value(out, item);
95            }
96            out.push(']');
97        }
98        Value::Object(map) => write_object(out, map),
99    }
100}
101
102/// Format a finite `f64` exactly like Python's `repr(float)`, which is what
103/// `json.dumps` emits.
104///
105/// Both use the shortest round-trip digits (ties to even); they differ in
106/// layout.  Python uses fixed notation for decimal exponents -4..=15 (always
107/// with a `.0` or fraction) and otherwise `d.ddde±XX` with at least two
108/// exponent digits, e.g. `1e-07`, `1e+16`, `1000000000000000.0`.
109fn python_float_repr(f: f64) -> String {
110    if f == 0.0 {
111        return if f.is_sign_negative() { "-0.0" } else { "0.0" }.to_string();
112    }
113    // Python's repr: the first correctly rounded precision that round-trips.
114    // Rust's `{:e}` is also shortest, but breaks exact ties upward where
115    // Python rounds half to even (e.g. float32 values widened to f64:
116    // 0.0215625762939453125 is `0.021562576293945312` in Python).
117    let sci = (0..17)
118        .map(|p| format!("{:.*e}", p, f.abs()))
119        .find(|s| s.parse::<f64>().ok() == Some(f.abs()))
120        .unwrap_or_else(|| format!("{:.16e}", f.abs()));
121    let (mantissa, exp) = sci.split_once('e').unwrap_or((sci.as_str(), "0"));
122    let exp: i32 = exp.parse().unwrap_or(0);
123    let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
124
125    let body = if (-4..16).contains(&exp) {
126        // Value is 0.DIGITS x 10^(exp + 1); `point` is where the decimal
127        // point goes, which lies in -3..=16 here.
128        let point = exp + 1;
129        match usize::try_from(point) {
130            Err(_) | Ok(0) => {
131                let zeros = usize::try_from(point.unsigned_abs()).unwrap_or(0);
132                format!("0.{}{digits}", "0".repeat(zeros))
133            }
134            Ok(p) if p >= digits.len() => {
135                format!("{digits}{}.0", "0".repeat(p - digits.len()))
136            }
137            Ok(p) => {
138                let (int, frac) = digits.split_at(p);
139                format!("{int}.{frac}")
140            }
141        }
142    } else {
143        let (first, rest) = digits.split_at(1.min(digits.len()));
144        let mantissa = if rest.is_empty() {
145            first.to_string()
146        } else {
147            format!("{first}.{rest}")
148        };
149        let sign = if exp < 0 { '-' } else { '+' };
150        format!("{mantissa}e{sign}{:02}", exp.unsigned_abs())
151    };
152    if f.is_sign_negative() {
153        format!("-{body}")
154    } else {
155        body
156    }
157}
158
159fn write_object(out: &mut String, map: &Map<String, Value>) {
160    let mut entries: Vec<(&String, &Value)> = map.iter().collect();
161    entries.sort_by(|a, b| a.0.cmp(b.0));
162    out.push('{');
163    for (i, (k, v)) in entries.into_iter().enumerate() {
164        if i > 0 {
165            out.push(',');
166        }
167        write_string(out, k);
168        out.push(':');
169        write_value(out, v);
170    }
171    out.push('}');
172}
173
174fn write_string(out: &mut String, s: &str) {
175    out.push('"');
176    for c in s.chars() {
177        match c {
178            '"' => out.push_str("\\\""),
179            '\\' => out.push_str("\\\\"),
180            '\u{0008}' => out.push_str("\\b"),
181            '\u{000c}' => out.push_str("\\f"),
182            '\n' => out.push_str("\\n"),
183            '\r' => out.push_str("\\r"),
184            '\t' => out.push_str("\\t"),
185            c if (' '..'\u{7f}').contains(&c) => out.push(c),
186            // Control characters, DEL and non-ASCII: `\uXXXX`, as a UTF-16
187            // surrogate pair above U+FFFF (Python's `ensure_ascii=True`).
188            c => {
189                let mut buf = [0u16; 2];
190                for unit in c.encode_utf16(&mut buf).iter() {
191                    out.push_str("\\u");
192                    push_hex(out, u32::from(*unit), 4);
193                }
194            }
195        }
196    }
197    out.push('"');
198}
199
200/// Append the low `width` hex digits of `value`, lowercase, zero-padded.
201pub(crate) fn push_hex(out: &mut String, value: u32, width: u32) {
202    for i in (0..width).rev() {
203        let nibble = (value >> (i * 4)) & 0xf;
204        out.push(char::from_digit(nibble, 16).unwrap_or('0'));
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211    use serde_json::json;
212
213    #[test]
214    fn canonical_json_sorts_keys_and_escapes_like_python() {
215        let v = json!({"b": 1, "a": [true, null, "é\n😀"], "c": {"z": 0.5, "y": "\u{7f}"}});
216        assert_eq!(
217            canonical_json(&v),
218            r#"{"a":[true,null,"\u00e9\n\ud83d\ude00"],"b":1,"c":{"y":"\u007f","z":0.5}}"#
219        );
220    }
221
222    #[test]
223    fn floats_match_python_repr() {
224        // Expected values are Python's repr() of the same floats.
225        for (f, expected) in [
226            (0.87, "0.87"),
227            (100.0, "100.0"),
228            (-3.25, "-3.25"),
229            (0.0001, "0.0001"),
230            (0.00001, "1e-05"),
231            (1.5e-7, "1.5e-07"),
232            (1e15, "1000000000000000.0"),
233            (1e16, "1e+16"),
234            (1.2345e20, "1.2345e+20"),
235            (123456789.125, "123456789.125"),
236            // An exact 17-digit tie (a float32 widened to f64): half to even.
237            (-0.021562576293945312, "-0.021562576293945312"),
238            (-0.0, "-0.0"),
239            (5e-324, "5e-324"),
240            (1.7976931348623157e308, "1.7976931348623157e+308"),
241        ] {
242            assert_eq!(python_float_repr(f), expected, "{f:e}");
243        }
244    }
245
246    #[test]
247    fn signing_payload_drops_signature_and_null_members() {
248        let v = json!({
249            "event_id": "e1",
250            "sent_at": null,
251            "provenance": {"signature": "abc", "key_id": "k1", "signed_fields": null},
252            "extensions": {"keep": [null, 1], "drop": null}
253        });
254        assert_eq!(
255            signing_payload_from_value(&v),
256            r#"{"event_id":"e1","extensions":{"keep":[null,1]},"provenance":{"key_id":"k1"}}"#
257        );
258        // A block holding only the signature signs like no block at all.
259        let v = json!({"event_id": "e1", "provenance": {"signature": "abc"}});
260        assert_eq!(signing_payload_from_value(&v), r#"{"event_id":"e1"}"#);
261    }
262}