vouch-core 4.1.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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
//! Post-quantum credentials as a Data Integrity proof set.
//!
//! The credential carries a `proof` ARRAY of independent proofs: exactly one
//! `eddsa-jcs-2022` proof, and one proof for each post-quantum suite the
//! issuer signs with, `mldsa44-jcs-2024` (ML-DSA-44, FIPS 204) and/or
//! `slhdsa128-jcs-2024` (SLH-DSA-SHA2-128s, FIPS 205). 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 some of
//! the cryptosuites can still check those proofs. Every member a verifier
//! knows must verify for the set to verify ([`verify_set`]); the Ed25519
//! member is always required.
//!
//! One pre-alignment identifier is accepted on verification and never
//! emitted: `mldsa44-jcs-2026`. The v1.6.x composite proof
//! (`hybrid-eddsa-mldsa44-jcs-2026`, one proofValue holding both signatures)
//! is refused by every verifier as of 4.0; such credentials are issued again
//! as a proof set.

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

use crate::data_integrity::{self, BuildProofOptions, PROOF_TYPE};
use crate::error::{CoreError, Result};
use crate::keys::Ed25519KeyPair;
use crate::pq::{self, MlDsa44KeyPair, MLDSA44_SIG_LEN};
use crate::slh::{self, SlhDsa128KeyPair, SLHDSA128_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 W3C Quantum-Resistant Cryptosuites identifier for SLH-DSA-SHA2-128s
/// over JCS.
pub const SLHDSA128_CRYPTOSUITE_ID: &str = "slhdsa128-jcs-2024";

/// Why a proof whose cryptosuite no verifier accepts is refused. The v1.6.x
/// composite `hybrid-eddsa-mldsa44-jcs-2026` proof gets this answer.
pub const REASON_UNSUPPORTED_CRYPTOSUITE: &str = "a proof uses an unsupported cryptosuite";

/// The signature a cryptosuite identifier names.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Suite {
    Eddsa,
    Mldsa44,
    Slhdsa128,
}

impl Suite {
    /// The identifier a new proof of this suite carries.
    pub fn id(self) -> &'static str {
        match self {
            Suite::Eddsa => EDDSA_CRYPTOSUITE_ID,
            Suite::Mldsa44 => MLDSA44_CRYPTOSUITE_ID,
            Suite::Slhdsa128 => SLHDSA128_CRYPTOSUITE_ID,
        }
    }

    /// The suite a cryptosuite identifier names, matched exactly (the
    /// pre-alignment `mldsa44-jcs-2026` is ML-DSA-44). None for every other
    /// identifier, the v1.6.x composite included.
    pub fn of(id: &str) -> Option<Suite> {
        match id {
            EDDSA_CRYPTOSUITE_ID => Some(Suite::Eddsa),
            MLDSA44_CRYPTOSUITE_ID | MLDSA44_LEGACY_CRYPTOSUITE_ID => Some(Suite::Mldsa44),
            SLHDSA128_CRYPTOSUITE_ID => Some(Suite::Slhdsa128),
            _ => None,
        }
    }

    /// The suite of one proof, from its `cryptosuite` member.
    pub fn of_proof(proof: &Value) -> Option<Suite> {
        proof
            .get("cryptosuite")
            .and_then(Value::as_str)
            .and_then(Suite::of)
    }
}

/// The members of a well-formed proof set, by suite.
#[derive(Debug, Clone, Copy)]
pub struct SetMembers<'a> {
    pub eddsa: &'a Value,
    pub mldsa44: Option<&'a Value>,
    pub slhdsa128: Option<&'a Value>,
}

impl SetMembers<'_> {
    /// The suites of the set, in a fixed order.
    pub fn suites(&self) -> Vec<Suite> {
        let mut out = vec![Suite::Eddsa];
        if self.mldsa44.is_some() {
            out.push(Suite::Mldsa44);
        }
        if self.slhdsa128.is_some() {
            out.push(Suite::Slhdsa128);
        }
        out
    }
}

/// Sort the members of a `proof` array by suite. A proof set is exactly one
/// `eddsa-jcs-2022` proof and at least one post-quantum proof, with at most
/// one proof of each post-quantum suite and no proof of any other suite.
/// None for every other array.
pub fn set_members(items: &[Value]) -> Option<SetMembers<'_>> {
    let (mut eddsa, mut mldsa44, mut slhdsa128) = (None, None, None);
    for p in items {
        let slot = match Suite::of_proof(p)? {
            Suite::Eddsa => &mut eddsa,
            Suite::Mldsa44 => &mut mldsa44,
            Suite::Slhdsa128 => &mut slhdsa128,
        };
        if slot.replace(p).is_some() {
            return None; // two proofs of one suite
        }
    }
    if mldsa44.is_none() && slhdsa128.is_none() {
        return None; // no post-quantum member
    }
    Some(SetMembers {
        eddsa: eddsa?,
        mldsa44,
        slhdsa128,
    })
}

/// The suites of a credential's (or a grant's) proof as a verifier counts
/// them: one `eddsa-jcs-2022` proof object is that one suite, a well-formed
/// proof set is its members' suites, anything else is none.
pub fn proof_suites(credential: &Value) -> Vec<Suite> {
    match credential.get("proof") {
        Some(p @ Value::Object(_)) if Suite::of_proof(p) == Some(Suite::Eddsa) => {
            vec![Suite::Eddsa]
        }
        Some(Value::Array(items)) => set_members(items).map(|m| m.suites()).unwrap_or_default(),
        _ => Vec::new(),
    }
}

/// Why a credential whose proofs lack a cryptosuite the verifier requires is
/// refused: a suite named by the verifier's `requireSuites` setting, or a
/// post-quantum suite whose key the caller handed over or the issuer's DID
/// document publishes for assertions.
pub const REASON_REQUIRED_SUITE_MISSING: &str =
    "the credential's proofs do not include a required cryptosuite";

/// What a verifier requires of a credential's proofs beyond the Ed25519
/// proof, which is always required.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Required {
    /// Some post-quantum proof: a single classical proof is refused.
    pub post_quantum: bool,
    /// The ML-DSA-44 proof.
    pub mldsa44: bool,
    /// The SLH-DSA-SHA2-128s proof.
    pub slhdsa128: bool,
}

impl Required {
    /// True when anything post-quantum is required, so a single classical
    /// proof cannot meet it.
    pub fn any(&self) -> bool {
        self.post_quantum || self.mldsa44 || self.slhdsa128
    }

    /// Require a suite by name (`eddsa-jcs-2022` adds nothing: it is always
    /// required).
    pub fn with(mut self, suite: Suite) -> Self {
        match suite {
            Suite::Eddsa => {}
            Suite::Mldsa44 => self.mldsa44 = true,
            Suite::Slhdsa128 => self.slhdsa128 = true,
        }
        self
    }

    /// True when a proof with these suites meets the requirement.
    pub fn met_by(&self, suites: &[Suite]) -> bool {
        let has = |s: Suite| suites.contains(&s);
        has(Suite::Eddsa)
            && (!self.post_quantum || has(Suite::Mldsa44) || has(Suite::Slhdsa128))
            && (!self.mldsa44 || has(Suite::Mldsa44))
            && (!self.slhdsa128 || has(Suite::Slhdsa128))
    }
}

/// Read a verifier's `requireSuites` setting: a list of cryptosuite
/// identifiers (`eddsa-jcs-2022`, `mldsa44-jcs-2024`, `slhdsa128-jcs-2024`),
/// each at most once. Anything else is an error.
pub fn required_suites_from_json(v: &Value) -> Result<Vec<Suite>> {
    let bad = || {
        CoreError::Json(
            "requireSuites must be a list of eddsa-jcs-2022, mldsa44-jcs-2024 or slhdsa128-jcs-2024, each at most once"
                .into(),
        )
    };
    let items = v.as_array().ok_or_else(bad)?;
    let mut out = Vec::new();
    for item in items {
        let suite = match item.as_str() {
            Some(EDDSA_CRYPTOSUITE_ID) => Suite::Eddsa,
            Some(MLDSA44_CRYPTOSUITE_ID) => Suite::Mldsa44,
            Some(SLHDSA128_CRYPTOSUITE_ID) => Suite::Slhdsa128,
            _ => return Err(bad()),
        };
        if out.contains(&suite) {
            return Err(bad());
        }
        out.push(suite);
    }
    Ok(out)
}

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 unsigned_proof(
    cryptosuite: &str,
    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(cryptosuite.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
}

/// A post-quantum key and the verificationMethod its proof names.
pub struct PqSigner<'a, K> {
    pub key: &'a K,
    pub verification_method: &'a str,
}

// Two references: copied whatever the key type is.
impl<K> Clone for PqSigner<'_, K> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<K> Copy for PqSigner<'_, K> {}

/// Build a proof set for `credential`: the `eddsa-jcs-2022` proof first, then
/// an `mldsa44-jcs-2024` proof and an `slhdsa128-jcs-2024` proof for each
/// post-quantum key given, all over the same unsecured document with the same
/// `created`. At least one post-quantum key is required.
pub fn build_proof_set(
    credential: &Value,
    ed25519_seed: &[u8],
    ed25519_verification_method: &str,
    mldsa: Option<PqSigner<'_, MlDsa44KeyPair>>,
    slhdsa: Option<PqSigner<'_, SlhDsa128KeyPair>>,
    created: &str,
) -> Result<Value> {
    if mldsa.is_none() && slhdsa.is_none() {
        return Err(CoreError::Crypto(
            "a proof set needs at least one post-quantum key".into(),
        ));
    }
    let base = strip_proof(credential)?;
    let mut proofs = vec![data_integrity::build_proof(
        &base,
        ed25519_seed,
        &BuildProofOptions::new(ed25519_verification_method, created),
    )?];
    // 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").
    if let Some(ml) = mldsa {
        let mut proof = unsigned_proof(MLDSA44_CRYPTOSUITE_ID, ml.verification_method, created);
        let sig = ml.key.sign(&data_integrity::hash_data(&base, &proof)?)?;
        proof.insert(
            "proofValue".into(),
            Value::String(format!("u{}", URL_SAFE_NO_PAD.encode(sig))),
        );
        proofs.push(Value::Object(proof));
    }
    if let Some(slh) = slhdsa {
        let mut proof = unsigned_proof(SLHDSA128_CRYPTOSUITE_ID, slh.verification_method, created);
        let sig = slh.key.sign(&data_integrity::hash_data(&base, &proof)?)?;
        proof.insert(
            "proofValue".into(),
            Value::String(format!("u{}", URL_SAFE_NO_PAD.encode(sig))),
        );
        proofs.push(Value::Object(proof));
    }
    Ok(Value::Array(proofs))
}

/// Build a proof set ([`build_proof_set`]) and attach it to the credential
/// under `proof`, replacing any existing proof.
pub fn sign_set(
    credential: &Value,
    ed25519_seed: &[u8],
    ed25519_verification_method: &str,
    mldsa: Option<PqSigner<'_, MlDsa44KeyPair>>,
    slhdsa: Option<PqSigner<'_, SlhDsa128KeyPair>>,
    created: &str,
) -> Result<Value> {
    let proof = build_proof_set(
        credential,
        ed25519_seed,
        ed25519_verification_method,
        mldsa,
        slhdsa,
        created,
    )?;
    let mut signed = strip_proof(credential)?;
    signed
        .as_object_mut()
        .unwrap()
        .insert("proof".into(), proof);
    Ok(signed)
}

/// Build a dual proof (an array of two proofs, Ed25519 and ML-DSA-44) 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> {
    build_proof_set(
        credential,
        ed25519_seed,
        ed25519_verification_method,
        Some(PqSigner {
            key: mldsa,
            verification_method: mldsa_verification_method,
        }),
        None,
        created,
    )
}

/// 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> {
    sign_set(
        credential,
        ed25519_seed,
        ed25519_verification_method,
        Some(PqSigner {
            key: mldsa,
            verification_method: mldsa_verification_method,
        }),
        None,
        created,
    )
}

/// Decode a multibase base64url ("u") proofValue strictly: no padding,
/// canonical trailing bits, exactly `expected` bytes.
fn decode_b64u_proof_value(proof_value: &str, expected: usize, name: &str) -> Result<Vec<u8>> {
    let body = proof_value.strip_prefix('u').ok_or_else(|| {
        CoreError::Json(format!("{name} proofValue must be multibase base64url (u)"))
    })?;
    // The longest value read is one that could hold the signature: nothing
    // longer is decoded.
    if body.len() > expected.div_ceil(3) * 4 {
        return Err(CoreError::InvalidSignatureLength {
            expected,
            got: body.len() / 4 * 3,
        });
    }
    // 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() != expected {
        return Err(CoreError::InvalidSignatureLength {
            expected,
            got: sig.len(),
        });
    }
    Ok(sig)
}

/// 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>> {
    decode_b64u_proof_value(proof_value, MLDSA44_SIG_LEN, "ML-DSA-44")
}

/// Decode an SLH-DSA-SHA2-128s proofValue strictly: multibase base64url
/// without padding ('u'), canonical trailing bits, exactly 7856 bytes.
pub fn decode_slhdsa128_proof_value(proof_value: &str) -> Result<Vec<u8>> {
    decode_b64u_proof_value(proof_value, SLHDSA128_SIG_LEN, "SLH-DSA")
}

/// Check one post-quantum member of a set against `base` (the document
/// without its proof): type "DataIntegrityProof", a strict proofValue, the
/// document's @context, and the signature over the 64-byte hashData. An
/// ML-DSA-44 member also verifies over the pre-alignment signing input.
fn verify_pq_member(base: &Value, proof: &Value, suite: Suite, public: &[u8]) -> Result<bool> {
    let name = if suite == Suite::Mldsa44 {
        "ml-dsa"
    } else {
        "slh-dsa"
    };
    let proof_obj = proof
        .as_object()
        .ok_or_else(|| CoreError::Json(format!("{name} proof must be an object")))?;
    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(format!("{name} proof missing proofValue")))?;
    let sig = match suite {
        Suite::Mldsa44 => decode_mldsa44_proof_value(pv)?,
        _ => decode_slhdsa128_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)?;
    if suite == Suite::Slhdsa128 {
        return slh::verify(public, &signing_input, &sig);
    }
    if pq::verify(public, &signing_input, &sig)? {
        return Ok(true);
    }
    let legacy = data_integrity::legacy_proof_digest(base, &unsigned)?;
    pq::verify(public, &legacy, &sig)
}

/// Which members of a set verified, or None when one did not.
struct Seen {
    eddsa: bool,
    mldsa44: bool,
    slhdsa128: bool,
}

fn verify_members(
    credential: &Value,
    ed25519_public: &[u8],
    mldsa_public: Option<&[u8]>,
    slhdsa_public: Option<&[u8]>,
    skip_unkeyed: bool,
) -> Result<Option<Seen>> {
    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()))?;
    // The array must be a proof set and nothing else: exactly one
    // `eddsa-jcs-2022` proof, at least one post-quantum proof, at most one of
    // each post-quantum suite, and no member of any other suite (the v1.6.x
    // composite included). Anything else is refused before a signature is
    // checked, so no member is ever left out of the answer.
    if set_members(proofs).is_none() {
        return Ok(None);
    }
    let base = strip_proof(credential)?;
    let Some(issuer) = crate::credentials::issuer_did(credential) else {
        return Ok(None);
    };

    // 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 seen = Seen {
        eddsa: false,
        mldsa44: false,
        slhdsa128: false,
    };
    for p in proofs {
        if !crate::credentials::proof_bound_to_issuer(p, issuer) {
            return Ok(None);
        }
        match Suite::of_proof(p) {
            Some(Suite::Eddsa) => {
                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(None);
                }
                seen.eddsa = true;
            }
            Some(suite) => {
                // A post-quantum member with no key to check it with fails
                // the set: a proof this verifier knows is never skipped.
                let key = if suite == Suite::Mldsa44 {
                    mldsa_public
                } else {
                    slhdsa_public
                };
                let Some(key) = key else {
                    if skip_unkeyed {
                        continue;
                    }
                    return Ok(None);
                };
                if !verify_pq_member(&base, p, suite, key)? {
                    return Ok(None);
                }
                if suite == Suite::Mldsa44 {
                    seen.mldsa44 = true;
                } else {
                    seen.slhdsa128 = true;
                }
            }
            // set_members let no other suite through.
            None => return Ok(None),
        }
    }
    Ok(Some(seen))
}

/// Verify a proof set with the issuer's keys: the Ed25519 proof and every
/// post-quantum proof in the array MUST validate. Returns Ok(true) only when
/// the array is a proof set ([`set_members`]) and every proof in it verified.
/// A post-quantum proof whose key is not given fails the set. So does an
/// array that is not a proof set: a member of another cryptosuite (the
/// v1.6.x composite included), no `eddsa-jcs-2022` proof or more than one,
/// or two proofs of one post-quantum suite.
///
/// Every member of the set must be bound to the credential's issuer
/// (proofPurpose "assertionMethod" and a verificationMethod of the issuer's
/// DID). A
/// post-quantum member must have type "DataIntegrityProof", its cryptosuite
/// identifier exactly (`mldsa44-jcs-2024`, the pre-alignment
/// `mldsa44-jcs-2026`, or `slhdsa128-jcs-2024`), and a strict proofValue
/// ([`decode_mldsa44_proof_value`], [`decode_slhdsa128_proof_value`]).
pub fn verify_set(
    credential: &Value,
    ed25519_public: &[u8],
    mldsa_public: Option<&[u8]>,
    slhdsa_public: Option<&[u8]>,
) -> Result<bool> {
    Ok(verify_members(
        credential,
        ed25519_public,
        mldsa_public,
        slhdsa_public,
        false,
    )?
    .is_some_and(|seen| seen.eddsa && (seen.mldsa44 || seen.slhdsa128)))
}

/// Verify the members of a proof set a verifier holds keys for: the Ed25519
/// proof must verify, and so must every post-quantum proof whose key is
/// given. A post-quantum proof whose key is not given is left unchecked. For
/// a grant in a delegation chain when post-quantum is not required; a
/// verifier that requires post-quantum uses [`verify_set`].
pub fn verify_set_known_keys(
    credential: &Value,
    ed25519_public: &[u8],
    mldsa_public: Option<&[u8]>,
    slhdsa_public: Option<&[u8]>,
) -> Result<bool> {
    Ok(verify_members(
        credential,
        ed25519_public,
        mldsa_public,
        slhdsa_public,
        true,
    )?
    .is_some_and(|seen| seen.eddsa))
}

/// 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. A set
/// that also carries an SLH-DSA proof fails here, because this call has no
/// key to check it with; use [`verify_set`] for such a set.
pub fn verify_dual(credential: &Value, ed25519_public: &[u8], mldsa_public: &[u8]) -> Result<bool> {
    // 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(
        verify_members(credential, ed25519_public, Some(mldsa_public), None, false)?
            .is_some_and(|seen| seen.eddsa && seen.mldsa44),
    )
}

/// 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())
}

/// The v1.6.x composite proof (one proof whose proofValue is
/// base58btc(ed25519_sig || mldsa44_sig) over the pre-alignment digest), for
/// tests that check every verifier refuses it. Built only in test builds:
/// the core has no way to emit this proof.
#[cfg(test)]
pub(crate) fn composite_for_tests(
    credential: &Value,
    ed25519_seed: &[u8],
    mldsa: &MlDsa44KeyPair,
    verification_method: &str,
    created: &str,
) -> Value {
    let base = strip_proof(credential).unwrap();
    let mut proof = unsigned_proof(
        "hybrid-eddsa-mldsa44-jcs-2026",
        verification_method,
        created,
    );
    let digest = data_integrity::legacy_proof_digest(&base, &proof).unwrap();
    let mut combined = Ed25519KeyPair::from_seed_slice(ed25519_seed)
        .unwrap()
        .sign(&digest)
        .to_vec();
    combined.extend_from_slice(&mldsa.sign(&digest).unwrap());
    proof.insert(
        "proofValue".into(),
        Value::String(format!("z{}", bs58::encode(combined).into_string())),
    );
    let mut signed = base;
    signed["proof"] = Value::Object(proof);
    signed
}

#[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"
        );
    }

    /// The set primitives refuse an array that is not a proof set, whatever
    /// its good members say: a member of another cryptosuite, the v1.6.x
    /// composite, no `eddsa-jcs-2022` proof or two of them, or two proofs of
    /// one post-quantum suite.
    #[test]
    fn an_array_that_is_not_a_proof_set_is_refused() {
        let seed = [4u8; 32];
        let ml = MlDsa44KeyPair::generate().unwrap();
        let vm = "did:web:agent.example.com#key-1";
        let created = "2026-04-26T10:00:00Z";
        let signed = sign_dual(
            &cred(),
            &seed,
            &ml,
            vm,
            "did:web:agent.example.com#key-2",
            created,
        )
        .unwrap();
        let ed_pub = ed25519_public_from_seed(&seed).unwrap();
        let ml_pub = ml.public_key();
        let proofs = signed["proof"].as_array().unwrap().clone();
        let (ed_proof, ml_proof) = (proofs[0].clone(), proofs[1].clone());
        assert!(verify_dual(&signed, &ed_pub, &ml_pub).unwrap());

        let mut future = ed_proof.clone();
        future["cryptosuite"] = json!("some-unregistered-suite-2030");
        // A composite proof with two valid signatures inside.
        let composite = composite_for_tests(&cred(), &seed, &ml, vm, created)["proof"].clone();
        // The pre-alignment identifier is ML-DSA-44 too, so it is a second
        // proof of that suite.
        let mut legacy_ml = ml_proof.clone();
        legacy_ml["cryptosuite"] = json!(MLDSA44_LEGACY_CRYPTOSUITE_ID);

        let cases: Vec<(&str, Value)> = vec![
            (
                "a member of an unknown suite",
                json!([ed_proof, ml_proof, future]),
            ),
            (
                "an unknown suite in place of the post-quantum proof",
                json!([ed_proof, future]),
            ),
            ("a composite member", json!([ed_proof, ml_proof, composite])),
            (
                "a composite member first",
                json!([composite, ed_proof, ml_proof]),
            ),
            ("no eddsa-jcs-2022 proof", json!([ml_proof])),
            (
                "two eddsa-jcs-2022 proofs",
                json!([ed_proof, ed_proof, ml_proof]),
            ),
            (
                "two ML-DSA-44 proofs",
                json!([ed_proof, ml_proof, ml_proof]),
            ),
            (
                "two ML-DSA-44 proofs under both identifiers",
                json!([ed_proof, ml_proof, legacy_ml]),
            ),
            (
                "a member that is not an object",
                json!([ed_proof, ml_proof, "x"]),
            ),
            ("an empty array", json!([])),
        ];
        for (name, proof) in cases {
            let mut c = signed.clone();
            c["proof"] = proof;
            assert!(!verify_dual(&c, &ed_pub, &ml_pub).unwrap(), "{name}");
            assert!(
                !verify_set(&c, &ed_pub, Some(&ml_pub), None).unwrap(),
                "{name}"
            );
            assert!(
                !verify_set_known_keys(&c, &ed_pub, Some(&ml_pub), None).unwrap(),
                "{name}"
            );
            // With no post-quantum key the lenient form checks the Ed25519
            // proof alone, and still refuses the array.
            assert!(
                !verify_set_known_keys(&c, &ed_pub, None, None).unwrap(),
                "{name}"
            );
        }
    }

    #[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());
    }

    fn three(vm: &str) -> (Value, [u8; 32], MlDsa44KeyPair, SlhDsa128KeyPair) {
        let seed = [4u8; 32];
        let ml = MlDsa44KeyPair::generate().unwrap();
        let slh_key = SlhDsa128KeyPair::generate().unwrap();
        let signed = sign_set(
            &cred(),
            &seed,
            &format!("{vm}#key-1"),
            Some(PqSigner {
                key: &ml,
                verification_method: &format!("{vm}#key-2"),
            }),
            Some(PqSigner {
                key: &slh_key,
                verification_method: &format!("{vm}#key-3"),
            }),
            "2026-04-26T10:00:00Z",
        )
        .unwrap();
        (
            signed,
            ed25519_public_from_seed(&seed).unwrap(),
            ml,
            slh_key,
        )
    }

    #[test]
    fn a_set_of_three_needs_every_key_and_every_proof() {
        let (s, ed, ml, slh_key) = three("did:web:agent.example.com");
        let (mlp, slhp) = (ml.public_key(), slh_key.public_key());
        assert_eq!(
            proof_suites(&s),
            [Suite::Eddsa, Suite::Mldsa44, Suite::Slhdsa128]
        );
        assert!(verify_set(&s, &ed, Some(&mlp), Some(&slhp)).unwrap());
        // A post-quantum proof with no key to check it fails the set.
        assert!(!verify_set(&s, &ed, Some(&mlp), None).unwrap());
        assert!(!verify_set(&s, &ed, None, Some(&slhp)).unwrap());
        assert!(!verify_dual(&s, &ed, &mlp).unwrap());
        // Another key pair's SLH-DSA key, and a changed document.
        let other = SlhDsa128KeyPair::generate().unwrap().public_key();
        assert!(!verify_set(&s, &ed, Some(&mlp), Some(&other)).unwrap());
        let mut t = s.clone();
        t["credentialSubject"]["intent"]["action"] = json!("delete");
        assert!(!verify_set(&t, &ed, Some(&mlp), Some(&slhp)).unwrap());
        // The SLH-DSA member's type, suite spelling and proofValue are strict.
        let mut t = s.clone();
        t["proof"][2]["type"] = json!("Ed25519Signature2020");
        assert!(!verify_set(&t, &ed, Some(&mlp), Some(&slhp)).unwrap());
        let pv = s["proof"][2]["proofValue"].as_str().unwrap().to_string();
        let raw = URL_SAFE_NO_PAD.decode(&pv[1..]).unwrap();
        for bad in [
            format!("{pv}="),
            format!("u{}", URL_SAFE_NO_PAD.encode(&raw[..raw.len() - 1])),
            format!("z{}", bs58::encode(&raw[..64]).into_string()),
            format!("u{}", "A".repeat(20_000)),
        ] {
            let mut t = s.clone();
            t["proof"][2]["proofValue"] = json!(bad);
            assert!(verify_set(&t, &ed, Some(&mlp), Some(&slhp)).is_err());
        }
    }

    #[test]
    fn set_shape_and_required_suites() {
        let (s, _, _, _) = three("did:web:agent.example.com");
        let p = s["proof"].as_array().unwrap().clone();
        let shape = |items: Vec<Value>| set_members(&items).map(|m| m.suites());
        assert_eq!(
            shape(vec![p[0].clone(), p[2].clone()]),
            Some(vec![Suite::Eddsa, Suite::Slhdsa128])
        );
        assert_eq!(
            shape(vec![p[2].clone(), p[1].clone(), p[0].clone()]).map(|v| v.len()),
            Some(3)
        );
        // No Ed25519 proof, no post-quantum proof, two of one suite, and an
        // unknown suite are not proof sets.
        assert!(shape(vec![p[1].clone(), p[2].clone()]).is_none());
        assert!(shape(vec![p[0].clone()]).is_none());
        assert!(shape(vec![p[0].clone(), p[2].clone(), p[2].clone()]).is_none());
        let mut composite = p[0].clone();
        composite["cryptosuite"] = json!("hybrid-eddsa-mldsa44-jcs-2026");
        assert!(shape(vec![p[0].clone(), p[1].clone(), composite.clone()]).is_none());
        assert_eq!(Suite::of("hybrid-eddsa-mldsa44-jcs-2026"), None);
        assert!(proof_suites(&json!({ "proof": composite })).is_empty());

        let need = |post_quantum, mldsa44, slhdsa128| Required {
            post_quantum,
            mldsa44,
            slhdsa128,
        };
        let (e, m, sl) = (Suite::Eddsa, Suite::Mldsa44, Suite::Slhdsa128);
        assert!(need(false, false, false).met_by(&[e]));
        assert!(!need(true, false, false).met_by(&[e]));
        assert!(need(true, false, false).met_by(&[e, sl]));
        assert!(!need(false, true, false).met_by(&[e, sl]));
        assert!(!need(false, false, true).met_by(&[e, m]));
        assert!(need(true, true, true).met_by(&[e, m, sl]));
        // The Ed25519 proof is always required.
        assert!(!need(false, false, false).met_by(&[m, sl]));
        assert_eq!(
            Required::default().with(sl).with(e),
            need(false, false, true)
        );

        assert_eq!(
            required_suites_from_json(&json!(["slhdsa128-jcs-2024", "eddsa-jcs-2022"])).unwrap(),
            vec![sl, e]
        );
        for bad in [
            json!("mldsa44-jcs-2024"),
            json!(["mldsa44-jcs-2026"]),
            json!(["hybrid-eddsa-mldsa44-jcs-2026"]),
            json!(["mldsa44-jcs-2024", "mldsa44-jcs-2024"]),
            json!([7]),
        ] {
            assert!(required_suites_from_json(&bad).is_err(), "{bad}");
        }
    }

    #[test]
    fn a_valid_composite_credential_is_refused() {
        // Both signatures in the composite proof are valid; no verifier here
        // reads it.
        let seed = [4u8; 32];
        let ml = MlDsa44KeyPair::generate().unwrap();
        let ed = ed25519_public_from_seed(&seed).unwrap();
        let composite = composite_for_tests(
            &cred(),
            &seed,
            &ml,
            "did:web:agent.example.com#key-1",
            "2026-04-26T10:00:00Z",
        );
        assert!(verify_dual(&composite, &ed, &ml.public_key()).is_err());
        assert!(verify_set(&composite, &ed, Some(&ml.public_key()), None).is_err());
        assert!(data_integrity::verify_proof(&composite, &ed).is_err());
        let opts = crate::delegation::ChainOptions::default();
        for key in [Some(&ml.public_key()[..]), None] {
            let (r, _) = crate::credentials::verify_with_keys(
                &composite,
                &ed,
                key,
                "2026-04-26T10:01:00Z",
                30,
                &opts,
            )
            .unwrap();
            assert!(!r.proof_valid && r.time_valid);
        }
        assert_eq!(
            crate::decision::read_proofs(&composite, "did:web:agent.example.com", 0, 0).err(),
            Some(REASON_UNSUPPORTED_CRYPTOSUITE)
        );
    }
}