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
//! Cross-language interop for robotics issuer binding.
//!
//! Runs every case of `test-vectors/robotics/binding_vector.json` (Python-signed,
//! with the verdict the Python reference computed) through the Rust core and
//! requires the same verdict: proofs bound to the issuer DID, strict windows,
//! and threshold predicates that count verified issuers.

use std::collections::BTreeMap;
use vouch_core::collections::HashSet;

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use serde_json::{json, Value};

use vouch_core::robotics as r;
use vouch_core::robotics_dtn as dtn;
use vouch_core::robotics_verify::{self as rv, Keys, VerifyOptions, Window};

fn vector() -> Value {
    let path = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-vectors/robotics/binding_vector.json"
    );
    serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
}

fn raw(x: &Value) -> Vec<u8> {
    URL_SAFE_NO_PAD.decode(x.as_str().unwrap()).unwrap()
}

fn key_map(v: &Value) -> BTreeMap<String, Vec<u8>> {
    v.as_object()
        .unwrap()
        .iter()
        .map(|(d, x)| (d.clone(), raw(x)))
        .collect()
}

fn list(v: &Value) -> Vec<Value> {
    v.as_array().unwrap().clone()
}

fn window(v: &Value) -> Window {
    match v.as_str().unwrap() {
        "required" => Window::Required,
        "from_required" => Window::FromRequired,
        _ => Window::IfPresent,
    }
}

fn strs(v: &Value) -> Vec<String> {
    v.as_array()
        .unwrap()
        .iter()
        .map(|s| s.as_str().unwrap().to_string())
        .collect()
}

/// The case's optional `trustedIssuers` list as a set.
fn trusted(case: &Value) -> Option<HashSet<String>> {
    case.get("trustedIssuers")
        .filter(|v| !v.is_null())
        .map(|v| strs(v).into_iter().collect())
}

fn pairs(
    creds: &[Value],
    keys: &BTreeMap<String, Vec<u8>>,
    ty: &str,
    now: &str,
    role: Option<&str>,
    members: Option<&HashSet<String>>,
) -> Vec<rv::VerifiedPair> {
    rv::collect_verified(
        creds,
        Keys::Map(keys),
        ty,
        rv::require_now(now).unwrap(),
        Window::IfPresent,
        role,
        members,
    )
}

fn run(case: &Value) -> Value {
    let now = case["now"].as_str().unwrap_or("2026-01-01T00:02:00Z");
    match case["kind"].as_str().unwrap() {
        "credential" => {
            let k = case["keys"].clone();
            let map;
            let bare;
            let mut keys = match case["keysMode"].as_str().unwrap() {
                "map" => {
                    map = key_map(&k);
                    Keys::Map(&map)
                }
                "bare" => {
                    bare = raw(&k);
                    Keys::Bare(&bare)
                }
                _ => Keys::Embedded,
            };
            // issuerDid pins the expected issuer (only meaningful with no key).
            if let Some(pin) = case.get("issuerDid").and_then(|v| v.as_str()) {
                keys = rv::pin_if_keyless(keys, Some(pin));
            }
            let t = trusted(case);
            let res = rv::verify_robotics_credential(
                &case["credential"],
                keys,
                case["expectedType"].as_str(),
                rv::require_now(now).unwrap(),
                VerifyOptions {
                    trusted_issuers: t.as_ref(),
                    ..VerifyOptions::window(window(&case["window"]))
                },
            );
            match res {
                Ok(v) => json!({"ok": true, "issuer": v.issuer}),
                Err(_) => json!({"ok": false, "issuer": null}),
            }
        }
        "quarantine" => {
            let keys = key_map(&case["keys"]);
            let p = pairs(
                &list(&case["credentials"]),
                &keys,
                dtn::DISTRESS_TYPE,
                now,
                Some("observer"),
                trusted(case).as_ref(),
            );
            let members: HashSet<String> = strs(&case["members"]).into_iter().collect();
            let w = case["window"].as_array().unwrap();
            let q = dtn::is_quarantined(
                &p,
                case["targetDid"].as_str().unwrap(),
                case["threshold"].as_u64().unwrap() as usize,
                &members,
                (w[0].as_i64().unwrap(), w[1].as_i64().unwrap()),
                if case["dedupeByKey"].as_bool().unwrap() {
                    Some(&keys)
                } else {
                    None
                },
            )
            .unwrap();
            json!({"quarantined": q})
        }
        "trust_update" => {
            let anchors: Vec<dtn::TrustAnchor> = case["anchors"]
                .as_object()
                .unwrap()
                .iter()
                .map(|(d, a)| dtn::TrustAnchor {
                    did: d.clone(),
                    public_key: raw(&a["x"]),
                    failure_domain: a["domain"].as_str().unwrap().to_string(),
                })
                .collect();
            let ok = dtn::accept_trust_state_update(
                &list(&case["updates"]),
                &anchors,
                case["currentEpoch"].as_i64().unwrap(),
                case["threshold"].as_u64().unwrap() as usize,
                None,
                now,
            )
            .unwrap();
            json!({"accepted": ok})
        }
        "key_continuity" => {
            let auth = key_map(&case["authorityKeys"]);
            let members = key_map(&case["memberKeys"]);
            let ok = dtn::verify_key_continuity(
                &case["predelegation"],
                Keys::Map(&auth),
                case["reissuanceId"].as_str().unwrap(),
                case["supersedes"].as_str().unwrap(),
                &list(&case["approvals"]),
                &members,
                &case["supersededCredential"],
                &case["reissuedCredential"],
                now,
            )
            .unwrap();
            json!({"confirmed": ok})
        }
        "perception_cross_check" => {
            let keys = key_map(&case["keys"]);
            let p = pairs(
                &list(&case["claims"]),
                &keys,
                dtn::PERCEPTION_CLAIM_TYPE,
                now,
                Some("id"),
                trusted(case).as_ref(),
            );
            let (c, f) = dtn::cross_check_perception(
                &p,
                case["tolerance"].as_f64().unwrap(),
                case["threshold"].as_u64().unwrap() as usize,
                None,
                None,
            )
            .unwrap();
            json!({"corroborated": c, "flagged": f})
        }
        "location" => {
            let keys = key_map(&case["keys"]);
            let p = pairs(
                &list(&case["observations"]),
                &keys,
                dtn::RANGE_OBSERVATION_TYPE,
                now,
                Some("observer"),
                trusted(case).as_ref(),
            );
            let c = case["claimedPosition"].as_array().unwrap();
            let pos = [
                c[0].as_f64().unwrap(),
                c[1].as_f64().unwrap(),
                c[2].as_f64().unwrap(),
            ];
            let tol = case["toleranceM"].as_f64().unwrap();
            let target = case["targetDid"].as_str();
            let confirmed = dtn::location_confirmed(
                &p,
                pos,
                tol,
                case["threshold"].as_u64().unwrap() as usize,
                target,
            )
            .unwrap();
            let count = dtn::count_consistent(&p, pos, tol, target).unwrap();
            json!({"confirmed": confirmed, "count": count})
        }
        "bundle_custody" => {
            let keys = key_map(&case["keys"]);
            let p = pairs(
                &list(&case["transfers"]),
                &keys,
                dtn::CUSTODY_TRANSFER_TYPE,
                now,
                None,
                trusted(case).as_ref(),
            );
            json!({"ok": dtn::custody_chain_ok(&p, case["bundleId"].as_str().unwrap(), case["originator"].as_str().unwrap())})
        }
        "physical_quorum" => {
            let keys: Vec<r::ApproverKey> = key_map(&case["keys"])
                .into_iter()
                .map(|(did, public_key)| r::ApproverKey { did, public_key })
                .collect();
            let set: Option<HashSet<String>> = case
                .get("approverSet")
                .filter(|v| !v.is_null())
                .map(|v| strs(v).into_iter().collect());
            let (ok, who) = r::verify_action_authorization(
                &list(&case["approvals"]),
                case["actionId"].as_str().unwrap(),
                case["robotDid"].as_str().unwrap(),
                &keys,
                case["threshold"].as_i64().unwrap(),
                set.as_ref(),
                now,
            )
            .unwrap();
            json!({"authorized": ok, "approvers": who})
        }
        "handoff_chain" => {
            let keys: Vec<r::ActorKey> = key_map(&case["keys"])
                .into_iter()
                .map(|(did, public_key)| r::ActorKey { did, public_key })
                .collect();
            let (ok, holder) = r::verify_handoff_chain(
                &list(&case["handoffs"]),
                &keys,
                case["taskId"].as_str().unwrap(),
                case["originActor"].as_str(),
                case["requireRelease"].as_bool().unwrap(),
                now,
            )
            .unwrap();
            json!({"ok": ok, "currentHolder": holder})
        }
        "ownership_chain" => {
            let keys: Vec<r::OwnerKey> = key_map(&case["keys"])
                .into_iter()
                .map(|(did, public_key)| r::OwnerKey { did, public_key })
                .collect();
            let (ok, owner) = r::verify_custody_chain(
                &list(&case["transfers"]),
                &keys,
                case["robotDid"].as_str().unwrap(),
                case["originOwner"].as_str(),
                now,
            )
            .unwrap();
            json!({"ok": ok, "currentOwner": owner})
        }
        "key_rotation" => {
            let trusted = raw(&case["trustedKey"]);
            let ok = r::verify_key_rotation(
                &case["credential"],
                Keys::Bare(&trusted),
                case["robotDid"].as_str(),
                now,
            )
            .unwrap()
            .is_some();
            json!({"ok": ok})
        }
        "blackbox_head" => {
            let keys = key_map(&case["keys"]);
            let res = r::verify_blackbox_head(
                &case["head"],
                Keys::Map(&keys),
                &list(&case["entries"]),
                None,
                now,
            )
            .unwrap();
            json!({"ok": res.ok})
        }
        "authority" => {
            // An authority credential signed by a freshly minted did:key, with
            // no key source: refused unless the trusted set names the issuer.
            let t = trusted(case);
            let robot = case["robotDid"].as_str().unwrap();
            let cred = &case["credential"];
            let ok = match case["fn"].as_str().unwrap() {
                "killswitch" => {
                    r::verify_killswitch_credential(cred, Keys::Embedded, t.as_ref(), now)
                }
                "decommission" => {
                    r::verify_decommission(cred, Keys::Embedded, t.as_ref(), Some(robot), now)
                }
                "access_grant" => r::verify_access_grant(cred, Keys::Embedded, t.as_ref(), now),
                "lease" => {
                    r::verify_delegation_lease(cred, Keys::Embedded, robot, None, t.as_ref(), now)
                }
                "physical_scope" => {
                    r::verify_physical_scope_credential(cred, Keys::Embedded, Some(robot), now)
                }
                "conformance_attestation" => r::verify_conformance_attestation(
                    cred,
                    Keys::Embedded,
                    Some(robot),
                    t.as_ref(),
                    now,
                ),
                other => panic!("unknown authority fn {other}"),
            }
            .unwrap()
            .is_some();
            json!({"ok": ok})
        }
        "blackbox_open" => {
            let key = raw(&case["aesKeyB64Url"]);
            match r::open_entry(&case["entry"], &key) {
                Ok(payload) => json!({"opens": true, "payload": payload}),
                Err(_) => json!({"opens": false}),
            }
        }
        other => panic!("unknown case kind {other}"),
    }
}

#[test]
fn every_binding_case_matches_python() {
    let v = vector();
    let cases = v["cases"].as_array().unwrap();
    assert!(cases.len() >= 60, "the vector carries the full case set");
    for case in cases {
        let got = run(case);
        let want = &case["expect"];
        for (k, w) in want.as_object().unwrap() {
            assert_eq!(&got[k], w, "{}: field {k}", case["name"]);
        }
    }
}