#[allow(unused_imports)]
use crate::prelude::*;
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};
use crate::error::{CoreError, Result};
use crate::jcs;
use crate::keys::{self, Ed25519KeyPair};
pub const CRYPTOSUITE_ID: &str = "eddsa-jcs-2022";
pub const PROOF_TYPE: &str = "DataIntegrityProof";
#[derive(Debug, Clone)]
pub struct BuildProofOptions {
pub verification_method: String,
pub proof_purpose: String,
pub created: String,
}
impl BuildProofOptions {
pub fn new(verification_method: impl Into<String>, created: impl Into<String>) -> Self {
Self {
verification_method: verification_method.into(),
proof_purpose: "assertionMethod".to_string(),
created: created.into(),
}
}
}
fn unsigned_proof(opts: &BuildProofOptions) -> Map<String, Value> {
let mut proof = Map::new();
proof.insert("type".into(), Value::String(PROOF_TYPE.into()));
proof.insert("cryptosuite".into(), Value::String(CRYPTOSUITE_ID.into()));
proof.insert("created".into(), Value::String(opts.created.clone()));
proof.insert(
"verificationMethod".into(),
Value::String(opts.verification_method.clone()),
);
proof.insert(
"proofPurpose".into(),
Value::String(opts.proof_purpose.clone()),
);
proof
}
fn unsecured_document(credential: &Value) -> Result<Value> {
let mut doc = credential.clone();
doc.as_object_mut()
.ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
.remove("proof");
Ok(doc)
}
fn proof_configuration(
document: &Value,
unsigned: &Map<String, Value>,
) -> Result<Map<String, Value>> {
let mut config = unsigned.clone();
config.remove("proofValue");
if !config.contains_key("@context") {
if let Some(ctx) = document.get("@context") {
config.insert("@context".into(), ctx.clone());
}
}
Ok(config)
}
pub fn add_document_context(document: &Value, proof: &mut Map<String, Value>) {
crate::nesting::deep_guard!((); document, proof);
let Some(ctx) = document.get("@context") else {
return;
};
let mut out = Map::new();
out.insert("@context".into(), ctx.clone());
for (k, v) in core::mem::take(proof) {
if k != "@context" {
out.insert(k, v);
}
}
*proof = out;
}
pub fn hash_data(credential: &Value, unsigned: &Map<String, Value>) -> Result<[u8; 64]> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, unsigned);
let document = unsecured_document(credential)?;
let config = proof_configuration(&document, unsigned)?;
let config_hash = Sha256::digest(jcs::canonicalize(&Value::Object(config)));
let document_hash = Sha256::digest(jcs::canonicalize(&document));
let mut out = [0u8; 64];
out[..32].copy_from_slice(&config_hash);
out[32..].copy_from_slice(&document_hash);
Ok(out)
}
pub fn legacy_proof_digest(credential: &Value, unsigned: &Map<String, Value>) -> Result<[u8; 32]> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, unsigned);
let mut with_proof = credential.clone();
with_proof
.as_object_mut()
.ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
.insert("proof".into(), Value::Object(unsigned.clone()));
let canonical = jcs::canonicalize(&with_proof);
let digest = Sha256::digest(&canonical);
Ok(digest.into())
}
pub fn build_proof(
credential: &Value,
raw_private_seed: &[u8],
opts: &BuildProofOptions,
) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let kp = Ed25519KeyPair::from_seed_slice(raw_private_seed)?;
let mut proof = unsigned_proof(opts);
add_document_context(&unsecured_document(credential)?, &mut proof);
let signing_input = hash_data(credential, &proof)?;
let signature = kp.sign(&signing_input);
let proof_value = format!("z{}", bs58::encode(signature).into_string());
proof.insert("proofValue".into(), Value::String(proof_value));
Ok(Value::Object(proof))
}
pub fn sign(
credential: &Value,
raw_private_seed: &[u8],
opts: &BuildProofOptions,
) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let proof = build_proof(credential, raw_private_seed, opts)?;
let mut signed = credential.clone();
signed
.as_object_mut()
.ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
.insert("proof".into(), proof);
Ok(signed)
}
pub fn verify_proof(credential: &Value, raw_public_key: &[u8]) -> Result<bool> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let obj = credential
.as_object()
.ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?;
let proof = obj
.get("proof")
.and_then(|p| p.as_object())
.ok_or_else(|| CoreError::Json("credential has no proof object".into()))?;
match proof.get("type").and_then(|v| v.as_str()) {
Some(PROOF_TYPE) => {}
other => return Err(CoreError::Json(format!("unexpected proof type: {other:?}"))),
}
match proof.get("cryptosuite").and_then(|v| v.as_str()) {
Some(CRYPTOSUITE_ID) => {}
other => {
return Err(CoreError::Json(format!(
"unexpected cryptosuite: {other:?}"
)))
}
}
let proof_value = proof
.get("proofValue")
.and_then(|v| v.as_str())
.ok_or_else(|| CoreError::Json("missing proofValue".into()))?;
let signature = decode_ed25519_proof_value(proof_value)?;
if !proof_context_matches(credential, proof) {
return Ok(false);
}
let mut unsigned = proof.clone();
unsigned.remove("proofValue");
let signing_input = hash_data(credential, &unsigned)?;
if keys::verify(raw_public_key, &signing_input, &signature)? {
return Ok(true);
}
let legacy = legacy_proof_digest(credential, &unsigned)?;
keys::verify(raw_public_key, &legacy, &signature)
}
pub fn decode_ed25519_proof_value(proof_value: &str) -> Result<Vec<u8>> {
let body = proof_value
.strip_prefix('z')
.ok_or_else(|| CoreError::Json("proofValue must be multibase base58btc (z)".into()))?;
let signature = crate::multikey::decode_base58_bounded(body)?;
if signature.len() != keys::ED25519_SIGNATURE_LEN {
return Err(CoreError::InvalidSignatureLength {
expected: keys::ED25519_SIGNATURE_LEN,
got: signature.len(),
});
}
Ok(signature)
}
fn context_values(ctx: &Value) -> Option<&[Value]> {
match ctx {
Value::Null => None,
Value::Array(items) if items.is_empty() => None,
Value::Array(items) => Some(items.as_slice()),
one => Some(core::slice::from_ref(one)),
}
}
pub fn proof_context_matches(document: &Value, proof: &Map<String, Value>) -> bool {
crate::nesting::deep_guard!(false; document, proof);
let Some(ctx) = proof.get("@context") else {
return true;
};
let (Some(want), Some(have)) = (
context_values(ctx),
document.get("@context").and_then(context_values),
) else {
return false;
};
have.len() >= want.len() && have[..want.len()] == *want
}
pub fn verify_with_seed(credential: &Value, raw_private_seed: &[u8]) -> Result<bool> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let kp = Ed25519KeyPair::from_seed_slice(raw_private_seed)?;
verify_proof(credential, &kp.public_key())
}
pub fn proof_verification_method(credential: &Value) -> Result<String> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
credential
.as_object()
.and_then(|o| o.get("proof"))
.and_then(|p| p.as_object())
.and_then(|p| p.get("verificationMethod"))
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.ok_or_else(|| CoreError::Json("proof has no verificationMethod".into()))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn verifies_pre_alignment_credential() {
let public_key = [
0x4c, 0xb5, 0xab, 0xf6, 0xad, 0x79, 0xfb, 0xf5, 0xab, 0xbc, 0xca, 0xfc, 0xc2, 0x69,
0xd8, 0x5c, 0xd2, 0x65, 0x1e, 0xd4, 0xb8, 0x85, 0xb5, 0x86, 0x9f, 0x24, 0x1a, 0xed,
0xf0, 0xa5, 0xba, 0x29,
];
let credential = json!({
"@context": [
"https://www.w3.org/ns/credentials/v2",
"https://vouch-protocol.com/contexts/v1"
],
"type": ["VerifiableCredential", "VouchCredential"],
"issuer": "did:web:test.example.com",
"validFrom": "2026-04-26T10:00:00Z",
"validUntil": "2026-04-26T10:05:00Z",
"credentialSubject": {
"id": "did:web:test.example.com",
"vouchVersion": "1.0",
"intent": {
"action": "read_database",
"target": "users_table",
"resource": "https://api.example.com/v1/users"
}
},
"proof": {
"type": "DataIntegrityProof",
"cryptosuite": "eddsa-jcs-2022",
"created": "2026-04-26T10:00:00Z",
"verificationMethod": "did:web:test.example.com#key-1",
"proofPurpose": "assertionMethod",
"proofValue": "z24FsZHuADF9uwHAfsjW3okmynrNCCN4QkQirEPfEy5MtcXzg4uhFqz4o3RVH57cFvVXg9oarC4m51YEmNu5UQRLQ"
}
});
assert!(verify_proof(&credential, &public_key).expect("verification error"));
}
fn sample_credential() -> Value {
json!({
"@context": ["https://www.w3.org/ns/credentials/v2"],
"type": ["VerifiableCredential", "VouchCredential"],
"issuer": "did:web:agent.example.com",
"validFrom": "2026-04-26T10:00:00Z",
"validUntil": "2026-04-26T10:05:00Z",
"credentialSubject": {
"id": "did:web:agent.example.com",
"vouchVersion": "1.0",
"intent": {
"action": "read_database",
"target": "users_table",
"resource": "https://api.example.com/v1/users"
}
}
})
}
#[test]
fn sign_then_verify_roundtrip() {
let seed = [9u8; 32];
let cred = sample_credential();
let opts =
BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
let signed = sign(&cred, &seed, &opts).unwrap();
assert!(verify_with_seed(&signed, &seed).unwrap());
}
#[test]
fn tamper_fails_verification() {
let seed = [9u8; 32];
let cred = sample_credential();
let opts =
BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
let mut signed = sign(&cred, &seed, &opts).unwrap();
signed["credentialSubject"]["intent"]["action"] = json!("delete_database");
assert!(!verify_with_seed(&signed, &seed).unwrap());
}
#[test]
fn exposes_proof_verification_method() {
let seed = [9u8; 32];
let opts =
BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
let signed = sign(&sample_credential(), &seed, &opts).unwrap();
assert_eq!(
proof_verification_method(&signed).unwrap(),
"did:web:agent.example.com#key-1"
);
assert!(proof_verification_method(&sample_credential()).is_err());
}
#[test]
fn deterministic_proof_value() {
let seed = [9u8; 32];
let cred = sample_credential();
let opts =
BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
let a = build_proof(&cred, &seed, &opts).unwrap();
let b = build_proof(&cred, &seed, &opts).unwrap();
assert_eq!(a["proofValue"], b["proofValue"]);
}
fn did_key_signed(seed: &[u8; 32]) -> Value {
let kp = Ed25519KeyPair::from_seed(seed);
let did = kp.did_key();
let mut cred = sample_credential();
cred["issuer"] = json!(did);
cred["@context"] = json!([
"https://www.w3.org/ns/credentials/v2",
"https://vouch-protocol.com/contexts/v1"
]);
let opts = BuildProofOptions::new(
crate::verification_method::ed25519_method(&did),
"2026-04-26T10:00:00Z",
);
sign(&cred, seed, &opts).unwrap()
}
#[test]
fn a_proof_carries_a_copy_of_the_document_context_first() {
let signed = did_key_signed(&[9u8; 32]);
let proof = signed["proof"].as_object().unwrap();
assert_eq!(proof.keys().next().map(String::as_str), Some("@context"));
assert_eq!(proof["@context"], signed["@context"]);
assert!(verify_with_seed(&signed, &[9u8; 32]).unwrap());
}
#[test]
fn a_document_without_context_gives_a_proof_without_one() {
let mut cred = sample_credential();
cred.as_object_mut().unwrap().remove("@context");
let opts =
BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
let proof = build_proof(&cred, &[9u8; 32], &opts).unwrap();
assert!(proof.get("@context").is_none());
}
#[test]
fn a_proof_without_context_still_verifies() {
let seed = [9u8; 32];
let signed = did_key_signed(&seed);
let mut older = signed.clone();
older["proof"].as_object_mut().unwrap().remove("@context");
assert!(verify_with_seed(&older, &seed).unwrap());
assert_eq!(older["proof"]["proofValue"], signed["proof"]["proofValue"]);
}
#[test]
fn a_tampered_proof_context_fails() {
let seed = [9u8; 32];
let signed = did_key_signed(&seed);
for ctx in [
json!(["https://other.example"]),
json!([
"https://vouch-protocol.com/contexts/v1",
"https://www.w3.org/ns/credentials/v2"
]),
json!([
"https://www.w3.org/ns/credentials/v2",
"https://vouch-protocol.com/contexts/v1",
"https://x"
]),
json!([]),
Value::Null,
json!({}),
] {
let mut bad = signed.clone();
bad["proof"]["@context"] = ctx.clone();
assert!(!verify_with_seed(&bad, &seed).unwrap(), "{ctx}");
}
let mut prefix = signed.clone();
prefix["proof"]["@context"] = json!(["https://www.w3.org/ns/credentials/v2"]);
assert!(!verify_with_seed(&prefix, &seed).unwrap());
}
#[test]
fn a_prefix_proof_context_signed_over_it_verifies() {
let seed = [9u8; 32];
let cred = sample_credential();
let mut unsigned = unsigned_proof(&BuildProofOptions::new(
"did:web:agent.example.com#key-1",
"2026-04-26T10:00:00Z",
));
unsigned.insert(
"@context".into(),
json!(["https://www.w3.org/ns/credentials/v2"]),
);
let mut doc = cred.clone();
doc["@context"] = json!(["https://www.w3.org/ns/credentials/v2", "https://x.example"]);
let input = hash_data(&doc, &unsigned).unwrap();
let sig = Ed25519KeyPair::from_seed(&seed).sign(&input);
unsigned.insert(
"proofValue".into(),
json!(format!("z{}", bs58::encode(sig).into_string())),
);
doc["proof"] = Value::Object(unsigned);
assert!(verify_with_seed(&doc, &seed).unwrap());
doc["@context"] = json!(["https://x.example", "https://www.w3.org/ns/credentials/v2"]);
assert!(!verify_with_seed(&doc, &seed).unwrap());
}
#[test]
fn context_prefix_rule() {
let doc = json!({"@context": ["a", "b"]});
let ok = |ctx: Value| {
let mut p = Map::new();
p.insert("@context".into(), ctx);
proof_context_matches(&doc, &p)
};
assert!(proof_context_matches(&doc, &Map::new()));
assert!(ok(json!(["a", "b"])));
assert!(ok(json!(["a"])));
assert!(ok(json!("a")));
assert!(!ok(json!("b")));
assert!(!ok(json!(["b", "a"])));
assert!(!ok(json!(["a", "b", "c"])));
assert!(!ok(json!([])));
assert!(!ok(Value::Null));
assert!(!proof_context_matches(&json!({}), &{
let mut p = Map::new();
p.insert("@context".into(), json!(["a"]));
p
}));
}
}