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
//! Segmented verification of long robotics logs and embodiment histories.
//!
//! A host checks a long black-box, safety or perception log, or a long fork
//! check, one segment at a time. After each segment the core hands back a
//! small state object: for a log, the next entry number and the hash the
//! next entry must link to; for a fork check, the open windows on one body
//! and the first fork. The host passes it with the next segment. Memory
//! stays bounded by one segment however long the log is, and the verdict
//! after the last segment is the one the whole-log check gives.
//!
//! The state carries a check value: HMAC-SHA256 over its canonical (JCS)
//! form. With the host's own 32-byte `stateKey`, a state changed while it
//! was stored (on disk between runs) is refused. Without one the check value
//! uses a random key made once per process, so a state made without a
//! `stateKey` resumes only in the process that made it: nobody outside the
//! process can write a state it accepts. A host that keeps the state outside
//! its own memory, or resumes it in another run, passes a key.
//!
//! A state is bound to the history it came from. It carries what it has
//! checked so far (for a log, the genesis, the next entry number and the
//! hash the next entry must link to; for a fork check, the running digest
//! of every embodiment before it), and the `historyId` the host named at
//! the first segment. A later segment that names another `historyId` is
//! refused, so a genuine state of another history cannot be passed off as
//! this one's.

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

use serde_json::{json, Map, Value};
use sha2::{Digest, Sha256};
use zeroize::Zeroizing;

use crate::error::{CoreError, Result};
use crate::jcs;
use crate::robotics::{self as r, ChainProgress, ForkConflict, ForkFailure, ForkProgress};

/// The state format version.
pub const STATE_VERSION: u64 = 1;

/// The reason a state whose check value does not match is refused.
pub const STATE_CHANGED: &str = "the segment state was changed, or was made under another stateKey";

/// The reason a state made for another history is refused.
pub const STATE_OTHER_HISTORY: &str = "the segment state belongs to another history";

/// The random key used when the host gives no `stateKey`: made once per
/// process, never written anywhere.
#[cfg(feature = "std")]
fn process_key() -> &'static [u8; 32] {
    static KEY: std::sync::OnceLock<[u8; 32]> = std::sync::OnceLock::new();
    KEY.get_or_init(|| {
        let mut k = [0u8; 32];
        if crate::random::fill(&mut k).is_err() {
            // No randomness: derive a key no other process shares from the
            // clock and this process's address space, never a fixed one.
            let seed = format!("{:?}{:p}", std::time::SystemTime::now(), &k as *const _);
            k.copy_from_slice(&Sha256::digest(seed.as_bytes()));
        }
        k
    })
}

/// HMAC-SHA256 (RFC 2104).
pub fn hmac_sha256(key: &[u8], msg: &[u8]) -> [u8; 32] {
    let mut k = [0u8; 64];
    if key.len() > 64 {
        k[..32].copy_from_slice(&Sha256::digest(key));
    } else {
        k[..key.len()].copy_from_slice(key);
    }
    let mut ipad = [0x36u8; 64];
    let mut opad = [0x5cu8; 64];
    for i in 0..64 {
        ipad[i] ^= k[i];
        opad[i] ^= k[i];
    }
    let inner = Sha256::new()
        .chain_update(ipad)
        .chain_update(msg)
        .finalize();
    Sha256::new()
        .chain_update(opad)
        .chain_update(inner)
        .finalize()
        .into()
}

fn state_key(key: Option<&[u8]>) -> Result<Zeroizing<Vec<u8>>> {
    match key {
        #[cfg(feature = "std")]
        None | Some([]) => Ok(Zeroizing::new(process_key().to_vec())),
        // No process-wide random key without `std`: the host gives one.
        #[cfg(not(feature = "std"))]
        None | Some([]) => Err(CoreError::Json(
            "stateKey is required in a no_std build (32 bytes)".into(),
        )),
        Some(k) if k.len() == 32 => Ok(Zeroizing::new(k.to_vec())),
        Some(_) => Err(CoreError::Json("stateKey must be 32 bytes".into())),
    }
}

fn check_value(body: &Map<String, Value>, key: &[u8]) -> String {
    r::mb64(&hmac_sha256(
        key,
        &jcs::canonicalize(&Value::Object(body.clone())),
    ))
}

fn seal(mut body: Map<String, Value>, key: &[u8]) -> Value {
    body.remove("check");
    let check = check_value(&body, key);
    body.insert("check".into(), json!(check));
    Value::Object(body)
}

/// The state's fields when its check value matches, else [`STATE_CHANGED`].
fn open(state: &Value, key: &[u8], kind: &str) -> core::result::Result<Map<String, Value>, String> {
    let mut body = state
        .as_object()
        .cloned()
        .ok_or_else(|| "the segment state must be an object".to_string())?;
    let given = match body.remove("check") {
        Some(Value::String(c)) => c,
        _ => return Err(STATE_CHANGED.into()),
    };
    let want = check_value(&body, key);
    let same = given.len() == want.len()
        && given
            .bytes()
            .zip(want.bytes())
            .fold(0u8, |acc, (a, b)| acc | (a ^ b))
            == 0;
    if !same {
        return Err(STATE_CHANGED.into());
    }
    if body.get("v").and_then(Value::as_u64) != Some(STATE_VERSION) {
        return Err("the segment state version is not supported".into());
    }
    if body.get("kind").and_then(Value::as_str) != Some(kind) {
        return Err(format!("the segment state is not a {kind} state"));
    }
    Ok(body)
}

/// Put the host's history id into a state body (absent when it named none).
fn set_history(body: &mut Map<String, Value>, history: Option<&str>) {
    if let Some(h) = history {
        body.insert("history".into(), json!(h));
    }
}

/// A state opened for a segment of `history`: the id sealed at the first
/// segment must be the one the host names now. A state with an id is
/// refused when the host names none, and the other way round.
pub fn check_history(state: &Value, history: Option<&str>) -> core::result::Result<(), String> {
    crate::nesting::deep_guard!(Err(crate::nesting::TOO_DEEP.into()); state);
    let sealed = state.get("history").and_then(Value::as_str);
    if sealed != history {
        return Err(STATE_OTHER_HISTORY.into());
    }
    Ok(())
}

fn time_text(t: i128) -> String {
    t.to_string()
}

fn time_of(v: &Value) -> Option<i128> {
    v.as_str().and_then(|s| s.parse::<i128>().ok())
}

// ---- hash-linked logs -------------------------------------------------------

/// A log state as JSON, sealed under `key`.
pub fn chain_state(progress: &ChainProgress, key: &[u8]) -> Value {
    chain_state_for(progress, None, key)
}

/// A log state for the history the host named `history`, sealed under `key`.
pub fn chain_state_for(progress: &ChainProgress, history: Option<&str>, key: &[u8]) -> Value {
    let mut body = Map::new();
    set_history(&mut body, history);
    body.insert("v".into(), json!(STATE_VERSION));
    body.insert("kind".into(), json!("log"));
    body.insert("genesis".into(), json!(progress.genesis));
    body.insert("nextSeq".into(), json!(progress.next_seq));
    body.insert("lastHash".into(), json!(progress.last_hash));
    body.insert("failure".into(), json!(progress.failure));
    seal(body, key)
}

/// A log state read back, or the reason it is refused.
pub fn read_chain_state(state: &Value, key: &[u8]) -> core::result::Result<ChainProgress, String> {
    crate::nesting::deep_guard!(Err(crate::nesting::TOO_DEEP.into()); state);
    let body = open(state, key, "log")?;
    let text = |k: &str| body.get(k).and_then(Value::as_str).map(String::from);
    let bad = || "the segment state is malformed".to_string();
    Ok(ChainProgress {
        genesis: text("genesis").ok_or_else(bad)?,
        next_seq: body
            .get("nextSeq")
            .and_then(Value::as_u64)
            .ok_or_else(bad)?,
        last_hash: text("lastHash").ok_or_else(bad)?,
        failure: match body.get("failure") {
            Some(Value::Null) => None,
            Some(Value::String(s)) => Some(s.clone()),
            _ => return Err(bad()),
        },
    })
}

// ---- fork check -------------------------------------------------------------

/// A fork-check state as JSON, sealed under `key`. `digest` is the running
/// hash of every embodiment checked (see [`fork_digest_step`]).
pub fn fork_state(progress: &ForkProgress, digest: &str, key: &[u8]) -> Value {
    fork_state_for(progress, digest, None, key)
}

/// A fork-check state for the history the host named `history`.
pub fn fork_state_for(
    progress: &ForkProgress,
    digest: &str,
    history: Option<&str>,
    key: &[u8],
) -> Value {
    let mut body = Map::new();
    set_history(&mut body, history);
    body.insert("v".into(), json!(STATE_VERSION));
    body.insert("kind".into(), json!("fork"));
    body.insert("count".into(), json!(progress.count));
    body.insert("digest".into(), json!(digest));
    body.insert(
        "lastStart".into(),
        json!(progress.last_start.map(time_text)),
    );
    body.insert("body".into(), json!(progress.body));
    body.insert(
        "windows".into(),
        Value::Array(
            progress
                .windows
                .iter()
                .map(|(s, e)| json!([time_text(*s), e.map(time_text)]))
                .collect(),
        ),
    );
    body.insert(
        "conflict".into(),
        match &progress.conflict {
            Some(c) => json!({"bodyA": c.body_a, "bodyB": c.body_b}),
            None => Value::Null,
        },
    );
    body.insert(
        "failure".into(),
        match &progress.failure {
            None => Value::Null,
            Some(ForkFailure::Malformed(i)) => json!({"kind": "malformed", "at": i}),
            Some(ForkFailure::OutOfOrder(i)) => json!({"kind": "order", "at": i}),
            Some(ForkFailure::TooManyWindows(i)) => json!({"kind": "windows", "at": i}),
        },
    );
    seal(body, key)
}

/// A fork-check state and its digest read back, or the reason it is refused.
pub fn read_fork_state(
    state: &Value,
    key: &[u8],
) -> core::result::Result<(ForkProgress, String), String> {
    crate::nesting::deep_guard!(Err(crate::nesting::TOO_DEEP.into()); state);
    let body = open(state, key, "fork")?;
    let bad = || "the segment state is malformed".to_string();
    let opt_time = |k: &str| -> core::result::Result<Option<i128>, String> {
        match body.get(k) {
            Some(Value::Null) => Ok(None),
            Some(v) => time_of(v).map(Some).ok_or_else(bad),
            None => Err(bad()),
        }
    };
    let mut windows = Vec::new();
    for w in body
        .get("windows")
        .and_then(Value::as_array)
        .ok_or_else(bad)?
    {
        let pair = w.as_array().filter(|p| p.len() == 2).ok_or_else(bad)?;
        let s = time_of(&pair[0]).ok_or_else(bad)?;
        let e = match &pair[1] {
            Value::Null => None,
            v => Some(time_of(v).ok_or_else(bad)?),
        };
        windows.push((s, e));
    }
    if windows.len() > r::MAX_FORK_WINDOWS {
        return Err(bad());
    }
    let conflict = match body.get("conflict") {
        Some(Value::Null) => None,
        Some(c) => Some(ForkConflict {
            body_a: c
                .get("bodyA")
                .and_then(Value::as_str)
                .ok_or_else(bad)?
                .into(),
            body_b: c
                .get("bodyB")
                .and_then(Value::as_str)
                .ok_or_else(bad)?
                .into(),
        }),
        None => return Err(bad()),
    };
    let failure = match body.get("failure") {
        Some(Value::Null) => None,
        Some(f) => {
            let at = f.get("at").and_then(Value::as_u64).ok_or_else(bad)?;
            match f.get("kind").and_then(Value::as_str) {
                Some("malformed") => Some(ForkFailure::Malformed(at)),
                Some("order") => Some(ForkFailure::OutOfOrder(at)),
                Some("windows") => Some(ForkFailure::TooManyWindows(at)),
                _ => return Err(bad()),
            }
        }
        None => return Err(bad()),
    };
    let body_name = match body.get("body") {
        Some(Value::Null) => None,
        Some(Value::String(b)) => Some(b.clone()),
        _ => return Err(bad()),
    };
    let progress = ForkProgress {
        count: body.get("count").and_then(Value::as_u64).ok_or_else(bad)?,
        last_start: opt_time("lastStart")?,
        body: body_name,
        windows,
        conflict,
        failure,
    };
    let digest = body
        .get("digest")
        .and_then(Value::as_str)
        .ok_or_else(bad)?
        .to_string();
    Ok((progress, digest))
}

/// The digest of an empty history.
pub fn fork_digest_start() -> String {
    r::mb64(&[0u8; 32])
}

/// The running digest after one more embodiment: SHA-256 of the previous
/// digest's bytes and the SHA-256 of the embodiment's JCS form. Two hosts
/// that checked the same history in any segments end at the same digest.
pub fn fork_digest_step(digest: &[u8], embodiment: &Value) -> Vec<u8> {
    let leaf = Sha256::digest(jcs::canonicalize(embodiment));
    Sha256::new()
        .chain_update(digest)
        .chain_update(leaf)
        .finalize()
        .to_vec()
}

/// The key for a state: the host's 32-byte key, or this process's random key.
pub fn key_for(state_key_bytes: Option<&[u8]>) -> Result<Zeroizing<Vec<u8>>> {
    state_key(state_key_bytes)
}

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

    #[test]
    fn hmac_matches_rfc4231_case_2() {
        let mac = hmac_sha256(b"Jefe", b"what do ya want for nothing?");
        let hex: String = mac.iter().map(|b| format!("{b:02x}")).collect();
        assert_eq!(
            hex,
            "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
        );
    }

    #[test]
    fn hmac_long_key_rfc4231_case_6() {
        let key = [0xaau8; 131];
        let mac = hmac_sha256(
            &key,
            b"Test Using Larger Than Block-Size Key - Hash Key First",
        );
        let hex: String = mac.iter().map(|b| format!("{b:02x}")).collect();
        assert_eq!(
            hex,
            "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"
        );
    }
}