vouch-core 4.2.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
Documentation
//! JSON Canonicalization Scheme (JCS) per RFC 8785.
//!
//! Byte-exact port of the TypeScript SDK `canonicalize()`
//! (packages/sdk-ts/src/jcs.ts) and `vouch/jcs.py`. Rules:
//!   - object members are sorted by UTF-16 code-unit order (matching ECMAScript
//!     Array.prototype.sort, which the reference SDK uses; for BMP code points
//!     this equals the code-point order RFC 8785 3.2 requires),
//!   - strings are escaped per JSON.stringify,
//!   - numbers use ECMAScript ToString, and -0 normalizes to 0.
//!
//! Cross-implementation interop is REQUIRED: this MUST produce byte-identical
//! output to the TypeScript and Python implementations for the same input.

#[allow(unused_imports)]
use crate::prelude::*;

use core::cmp::Ordering;
use serde_json::Value;

/// Canonicalize a JSON value to its RFC 8785 UTF-8 byte sequence (for hashing
/// and signing).
pub fn canonicalize(value: &Value) -> Vec<u8> {
    canonicalize_to_string(value).into_bytes()
}

/// Canonicalize to a string (useful for debugging and vector comparison).
pub fn canonicalize_to_string(value: &Value) -> String {
    let mut out = String::new();
    serialize(value, &mut out);
    out
}

/// Writes `value` in canonical form. It walks the value with its own stack
/// instead of recursing, so the call stack it needs does not grow with how
/// deeply the value nests (on a microcontroller that matters).
fn serialize(value: &Value, out: &mut String) {
    enum Frame<'a> {
        Array(core::slice::Iter<'a, Value>, bool),
        Object(&'a serde_json::Map<String, Value>, Vec<&'a String>, usize),
    }
    let mut stack: Vec<Frame<'_>> = Vec::new();
    let mut next: Option<&Value> = Some(value);
    loop {
        if let Some(v) = next.take() {
            match v {
                Value::Null => out.push_str("null"),
                Value::Bool(true) => out.push_str("true"),
                Value::Bool(false) => out.push_str("false"),
                Value::Number(n) => out.push_str(&format_number(n)),
                Value::String(s) => escape_string(s, out),
                Value::Array(items) => {
                    out.push('[');
                    stack.push(Frame::Array(items.iter(), true));
                }
                Value::Object(map) => {
                    let mut keys: Vec<&String> = map.keys().collect();
                    keys.sort_by(|a, b| utf16_cmp(a, b));
                    out.push('{');
                    stack.push(Frame::Object(map, keys, 0));
                }
            }
        }
        let Some(top) = stack.last_mut() else {
            break;
        };
        match top {
            Frame::Array(items, first) => match items.next() {
                Some(item) => {
                    if !*first {
                        out.push(',');
                    }
                    *first = false;
                    next = Some(item);
                }
                None => {
                    out.push(']');
                    stack.pop();
                }
            },
            Frame::Object(map, keys, i) => {
                if *i < keys.len() {
                    if *i > 0 {
                        out.push(',');
                    }
                    let k = keys[*i];
                    escape_string(k, out);
                    out.push(':');
                    next = Some(&map[k]);
                    *i += 1;
                } else {
                    out.push('}');
                    stack.pop();
                }
            }
        }
    }
}

/// Compare two strings by their UTF-16 code-unit sequence (ECMAScript string
/// ordering, used by the reference SDK's `Object.keys(obj).sort()`).
fn utf16_cmp(a: &str, b: &str) -> Ordering {
    a.encode_utf16().cmp(b.encode_utf16())
}

/// JSON string escaping matching ECMAScript JSON.stringify. serde_json escapes
/// identically for the relevant cases (quote, backslash, control chars as
/// \b \t \n \f \r or \u00xx; non-ASCII emitted raw as UTF-8), so it is reused
/// as a single source of truth.
fn escape_string(s: &str, out: &mut String) {
    let encoded = serde_json::to_string(s).expect("a string is always serializable");
    out.push_str(&encoded);
}

/// Number formatting per RFC 8785 3.2.2.5 (ECMAScript ToString), matching
/// jcs.ts `formatNumber`.
fn format_number(n: &serde_json::Number) -> String {
    if let Some(i) = n.as_i64() {
        return i.to_string();
    }
    if let Some(u) = n.as_u64() {
        return u.to_string();
    }
    let f = n.as_f64().expect("a serde_json number is i64, u64, or f64");
    if f == 0.0 {
        // Normalizes both 0.0 and -0.0 to "0" (RFC 8785).
        return "0".to_string();
    }
    // ECMAScript Number.prototype.toString via ryu-js. This matches JavaScript
    // exactly, including the exponential thresholds and format ("1e+21",
    // "1e-7"), so the canonical form is byte-identical to the TypeScript SDK and
    // to a conformant Python implementation for any finite number.
    let mut buf = ryu_js::Buffer::new();
    buf.format(f).to_string()
}

/// The deepest nesting [`parse_deep`] reads: a value the reference can
/// canonicalize (up to 500 levels) fits, inside a request, with room.
pub const MAX_DEEP_NESTING: usize = 512;

/// Read JSON text that may nest deeper than the reader's default of 128
/// levels, up to [`MAX_DEEP_NESTING`] (checked by a scan before parsing, so
/// the parser's stack stays bounded). For entries whose values the reference
/// canonicalizes whatever their depth: proofs, signing inputs, chains of
/// trust credentials.
///
/// The `no_std` build has no such allowance: it refuses text nested past
/// [`crate::nesting::NO_STD_MAX_NESTING`] with the same scan, before parsing,
/// and reads the rest with the reader's default limit.
pub fn parse_deep(text: &str) -> crate::error::Result<serde_json::Value> {
    #[cfg(not(feature = "std"))]
    {
        crate::nesting::parse(text)
    }
    #[cfg(feature = "std")]
    parse_deep_std(text)
}

#[cfg(feature = "std")]
fn parse_deep_std(text: &str) -> crate::error::Result<serde_json::Value> {
    use crate::error::CoreError;
    if crate::did_webvh::json_too_deep(text.as_bytes(), MAX_DEEP_NESTING) {
        return Err(CoreError::Json("the request is nested too deeply".into()));
    }
    let mut de = serde_json::Deserializer::from_str(text);
    de.disable_recursion_limit();
    let value: serde_json::Value = serde::Deserialize::deserialize(&mut de)
        .map_err(|e| CoreError::Json(format!("json: {e}")))?;
    de.end()
        .map_err(|e| CoreError::Json(format!("json: {e}")))?;
    Ok(value)
}

/// How deep a request may nest and still be read on the caller's own stack.
pub const SHALLOW_NESTING: usize = 128;
/// The stack a deeper request is read on: the core's walkers (the reader,
/// canonicalization, comparison, dropping) take about 300 KiB at
/// [`MAX_DEEP_NESTING`] levels, more than a small thread (a 128 KiB musl
/// default, a 256 KiB worker) has.
pub const DEEP_STACK_BYTES: usize = 8 << 20;

/// Whether the request `text` nests deeper than [`SHALLOW_NESTING`] levels,
/// so it is read on a stack of its own ([`on_deep_stack`]).
pub fn needs_deep_stack(text: &str) -> bool {
    crate::did_webvh::json_too_deep(text.as_bytes(), SHALLOW_NESTING)
}

/// Run `f` (which reads and answers a request) where the request's depth
/// has the stack it needs: on the caller's thread unless `deep` (see
/// [`needs_deep_stack`]), else on a thread of its own with
/// [`DEEP_STACK_BYTES`] of stack, joined before this returns. A panic in `f`
/// carries on in the caller. In WebAssembly there are no threads: `f` runs
/// in place (the module's own stack is 1 MiB). Part of the `std` build: the
/// `no_std` build never reads a request that deep.
#[cfg(feature = "std")]
pub fn on_deep_stack<T: Send>(deep: bool, f: impl FnOnce() -> T + Send) -> T {
    #[cfg(not(target_arch = "wasm32"))]
    if deep {
        let mut f = Some(f);
        let joined = std::thread::scope(|s| {
            let run = || (f.take().expect("runs once"))();
            std::thread::Builder::new()
                .stack_size(DEEP_STACK_BYTES)
                .spawn_scoped(s, run)
                .ok()
                .map(|handle| handle.join())
        });
        return match joined {
            Some(Ok(out)) => out,
            Some(Err(panic)) => std::panic::resume_unwind(panic),
            // No thread to be had: run in place.
            None => (f.take().expect("not run"))(),
        };
    }
    #[cfg(target_arch = "wasm32")]
    let _ = deep;
    f()
}

/// Wipe every string of a parsed request (its secrets travel as base64 or
/// Multikey text) before the value is dropped. The walk keeps its own stack
/// on the heap, so a deep value costs no call stack (the `no_std` build's
/// callers may hand it any value).
pub fn wipe_strings(value: &mut serde_json::Value) {
    use zeroize::Zeroize;
    let mut pending: alloc::vec::Vec<&mut serde_json::Value> = alloc::vec![value];
    while let Some(v) = pending.pop() {
        match v {
            serde_json::Value::String(s) => s.zeroize(),
            serde_json::Value::Array(items) => pending.extend(items.iter_mut()),
            serde_json::Value::Object(map) => pending.extend(map.values_mut()),
            _ => {}
        }
    }
}

/// An answer that may hold a secret (a decoded secret key, a recovered seed,
/// recovery shares) as JSON text. The text is written into a buffer of
/// exactly its size, so no growing buffer leaves a copy behind, and every
/// string in the answer is wiped once it is written. The caller keeps the
/// text in a `Zeroizing` wrapper while it holds it. Part of the `std` build,
/// where the secrets it writes (recovery shares) are made.
#[cfg(feature = "std")]
pub fn secret_json_text(mut value: serde_json::Value) -> String {
    let text = exact_json_text(&value);
    wipe_strings(&mut value);
    text
}

/// JSON text of a value that holds a secret, written into a buffer of exactly
/// its size (so no growing buffer leaves a copy behind) and held in a
/// `Zeroizing` wrapper. The value itself is left as it is.
#[cfg(feature = "std")]
pub(crate) fn secret_value_text(value: &serde_json::Value) -> zeroize::Zeroizing<String> {
    zeroize::Zeroizing::new(exact_json_text(value))
}

/// `value.to_string()`, written in two passes: one to count the bytes, one to
/// write them into a buffer of that size.
#[cfg(feature = "std")]
fn exact_json_text(value: &serde_json::Value) -> String {
    struct Count(usize);
    impl std::io::Write for Count {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.0 += buf.len();
            Ok(buf.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    let mut count = Count(0);
    // Writing a Value to memory cannot fail.
    let _ = serde_json::to_writer(&mut count, value);
    let mut buf = Vec::with_capacity(count.0);
    let _ = serde_json::to_writer(&mut buf, value);
    String::from_utf8(buf).unwrap_or_default()
}

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

    /// The walk keeps its own stack: a value nested 10,000 deep canonicalizes
    /// on a 64 KiB thread stack, the same bytes as a plain string build.
    #[test]
    fn deep_nesting_needs_no_deep_call_stack() {
        let depth = 10_000;
        let out = std::thread::Builder::new()
            .stack_size(64 * 1024)
            .spawn(move || {
                let mut v = json!(1);
                for _ in 0..depth {
                    let mut m = serde_json::Map::new();
                    m.insert("a".into(), v);
                    v = Value::Object(m);
                }
                let text = canonicalize_to_string(&v);
                // Dropping the value recurses (serde_json), so it is left.
                core::mem::forget(v);
                text
            })
            .unwrap()
            .join()
            .unwrap();
        let want = format!("{}1{}", "{\"a\":".repeat(depth), "}".repeat(depth));
        assert_eq!(out, want);
    }
    use serde_json::json;

    #[test]
    #[cfg(feature = "std")]
    fn a_deep_request_is_read_on_a_stack_of_its_own() {
        // 500 levels inside a request, on a thread far smaller than the
        // walkers need: parsed, canonicalized and dropped on the deep stack.
        let text = format!("{{\"x\":{}1{}}}", "[".repeat(500), "]".repeat(500));
        assert!(needs_deep_stack(&text));
        assert!(!needs_deep_stack("[[1]]"));
        let small = std::thread::Builder::new()
            .stack_size(64 * 1024)
            .spawn(move || {
                on_deep_stack(needs_deep_stack(&text), || {
                    let value = parse_deep(&text).unwrap();
                    canonicalize_to_string(&value).len()
                })
            })
            .unwrap();
        assert_eq!(small.join().unwrap(), 1007);
    }

    #[test]
    #[cfg(feature = "std")]
    fn a_secret_answer_is_written_at_its_exact_size() {
        let value = json!({"seed": "c2VjcmV0", "keys": [{"private_key": "a2V5"}], "n": 1});
        let text = secret_json_text(value.clone());
        assert_eq!(text, value.to_string());
        assert_eq!(text.capacity(), text.len());
    }

    #[test]
    #[cfg_attr(feature = "std", ignore = "checks the no_std build")]
    fn no_std_parse_deep_refuses_past_the_cap() {
        let nested = |n: usize| format!("{}1{}", "[".repeat(n), "]".repeat(n));
        assert!(parse_deep(&nested(crate::nesting::NO_STD_MAX_NESTING)).is_ok());
        for n in [crate::nesting::NO_STD_MAX_NESTING + 1, 129, 500] {
            let e = parse_deep(&nested(n)).unwrap_err();
            assert_eq!(e.to_string(), crate::nesting::too_deep().to_string());
        }
    }

    #[test]
    fn empty_containers() {
        assert_eq!(canonicalize_to_string(&json!({})), "{}");
        assert_eq!(canonicalize_to_string(&json!([])), "[]");
    }

    #[test]
    fn sorts_object_keys() {
        assert_eq!(
            canonicalize_to_string(&json!({"b": 1, "a": 2, "c": 3})),
            "{\"a\":2,\"b\":1,\"c\":3}"
        );
    }

    #[test]
    fn array_preserves_order() {
        assert_eq!(canonicalize_to_string(&json!([3, 1, 2])), "[3,1,2]");
    }

    #[test]
    fn negative_zero_normalized() {
        assert_eq!(canonicalize_to_string(&json!({"n": -0})), "{\"n\":0}");
    }
}