-
Notifications
You must be signed in to change notification settings - Fork 2
/
credential.go
404 lines (340 loc) · 11 KB
/
credential.go
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
package verifiable
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"fmt"
"math/big"
"time"
core "github.com/iden3/go-iden3-core/v2"
"github.com/iden3/go-iden3-core/v2/w3c"
"github.com/iden3/go-iden3-crypto/babyjub"
"github.com/iden3/go-iden3-crypto/poseidon"
"github.com/iden3/go-merkletree-sql/v2"
"github.com/iden3/go-schema-processor/v2/merklize"
"github.com/pkg/errors"
)
// W3CCredential is struct that represents claim json-ld document
type W3CCredential struct {
ID string `json:"id,omitempty"`
Context []string `json:"@context"`
Type []string `json:"type"`
Expiration *time.Time `json:"expirationDate,omitempty"`
IssuanceDate *time.Time `json:"issuanceDate,omitempty"`
CredentialSubject map[string]interface{} `json:"credentialSubject"`
CredentialStatus interface{} `json:"credentialStatus,omitempty"`
Issuer string `json:"issuer"`
CredentialSchema CredentialSchema `json:"credentialSchema"`
Proof CredentialProofs `json:"proof,omitempty"`
RefreshService *RefreshService `json:"refreshService,omitempty"`
DisplayMethod *DisplayMethod `json:"displayMethod,omitempty"`
}
// VerifyProof verify credential proof
func (vc *W3CCredential) VerifyProof(ctx context.Context, proofType ProofType,
didResolver DIDResolver, opts ...W3CProofVerificationOpt) error {
verifyConfig := w3CProofVerificationConfig{}
for _, o := range opts {
o(&verifyConfig)
}
var credProof CredentialProof
for _, p := range vc.Proof {
if p.ProofType() == proofType {
credProof = p
break
}
}
if credProof == nil {
return ErrProofNotFound
}
coreClaim, err := credProof.GetCoreClaim()
if err != nil {
return errors.New("can't get core claim")
}
switch proofType {
case BJJSignatureProofType:
var proof BJJSignatureProof2021
err = remarshalObj(&proof, credProof)
if err != nil {
return err
}
return verifyBJJSignatureProof(ctx, proof, coreClaim, didResolver,
verifyConfig)
case Iden3SparseMerkleTreeProofType:
var proof Iden3SparseMerkleTreeProof
err = remarshalObj(&proof, credProof)
if err != nil {
return err
}
return verifyIden3SparseMerkleTreeProof(ctx, proof, coreClaim,
didResolver)
default:
return ErrProofNotSupported
}
}
func verifyBJJSignatureProof(ctx context.Context, proof BJJSignatureProof2021,
coreClaim *core.Claim, didResolver DIDResolver,
verifyConfig w3CProofVerificationConfig) error {
// issuer's claim with public key
authClaim, err := proof.IssuerData.authClaim()
if err != nil {
return err
}
// core claim's signature
sig, err := bjjSignatureFromHexString(proof.Signature)
if err != nil || sig == nil {
return err
}
err = verifyClaimSignature(coreClaim, sig, authClaim)
if err != nil {
return err
}
issuerDID, err := w3c.ParseDID(proof.IssuerData.ID)
if err != nil {
return err
}
issuerStateHash, err := merkletree.NewHashFromHex(*proof.IssuerData.State.Value)
if err != nil {
return fmt.Errorf("invalid state formant: %v", err)
}
issuerDID.Query = fmt.Sprintf("state=%s", issuerStateHash.Hex())
didDoc, err := didResolver.Resolve(ctx, issuerDID)
if err != nil {
return err
}
vm, err := getIden3StateInfo2023FromDIDDocument(didDoc)
if err != nil {
return err
}
// Published or genesis
if !*vm.IdentityState.Published {
var (
isGenesisState bool
issuerID core.ID
)
issuerID, err = core.IDFromDID(*issuerDID)
if err != nil {
return err
}
isGenesisState, err = core.CheckGenesisStateID(issuerID.BigInt(), issuerStateHash.BigInt())
if err != nil {
return err
}
if !isGenesisState {
return errors.New("issuer state not published and not genesis")
}
}
err = validateAuthClaimRevocation(ctx, proof.IssuerData,
verifyConfig.credStatusValidationOpts...)
if err != nil {
return err
}
return err
}
func verifyClaimSignature(claim *core.Claim, sig *babyjub.Signature,
authClaim *core.Claim) error {
publicKey := publicKeyFromClaim(authClaim)
// core claim hash
hi, hv, err := claim.HiHv()
if err != nil {
return err
}
claimHash, err := poseidon.Hash([]*big.Int{hi, hv})
if err != nil {
return err
}
valid := publicKey.VerifyPoseidon(claimHash, sig)
if !valid {
return errors.New("claim signature validation failed")
}
return nil
}
func publicKeyFromClaim(claim *core.Claim) *babyjub.PublicKey {
rawSlotInts := claim.RawSlotsAsInts()
var publicKey babyjub.PublicKey
publicKey.X = rawSlotInts[2] // Ax should be in indexSlotA
publicKey.Y = rawSlotInts[3] // Ay should be in indexSlotB
return &publicKey
}
func validateAuthClaimRevocation(ctx context.Context, issuerData IssuerData,
opts ...CredentialStatusValidationOption) error {
credStatus, err := coerceCredentialStatus(issuerData.CredentialStatus)
if err != nil {
return err
}
authClaim, err := issuerData.authClaim()
if err != nil {
return err
}
if credStatus.RevocationNonce != authClaim.GetRevocationNonce() {
return fmt.Errorf("revocation nonce mismatch: credential revocation "+
"nonce (%v) != auth claim revocation nonce (%v)",
credStatus.RevocationNonce, authClaim.GetRevocationNonce())
}
_, err = ValidateCredentialStatus(ctx, *credStatus, opts...)
return err
}
func verifyIden3SparseMerkleTreeProof(ctx context.Context,
proof Iden3SparseMerkleTreeProof, coreClaim *core.Claim,
didResolver DIDResolver) error {
var err error
issuerDID, err := w3c.ParseDID(proof.IssuerData.ID)
if err != nil {
return err
}
issuerStateHash, err := merkletree.NewHashFromHex(*proof.IssuerData.State.Value)
if err != nil {
return fmt.Errorf("invalid state formant: %v", err)
}
issuerDID.Query = fmt.Sprintf("state=%s", issuerStateHash.Hex())
didDoc, err := didResolver.Resolve(ctx, issuerDID)
if err != nil {
return err
}
vm, err := getIden3StateInfo2023FromDIDDocument(didDoc)
if err != nil {
return err
}
// Published or genesis
if !*vm.IdentityState.Published {
var (
isGenesisState bool
issuerID core.ID
)
issuerID, err = core.IDFromDID(*issuerDID)
if err != nil {
return err
}
isGenesisState, err = core.CheckGenesisStateID(issuerID.BigInt(), issuerStateHash.BigInt())
if err != nil {
return err
}
if !isGenesisState {
return errors.New("issuer state not published and not genesis")
}
}
// 3. root from proof == issuerData.state.сlaimsTreeRoot
hi, hv, err := coreClaim.HiHv()
if err != nil {
return err
}
rootFromProof, err := merkletree.RootFromProof(proof.MTP, hi, hv)
if err != nil {
return err
}
issuerClaimsTreeRoot, err := merkletree.NewHashFromHex(*proof.IssuerData.State.ClaimsTreeRoot)
if err != nil {
return fmt.Errorf("invalid state formant: %v", err)
}
if rootFromProof.BigInt().Cmp(issuerClaimsTreeRoot.BigInt()) != 0 {
return errors.New("verifyIden3SparseMerkleTreeProof: root from proof not equal to issuer data claims tree root")
}
return nil
}
func bjjSignatureFromHexString(sigHex string) (*babyjub.Signature, error) {
signatureBytes, err := hex.DecodeString(sigHex)
if err != nil {
return nil, errors.WithStack(err)
}
var sig [64]byte
copy(sig[:], signatureBytes)
bjjSig, err := new(babyjub.Signature).Decompress(sig)
return bjjSig, errors.WithStack(err)
}
func getIden3StateInfo2023FromDIDDocument(document DIDDocument) (*CommonVerificationMethod, error) {
var iden3StateInfo2023 *CommonVerificationMethod
for _, a := range document.VerificationMethod {
if a.Type == "Iden3StateInfo2023" {
a2 := a
iden3StateInfo2023 = &a2
break
}
}
if iden3StateInfo2023 == nil {
return nil, errors.New("Issuer Iden3StateInfo2023 auth info not found")
}
return iden3StateInfo2023, nil
}
// Merklize merklizes verifiable credential
func (vc *W3CCredential) Merklize(ctx context.Context,
opts ...merklize.MerklizeOption) (*merklize.Merklizer, error) {
credentialBytes, err := json.Marshal(vc)
if err != nil {
return nil, err
}
var credentialAsMap map[string]interface{}
err = json.Unmarshal(credentialBytes, &credentialAsMap)
if err != nil {
return nil, err
}
delete(credentialAsMap, "proof")
credentialWithoutProofBytes, err := json.Marshal(credentialAsMap)
if err != nil {
return nil, err
}
mk, err := merklize.MerklizeJSONLD(ctx,
bytes.NewReader(credentialWithoutProofBytes), opts...)
if err != nil {
return nil, err
}
return mk, nil
}
// ErrProofNotFound is an error when specific proof is not found in the credential
var ErrProofNotFound = errors.New("proof not found")
// ErrProofNotSupported is an error when specific proof is not supported for validation
var ErrProofNotSupported = errors.New("proof not supported")
// GetCoreClaimFromProof returns core claim from given proof
func (vc *W3CCredential) GetCoreClaimFromProof(proofType ProofType) (*core.Claim, error) {
for _, p := range vc.Proof {
if p.ProofType() == proofType {
return p.GetCoreClaim()
}
}
return nil, ErrProofNotFound
}
// CredentialSchema represent the information about credential schema
type CredentialSchema struct {
ID string `json:"id"`
Type string `json:"type"`
}
// CredentialStatus represents the URL to fetch claim revocation info directly from the issuer.
type CredentialStatus struct {
ID string `json:"id"`
Type CredentialStatusType `json:"type"`
RevocationNonce uint64 `json:"revocationNonce"`
StatusIssuer *CredentialStatus `json:"statusIssuer,omitempty"`
}
// RHSCredentialStatus contains type, url to fetch RHS info, issuer ID and revocation nonce and backup option to fetch credential status
// Deprecated: use CredentialStatus instead
type RHSCredentialStatus struct {
ID string `json:"id"`
Type CredentialStatusType `json:"type"`
RevocationNonce uint64 `json:"revocationNonce"`
StatusIssuer *CredentialStatus `json:"statusIssuer,omitempty"`
}
// CredentialStatusType type for understanding revocation type
type CredentialStatusType string
// RevocationStatus status of revocation nonce. Info required to check revocation state of claim in circuits
type RevocationStatus struct {
Issuer TreeState `json:"issuer"`
MTP merkletree.Proof `json:"mtp"`
}
type TreeState struct {
State *string `json:"state"`
RootOfRoots *string `json:"rootOfRoots,omitempty"`
ClaimsTreeRoot *string `json:"claimsTreeRoot,omitempty"`
RevocationTreeRoot *string `json:"revocationTreeRoot,omitempty"`
}
// WithStatusResolverRegistry return new options
func WithStatusResolverRegistry(registry *CredentialStatusResolverRegistry) W3CProofVerificationOpt {
return func(opts *w3CProofVerificationConfig) {
opts.credStatusValidationOpts = append(opts.credStatusValidationOpts,
WithValidationStatusResolverRegistry(registry))
}
}
// W3CProofVerificationOpt returns configuration options for W3C proof verification
type W3CProofVerificationOpt func(opts *w3CProofVerificationConfig)
// w3CProofVerificationConfig options for W3C proof verification
type w3CProofVerificationConfig struct {
credStatusValidationOpts []CredentialStatusValidationOption
}