use serde_json::{json, Value};
use vouch_core::attenuation;
use vouch_core::credentials::{self, BuildCredentialOptions};
use vouch_core::data_integrity::{verify_proof, BuildProofOptions};
use vouch_core::jcs;
use vouch_core::keys::{self, Ed25519KeyPair};
use vouch_core::robotics::{check_physical_action, PhysicalAction};
const NOW: &str = "2026-05-01T12:01:00Z";
fn vector(rel: &str) -> Value {
let path = format!("{}/../../test-vectors/{rel}", env!("CARGO_MANIFEST_DIR"));
serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap()
}
fn intent(action: &str, resource: &str) -> Value {
json!({"action": action, "target": "did:web:files.example", "resource": resource})
}
#[test]
fn reports_which_build_this_is() {
println!(
"vouch-core built with std = {}, map type = {}",
cfg!(feature = "std"),
core::any::type_name::<vouch_core::collections::HashSet<u8>>()
);
if !cfg!(feature = "std") {
assert!(
core::any::type_name::<vouch_core::collections::HashSet<u8>>().contains("BTreeSet")
);
}
}
#[test]
fn shared_eddsa_vector_verifies() {
let v = vector("data-integrity-eddsa-jcs-2022/vector.json");
let public = base64_decode(v["ed25519"]["public_key_b64"].as_str().unwrap());
assert!(verify_proof(&v["signed_credential"], &public).unwrap());
let mut tampered = v["signed_credential"].clone();
tampered["credentialSubject"]["intent"]["action"] = json!("delete");
assert!(!verify_proof(&tampered, &public).unwrap());
}
#[test]
fn jcs_vectors_are_byte_identical() {
let v = vector("jcs/vectors.json");
let cases = v.as_array().or_else(|| v["vectors"].as_array()).unwrap();
assert!(!cases.is_empty());
for case in cases {
let want = case["canonical"]
.as_str()
.or_else(|| case["expected"].as_str())
.unwrap();
assert_eq!(jcs::canonicalize_to_string(&case["input"]), want, "{case}");
}
}
#[test]
fn sign_and_verify_with_a_caller_seed_and_caller_time() {
let pair = Ed25519KeyPair::from_seed(&[7u8; 32]);
let did = pair.did_key();
assert_eq!(
keys::did_key_to_ed25519(&did).unwrap(),
pair.public_key().to_vec()
);
let opts = BuildCredentialOptions {
issuer_did: did.clone(),
credential_id: "urn:uuid:00000000-0000-4000-8000-000000000001".into(),
intent: intent("read", "https://files.example/q3"),
valid_from: "2026-05-01T12:00:00Z".into(),
valid_until: "2026-05-01T12:05:00Z".into(),
reputation_score: None,
delegation_chain: None,
credential_status: None,
};
let proof = BuildProofOptions::new(format!("{did}#key-1"), "2026-05-01T12:00:00Z");
let cred = credentials::sign_vouch_credential(&opts, &pair.seed(), &proof).unwrap();
let ok = credentials::verify(&cred, &pair.public_key(), NOW, 30).unwrap();
assert!(ok.proof_valid && ok.time_valid && ok.chain_valid);
let late = credentials::verify(&cred, &pair.public_key(), "2026-05-01T13:00:00Z", 30).unwrap();
assert!(late.proof_valid && !late.time_valid);
let other = Ed25519KeyPair::from_seed(&[8u8; 32]);
assert!(
!credentials::verify(&cred, &other.public_key(), NOW, 30)
.unwrap()
.proof_valid
);
}
#[test]
fn grant_narrowing_is_checked() {
let parent = json!({"intent": intent("read", "https://files.example/")});
let narrower = json!({"intent": intent("read", "https://files.example/q3")});
let wider = json!({"intent": intent("read", "https://other.example/")});
assert!(attenuation::non_expansion(&parent, &narrower).is_ok());
assert!(attenuation::non_expansion(&parent, &wider).is_err());
}
#[test]
fn robot_command_is_checked_against_its_scope() {
let scope = json!({"maxForceN": 50.0, "maxSpeedMps": 1.5, "maxSpeedNearHumansMps": 0.5});
let mut action = PhysicalAction {
force_n: Some(20.0),
speed_mps: Some(1.0),
near_humans: false,
zone: None,
time_hm: None,
};
assert!(check_physical_action(&scope, &action).ok);
action.near_humans = true;
let near = check_physical_action(&scope, &action);
assert!(!near.ok && !near.reasons.is_empty());
}
#[test]
#[cfg_attr(feature = "std", ignore = "checks the no_std build")]
fn no_std_build_refuses_what_needs_std() {
let e = Ed25519KeyPair::generate().err().expect("no random source");
assert!(e.to_string().contains("no random source"), "{e}");
let e = vouch_core::status_list::decode_bitstring("uH4sIAAAAAAAA_wMAAAAAAAAAAAA")
.err()
.expect("no gzip");
assert!(e.to_string().contains("std feature"), "{e}");
let bits = vec![0u8; vouch_core::status_list::DEFAULT_BITSTRING_LENGTH / 8];
let encoded = vouch_core::status_list::encode_bitstring(&bits).unwrap();
assert!(encoded.starts_with("uH4sI"), "{encoded}");
let e = vouch_core::did_webvh::LogClock::System
.now_ns()
.err()
.expect("no clock");
assert!(e.to_string().contains("no system clock"), "{e}");
let e = vouch_core::robotics_dtn::decay_weight(1, 10.0, "exponential")
.err()
.expect("no powf");
assert!(e.to_string().contains("std feature"), "{e}");
assert_eq!(
vouch_core::robotics_dtn::decay_weight(10, 10.0, "linear").unwrap(),
0.5
);
}
#[test]
#[cfg_attr(feature = "std", ignore = "checks the no_std build")]
fn no_std_build_refuses_deep_json_on_a_small_stack() {
use vouch_core::nesting::{self, NO_STD_MAX_NESTING};
let deep = |n: usize| format!("{}1{}", "{\"a\":".repeat(n), "}".repeat(n));
assert!(nesting::parse(&deep(NO_STD_MAX_NESTING)).is_ok());
let refusals = std::thread::Builder::new()
.stack_size(32 * 1024)
.spawn(move || {
let mut out = Vec::new();
out.push(vouch_core::robotics_json::decay_weight(&deep(127), NOW).err());
out.push(nesting::parse(&deep(NO_STD_MAX_NESTING + 1)).err());
out.push(vouch_core::authority_state::parse_json_no_duplicates(&deep(127)).err());
out.push(vouch_core::issuance::issue_json_text(deep(127)).err());
let mut inner = json!(1);
for _ in 0..127 {
let mut m = serde_json::Map::new();
m.insert("a".into(), inner);
inner = Value::Object(m);
}
let mut subject = serde_json::Map::new();
subject.insert("intent".into(), inner);
let mut cred = serde_json::Map::new();
cred.insert("issuer".into(), json!("did:example:x"));
cred.insert("credentialSubject".into(), Value::Object(subject));
let cred = Value::Object(cred);
out.push(credentials::verify(&cred, &[0u8; 32], NOW, 30).err());
out.push(verify_proof(&cred, &[0u8; 32]).err());
std::mem::forget(cred);
out.into_iter()
.map(|e| e.map(|e| e.to_string()))
.collect::<Vec<_>>()
})
.unwrap()
.join()
.unwrap();
let limit = "levels deep, the limit of the no_std build";
for r in &refusals {
assert!(r.as_deref().unwrap_or("").contains(limit), "{refusals:?}");
}
}
#[test]
fn revocation_tree_builds_on_a_small_stack() {
use vouch_core::robotics_dtn::{verify_non_revocation_proof, SparseMerkleTree};
let ok = std::thread::Builder::new()
.stack_size(32 * 1024)
.spawn(|| {
let mut smt = SparseMerkleTree::new();
for i in 0..8 {
smt.revoke(&format!("urn:uuid:{i}"));
}
let root = smt.root();
let proof = smt.non_revocation_proof("urn:uuid:not-revoked");
let revoked = smt.non_revocation_proof("urn:uuid:3");
verify_non_revocation_proof("urn:uuid:not-revoked", &proof, &root)
&& !verify_non_revocation_proof("urn:uuid:3", &revoked, &root)
})
.unwrap()
.join()
.unwrap();
assert!(ok);
}
fn base64_decode(s: &str) -> Vec<u8> {
use base64::{engine::general_purpose::STANDARD, Engine};
STANDARD.decode(s).unwrap()
}