vouch-core 3.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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
//! Post-quantum credentials as a Data Integrity proof set.
//!
//! The credential carries a `proof` ARRAY of two independent proofs,
//! `eddsa-jcs-2022` and `mldsa44-jcs-2024`. Each proof is computed over the
//! same unsecured document with only its own proof configuration, and each
//! verifies on its own, so a verifier that understands only one of the two
//! cryptosuites can still check that proof. Both must verify for
//! [`verify_dual`] to succeed.
//!
//! Two pre-alignment shapes are accepted on verification and never emitted:
//! the `mldsa44-jcs-2026` identifier, and the v1.6.x composite
//! `hybrid-eddsa-mldsa44-jcs-2026` whose single proofValue was
//! base58btc(ed25519_sig || mldsa44_sig).

use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use serde_json::{Map, Value};

use crate::data_integrity::{self, legacy_proof_digest, BuildProofOptions, PROOF_TYPE};
use crate::error::{CoreError, Result};
use crate::keys::{self, Ed25519KeyPair};
use crate::pq::{self, MlDsa44KeyPair, MLDSA44_SIG_LEN};

pub const EDDSA_CRYPTOSUITE_ID: &str = "eddsa-jcs-2022";
/// The W3C Quantum-Resistant Cryptosuites identifier for ML-DSA-44 over JCS.
pub const MLDSA44_CRYPTOSUITE_ID: &str = "mldsa44-jcs-2024";
/// Pre-alignment identifier, accepted on verification only.
pub const MLDSA44_LEGACY_CRYPTOSUITE_ID: &str = "mldsa44-jcs-2026";
/// The v1.6.x composite. Accepted on verification only; never emitted.
pub const HYBRID_COMPOSITE_CRYPTOSUITE_ID: &str = "hybrid-eddsa-mldsa44-jcs-2026";

const ED25519_SIG_LEN: usize = 64;

fn strip_proof(credential: &Value) -> Result<Value> {
    let mut base = credential.clone();
    base.as_object_mut()
        .ok_or_else(|| CoreError::Json("credential must be an object".into()))?
        .remove("proof");
    Ok(base)
}

fn mldsa_unsigned_proof(verification_method: &str, created: &str) -> Map<String, Value> {
    let mut p = Map::new();
    p.insert("type".into(), Value::String(PROOF_TYPE.into()));
    p.insert(
        "cryptosuite".into(),
        Value::String(MLDSA44_CRYPTOSUITE_ID.into()),
    );
    p.insert("created".into(), Value::String(created.into()));
    p.insert(
        "verificationMethod".into(),
        Value::String(verification_method.into()),
    );
    p.insert(
        "proofPurpose".into(),
        Value::String("assertionMethod".into()),
    );
    p
}

/// Build a dual proof (an array of two proofs) for `credential`.
pub fn build_dual_proof(
    credential: &Value,
    ed25519_seed: &[u8],
    mldsa: &MlDsa44KeyPair,
    ed25519_verification_method: &str,
    mldsa_verification_method: &str,
    created: &str,
) -> Result<Value> {
    let base = strip_proof(credential)?;

    let ed_proof = data_integrity::build_proof(
        &base,
        ed25519_seed,
        &BuildProofOptions::new(ed25519_verification_method, created),
    )?;

    let mut ml_proof = mldsa_unsigned_proof(mldsa_verification_method, created);
    let ml_signing_input = data_integrity::hash_data(&base, &ml_proof)?;
    let ml_sig = mldsa.sign(&ml_signing_input)?;
    // The Quantum-Resistant Cryptosuites specification encodes proofValue as a
    // base64url-nopad Multibase value ("u"). The classical eddsa-jcs-2022 suite
    // is specified separately and keeps base58btc ("z").
    ml_proof.insert(
        "proofValue".into(),
        Value::String(format!("u{}", URL_SAFE_NO_PAD.encode(ml_sig))),
    );

    Ok(Value::Array(vec![ed_proof, Value::Object(ml_proof)]))
}

/// Build a dual proof and attach it to the credential under `proof`.
pub fn sign_dual(
    credential: &Value,
    ed25519_seed: &[u8],
    mldsa: &MlDsa44KeyPair,
    ed25519_verification_method: &str,
    mldsa_verification_method: &str,
    created: &str,
) -> Result<Value> {
    let proof = build_dual_proof(
        credential,
        ed25519_seed,
        mldsa,
        ed25519_verification_method,
        mldsa_verification_method,
        created,
    )?;
    let mut signed = strip_proof(credential)?;
    signed
        .as_object_mut()
        .unwrap()
        .insert("proof".into(), proof);
    Ok(signed)
}

/// Decode an ML-DSA-44 proofValue strictly: multibase base64url without
/// padding ('u'), canonical trailing bits, exactly 2420 bytes.
pub fn decode_mldsa44_proof_value(proof_value: &str) -> Result<Vec<u8>> {
    let body = proof_value.strip_prefix('u').ok_or_else(|| {
        CoreError::Json("ML-DSA-44 proofValue must be multibase base64url (u)".into())
    })?;
    // URL_SAFE_NO_PAD refuses padding and non-canonical trailing bits.
    let sig = URL_SAFE_NO_PAD
        .decode(body)
        .map_err(|e| CoreError::Json(format!("bad base64url proofValue: {e}")))?;
    if sig.len() != MLDSA44_SIG_LEN {
        return Err(CoreError::InvalidSignatureLength {
            expected: MLDSA44_SIG_LEN,
            got: sig.len(),
        });
    }
    Ok(sig)
}

/// Verify a dual proof: both the Ed25519 and the ML-DSA-44 proofs in the array
/// MUST validate. Returns Ok(true) only if both are present and valid.
///
/// Every member of the set must be bound to the credential's issuer
/// (proofPurpose "assertionMethod" and a verificationMethod of the issuer's
/// DID), including a member of a cryptosuite this verifier does not know. The
/// ML-DSA-44 member must have type "DataIntegrityProof" and the cryptosuite
/// `mldsa44-jcs-2024` (or the pre-alignment `mldsa44-jcs-2026`) exactly, and a
/// strict proofValue ([`decode_mldsa44_proof_value`]).
pub fn verify_dual(credential: &Value, ed25519_public: &[u8], mldsa_public: &[u8]) -> Result<bool> {
    let proofs = credential
        .as_object()
        .and_then(|o| o.get("proof"))
        .and_then(|p| p.as_array())
        .ok_or_else(|| CoreError::Json("dual proof requires a proof array".into()))?;
    let base = strip_proof(credential)?;
    let Some(issuer) = crate::credentials::issuer_did(credential) else {
        return Ok(false);
    };

    // Every proof present in the set must verify. A proof that fails fails the
    // whole set immediately, so a later proof of the same cryptosuite can never
    // overwrite an earlier failure.
    let mut ed_seen = false;
    let mut ml_seen = false;

    for p in proofs {
        if !crate::credentials::proof_bound_to_issuer(p, issuer) {
            return Ok(false);
        }
        let cs = p.get("cryptosuite").and_then(|v| v.as_str());
        match cs {
            Some(EDDSA_CRYPTOSUITE_ID) => {
                let mut c = base.clone();
                c.as_object_mut().unwrap().insert("proof".into(), p.clone());
                if !data_integrity::verify_proof(&c, ed25519_public)? {
                    return Ok(false);
                }
                ed_seen = true;
            }
            Some(MLDSA44_CRYPTOSUITE_ID) | Some(MLDSA44_LEGACY_CRYPTOSUITE_ID) => {
                let proof_obj = p
                    .as_object()
                    .ok_or_else(|| CoreError::Json("ml-dsa proof must be an object".into()))?;
                if proof_obj.get("type").and_then(|v| v.as_str()) != Some(PROOF_TYPE) {
                    return Ok(false);
                }
                let pv = proof_obj
                    .get("proofValue")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| CoreError::Json("ml-dsa proof missing proofValue".into()))?;
                let sig = decode_mldsa44_proof_value(pv)?;
                if !data_integrity::proof_context_matches(&base, proof_obj) {
                    return Ok(false);
                }
                let mut unsigned = proof_obj.clone();
                unsigned.remove("proofValue");
                let signing_input = data_integrity::hash_data(&base, &unsigned)?;
                let mut ok = pq::verify(mldsa_public, &signing_input, &sig)?;
                if !ok {
                    let legacy = data_integrity::legacy_proof_digest(&base, &unsigned)?;
                    ok = pq::verify(mldsa_public, &legacy, &sig)?;
                }
                if !ok {
                    return Ok(false);
                }
                ml_seen = true;
            }
            _ => {}
        }
    }
    // Both members of the set must be present, so a credential cannot drop the
    // post-quantum proof and still be accepted as a proof set.
    Ok(ed_seen && ml_seen)
}

fn composite_unsigned_proof(verification_method: &str, created: &str) -> Map<String, Value> {
    let mut p = Map::new();
    p.insert("type".into(), Value::String(PROOF_TYPE.into()));
    p.insert(
        "cryptosuite".into(),
        Value::String(HYBRID_COMPOSITE_CRYPTOSUITE_ID.into()),
    );
    p.insert("created".into(), Value::String(created.into()));
    p.insert(
        "verificationMethod".into(),
        Value::String(verification_method.into()),
    );
    p.insert(
        "proofPurpose".into(),
        Value::String("assertionMethod".into()),
    );
    p
}

/// Build a v1.6.x composite proof (a single proof whose proofValue is
/// base58btc(ed25519_sig || mldsa44_sig)) for `credential`, using the
/// pre-alignment signing input that format was issued under.
///
/// Retained only so the older wire format can be reproduced for regression
/// checks. New credentials use [`build_dual_proof`], which emits a proof set.
#[deprecated(note = "the composite wire format is verify-only; use build_dual_proof")]
pub fn build_composite(
    credential: &Value,
    ed25519_seed: &[u8],
    mldsa: &MlDsa44KeyPair,
    verification_method: &str,
    created: &str,
) -> Result<Value> {
    let base = strip_proof(credential)?;
    let mut proof = composite_unsigned_proof(verification_method, created);
    let digest = legacy_proof_digest(&base, &proof)?;

    let kp = Ed25519KeyPair::from_seed_slice(ed25519_seed)?;
    let ed_sig = kp.sign(&digest);
    let ml_sig = mldsa.sign(&digest)?;

    let mut combined = Vec::with_capacity(ED25519_SIG_LEN + ml_sig.len());
    combined.extend_from_slice(&ed_sig);
    combined.extend_from_slice(&ml_sig);
    proof.insert(
        "proofValue".into(),
        Value::String(format!("z{}", bs58::encode(combined).into_string())),
    );
    Ok(Value::Object(proof))
}

/// Build a composite proof and attach it to the credential under `proof`,
/// replacing any existing proof. Verify-only wire format, retained for
/// regression checks against credentials issued under v1.6.x.
#[deprecated(note = "the composite wire format is verify-only; use sign_dual")]
#[allow(deprecated)]
pub fn sign_composite(
    credential: &Value,
    ed25519_seed: &[u8],
    mldsa: &MlDsa44KeyPair,
    verification_method: &str,
    created: &str,
) -> Result<Value> {
    let proof = build_composite(
        credential,
        ed25519_seed,
        mldsa,
        verification_method,
        created,
    )?;
    let mut signed = strip_proof(credential)?;
    signed
        .as_object_mut()
        .unwrap()
        .insert("proof".into(), proof);
    Ok(signed)
}

/// Verify a v1.6.x composite hybrid proof (single proof, concatenated
/// proofValue). Both embedded signatures MUST validate, and the proof must be
/// bound to the issuer (proofPurpose "assertionMethod", a verificationMethod
/// of the issuer's DID).
pub fn verify_composite(
    credential: &Value,
    ed25519_public: &[u8],
    mldsa_public: &[u8],
) -> Result<bool> {
    let proof = credential
        .as_object()
        .and_then(|o| o.get("proof"))
        .and_then(|p| p.as_object())
        .ok_or_else(|| CoreError::Json("composite proof must be an object".into()))?;
    if proof.get("cryptosuite").and_then(|v| v.as_str()) != Some(HYBRID_COMPOSITE_CRYPTOSUITE_ID) {
        return Err(CoreError::Json("not a composite hybrid proof".into()));
    }
    if proof.get("type").and_then(|v| v.as_str()) != Some(PROOF_TYPE) {
        return Ok(false);
    }
    match crate::credentials::issuer_did(credential) {
        Some(issuer)
            if crate::credentials::proof_bound_to_issuer(&Value::Object(proof.clone()), issuer) => {
        }
        _ => return Ok(false),
    }
    let pv = proof
        .get("proofValue")
        .and_then(|v| v.as_str())
        .ok_or_else(|| CoreError::Json("missing proofValue".into()))?;
    let body = pv
        .strip_prefix('z')
        .ok_or_else(|| CoreError::Json("proofValue must be base58btc (z)".into()))?;
    let combined = crate::multikey::decode_base58_bounded(body)?;
    if combined.len() != ED25519_SIG_LEN + MLDSA44_SIG_LEN {
        return Ok(false);
    }
    let ed_sig = &combined[..ED25519_SIG_LEN];
    let ml_sig = &combined[ED25519_SIG_LEN..];

    let mut unsigned = proof.clone();
    unsigned.remove("proofValue");
    let base = strip_proof(credential)?;
    let digest = legacy_proof_digest(&base, &unsigned)?;

    Ok(
        keys::verify(ed25519_public, &digest, ed_sig)?
            && pq::verify(mldsa_public, &digest, ml_sig)?,
    )
}

/// Convenience: derive the Ed25519 public key for a dual self-check.
pub fn ed25519_public_from_seed(seed: &[u8]) -> Result<[u8; 32]> {
    Ok(Ed25519KeyPair::from_seed_slice(seed)?.public_key())
}

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

    fn cred() -> 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", "target": "t", "resource": "https://api/x" } }
        })
    }

    #[test]
    fn dual_proof_roundtrip() {
        let seed = [4u8; 32];
        let ml = MlDsa44KeyPair::generate().unwrap();
        let signed = sign_dual(
            &cred(),
            &seed,
            &ml,
            "did:web:agent.example.com#key-1",
            "did:web:agent.example.com#key-2",
            "2026-04-26T10:00:00Z",
        )
        .unwrap();
        assert!(signed["proof"].is_array());
        let ed_pub = ed25519_public_from_seed(&seed).unwrap();
        assert!(verify_dual(&signed, &ed_pub, &ml.public_key()).unwrap());
    }

    #[test]
    fn dual_proof_tamper_fails() {
        let seed = [4u8; 32];
        let ml = MlDsa44KeyPair::generate().unwrap();
        let mut signed = sign_dual(
            &cred(),
            &seed,
            &ml,
            "did:web:agent.example.com#key-1",
            "did:web:agent.example.com#key-2",
            "2026-04-26T10:00:00Z",
        )
        .unwrap();
        signed["credentialSubject"]["intent"]["action"] = json!("delete");
        let ed_pub = ed25519_public_from_seed(&seed).unwrap();
        assert!(!verify_dual(&signed, &ed_pub, &ml.public_key()).unwrap());
    }

    /// A failing proof cannot be masked by appending a second, valid proof of
    /// the same cryptosuite after it.
    #[test]
    fn appended_valid_proof_cannot_mask_a_failing_one() {
        let seed = [4u8; 32];
        let ml = MlDsa44KeyPair::generate().unwrap();
        let signed = sign_dual(
            &cred(),
            &seed,
            &ml,
            "did:web:agent.example.com#key-1",
            "did:web:agent.example.com#key-2",
            "2026-04-26T10:00:00Z",
        )
        .unwrap();
        let ed_pub = ed25519_public_from_seed(&seed).unwrap();
        let proofs = signed["proof"].as_array().unwrap().clone();

        // Corrupt the classical proof, then append the untouched valid one.
        let mut broken = proofs[0].clone();
        broken["proofValue"] = json!("z2SkKQBFXKcxxHbEnDaZjXPRWzHnbe1ZgArebQmqQ1Rf6H3nJa4vp3rzYaC5nnrFVFTL6wPMuJUAQGf7oEENy4vX");

        let mut attacked = signed.clone();
        attacked["proof"] = json!([broken, proofs[0].clone(), proofs[1].clone()]);
        assert!(
            !verify_dual(&attacked, &ed_pub, &ml.public_key()).unwrap(),
            "a failing proof must fail the set even when a valid proof follows it"
        );
    }

    /// A proof set may carry an extra proof for an unrecognized cryptosuite
    /// without breaking a verifier that predates it, as long as both known
    /// members are present and verify.
    #[test]
    fn unrecognized_extra_proof_is_ignored() {
        let seed = [4u8; 32];
        let ml = MlDsa44KeyPair::generate().unwrap();
        let signed = sign_dual(
            &cred(),
            &seed,
            &ml,
            "did:web:agent.example.com#key-1",
            "did:web:agent.example.com#key-2",
            "2026-04-26T10:00:00Z",
        )
        .unwrap();
        let ed_pub = ed25519_public_from_seed(&seed).unwrap();
        let proofs = signed["proof"].as_array().unwrap().clone();

        let mut future = proofs[0].clone();
        future["cryptosuite"] = json!("some-unregistered-suite-2030");

        // Extra unknown proof alongside both known members: still verifies.
        let mut extended = signed.clone();
        extended["proof"] = json!([proofs[0].clone(), proofs[1].clone(), future.clone()]);
        assert!(verify_dual(&extended, &ed_pub, &ml.public_key()).unwrap());

        // The unknown proof cannot substitute for a missing known member.
        let mut ed_only_plus_unknown = signed.clone();
        ed_only_plus_unknown["proof"] = json!([proofs[0].clone(), future]);
        assert!(!verify_dual(&ed_only_plus_unknown, &ed_pub, &ml.public_key()).unwrap());
    }

    /// A proof set that drops the post-quantum member must not verify.
    #[test]
    fn proof_set_without_the_post_quantum_member_fails() {
        let seed = [4u8; 32];
        let ml = MlDsa44KeyPair::generate().unwrap();
        let signed = sign_dual(
            &cred(),
            &seed,
            &ml,
            "did:web:agent.example.com#key-1",
            "did:web:agent.example.com#key-2",
            "2026-04-26T10:00:00Z",
        )
        .unwrap();
        let ed_pub = ed25519_public_from_seed(&seed).unwrap();
        let classical_only = signed["proof"].as_array().unwrap()[0].clone();

        let mut stripped = signed.clone();
        stripped["proof"] = json!([classical_only]);
        assert!(!verify_dual(&stripped, &ed_pub, &ml.public_key()).unwrap());
    }

    fn signed(vm_ed: &str, vm_ml: &str) -> (Value, [u8; 32], MlDsa44KeyPair) {
        let seed = [4u8; 32];
        let ml = MlDsa44KeyPair::generate().unwrap();
        let signed = sign_dual(&cred(), &seed, &ml, vm_ed, vm_ml, "2026-04-26T10:00:00Z").unwrap();
        (signed, ed25519_public_from_seed(&seed).unwrap(), ml)
    }

    #[test]
    fn every_member_must_be_bound_to_the_issuer() {
        let (s, ed, ml) = signed(
            "did:web:agent.example.com#key-1",
            "did:web:other.example.com#key-2",
        );
        assert!(!verify_dual(&s, &ed, &ml.public_key()).unwrap());
        // An unknown extra member that names another DID also fails the set.
        let (s, ed, ml) = signed(
            "did:web:agent.example.com#key-1",
            "did:web:agent.example.com#key-2",
        );
        let mut extra = s["proof"][0].clone();
        extra["cryptosuite"] = json!("some-unregistered-suite-2030");
        extra["verificationMethod"] = json!("did:web:someone-else.example#key-1");
        let mut set = s.clone();
        set["proof"].as_array_mut().unwrap().push(extra);
        assert!(!verify_dual(&set, &ed, &ml.public_key()).unwrap());
    }

    #[test]
    fn mldsa_member_type_and_proof_value_are_strict() {
        let (s, ed, ml) = signed(
            "did:web:agent.example.com#key-1",
            "did:web:agent.example.com#key-2",
        );
        let pk = ml.public_key();
        assert!(verify_dual(&s, &ed, &pk).unwrap());
        let mut t = s.clone();
        t["proof"][1]["type"] = json!("Ed25519Signature2020");
        assert!(!verify_dual(&t, &ed, &pk).unwrap());
        let mut t = s.clone();
        t["proof"][1]["cryptosuite"] = json!("MLDSA44-JCS-2024");
        assert!(
            !verify_dual(&t, &ed, &pk).unwrap(),
            "case-changed suite is not ML-DSA"
        );
        let pv = s["proof"][1]["proofValue"].as_str().unwrap().to_string();
        let raw = URL_SAFE_NO_PAD.decode(&pv[1..]).unwrap();
        // base58btc instead of base64url, padding, a short signature.
        for bad in [
            format!("z{}", bs58::encode(&raw).into_string()),
            format!("{pv}=="),
            format!("u{}", URL_SAFE_NO_PAD.encode(&raw[..2419])),
        ] {
            let mut t = s.clone();
            t["proof"][1]["proofValue"] = json!(bad);
            assert!(verify_dual(&t, &ed, &pk).is_err());
        }
        assert!(decode_mldsa44_proof_value(&pv).is_ok());
    }
}