sansid 0.1.0

Anonymous age verification with BBS+ proofs and blind issuance
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
//! SansID is a fixed-profile reference implementation for unlinkable attribute proofs.
//!
//! An issuer signs a holder secret, the fixed credential schema, and an attribute predicate. A
//! presentation proves knowledge of that signature while revealing only the schema and predicate.
//! The holder secret remains hidden and the proof is bound to one verifier challenge and origin.

#![forbid(unsafe_code)]

use std::{collections::BTreeMap, fmt, io::Cursor, sync::OnceLock};

use ark_bls12_381::{Bls12_381, Fr, G1Affine};
use ark_ff::{PrimeField, UniformRand};
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use bbs_plus::{
    proof::{PoKOfSignatureG1Proof, PoKOfSignatureG1Protocol},
    setup::{KeypairG2, PublicKeyG2, SignatureParamsG1},
    signature::SignatureG1,
};
use dock_crypto_utils::signature::MessageOrBlinding;
use rand::{RngCore, rngs::OsRng};
use schnorr_pok::{
    compute_random_oracle_challenge,
    discrete_log::{PokPedersenCommitment, PokPedersenCommitmentProtocol},
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha512};
use thiserror::Error;
use url::Url;
use zeroize::Zeroizing;

/// Current SansID wire-protocol version.
pub const PROTOCOL_VERSION: &str = "sansid/1";

/// The only BBS+ ciphersuite and profile accepted by this implementation.
pub const CIPHERSUITE: &str = "BBS+-BLS12-381-SHA-512-SANSID-1";

const SCHEMA_ID: &str = "org.sansid.age-over-18/1";
const PARAMETER_LABEL: &[u8] = b"SansID BBS+ public parameters v1";
const HOLDER_SECRET_LABEL: &[u8] = b"SansID holder secret scalar v1";
const SCHEMA_LABEL: &[u8] = b"SansID credential schema scalar v1";
const PREDICATE_LABEL: &[u8] = b"SansID predicate scalar v1";
const KEY_ID_LABEL: &[u8] = b"SansID issuer key identifier v1";
const TRANSCRIPT_LABEL: &[u8] = b"SansID BBS+ presentation transcript v1";
const ISSUANCE_TRANSCRIPT_LABEL: &[u8] = b"SansID blind issuance transcript v1";
const MESSAGE_COUNT: u32 = 3;
const HOLDER_SECRET_INDEX: usize = 0;
const SCHEMA_INDEX: usize = 1;
const PREDICATE_INDEX: usize = 2;
const NONCE_BYTES: usize = 32;
const MAX_PRESENTATION_JSON_BYTES: usize = 8 * 1024;
const MAX_PROOF_BYTES: usize = 2 * 1024;
const MAX_PUBLIC_KEY_BYTES: usize = 256;

/// Errors returned while creating, encoding, or verifying SansID protocol values.
#[derive(Debug, Error)]
pub enum SansIdError {
    /// A verifier challenge was not exactly 32 bytes.
    #[error("a verifier nonce must be exactly 32 bytes")]
    InvalidNonceLength,

    /// An origin was malformed or did not identify an HTTPS origin.
    #[error(
        "an origin must be a canonical HTTPS origin without credentials, path, query, or fragment"
    )]
    InvalidOrigin,

    /// A presentation was received for a different request.
    #[error("presentation does not match the verifier request")]
    RequestMismatch,

    /// A credential was asked to satisfy an attribute it does not contain.
    #[error("credential does not satisfy the requested predicate")]
    PredicateMismatch,

    /// A presentation uses a different protocol profile.
    #[error("presentation uses an unsupported SansID protocol profile")]
    UnsupportedProfile,

    /// A presentation did not contain valid base64url or canonical cryptographic bytes.
    #[error("presentation contains malformed encoded data")]
    InvalidEncoding,

    /// A presentation exceeded the fixed input limits.
    #[error("presentation exceeds the protocol input limits")]
    PresentationTooLarge,

    /// The presentation did not contain the verifier's configured issuer key.
    #[error("presentation issuer key is not trusted for this verification")]
    UntrustedIssuer,

    /// A supplied issuer public key was not a valid BBS+ group element.
    #[error("issuer public key is invalid")]
    InvalidIssuerKey,

    /// The zero-knowledge proof did not verify.
    #[error("zero-knowledge proof verification failed")]
    InvalidProof,

    /// The holder did not prove knowledge of the secret committed during issuance.
    #[error("holder secret commitment proof verification failed")]
    InvalidIssuanceProof,

    /// The BBS+ operation failed while producing a new credential or proof.
    #[error("BBS+ operation failed")]
    Crypto,

    /// Canonical serialization failed.
    #[error("canonical serialization failed")]
    Serialization,

    /// JSON encoding or decoding failed.
    #[error("JSON encoding or decoding failed")]
    Json,
}

/// The attribute predicates supported by the fixed SansID v1 schema.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum Predicate {
    /// The issuer has attested that the holder is at least eighteen years old.
    #[serde(rename = "age_over_18")]
    AgeOver18,
}

impl Predicate {
    fn as_bytes(self) -> &'static [u8] {
        match self {
            Self::AgeOver18 => b"age_over_18",
        }
    }
}

impl fmt::Display for Predicate {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(std::str::from_utf8(self.as_bytes()).expect("static UTF-8 predicate"))
    }
}

/// A canonical HTTPS origin approved by the holder for one presentation.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Origin(String);

impl Origin {
    /// Parses and canonicalizes an HTTPS origin.
    pub fn parse(value: &str) -> Result<Self, SansIdError> {
        if value.len() > 255 {
            return Err(SansIdError::InvalidOrigin);
        }

        let parsed = Url::parse(value).map_err(|_| SansIdError::InvalidOrigin)?;
        if parsed.scheme() != "https"
            || parsed.host().is_none()
            || !parsed.username().is_empty()
            || parsed.password().is_some()
            || parsed.query().is_some()
            || parsed.fragment().is_some()
            || parsed.path() != "/"
        {
            return Err(SansIdError::InvalidOrigin);
        }

        Ok(Self(parsed.origin().ascii_serialization()))
    }

    /// Returns the canonical serialized origin.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl TryFrom<&str> for Origin {
    type Error = SansIdError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

/// A verifier-supplied request that authorizes exactly one presentation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProofRequest {
    origin: Origin,
    predicate: Predicate,
    nonce: [u8; NONCE_BYTES],
}

impl ProofRequest {
    /// Creates a request from a canonical HTTPS origin and an exactly 32-byte random nonce.
    pub fn new(
        origin: impl AsRef<str>,
        predicate: Predicate,
        nonce: &[u8],
    ) -> Result<Self, SansIdError> {
        let nonce: [u8; NONCE_BYTES] =
            nonce.try_into().map_err(|_| SansIdError::InvalidNonceLength)?;
        Ok(Self { origin: Origin::parse(origin.as_ref())?, predicate, nonce })
    }

    /// Creates a request from a base64url-encoded verifier nonce.
    pub fn from_base64(
        origin: impl AsRef<str>,
        predicate: Predicate,
        nonce: &str,
    ) -> Result<Self, SansIdError> {
        let decoded = decode_base64(nonce, NONCE_BYTES)?;
        Self::new(origin, predicate, &decoded)
    }

    /// Returns the HTTPS origin to which the proof is bound.
    #[must_use]
    pub fn origin(&self) -> &Origin {
        &self.origin
    }

    /// Returns the requested predicate.
    #[must_use]
    pub fn predicate(&self) -> Predicate {
        self.predicate
    }

    /// Returns the verifier nonce encoded as unpadded base64url.
    #[must_use]
    pub fn nonce_base64(&self) -> String {
        URL_SAFE_NO_PAD.encode(self.nonce)
    }
}

/// A 256-bit holder secret released by an approved holder-secret provider.
///
/// A deployment releases this value only after native hardware authorization and zeroizes it after
/// presentation. The development provider in this crate keeps it in memory solely for examples.
#[derive(Clone)]
pub struct HolderSecret(Zeroizing<[u8; NONCE_BYTES]>);

impl HolderSecret {
    /// Generates a fresh secret from the operating system random number generator.
    #[must_use]
    pub fn generate() -> Self {
        let mut bytes = [0_u8; NONCE_BYTES];
        OsRng.fill_bytes(&mut bytes);
        Self(Zeroizing::new(bytes))
    }

    /// Imports a secret for a hardware-backed key-provider adapter.
    ///
    /// The caller must not use an ordinary application database as that adapter.
    pub fn from_bytes(bytes: [u8; NONCE_BYTES]) -> Result<Self, SansIdError> {
        if bytes.iter().all(|byte| *byte == 0) {
            return Err(SansIdError::InvalidEncoding);
        }
        Ok(Self(Zeroizing::new(bytes)))
    }

    fn scalar(&self) -> Fr {
        scalar_from_bytes(HOLDER_SECRET_LABEL, self.0.as_ref())
    }

    /// Commits to this holder secret for blind issuance by a trusted issuer.
    ///
    /// Only the commitment and its proof of knowledge are sent to the issuer. This method consumes
    /// the secret so it remains paired with the signature blinding until issuance is completed.
    pub fn begin_issuance(
        self,
        issuer: &IssuerPublicKey,
        challenge: &IssuanceChallenge,
    ) -> Result<IssuanceRequest, SansIdError> {
        let secret_scalar = self.scalar();
        let signature_blinding = Fr::rand(&mut OsRng);
        let commitment = parameters()
            .commit_to_messages([(HOLDER_SECRET_INDEX, &secret_scalar)], &signature_blinding)
            .map_err(|_| SansIdError::Crypto)?;

        let knowledge_protocol = PokPedersenCommitmentProtocol::init(
            secret_scalar,
            Fr::rand(&mut OsRng),
            &parameters().h[HOLDER_SECRET_INDEX],
            signature_blinding,
            Fr::rand(&mut OsRng),
            &parameters().h_0,
        );
        let proof_challenge =
            issuance_protocol_challenge(&knowledge_protocol, &commitment, issuer, challenge)?;

        Ok(IssuanceRequest {
            commitment,
            knowledge_proof: knowledge_protocol.gen_proof(&proof_challenge),
            holder_secret: self,
            signature_blinding,
            issuer_public_key: issuer.clone(),
        })
    }
}

/// The platform boundary that authorizes release of a holder secret.
///
/// The values identify the native integration used to protect the credential envelope. They do not
/// claim that the native hardware directly runs BLS12-381 proof arithmetic.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum HolderKeyBackend {
    /// In-memory development material. This must never be selected for a real holder profile.
    DevelopmentMemory,
    /// A TPM 2.0-backed key on Linux or another TPM-capable desktop platform.
    Tpm2,
    /// Windows CNG through the Microsoft Platform Crypto Provider.
    WindowsPlatformCryptoProvider,
    /// Apple Keychain access control with a Secure Enclave key.
    AppleSecureEnclave,
    /// Android Keystore with Trusted Environment or StrongBox protection.
    AndroidKeystore,
    /// A PKCS#11 token such as a smart card, YubiKey PIV applet, or network HSM.
    Pkcs11,
}

/// Supplies the holder secret after platform-native authorization.
///
/// A provider stores an encrypted credential envelope and uses a non-exportable native key to
/// authorize its release. The resulting `HolderSecret` exists only long enough to create one BBS+
/// presentation and is zeroized on drop. See `docs/platform-integration.md` for the native adapter
/// contract on each operating system.
pub trait HolderSecretProvider {
    /// Returns the protection backend used by this provider.
    fn backend(&self) -> HolderKeyBackend;

    /// Obtains user authorization and returns the secret for one proof request.
    fn unlock_for_presentation(&self, request: &ProofRequest) -> Result<HolderSecret, SansIdError>;
}

impl HolderSecretProvider for HolderSecret {
    fn backend(&self) -> HolderKeyBackend {
        HolderKeyBackend::DevelopmentMemory
    }

    fn unlock_for_presentation(
        &self,
        _request: &ProofRequest,
    ) -> Result<HolderSecret, SansIdError> {
        Ok(self.clone())
    }
}

/// A one-time 32-byte nonce that binds a blind-issuance request to an issuer session.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IssuanceChallenge([u8; NONCE_BYTES]);

impl IssuanceChallenge {
    fn generate() -> Self {
        let mut nonce = [0_u8; NONCE_BYTES];
        OsRng.fill_bytes(&mut nonce);
        Self(nonce)
    }
}

/// A holder-created blind issuance request.
///
/// The private holder secret and signature blinding never leave this value's holder-side state.
/// The issuer consumes only the commitment and proof of knowledge represented by this API.
pub struct IssuanceRequest {
    commitment: G1Affine,
    knowledge_proof: PokPedersenCommitment<G1Affine>,
    holder_secret: HolderSecret,
    signature_blinding: Fr,
    issuer_public_key: IssuerPublicKey,
}

impl IssuanceRequest {
    /// Unblinds and verifies the issuer response before returning provisioned credential material.
    pub fn complete(self, response: BlindCredential) -> Result<ProvisionedCredential, SansIdError> {
        if response.issuer_public_key != self.issuer_public_key {
            return Err(SansIdError::UntrustedIssuer);
        }

        let signature = response.signature.unblind(&self.signature_blinding);
        let messages = credential_messages(&self.holder_secret, response.predicate);
        signature
            .verify(&messages, response.issuer_public_key.key.clone(), parameters().clone())
            .map_err(|_| SansIdError::InvalidProof)?;

        Ok(ProvisionedCredential {
            credential: Credential {
                signature,
                predicate: response.predicate,
                issuer_public_key: response.issuer_public_key,
            },
            holder_secret: self.holder_secret,
        })
    }
}

/// An issuer response carrying a BBS+ signature that remains blinded to the holder secret.
pub struct BlindCredential {
    signature: SignatureG1<Bls12_381>,
    predicate: Predicate,
    issuer_public_key: IssuerPublicKey,
}

/// A public issuer key and its deterministic SansID key identifier.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IssuerPublicKey {
    key: PublicKeyG2<Bls12_381>,
    key_id: String,
}

impl IssuerPublicKey {
    /// Parses a canonical issuer public key received as unpadded base64url.
    pub fn from_base64(value: &str) -> Result<Self, SansIdError> {
        let bytes = decode_base64(value, MAX_PUBLIC_KEY_BYTES)?;
        let key = canonical_decode::<PublicKeyG2<Bls12_381>>(&bytes)?;
        if !key.is_valid() {
            return Err(SansIdError::InvalidIssuerKey);
        }
        Self::from_key(key)
    }

    fn from_key(key: PublicKeyG2<Bls12_381>) -> Result<Self, SansIdError> {
        let bytes = canonical_encode(&key)?;
        let key_id = URL_SAFE_NO_PAD.encode(hash_bytes(KEY_ID_LABEL, &bytes));
        Ok(Self { key, key_id })
    }

    /// Returns the stable identifier for this public issuer key.
    #[must_use]
    pub fn key_id(&self) -> &str {
        &self.key_id
    }

    /// Returns this issuer public key as canonical unpadded base64url.
    pub fn to_base64(&self) -> Result<String, SansIdError> {
        Ok(URL_SAFE_NO_PAD.encode(canonical_encode(&self.key)?))
    }
}

/// An issuer able to create credentials under one public key.
///
/// Keep this object inside a hardened issuer boundary. It is intentionally not serializable.
pub struct Issuer {
    keypair: KeypairG2<Bls12_381>,
    public_key: IssuerPublicKey,
}

impl Issuer {
    /// Creates a fresh issuer signing key using operating system randomness.
    pub fn generate() -> Result<Self, SansIdError> {
        let keypair = KeypairG2::<Bls12_381>::generate_using_rng(&mut OsRng, parameters());
        let public_key = IssuerPublicKey::from_key(keypair.public_key.clone())?;
        Ok(Self { keypair, public_key })
    }

    /// Returns the public key that verifiers pin through their issuer trust configuration.
    #[must_use]
    pub fn public_key(&self) -> &IssuerPublicKey {
        &self.public_key
    }

    /// Generates a nonce for one blind-issuance session.
    ///
    /// The issuer must keep this challenge server-side and accept it only once.
    #[must_use]
    pub fn issuance_challenge(&self) -> IssuanceChallenge {
        IssuanceChallenge::generate()
    }

    /// Blindly issues an age credential after independent real-world verification.
    ///
    /// The issuer verifies proof of knowledge for the hidden holder-secret commitment before
    /// signing it with the fixed schema and predicate messages.
    pub fn blind_issue(
        &self,
        request: &IssuanceRequest,
        challenge: &IssuanceChallenge,
        predicate: Predicate,
    ) -> Result<BlindCredential, SansIdError> {
        if request.issuer_public_key != self.public_key {
            return Err(SansIdError::UntrustedIssuer);
        }
        let proof_challenge = issuance_proof_challenge(
            &request.knowledge_proof,
            &request.commitment,
            &self.public_key,
            challenge,
        )?;
        if !request.knowledge_proof.verify(
            &request.commitment,
            &parameters().h[HOLDER_SECRET_INDEX],
            &parameters().h_0,
            &proof_challenge,
        ) {
            return Err(SansIdError::InvalidIssuanceProof);
        }

        let messages = issued_messages(predicate);
        let signature = SignatureG1::<Bls12_381>::new_with_committed_messages(
            &mut OsRng,
            &request.commitment,
            BTreeMap::from([(SCHEMA_INDEX, &messages[0]), (PREDICATE_INDEX, &messages[1])]),
            &self.keypair.secret_key,
            parameters(),
        )
        .map_err(|_| SansIdError::Crypto)?;

        Ok(BlindCredential { signature, predicate, issuer_public_key: self.public_key.clone() })
    }
}

/// The public BBS+ credential kept in a holder's encrypted credential envelope.
pub struct Credential {
    signature: SignatureG1<Bls12_381>,
    predicate: Predicate,
    issuer_public_key: IssuerPublicKey,
}

impl Credential {
    /// Creates a fresh proof for one verifier request after a provider releases the holder secret.
    pub fn present_with_provider<P: HolderSecretProvider>(
        &self,
        provider: &P,
        request: &ProofRequest,
    ) -> Result<Presentation, SansIdError> {
        let holder_secret = provider.unlock_for_presentation(request)?;
        self.present(&holder_secret, request)
    }

    /// Creates a fresh proof for one verifier request using an authorized holder secret.
    pub fn present(
        &self,
        holder_secret: &HolderSecret,
        request: &ProofRequest,
    ) -> Result<Presentation, SansIdError> {
        if self.predicate != request.predicate {
            return Err(SansIdError::PredicateMismatch);
        }

        let messages = credential_messages(holder_secret, self.predicate);
        let message_proof_inputs = [
            MessageOrBlinding::BlindMessageRandomly(&messages[HOLDER_SECRET_INDEX]),
            MessageOrBlinding::RevealMessage(&messages[SCHEMA_INDEX]),
            MessageOrBlinding::RevealMessage(&messages[PREDICATE_INDEX]),
        ];
        let protocol = PoKOfSignatureG1Protocol::<Bls12_381>::init(
            &mut OsRng,
            &self.signature,
            parameters(),
            message_proof_inputs,
        )
        .map_err(|_| SansIdError::Crypto)?;
        let challenge = protocol_challenge(&protocol, request, &self.issuer_public_key)?;
        let proof = protocol.gen_proof(&challenge).map_err(|_| SansIdError::Crypto)?;

        Ok(Presentation {
            protocol_version: PROTOCOL_VERSION.to_owned(),
            ciphersuite: CIPHERSUITE.to_owned(),
            schema: SCHEMA_ID.to_owned(),
            predicate: self.predicate,
            origin: request.origin.clone(),
            nonce: request.nonce_base64(),
            issuer_key_id: self.issuer_public_key.key_id().to_owned(),
            issuer_public_key: self.issuer_public_key.to_base64()?,
            proof: URL_SAFE_NO_PAD.encode(canonical_encode(&proof)?),
        })
    }
}

/// Credential material returned after blind issuance.
///
/// Install the public credential in an encrypted credential envelope and install the secret through
/// a `HolderSecretProvider` backed by the selected operating-system key facility.
pub struct ProvisionedCredential {
    credential: Credential,
    holder_secret: HolderSecret,
}

impl ProvisionedCredential {
    /// Splits newly issued material for installation into a credential envelope and secret provider.
    #[must_use]
    pub fn into_parts(self) -> (Credential, HolderSecret) {
        (self.credential, self.holder_secret)
    }
}

/// The complete wire value sent from a holder to a verifier backend.
///
/// All fields are public. It intentionally contains no holder identifier, account identifier,
/// birthdate, document image, signature, or holder secret.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Presentation {
    /// Protocol version, fixed to `sansid/1`.
    pub protocol_version: String,
    /// Ciphersuite profile, fixed to `BBS+-BLS12-381-SHA-512-SANSID-1`.
    pub ciphersuite: String,
    /// Credential schema, fixed to `org.sansid.age-over-18/1`.
    pub schema: String,
    /// Predicate revealed by this presentation.
    pub predicate: Predicate,
    /// HTTPS origin approved by the holder and bound to the proof transcript.
    pub origin: Origin,
    /// Verifier nonce as unpadded base64url.
    pub nonce: String,
    /// Deterministic identifier for the issuer public key.
    pub issuer_key_id: String,
    /// Canonical issuer public key as unpadded base64url. Verifiers must pin and compare it.
    pub issuer_public_key: String,
    /// Canonical BBS+ proof as unpadded base64url.
    pub proof: String,
}

impl Presentation {
    /// Encodes the presentation for browser-to-backend transport.
    pub fn to_json(&self) -> Result<String, SansIdError> {
        serde_json::to_string(self).map_err(|_| SansIdError::Json)
    }

    /// Decodes a bounded JSON presentation and applies structural input checks.
    pub fn from_json(value: &str) -> Result<Self, SansIdError> {
        if value.len() > MAX_PRESENTATION_JSON_BYTES {
            return Err(SansIdError::PresentationTooLarge);
        }
        let presentation: Self = serde_json::from_str(value).map_err(|_| SansIdError::Json)?;
        presentation.validate_structure()?;
        Ok(presentation)
    }

    fn validate_structure(&self) -> Result<(), SansIdError> {
        if self.protocol_version != PROTOCOL_VERSION
            || self.ciphersuite != CIPHERSUITE
            || self.schema != SCHEMA_ID
        {
            return Err(SansIdError::UnsupportedProfile);
        }
        if Origin::parse(self.origin.as_str())? != self.origin {
            return Err(SansIdError::InvalidOrigin);
        }
        if decode_base64(&self.nonce, NONCE_BYTES)?.len() != NONCE_BYTES {
            return Err(SansIdError::InvalidNonceLength);
        }
        decode_base64(&self.issuer_public_key, MAX_PUBLIC_KEY_BYTES)?;
        decode_base64(&self.proof, MAX_PROOF_BYTES)?;
        Ok(())
    }
}

/// Verifies one presentation against a verifier's fresh request and trusted issuer key.
///
/// A verifier must issue a new unpredictable request nonce for every attempt, keep it server-side,
/// and atomically mark it consumed after a successful verification.
pub fn verify(
    presentation: &Presentation,
    request: &ProofRequest,
    trusted_issuer: &IssuerPublicKey,
) -> Result<(), SansIdError> {
    presentation.validate_structure()?;
    if presentation.predicate != request.predicate
        || presentation.origin != request.origin
        || presentation.nonce != request.nonce_base64()
    {
        return Err(SansIdError::RequestMismatch);
    }
    if presentation.issuer_key_id != trusted_issuer.key_id() {
        return Err(SansIdError::UntrustedIssuer);
    }

    let supplied_issuer = IssuerPublicKey::from_base64(&presentation.issuer_public_key)?;
    if supplied_issuer != *trusted_issuer {
        return Err(SansIdError::UntrustedIssuer);
    }

    let proof_bytes = decode_base64(&presentation.proof, MAX_PROOF_BYTES)?;
    let proof = canonical_decode::<PoKOfSignatureG1Proof<Bls12_381>>(&proof_bytes)?;
    let challenge = proof_challenge(&proof, request, trusted_issuer)?;
    let revealed_messages = revealed_messages(request.predicate);
    proof
        .verify(&revealed_messages, &challenge, trusted_issuer.key.clone(), parameters().clone())
        .map_err(|_| SansIdError::InvalidProof)
}

fn parameters() -> &'static SignatureParamsG1<Bls12_381> {
    static PARAMETERS: OnceLock<SignatureParamsG1<Bls12_381>> = OnceLock::new();
    PARAMETERS.get_or_init(|| {
        SignatureParamsG1::<Bls12_381>::new::<Sha512>(PARAMETER_LABEL, MESSAGE_COUNT)
    })
}

fn credential_messages(
    secret: &HolderSecret,
    predicate: Predicate,
) -> [Fr; MESSAGE_COUNT as usize] {
    [secret.scalar(), issued_messages(predicate)[0], issued_messages(predicate)[1]]
}

fn issued_messages(predicate: Predicate) -> [Fr; 2] {
    [
        scalar_from_bytes(SCHEMA_LABEL, SCHEMA_ID.as_bytes()),
        scalar_from_bytes(PREDICATE_LABEL, predicate.as_bytes()),
    ]
}

fn revealed_messages(predicate: Predicate) -> BTreeMap<usize, Fr> {
    BTreeMap::from([
        (SCHEMA_INDEX, scalar_from_bytes(SCHEMA_LABEL, SCHEMA_ID.as_bytes())),
        (PREDICATE_INDEX, scalar_from_bytes(PREDICATE_LABEL, predicate.as_bytes())),
    ])
}

fn protocol_challenge(
    protocol: &PoKOfSignatureG1Protocol<Bls12_381>,
    request: &ProofRequest,
    issuer: &IssuerPublicKey,
) -> Result<Fr, SansIdError> {
    let mut transcript = transcript_prefix(request, issuer)?;
    PoKOfSignatureG1Protocol::compute_challenge_contribution(
        &protocol.A_prime,
        &protocol.A_bar,
        &protocol.d,
        &protocol.sc_comm_1.t,
        &protocol.sc_comm_2.t,
        &revealed_messages(request.predicate),
        parameters(),
        &mut transcript,
    )
    .map_err(|_| SansIdError::Crypto)?;
    Ok(compute_random_oracle_challenge::<Fr, Sha512>(&transcript))
}

fn proof_challenge(
    proof: &PoKOfSignatureG1Proof<Bls12_381>,
    request: &ProofRequest,
    issuer: &IssuerPublicKey,
) -> Result<Fr, SansIdError> {
    let mut transcript = transcript_prefix(request, issuer)?;
    proof
        .challenge_contribution(
            &revealed_messages(request.predicate),
            parameters(),
            &mut transcript,
        )
        .map_err(|_| SansIdError::InvalidProof)?;
    Ok(compute_random_oracle_challenge::<Fr, Sha512>(&transcript))
}

fn issuance_protocol_challenge(
    protocol: &PokPedersenCommitmentProtocol<G1Affine>,
    commitment: &G1Affine,
    issuer: &IssuerPublicKey,
    challenge: &IssuanceChallenge,
) -> Result<Fr, SansIdError> {
    let mut transcript = issuance_transcript_prefix(issuer, challenge)?;
    protocol
        .challenge_contribution(
            &parameters().h[HOLDER_SECRET_INDEX],
            &parameters().h_0,
            commitment,
            &mut transcript,
        )
        .map_err(|_| SansIdError::Crypto)?;
    Ok(compute_random_oracle_challenge::<Fr, Sha512>(&transcript))
}

fn issuance_proof_challenge(
    proof: &PokPedersenCommitment<G1Affine>,
    commitment: &G1Affine,
    issuer: &IssuerPublicKey,
    challenge: &IssuanceChallenge,
) -> Result<Fr, SansIdError> {
    let mut transcript = issuance_transcript_prefix(issuer, challenge)?;
    proof
        .challenge_contribution(
            &parameters().h[HOLDER_SECRET_INDEX],
            &parameters().h_0,
            commitment,
            &mut transcript,
        )
        .map_err(|_| SansIdError::InvalidIssuanceProof)?;
    Ok(compute_random_oracle_challenge::<Fr, Sha512>(&transcript))
}

fn transcript_prefix(
    request: &ProofRequest,
    issuer: &IssuerPublicKey,
) -> Result<Vec<u8>, SansIdError> {
    let mut transcript = Vec::with_capacity(256);
    append_transcript_field(&mut transcript, TRANSCRIPT_LABEL);
    append_transcript_field(&mut transcript, PROTOCOL_VERSION.as_bytes());
    append_transcript_field(&mut transcript, CIPHERSUITE.as_bytes());
    append_transcript_field(&mut transcript, SCHEMA_ID.as_bytes());
    append_transcript_field(&mut transcript, issuer.key_id().as_bytes());
    append_transcript_field(&mut transcript, &canonical_encode(&issuer.key)?);
    append_transcript_field(&mut transcript, request.origin.as_str().as_bytes());
    append_transcript_field(&mut transcript, request.predicate.as_bytes());
    append_transcript_field(&mut transcript, &request.nonce);
    Ok(transcript)
}

fn issuance_transcript_prefix(
    issuer: &IssuerPublicKey,
    challenge: &IssuanceChallenge,
) -> Result<Vec<u8>, SansIdError> {
    let mut transcript = Vec::with_capacity(192);
    append_transcript_field(&mut transcript, ISSUANCE_TRANSCRIPT_LABEL);
    append_transcript_field(&mut transcript, PROTOCOL_VERSION.as_bytes());
    append_transcript_field(&mut transcript, CIPHERSUITE.as_bytes());
    append_transcript_field(&mut transcript, SCHEMA_ID.as_bytes());
    append_transcript_field(&mut transcript, issuer.key_id().as_bytes());
    append_transcript_field(&mut transcript, &canonical_encode(&issuer.key)?);
    append_transcript_field(&mut transcript, &challenge.0);
    Ok(transcript)
}

fn append_transcript_field(target: &mut Vec<u8>, value: &[u8]) {
    target.extend_from_slice(&(value.len() as u64).to_be_bytes());
    target.extend_from_slice(value);
}

fn hash_bytes(label: &[u8], value: &[u8]) -> [u8; 64] {
    let mut hash = Sha512::new();
    hash.update((label.len() as u64).to_be_bytes());
    hash.update(label);
    hash.update((value.len() as u64).to_be_bytes());
    hash.update(value);
    hash.finalize().into()
}

fn scalar_from_bytes(label: &[u8], value: &[u8]) -> Fr {
    let mut hash = Sha512::new();
    hash.update((label.len() as u64).to_be_bytes());
    hash.update(label);
    hash.update((value.len() as u64).to_be_bytes());
    hash.update(value);
    Fr::from_le_bytes_mod_order(&hash.finalize())
}

fn canonical_encode<T: CanonicalSerialize>(value: &T) -> Result<Vec<u8>, SansIdError> {
    let mut bytes = Vec::new();
    value.serialize_compressed(&mut bytes).map_err(|_| SansIdError::Serialization)?;
    Ok(bytes)
}

fn canonical_decode<T: CanonicalDeserialize>(bytes: &[u8]) -> Result<T, SansIdError> {
    let mut cursor = Cursor::new(bytes);
    let value = T::deserialize_compressed(&mut cursor).map_err(|_| SansIdError::InvalidEncoding)?;
    if cursor.position() != bytes.len() as u64 {
        return Err(SansIdError::InvalidEncoding);
    }
    Ok(value)
}

fn decode_base64(value: &str, maximum_length: usize) -> Result<Vec<u8>, SansIdError> {
    if value.len() > maximum_length.saturating_mul(2) {
        return Err(SansIdError::PresentationTooLarge);
    }
    let decoded = URL_SAFE_NO_PAD.decode(value).map_err(|_| SansIdError::InvalidEncoding)?;
    if decoded.len() > maximum_length {
        return Err(SansIdError::PresentationTooLarge);
    }
    Ok(decoded)
}

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

    fn fixture() -> (Credential, HolderSecret, IssuerPublicKey, ProofRequest) {
        let issuer = Issuer::generate().expect("issuer generation");
        let key = issuer.public_key().clone();
        let issuance_challenge = issuer.issuance_challenge();
        let issuance_request = HolderSecret::generate()
            .begin_issuance(issuer.public_key(), &issuance_challenge)
            .expect("issuance request");
        let response = issuer
            .blind_issue(&issuance_request, &issuance_challenge, Predicate::AgeOver18)
            .expect("blind issuance");
        let (credential, holder_secret) =
            issuance_request.complete(response).expect("credential completion").into_parts();
        let request =
            ProofRequest::new("https://video.example", Predicate::AgeOver18, &[7_u8; NONCE_BYTES])
                .expect("proof request");
        (credential, holder_secret, key, request)
    }

    #[test]
    fn age_presentation_verifies() {
        let (credential, holder_secret, issuer, request) = fixture();
        let presentation = credential.present(&holder_secret, &request).expect("presentation");
        verify(&presentation, &request, &issuer).expect("proof verifies");
    }

    #[test]
    fn provider_boundary_authorizes_a_presentation() {
        let (credential, holder_secret, issuer, request) = fixture();
        assert_eq!(holder_secret.backend(), HolderKeyBackend::DevelopmentMemory);
        let presentation = credential
            .present_with_provider(&holder_secret, &request)
            .expect("provider presentation");
        verify(&presentation, &request, &issuer).expect("proof verifies");
    }

    #[test]
    fn presentations_are_fresh_and_unlinkable_at_the_proof_layer() {
        let (credential, holder_secret, issuer, request) = fixture();
        let first = credential.present(&holder_secret, &request).expect("first presentation");
        let second = credential.present(&holder_secret, &request).expect("second presentation");
        assert_ne!(first.proof, second.proof);
        verify(&first, &request, &issuer).expect("first proof verifies");
        verify(&second, &request, &issuer).expect("second proof verifies");
    }

    #[test]
    fn proof_cannot_be_replayed_for_a_different_nonce() {
        let (credential, holder_secret, issuer, request) = fixture();
        let presentation = credential.present(&holder_secret, &request).expect("presentation");
        let other_request =
            ProofRequest::new("https://video.example", Predicate::AgeOver18, &[8_u8; NONCE_BYTES])
                .expect("different request");
        assert!(matches!(
            verify(&presentation, &other_request, &issuer),
            Err(SansIdError::RequestMismatch)
        ));
    }

    #[test]
    fn proof_cannot_be_replayed_for_a_different_origin() {
        let (credential, holder_secret, issuer, request) = fixture();
        let presentation = credential.present(&holder_secret, &request).expect("presentation");
        let other_request =
            ProofRequest::new("https://other.example", Predicate::AgeOver18, &[7_u8; NONCE_BYTES])
                .expect("different request");
        assert!(matches!(
            verify(&presentation, &other_request, &issuer),
            Err(SansIdError::RequestMismatch)
        ));
    }

    #[test]
    fn blind_issuance_rejects_a_different_issuer_nonce() {
        let issuer = Issuer::generate().expect("issuer generation");
        let first_challenge = issuer.issuance_challenge();
        let request = HolderSecret::generate()
            .begin_issuance(issuer.public_key(), &first_challenge)
            .expect("issuance request");
        let second_challenge = issuer.issuance_challenge();

        assert!(matches!(
            issuer.blind_issue(&request, &second_challenge, Predicate::AgeOver18),
            Err(SansIdError::InvalidIssuanceProof)
        ));
    }

    #[test]
    fn altered_proof_bytes_are_rejected() {
        let (credential, holder_secret, issuer, request) = fixture();
        let mut presentation = credential.present(&holder_secret, &request).expect("presentation");
        let mut proof = decode_base64(&presentation.proof, MAX_PROOF_BYTES).expect("proof bytes");
        proof[0] ^= 1;
        presentation.proof = URL_SAFE_NO_PAD.encode(proof);

        assert!(matches!(
            verify(&presentation, &request, &issuer),
            Err(SansIdError::InvalidEncoding | SansIdError::InvalidProof)
        ));
    }

    #[test]
    fn json_round_trip_preserves_a_valid_presentation() {
        let (credential, holder_secret, issuer, request) = fixture();
        let encoded = credential
            .present(&holder_secret, &request)
            .expect("presentation")
            .to_json()
            .expect("JSON encoding");
        let decoded = Presentation::from_json(&encoded).expect("JSON decoding");
        verify(&decoded, &request, &issuer).expect("proof verifies");
    }

    #[test]
    fn predicate_json_uses_the_documented_wire_name() {
        let encoded = serde_json::to_string(&Predicate::AgeOver18).expect("predicate serializes");
        assert_eq!(encoded, "\"age_over_18\"");

        let decoded: Predicate = serde_json::from_str("\"age_over_18\"").expect("parses");
        assert_eq!(decoded, Predicate::AgeOver18);
    }

    #[test]
    fn origin_must_be_canonical_https() {
        assert!(Origin::parse("http://video.example").is_err());
        assert!(Origin::parse("https://video.example/path").is_err());
        assert!(Origin::parse("https://user@video.example").is_err());
        assert_eq!(
            Origin::parse("https://video.example/").expect("canonical origin").as_str(),
            "https://video.example"
        );
    }
}