1use serde_json::{Map, Value};
19use sha2::{Digest, Sha256};
20
21use crate::error::{CoreError, Result};
22use crate::jcs;
23use crate::keys::{self, Ed25519KeyPair};
24
25pub const CRYPTOSUITE_ID: &str = "eddsa-jcs-2022";
26pub const PROOF_TYPE: &str = "DataIntegrityProof";
27
28#[derive(Debug, Clone)]
32pub struct BuildProofOptions {
33 pub verification_method: String,
34 pub proof_purpose: String,
35 pub created: String,
36}
37
38impl BuildProofOptions {
39 pub fn new(verification_method: impl Into<String>, created: impl Into<String>) -> Self {
40 Self {
41 verification_method: verification_method.into(),
42 proof_purpose: "assertionMethod".to_string(),
43 created: created.into(),
44 }
45 }
46}
47
48fn unsigned_proof(opts: &BuildProofOptions) -> Map<String, Value> {
49 let mut proof = Map::new();
53 proof.insert("type".into(), Value::String(PROOF_TYPE.into()));
54 proof.insert("cryptosuite".into(), Value::String(CRYPTOSUITE_ID.into()));
55 proof.insert("created".into(), Value::String(opts.created.clone()));
56 proof.insert(
57 "verificationMethod".into(),
58 Value::String(opts.verification_method.clone()),
59 );
60 proof.insert(
61 "proofPurpose".into(),
62 Value::String(opts.proof_purpose.clone()),
63 );
64 proof
65}
66
67fn unsecured_document(credential: &Value) -> Result<Value> {
69 let mut doc = credential.clone();
70 doc.as_object_mut()
71 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
72 .remove("proof");
73 Ok(doc)
74}
75
76fn proof_configuration(
79 document: &Value,
80 unsigned: &Map<String, Value>,
81) -> Result<Map<String, Value>> {
82 let mut config = unsigned.clone();
83 config.remove("proofValue");
84 if let Some(ctx) = document.get("@context") {
85 config.insert("@context".into(), ctx.clone());
86 }
87 Ok(config)
88}
89
90pub fn hash_data(credential: &Value, unsigned: &Map<String, Value>) -> Result<[u8; 64]> {
94 let document = unsecured_document(credential)?;
95 let config = proof_configuration(&document, unsigned)?;
96
97 let config_hash = Sha256::digest(&jcs::canonicalize(&Value::Object(config)));
98 let document_hash = Sha256::digest(&jcs::canonicalize(&document));
99
100 let mut out = [0u8; 64];
101 out[..32].copy_from_slice(&config_hash);
102 out[32..].copy_from_slice(&document_hash);
103 Ok(out)
104}
105
106pub fn legacy_proof_digest(credential: &Value, unsigned: &Map<String, Value>) -> Result<[u8; 32]> {
111 let mut with_proof = credential.clone();
112 with_proof
113 .as_object_mut()
114 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
115 .insert("proof".into(), Value::Object(unsigned.clone()));
116 let canonical = jcs::canonicalize(&with_proof);
117 let digest = Sha256::digest(&canonical);
118 Ok(digest.into())
119}
120
121pub fn build_proof(
124 credential: &Value,
125 raw_private_seed: &[u8],
126 opts: &BuildProofOptions,
127) -> Result<Value> {
128 let kp = Ed25519KeyPair::from_seed_slice(raw_private_seed)?;
129 let mut proof = unsigned_proof(opts);
130 let signing_input = hash_data(credential, &proof)?;
131 let signature = kp.sign(&signing_input);
132 let proof_value = format!("z{}", bs58::encode(signature).into_string());
133 proof.insert("proofValue".into(), Value::String(proof_value));
134 Ok(Value::Object(proof))
135}
136
137pub fn sign(
140 credential: &Value,
141 raw_private_seed: &[u8],
142 opts: &BuildProofOptions,
143) -> Result<Value> {
144 let proof = build_proof(credential, raw_private_seed, opts)?;
145 let mut signed = credential.clone();
146 signed
147 .as_object_mut()
148 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
149 .insert("proof".into(), proof);
150 Ok(signed)
151}
152
153pub fn verify_proof(credential: &Value, raw_public_key: &[u8]) -> Result<bool> {
163 let obj = credential
164 .as_object()
165 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?;
166 let proof = obj
167 .get("proof")
168 .and_then(|p| p.as_object())
169 .ok_or_else(|| CoreError::Json("credential has no proof object".into()))?;
170
171 match proof.get("type").and_then(|v| v.as_str()) {
172 Some(PROOF_TYPE) => {}
173 other => return Err(CoreError::Json(format!("unexpected proof type: {other:?}"))),
174 }
175 match proof.get("cryptosuite").and_then(|v| v.as_str()) {
176 Some(CRYPTOSUITE_ID) => {}
177 other => {
178 return Err(CoreError::Json(format!(
179 "unexpected cryptosuite: {other:?}"
180 )))
181 }
182 }
183 let proof_value = proof
184 .get("proofValue")
185 .and_then(|v| v.as_str())
186 .ok_or_else(|| CoreError::Json("missing proofValue".into()))?;
187 let body = proof_value
188 .strip_prefix('z')
189 .ok_or_else(|| CoreError::Json("proofValue must be multibase base58btc (z)".into()))?;
190 let signature = crate::multikey::decode_base58_bounded(body)?;
191
192 let mut unsigned = proof.clone();
193 unsigned.remove("proofValue");
194
195 let signing_input = hash_data(credential, &unsigned)?;
196 if keys::verify(raw_public_key, &signing_input, &signature)? {
197 return Ok(true);
198 }
199 let legacy = legacy_proof_digest(credential, &unsigned)?;
202 keys::verify(raw_public_key, &legacy, &signature)
203}
204
205pub fn verify_with_seed(credential: &Value, raw_private_seed: &[u8]) -> Result<bool> {
207 let kp = Ed25519KeyPair::from_seed_slice(raw_private_seed)?;
208 verify_proof(credential, &kp.public_key())
209}
210
211pub fn proof_verification_method(credential: &Value) -> Result<String> {
216 credential
217 .as_object()
218 .and_then(|o| o.get("proof"))
219 .and_then(|p| p.as_object())
220 .and_then(|p| p.get("verificationMethod"))
221 .and_then(|v| v.as_str())
222 .map(|s| s.to_string())
223 .ok_or_else(|| CoreError::Json("proof has no verificationMethod".into()))
224}
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229 use serde_json::json;
230
231 #[test]
234 fn verifies_pre_alignment_credential() {
235 let public_key = [
236 0x4c, 0xb5, 0xab, 0xf6, 0xad, 0x79, 0xfb, 0xf5, 0xab, 0xbc, 0xca, 0xfc, 0xc2, 0x69,
237 0xd8, 0x5c, 0xd2, 0x65, 0x1e, 0xd4, 0xb8, 0x85, 0xb5, 0x86, 0x9f, 0x24, 0x1a, 0xed,
238 0xf0, 0xa5, 0xba, 0x29,
239 ];
240 let credential = json!({
241 "@context": [
242 "https://www.w3.org/ns/credentials/v2",
243 "https://vouch-protocol.com/contexts/v1"
244 ],
245 "type": ["VerifiableCredential", "VouchCredential"],
246 "issuer": "did:web:test.example.com",
247 "validFrom": "2026-04-26T10:00:00Z",
248 "validUntil": "2026-04-26T10:05:00Z",
249 "credentialSubject": {
250 "id": "did:web:test.example.com",
251 "vouchVersion": "1.0",
252 "intent": {
253 "action": "read_database",
254 "target": "users_table",
255 "resource": "https://api.example.com/v1/users"
256 }
257 },
258 "proof": {
259 "type": "DataIntegrityProof",
260 "cryptosuite": "eddsa-jcs-2022",
261 "created": "2026-04-26T10:00:00Z",
262 "verificationMethod": "did:web:test.example.com#key-1",
263 "proofPurpose": "assertionMethod",
264 "proofValue": "z24FsZHuADF9uwHAfsjW3okmynrNCCN4QkQirEPfEy5MtcXzg4uhFqz4o3RVH57cFvVXg9oarC4m51YEmNu5UQRLQ"
265 }
266 });
267 assert!(verify_proof(&credential, &public_key).expect("verification error"));
268 }
269
270 fn sample_credential() -> Value {
271 json!({
272 "@context": ["https://www.w3.org/ns/credentials/v2"],
273 "type": ["VerifiableCredential", "VouchCredential"],
274 "issuer": "did:web:agent.example.com",
275 "validFrom": "2026-04-26T10:00:00Z",
276 "validUntil": "2026-04-26T10:05:00Z",
277 "credentialSubject": {
278 "id": "did:web:agent.example.com",
279 "vouchVersion": "1.0",
280 "intent": {
281 "action": "read_database",
282 "target": "users_table",
283 "resource": "https://api.example.com/v1/users"
284 }
285 }
286 })
287 }
288
289 #[test]
290 fn sign_then_verify_roundtrip() {
291 let seed = [9u8; 32];
292 let cred = sample_credential();
293 let opts =
294 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
295 let signed = sign(&cred, &seed, &opts).unwrap();
296 assert!(verify_with_seed(&signed, &seed).unwrap());
297 }
298
299 #[test]
300 fn tamper_fails_verification() {
301 let seed = [9u8; 32];
302 let cred = sample_credential();
303 let opts =
304 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
305 let mut signed = sign(&cred, &seed, &opts).unwrap();
306 signed["credentialSubject"]["intent"]["action"] = json!("delete_database");
307 assert!(!verify_with_seed(&signed, &seed).unwrap());
308 }
309
310 #[test]
311 fn exposes_proof_verification_method() {
312 let seed = [9u8; 32];
313 let opts =
314 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
315 let signed = sign(&sample_credential(), &seed, &opts).unwrap();
316 assert_eq!(
317 proof_verification_method(&signed).unwrap(),
318 "did:web:agent.example.com#key-1"
319 );
320 assert!(proof_verification_method(&sample_credential()).is_err());
321 }
322
323 #[test]
324 fn deterministic_proof_value() {
325 let seed = [9u8; 32];
326 let cred = sample_credential();
327 let opts =
328 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
329 let a = build_proof(&cred, &seed, &opts).unwrap();
330 let b = build_proof(&cred, &seed, &opts).unwrap();
331 assert_eq!(a["proofValue"], b["proofValue"]);
332 }
333}