Skip to main content

ratify_protocol/
canonical.rs

1//! Canonical JSON serialization per Ratify Protocol SPEC §6.
2//!
3//! Every implementation MUST produce byte-identical output for the same
4//! input or signatures will not verify across languages.
5//!
6//! Rules:
7//!   - Object members in lex order (byte order on UTF-8), RECURSIVELY.
8//!   - No whitespace between tokens. No trailing newline.
9//!   - UTF-8 encoding.
10//!   - Integers as shortest decimal.
11//!   - Byte arrays as base64-standard strings with padding.
12//!   - '<', '>', '&' pass through unmodified.
13//!   - U+2028 / U+2029 escape as \\u2028 / \\u2029 (matches Go behavior).
14//!   - Minimum string escaping per RFC 8259.
15
16#[cfg(not(feature = "std"))]
17use alloc::{format, string::String, string::ToString, vec::Vec};
18
19use base64::{engine::general_purpose::STANDARD, Engine as _};
20
21/// Canonical JSON-encode a serde_json::Value.
22///
23/// Available with the `std` feature only (requires `serde_json`).
24#[cfg(feature = "std")]
25pub fn canonical_json(value: &serde_json::Value) -> Vec<u8> {
26    let mut out = String::new();
27    encode_value(value, &mut out);
28    out.into_bytes()
29}
30
31#[cfg(feature = "std")]
32fn encode_value(v: &serde_json::Value, out: &mut String) {
33    use serde_json::Value;
34    match v {
35        Value::Null => out.push_str("null"),
36        Value::Bool(true) => out.push_str("true"),
37        Value::Bool(false) => out.push_str("false"),
38        Value::Number(n) => out.push_str(&encode_number(n)),
39        Value::String(s) => encode_string(s, out),
40        Value::Array(arr) => {
41            out.push('[');
42            for (i, item) in arr.iter().enumerate() {
43                if i > 0 {
44                    out.push(',');
45                }
46                encode_value(item, out);
47            }
48            out.push(']');
49        }
50        Value::Object(obj) => {
51            // Collect keys and sort lex-order.
52            let mut keys: Vec<&String> = obj.keys().collect();
53            keys.sort();
54            out.push('{');
55            let mut first = true;
56            for k in keys {
57                let val = &obj[k];
58                // Skip nulls — matches Go's omitempty for optional fields.
59                if val.is_null() {
60                    continue;
61                }
62                if !first {
63                    out.push(',');
64                }
65                encode_string(k, out);
66                out.push(':');
67                encode_value(val, out);
68                first = false;
69            }
70            out.push('}');
71        }
72    }
73}
74
75// encode_number reproduces the Go / TS / Python policy: integers and
76// integer-valued floats serialize as shortest decimal integer (no "500.0"),
77// non-integer floats serialize via their default textual representation.
78// Without this, serde_json's f64 default emits "500.0" where the other
79// implementations emit "500", breaking cross-SDK byte identicality.
80#[cfg(feature = "std")]
81fn encode_number(n: &serde_json::Number) -> String {
82    if let Some(i) = n.as_i64() {
83        return i.to_string();
84    }
85    if let Some(u) = n.as_u64() {
86        return u.to_string();
87    }
88    if let Some(f) = n.as_f64() {
89        if f.is_finite() && f.fract() == 0.0 && f.abs() < 1e15 {
90            // Whole-number f64 → integer form.
91            return (f as i64).to_string();
92        }
93        return f.to_string();
94    }
95    n.to_string()
96}
97
98fn encode_string(s: &str, out: &mut String) {
99    out.push('"');
100    for c in s.chars() {
101        match c {
102            '"' => out.push_str("\\\""),
103            '\\' => out.push_str("\\\\"),
104            '\u{0008}' => out.push_str("\\b"),
105            '\u{0009}' => out.push_str("\\t"),
106            '\u{000A}' => out.push_str("\\n"),
107            '\u{000C}' => out.push_str("\\f"),
108            '\u{000D}' => out.push_str("\\r"),
109            '\u{2028}' => out.push_str("\\u2028"),
110            '\u{2029}' => out.push_str("\\u2029"),
111            c if (c as u32) < 0x20 => {
112                out.push_str(&format!("\\u{:04x}", c as u32));
113            }
114            // Everything else passes through unmodified (NO HTML escape).
115            c => out.push(c),
116        }
117    }
118    out.push('"');
119}
120
121/// Standard base64 encode with padding.
122pub fn base64_std_encode(data: &[u8]) -> String {
123    STANDARD.encode(data)
124}
125
126/// Standard base64 decode.
127pub fn base64_std_decode(s: &str) -> Result<Vec<u8>, base64::DecodeError> {
128    STANDARD.decode(s)
129}
130
131/// Lowercase hex.
132pub fn hex_encode(data: &[u8]) -> String {
133    hex::encode(data)
134}
135
136/// Lower- or upper-case hex.
137pub fn hex_decode(s: &str) -> Result<Vec<u8>, hex::FromHexError> {
138    hex::decode(s)
139}
140
141// ---------------------------------------------------------------------------
142// Low-level canonical-JSON helpers (no serde_json::Value intermediary)
143//
144// These write directly into a &mut String and are the building blocks for
145// the no_std signing-bytes functions in crypto.rs and receipts.rs.
146// ---------------------------------------------------------------------------
147
148/// Write a canonical-JSON string (with escaping) into `out`.
149pub fn encode_str(s: &str, out: &mut String) {
150    encode_string(s, out);
151}
152
153/// Write a canonical-JSON i64 (shortest decimal) into `out`.
154pub fn encode_i64(n: i64, out: &mut String) {
155    out.push_str(&n.to_string());
156}
157
158/// Write a canonical-JSON i32 into `out`.
159pub fn encode_i32(n: i32, out: &mut String) {
160    out.push_str(&n.to_string());
161}
162
163/// Write a canonical-JSON f64 following the Ratify integer-valued rule:
164/// whole-number f64s emit as shortest decimal integer; others as-is.
165pub fn encode_f64(n: f64, out: &mut String) {
166    if n.is_finite() && n.fract() == 0.0 && n.abs() < 1e15 {
167        out.push_str(&(n as i64).to_string());
168    } else {
169        out.push_str(&n.to_string());
170    }
171}
172
173/// Write a canonical-JSON bool into `out`.
174pub fn encode_bool(b: bool, out: &mut String) {
175    out.push_str(if b { "true" } else { "false" });
176}
177
178/// Write a base64-standard-encoded byte slice as a canonical-JSON string.
179pub fn encode_bytes_b64(b: &[u8], out: &mut String) {
180    let s = base64_std_encode(b);
181    encode_string(&s, out);
182}
183
184/// Write a canonical-JSON array of strings into `out`.
185pub fn encode_str_array(arr: &[String], out: &mut String) {
186    out.push('[');
187    for (i, s) in arr.iter().enumerate() {
188        if i > 0 {
189            out.push(',');
190        }
191        encode_string(s, out);
192    }
193    out.push(']');
194}
195
196/// Write a canonical-JSON array of [f64; 2] pairs (geo polygon points).
197pub fn encode_points_array(pts: &[[f64; 2]], out: &mut String) {
198    out.push('[');
199    for (i, pt) in pts.iter().enumerate() {
200        if i > 0 {
201            out.push(',');
202        }
203        out.push('[');
204        encode_f64(pt[0], out);
205        out.push(',');
206        encode_f64(pt[1], out);
207        out.push(']');
208    }
209    out.push(']');
210}
211
212/// Write a canonical Constraint object into `out`, matching the per-kind
213/// shape emitted by Constraint's Serialize impl (alphabetical keys).
214pub fn encode_constraint(c: &crate::types::Constraint, out: &mut String) {
215    match c.kind.as_str() {
216        "geo_circle" => {
217            // keys: lat, lon, radius_m, type
218            out.push('{');
219            out.push_str("\"lat\":");  encode_f64(c.lat, out);
220            out.push_str(",\"lon\":");  encode_f64(c.lon, out);
221            out.push_str(",\"radius_m\":");  encode_f64(c.radius_m, out);
222            out.push_str(",\"type\":");  encode_string(&c.kind, out);
223            out.push('}');
224        }
225        "geo_polygon" => {
226            // keys: points, type
227            out.push('{');
228            out.push_str("\"points\":");  encode_points_array(&c.points, out);
229            out.push_str(",\"type\":");  encode_string(&c.kind, out);
230            out.push('}');
231        }
232        "geo_bbox" => {
233            // base keys: max_lat, max_lon, min_lat, min_lon, type
234            // optional altitude keys (alphabetical insert): max_alt_m < max_lat, min_alt_m < min_lat
235            out.push('{');
236            let has_alt = c.min_alt_m != 0.0 || c.max_alt_m != 0.0;
237            if has_alt {
238                out.push_str("\"max_alt_m\":");  encode_f64(c.max_alt_m, out);
239                out.push(',');
240            }
241            out.push_str("\"max_lat\":");  encode_f64(c.max_lat, out);
242            out.push_str(",\"max_lon\":");  encode_f64(c.max_lon, out);
243            if has_alt {
244                out.push_str(",\"min_alt_m\":");  encode_f64(c.min_alt_m, out);
245            }
246            out.push_str(",\"min_lat\":");  encode_f64(c.min_lat, out);
247            out.push_str(",\"min_lon\":");  encode_f64(c.min_lon, out);
248            out.push_str(",\"type\":");  encode_string(&c.kind, out);
249            out.push('}');
250        }
251        "time_window" => {
252            // keys: end, start, type, tz
253            out.push('{');
254            out.push_str("\"end\":");  encode_string(&c.end, out);
255            out.push_str(",\"start\":");  encode_string(&c.start, out);
256            out.push_str(",\"type\":");  encode_string(&c.kind, out);
257            out.push_str(",\"tz\":");  encode_string(&c.tz, out);
258            out.push('}');
259        }
260        "max_speed_mps" => {
261            // keys: max_mps, type
262            out.push('{');
263            out.push_str("\"max_mps\":");  encode_f64(c.max_mps, out);
264            out.push_str(",\"type\":");  encode_string(&c.kind, out);
265            out.push('}');
266        }
267        "max_amount" => {
268            // keys: currency, max_amount, type
269            out.push('{');
270            out.push_str("\"currency\":");  encode_string(&c.currency, out);
271            out.push_str(",\"max_amount\":");  encode_f64(c.max_amount, out);
272            out.push_str(",\"type\":");  encode_string(&c.kind, out);
273            out.push('}');
274        }
275        "max_rate" => {
276            // keys: count, type, window_s
277            out.push('{');
278            out.push_str("\"count\":");  encode_i64(c.count, out);
279            out.push_str(",\"type\":");  encode_string(&c.kind, out);
280            out.push_str(",\"window_s\":");  encode_i64(c.window_s, out);
281            out.push('}');
282        }
283        "resource_path" => {
284            // keys: path_prefix (only when present), resource_id, type.
285            out.push('{');
286            if let Some(prefix) = &c.path_prefix {
287                out.push_str("\"path_prefix\":");  encode_string(prefix, out);
288                out.push(',');
289            }
290            out.push_str("\"resource_id\":");  encode_string(&c.resource_id, out);
291            out.push_str(",\"type\":");  encode_string(&c.kind, out);
292            out.push('}');
293        }
294        // Extension kind: emit params (when present) plus the type tag,
295        // matching the Serialize impl. "params" sorts before "type".
296        _ => {
297            out.push('{');
298            if let Some(params) = &c.params {
299                out.push_str("\"params\":");  encode_params_object(params, out);
300                out.push(',');
301            }
302            out.push_str("\"type\":");  encode_string(&c.kind, out);
303            out.push('}');
304        }
305    }
306}
307
308/// Write a canonical `params` object (SPEC §5.7.1). Keys are held in a
309/// `BTreeMap` so iteration is byte-lex order (RFC 8785) with no extra sort.
310pub fn encode_params_object(
311    map: &alloc::collections::BTreeMap<String, crate::types::ParamsValue>,
312    out: &mut String,
313) {
314    out.push('{');
315    for (i, (k, v)) in map.iter().enumerate() {
316        if i > 0 {
317            out.push(',');
318        }
319        encode_string(k, out);
320        out.push(':');
321        encode_params_value(v, out);
322    }
323    out.push('}');
324}
325
326/// Write a canonical `params` value under the restricted value model.
327pub fn encode_params_value(v: &crate::types::ParamsValue, out: &mut String) {
328    use crate::types::ParamsValue;
329    match v {
330        ParamsValue::Null => out.push_str("null"),
331        ParamsValue::Bool(b) => encode_bool(*b, out),
332        ParamsValue::Int(n) => encode_i64(*n, out),
333        ParamsValue::Str(s) => encode_string(s, out),
334        ParamsValue::Array(items) => {
335            out.push('[');
336            for (i, item) in items.iter().enumerate() {
337                if i > 0 {
338                    out.push(',');
339                }
340                encode_params_value(item, out);
341            }
342            out.push(']');
343        }
344        ParamsValue::Object(map) => encode_params_object(map, out),
345    }
346}
347
348/// Write a canonical-JSON array of Constraint objects.
349pub fn encode_constraints(cs: &[crate::types::Constraint], out: &mut String) {
350    out.push('[');
351    for (i, c) in cs.iter().enumerate() {
352        if i > 0 {
353            out.push(',');
354        }
355        encode_constraint(c, out);
356    }
357    out.push(']');
358}
359
360/// Write a canonical HybridPublicKey object: `{"ed25519":"...","ml_dsa_65":"..."}`.
361/// Keys are already in lex order: "ed25519" < "ml_dsa_65".
362pub fn encode_hybrid_pub_key(pk: &crate::types::HybridPublicKey, out: &mut String) {
363    out.push('{');
364    out.push_str("\"ed25519\":");  encode_bytes_b64(&pk.ed25519, out);
365    out.push_str(",\"ml_dsa_65\":");  encode_bytes_b64(&pk.ml_dsa_65, out);
366    out.push('}');
367}
368
369/// Write a canonical HybridSignature object: `{"ed25519":"...","ml_dsa_65":"..."}`.
370pub fn encode_hybrid_sig(sig: &crate::types::HybridSignature, out: &mut String) {
371    out.push('{');
372    out.push_str("\"ed25519\":");  encode_bytes_b64(&sig.ed25519, out);
373    out.push_str(",\"ml_dsa_65\":");  encode_bytes_b64(&sig.ml_dsa_65, out);
374    out.push('}');
375}
376
377/// serde helper to (de)serialize Vec<u8> as base64-standard strings.
378pub mod base64_bytes {
379    #[cfg(not(feature = "std"))]
380    use alloc::{format, string::String, vec::Vec};
381    use super::{base64_std_decode, base64_std_encode};
382    use serde::{de::Error, Deserialize, Deserializer, Serializer};
383
384    pub fn serialize<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
385    where
386        S: Serializer,
387    {
388        serializer.serialize_str(&base64_std_encode(bytes))
389    }
390
391    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
392    where
393        D: Deserializer<'de>,
394    {
395        let s = String::deserialize(deserializer)?;
396        base64_std_decode(&s).map_err(|e| D::Error::custom(format!("base64 decode: {e}")))
397    }
398}
399
400/// Serde guards for JSON integer wire fields (SPEC §6.2), applied with
401/// `#[serde(deserialize_with = ..., serialize_with = ...)]` on the int64
402/// wire fields.
403///
404/// The interoperable integer domain is the IEEE-754 safe-integer range
405/// [-(2^53-1), 2^53-1]: binary signable representations use 64-bit fields,
406/// but a JSON integer outside that range does not survive a
407/// double-precision JSON parser, so strict wire acceptance rejects it on
408/// the way in and guarded wire serialization refuses to emit it on the
409/// way out. Note the boundary being guarded: callers can still construct
410/// structs with out-of-domain values directly, and the infallible
411/// sign-byte helpers keep their API — the guarantee is that such values
412/// never become conforming transport documents, not that they cannot
413/// exist in memory.
414pub mod wire_int {
415    use serde::{de::Error as DeError, ser::Error as SerError, Deserialize, Deserializer, Serializer};
416
417    /// Largest integer exactly representable in an IEEE-754 double: 2^53-1.
418    pub const MAX_SAFE_INTEGER: i64 = (1 << 53) - 1;
419
420    /// True iff `v` lies in the interoperable JSON integer domain.
421    pub fn in_domain(v: i64) -> bool {
422        (-MAX_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(&v)
423    }
424
425    pub fn deserialize<'de, D>(deserializer: D) -> Result<i64, D::Error>
426    where
427        D: Deserializer<'de>,
428    {
429        let v = i64::deserialize(deserializer)?;
430        if !in_domain(v) {
431            return Err(D::Error::custom(
432                "integer outside the safe-integer range [-(2^53-1), 2^53-1]",
433            ));
434        }
435        Ok(v)
436    }
437
438    /// Encoder side of the same rule: a serializer must never emit an
439    /// integer that strict wire decoders reject.
440    pub fn serialize<S>(v: &i64, serializer: S) -> Result<S::Ok, S::Error>
441    where
442        S: Serializer,
443    {
444        if !in_domain(*v) {
445            return Err(S::Error::custom(
446                "integer outside the safe-integer range [-(2^53-1), 2^53-1]",
447            ));
448        }
449        serializer.serialize_i64(*v)
450    }
451}