This repository has been archived by the owner on Mar 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 158
/
wallet.go
1089 lines (908 loc) · 34.4 KB
/
wallet.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
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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package wallet
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/piprate/json-gold/ld"
"github.com/hyperledger/aries-framework-go/pkg/client/didexchange"
"github.com/hyperledger/aries-framework-go/pkg/client/outofband"
"github.com/hyperledger/aries-framework-go/pkg/client/presentproof"
"github.com/hyperledger/aries-framework-go/pkg/common/log"
"github.com/hyperledger/aries-framework-go/pkg/crypto"
"github.com/hyperledger/aries-framework-go/pkg/didcomm/common/service"
"github.com/hyperledger/aries-framework-go/pkg/didcomm/protocol/decorator"
didexchangeSvc "github.com/hyperledger/aries-framework-go/pkg/didcomm/protocol/didexchange"
presentproofSvc "github.com/hyperledger/aries-framework-go/pkg/didcomm/protocol/presentproof"
"github.com/hyperledger/aries-framework-go/pkg/doc/did"
"github.com/hyperledger/aries-framework-go/pkg/doc/signature/jsonld"
"github.com/hyperledger/aries-framework-go/pkg/doc/signature/signer"
"github.com/hyperledger/aries-framework-go/pkg/doc/signature/suite"
"github.com/hyperledger/aries-framework-go/pkg/doc/signature/suite/bbsblssignature2020"
"github.com/hyperledger/aries-framework-go/pkg/doc/signature/suite/ed25519signature2018"
"github.com/hyperledger/aries-framework-go/pkg/doc/signature/suite/jsonwebsignature2020"
"github.com/hyperledger/aries-framework-go/pkg/doc/verifiable"
"github.com/hyperledger/aries-framework-go/pkg/framework/aries/api/vdr"
"github.com/hyperledger/aries-framework-go/pkg/kms"
"github.com/hyperledger/aries-framework-go/pkg/store/connection"
"github.com/hyperledger/aries-framework-go/spi/storage"
)
// Proof types.
const (
// Ed25519Signature2018 ed25519 signature suite.
Ed25519Signature2018 = "Ed25519Signature2018"
// JSONWebSignature2020 json web signature suite.
JSONWebSignature2020 = "JsonWebSignature2020"
// BbsBlsSignature2020 BBS signature suite.
BbsBlsSignature2020 = "BbsBlsSignature2020"
)
// miscellaneous constants.
const (
bbsContext = "https://w3id.org/security/bbs/v1"
emptyRawLength = 4
msgEventBufferSize = 10
presentProofMimeType = "application/ld+json"
// timeout constants.
defaultDIDExchangeTimeOut = 120 * time.Second
defaultWaitForRequestPresentationTimeOut = 120 * time.Second
retryDelay = 500 * time.Millisecond
)
// proof options.
// nolint:gochecknoglobals
var (
defaultSignatureRepresentation = verifiable.SignatureJWS
supportedRelationships = map[did.VerificationRelationship]string{
did.Authentication: "authentication",
did.AssertionMethod: "assertionMethod",
}
)
var logger = log.New("aries-framework/wallet")
// provider contains dependencies for the verifiable credential wallet
// and is typically created by using aries.Context().
type provider interface {
StorageProvider() storage.Provider
VDRegistry() vdr.Registry
Crypto() crypto.Crypto
JSONLDDocumentLoader() ld.DocumentLoader
didCommProvider // to be used only if wallet needs to be participated in DIDComm.
}
// didCommProvider to be used only if wallet needs to be participated in DIDComm operation.
// TODO: using wallet KMS instead of provider KMS.
// TODO: reconcile Protocol storage with wallet store.
type didCommProvider interface {
KMS() kms.KeyManager
ServiceEndpoint() string
ProtocolStateStorageProvider() storage.Provider
Service(id string) (interface{}, error)
KeyType() kms.KeyType
KeyAgreementType() kms.KeyType
}
type provable interface {
AddLinkedDataProof(context *verifiable.LinkedDataProofContext, jsonldOpts ...jsonld.ProcessorOpts) error
}
// Wallet enables access to verifiable credential wallet features.
type Wallet struct {
// ID of wallet content owner
userID string
// wallet profile
profile *profile
// wallet content store
contents *contentStore
// crypto for wallet
walletCrypto crypto.Crypto
// storage provider
storeProvider storage.Provider
// wallet VDR
vdr vdr.Registry
// document loader for JSON-LD contexts
jsonldDocumentLoader ld.DocumentLoader
// present proof client
presentProofClient *presentproof.Client
// out of band client
oobClient *outofband.Client
// did-exchange client
didexchangeClient *didexchange.Client
// connection lookup
connectionLookup *connection.Lookup
}
// New returns new verifiable credential wallet for given user.
// returns error if wallet profile is not found.
// To create a new wallet profile, use `CreateProfile()`.
// To update an existing profile, use `UpdateProfile()`.
func New(userID string, ctx provider) (*Wallet, error) {
store, err := newProfileStore(ctx.StorageProvider())
if err != nil {
return nil, fmt.Errorf("failed to get store to fetch VC wallet profile info: %w", err)
}
profile, err := store.get(userID)
if err != nil {
return nil, fmt.Errorf("failed to get VC wallet profile: %w", err)
}
presentProofClient, err := presentproof.New(ctx)
if err != nil {
return nil, fmt.Errorf("failed to initialize present proof client: %w", err)
}
oobClient, err := outofband.New(ctx)
if err != nil {
return nil, fmt.Errorf("failed to initialize out-of-band client: %w", err)
}
connectionLookup, err := connection.NewLookup(ctx)
if err != nil {
return nil, fmt.Errorf("failed to initialize connection lookup: %w", err)
}
didexchangeClient, err := didexchange.New(ctx)
if err != nil {
return nil, fmt.Errorf("failed to initialize didexchange client: %w", err)
}
return &Wallet{
userID: userID,
profile: profile,
storeProvider: ctx.StorageProvider(),
walletCrypto: ctx.Crypto(),
contents: newContentStore(ctx.StorageProvider(), profile),
vdr: ctx.VDRegistry(),
jsonldDocumentLoader: ctx.JSONLDDocumentLoader(),
presentProofClient: presentProofClient,
oobClient: oobClient,
didexchangeClient: didexchangeClient,
connectionLookup: connectionLookup,
}, nil
}
// CreateProfile creates a new verifiable credential wallet profile for given user.
// returns error if wallet profile is already created.
// Use `UpdateProfile()` for replacing an already created verifiable credential wallet profile.
func CreateProfile(userID string, ctx provider, options ...ProfileOptions) error {
return createOrUpdate(userID, ctx, false, options...)
}
// UpdateProfile updates existing verifiable credential wallet profile.
// Caution:
// - you might lose your existing keys if you change kms options.
// - you might lose your existing wallet contents if you change storage/EDV options
// (ex: switching context storage provider or changing EDV settings).
func UpdateProfile(userID string, ctx provider, options ...ProfileOptions) error {
return createOrUpdate(userID, ctx, true, options...)
}
// CreateDataVaultKeyPairs can be used create EDV key pairs for given profile.
// Wallet will create key pairs in profile kms and updates profile with newly generate EDV encryption & MAC key IDs.
func CreateDataVaultKeyPairs(userID string, ctx provider, options ...UnlockOptions) error {
store, err := newProfileStore(ctx.StorageProvider())
if err != nil {
return fmt.Errorf("failed to get wallet user profile: failed to get store: %w", err)
}
profile, err := store.get(userID)
if err != nil {
return fmt.Errorf("failed to get wallet user profile: %w", err)
}
if profile.EDVConf == nil {
return fmt.Errorf("invalid operation, no edv configuration found in profile: %w", err)
}
opts := &unlockOpts{}
for _, opt := range options {
opt(opts)
}
// unlock key manager
token, err := keyManager().createKeyManager(profile, ctx.StorageProvider(), opts)
if err != nil {
return fmt.Errorf("failed to get key manager: %w", err)
}
defer keyManager().removeKeyManager(userID)
// update profile
err = updateProfile(token, profile)
if err != nil {
return fmt.Errorf("failed to create key pairs: %w", err)
}
// update profile
err = store.save(profile, true)
if err != nil {
return fmt.Errorf("failed to update profile: %w", err)
}
return nil
}
func createOrUpdate(userID string, ctx provider, update bool, options ...ProfileOptions) error {
opts := &profileOpts{}
for _, opt := range options {
opt(opts)
}
store, err := newProfileStore(ctx.StorageProvider())
if err != nil {
return fmt.Errorf("failed to get store to save VC wallet profile: %w", err)
}
var profile *profile
// nolint: nestif
if update {
// find existing profile and update it.
profile, err = store.get(userID)
if err != nil {
return fmt.Errorf("failed to update wallet user profile: %w", err)
}
err = profile.setKMSOptions(opts.passphrase, opts.secretLockSvc, opts.keyServerURL)
if err != nil {
return fmt.Errorf("failed to update wallet user profile KMS options: %w", err)
}
err = profile.setEDVOptions(opts.edvConf)
if err != nil {
return fmt.Errorf("failed to update EDV configuration")
}
} else {
// create new profile.
profile, err = createProfile(userID, opts)
if err != nil {
return fmt.Errorf("failed to create new wallet user profile: %w", err)
}
}
err = store.save(profile, update)
if err != nil {
return fmt.Errorf("failed to save VC wallet profile: %w", err)
}
return nil
}
// ProfileExists checks if profile exists for given wallet user, returns error if not found.
func ProfileExists(userID string, ctx provider) error {
store, err := newProfileStore(ctx.StorageProvider())
if err != nil {
return fmt.Errorf("failed to get store to get VC wallet profile: %w", err)
}
_, err = store.get(userID)
return err
}
// Open unlocks wallet's key manager instance & open wallet content store and
// returns a token for subsequent use of wallet features.
//
// Args:
// - unlock options for opening wallet.
//
// Returns token with expiry that can be used for subsequent use of wallet features.
func (c *Wallet) Open(options ...UnlockOptions) (string, error) {
opts := &unlockOpts{}
for _, opt := range options {
opt(opts)
}
// unlock key manager
token, err := keyManager().createKeyManager(c.profile, c.storeProvider, opts)
if err != nil {
return "", err
}
// open content store using token
err = c.contents.Open(token, opts)
if err != nil {
// close wallet if it fails to open store
c.Close()
return "", err
}
return token, nil
}
// Close expires token issued to this VC wallet, removes the key manager instance and closes wallet content store.
// returns false if token is not found or already expired for this wallet user.
func (c *Wallet) Close() bool {
return keyManager().removeKeyManager(c.userID) && c.contents.Close()
}
// Export produces a serialized exported wallet representation.
// Only ciphertext wallet contents can be exported.
//
// Args:
// - auth: token to be used to lock the wallet before exporting.
//
// Returns exported locked wallet.
//
// Supported data models:
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#Collection
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#Credential
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#DIDResolutionResponse
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#meta-data
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#connection
//
func (c *Wallet) Export(auth string) (json.RawMessage, error) {
// TODO to be added #2433
return nil, fmt.Errorf("to be implemented")
}
// Import Takes a serialized exported wallet representation as input
// and imports all contents into wallet.
//
// Args:
// - contents: wallet content to be imported.
// - auth: token used while exporting the wallet.
//
// Supported data models:
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#Collection
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#Credential
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#DIDResolutionResponse
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#meta-data
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#connection
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#Key
//
func (c *Wallet) Import(auth string, contents json.RawMessage) error {
// TODO to be added #2433
return fmt.Errorf("to be implemented")
}
// Add adds given data model to wallet contents store.
//
// Supported data models:
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#Collection
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#Credential
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#DIDResolutionResponse
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#meta-data
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#connection
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#Key
//
func (c *Wallet) Add(authToken string, contentType ContentType, content json.RawMessage, options ...AddContentOptions) error { //nolint: lll
return c.contents.Save(authToken, contentType, content, options...)
}
// Remove removes wallet content by content ID.
//
// Supported data models:
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#Collection
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#Credential
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#DIDResolutionResponse
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#meta-data
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#connection
//
func (c *Wallet) Remove(authToken string, contentType ContentType, contentID string) error {
return c.contents.Remove(authToken, contentID, contentType)
}
// Get fetches a wallet content by content ID.
//
// Supported data models:
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#Collection
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#Credential
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#DIDResolutionResponse
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#meta-data
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#connection
//
func (c *Wallet) Get(authToken string, contentType ContentType, contentID string) (json.RawMessage, error) {
return c.contents.Get(authToken, contentID, contentType)
}
// GetAll fetches all wallet contents of given type.
// Returns map of key value from content store for given content type.
//
// Supported data models:
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#Collection
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#Credential
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#DIDResolutionResponse
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#meta-data
// - https://w3c-ccg.github.io/universal-wallet-interop-spec/#connection
//
func (c *Wallet) GetAll(authToken string, contentType ContentType, options ...GetAllContentsOptions) (map[string]json.RawMessage, error) { //nolint: lll
opts := &getAllContentsOpts{}
for _, option := range options {
option(opts)
}
if opts.collectionID != "" {
return c.contents.GetAllByCollection(authToken, opts.collectionID, contentType)
}
return c.contents.GetAll(authToken, contentType)
}
// Query runs query against wallet credential contents and returns presentation containing credential results.
//
// This function may return multiple presentations as query result based on combination of query types used.
//
// https://w3c-ccg.github.io/universal-wallet-interop-spec/#query
//
// Supported Query Types:
// - https://www.w3.org/TR/json-ld11-framing
// - https://identity.foundation/presentation-exchange
// - https://w3c-ccg.github.io/vp-request-spec/#query-by-example
// - https://w3c-ccg.github.io/vp-request-spec/#did-authentication-request
//
func (c *Wallet) Query(authToken string, params ...*QueryParams) ([]*verifiable.Presentation, error) {
vcContents, err := c.contents.GetAll(authToken, Credential)
if err != nil {
return nil, fmt.Errorf("failed to query credentials: %w", err)
}
query := NewQuery(verifiable.NewVDRKeyResolver(newContentBasedVDR(authToken, c.vdr, c.contents)).PublicKeyFetcher(),
c.jsonldDocumentLoader, params...)
return query.PerformQuery(vcContents)
}
// Issue adds proof to a Verifiable Credential.
//
// Args:
// - auth token for unlocking kms.
// - A verifiable credential with or without proof.
// - Proof options.
//
func (c *Wallet) Issue(authToken string, credential json.RawMessage,
options *ProofOptions) (*verifiable.Credential, error) {
vc, err := verifiable.ParseCredential(credential, verifiable.WithDisabledProofCheck(),
verifiable.WithJSONLDDocumentLoader(c.jsonldDocumentLoader))
if err != nil {
return nil, fmt.Errorf("failed to parse credential: %w", err)
}
purpose := did.AssertionMethod
err = c.validateProofOption(authToken, options, purpose)
if err != nil {
return nil, fmt.Errorf("failed to prepare proof: %w", err)
}
err = c.addLinkedDataProof(authToken, vc, options, purpose)
if err != nil {
return nil, fmt.Errorf("failed to issue credential: %w", err)
}
return vc, nil
}
// Prove produces a Verifiable Presentation.
//
// Args:
// - auth token for unlocking kms.
// - list of interfaces (string of credential IDs which can be resolvable to stored credentials in wallet or
// raw credential or a presentation).
// - proof options
//
func (c *Wallet) Prove(authToken string, proofOptions *ProofOptions, credentials ...ProveOptions) (*verifiable.Presentation, error) { //nolint: lll
presentation, err := c.resolveOptionsToPresent(authToken, credentials...)
if err != nil {
return nil, fmt.Errorf("failed to resolve credentials from request: %w", err)
}
purpose := did.Authentication
err = c.validateProofOption(authToken, proofOptions, purpose)
if err != nil {
return nil, fmt.Errorf("failed to prepare proof: %w", err)
}
presentation.Holder = proofOptions.Controller
err = c.addLinkedDataProof(authToken, presentation, proofOptions, purpose)
if err != nil {
return nil, fmt.Errorf("failed to prove credentials: %w", err)
}
return presentation, nil
}
// Verify takes Takes a Verifiable Credential or Verifiable Presentation as input,.
//
// Args:
// - verification option for sending different models (stored credential ID, raw credential, raw presentation).
//
// Returns: a boolean verified, and an error if verified is false.
func (c *Wallet) Verify(authToken string, options VerificationOption) (bool, error) {
requestOpts := &verifyOpts{}
options(requestOpts)
switch {
case requestOpts.credentialID != "":
raw, err := c.contents.Get(authToken, requestOpts.credentialID, Credential)
if err != nil {
return false, fmt.Errorf("failed to get credential: %w", err)
}
return c.verifyCredential(authToken, raw)
case len(requestOpts.rawCredential) > 0:
return c.verifyCredential(authToken, requestOpts.rawCredential)
case len(requestOpts.rawPresentation) > 0:
return c.verifyPresentation(authToken, requestOpts.rawPresentation)
default:
return false, fmt.Errorf("invalid verify request")
}
}
// Derive derives a credential and returns response credential.
//
// Args:
// - credential to derive (ID of the stored credential, raw credential or credential instance).
// - derive options.
//
func (c *Wallet) Derive(authToken string, credential CredentialToDerive, options *DeriveOptions) (*verifiable.Credential, error) { //nolint: lll
vc, err := c.resolveCredentialToDerive(authToken, credential)
if err != nil {
return nil, fmt.Errorf("failed to resolve request : %w", err)
}
derived, err := vc.GenerateBBSSelectiveDisclosure(options.Frame, []byte(options.Nonce),
verifiable.WithPublicKeyFetcher(
verifiable.NewVDRKeyResolver(newContentBasedVDR(authToken, c.vdr, c.contents)).PublicKeyFetcher(),
), verifiable.WithJSONLDDocumentLoader(c.jsonldDocumentLoader))
if err != nil {
return nil, fmt.Errorf("failed to derive credential : %w", err)
}
return derived, nil
}
// CreateKeyPair creates key pair inside a wallet.
//
// Args:
// - authToken: authorization for performing create key pair operation.
// - keyType: type of the key to be created.
//
func (c *Wallet) CreateKeyPair(authToken string, keyType kms.KeyType) (*KeyPair, error) {
kmgr, err := keyManager().getKeyManger(authToken)
if err != nil {
return nil, ErrInvalidAuthToken
}
kid, pubBytes, err := kmgr.CreateAndExportPubKeyBytes(keyType)
if err != nil {
return nil, err
}
return &KeyPair{
KeyID: kid,
PublicKey: base64.RawURLEncoding.EncodeToString(pubBytes),
}, nil
}
// Connect accepts out-of-band invitations and performs DID exchange.
//
// Args:
// - authToken: authorization for performing create key pair operation.
// - invitation: out-of-band invitation.
// - options: connection options.
//
// Returns:
// - connection ID if DID exchange is successful.
// - error if operation false.
//
func (c *Wallet) Connect(authToken string, invitation *outofband.Invitation, options ...ConnectOptions) (string, error) { //nolint: lll
statusCh := make(chan service.StateMsg, msgEventBufferSize)
err := c.didexchangeClient.RegisterMsgEvent(statusCh)
if err != nil {
return "", fmt.Errorf("failed to register msg event : %w", err)
}
defer func() {
e := c.didexchangeClient.UnregisterMsgEvent(statusCh)
if e != nil {
logger.Warnf("Failed to unregister msg event for connect: %w", e)
}
}()
opts := &connectOpts{}
for _, opt := range options {
opt(opts)
}
connID, err := c.oobClient.AcceptInvitation(invitation, opts.Label, getOobMessageOptions(opts)...)
if err != nil {
return "", fmt.Errorf("failed to accept invitation : %w", err)
}
if opts.timeout == 0 {
opts.timeout = defaultDIDExchangeTimeOut
}
ctx, cancel := context.WithTimeout(context.Background(), opts.timeout)
defer cancel()
err = waitForConnect(ctx, statusCh, connID)
if err != nil {
return "", fmt.Errorf("wallet connect failed : %w", err)
}
return connID, nil
}
// ProposePresentation accepts out-of-band invitation and sends message proposing presentation
// from wallet to relying party.
// https://w3c-ccg.github.io/universal-wallet-interop-spec/#proposepresentation
//
// Currently Supporting
// [0454-present-proof-v2](https://github.com/hyperledger/aries-rfcs/tree/master/features/0454-present-proof-v2)
//
// Args:
// - authToken: authorization for performing operation.
// - invitation: out-of-band invitation from relying party.
// - options: options for accepting invitation and send propose presentation message.
//
// Returns:
// - DIDCommMsgMap containing request presentation message if operation is successful.
// - error if operation fails.
//
func (c *Wallet) ProposePresentation(authToken string, invitation *outofband.Invitation, options ...ProposePresentationOption) (*service.DIDCommMsgMap, error) { //nolint: lll
opts := &proposePresOpts{}
for _, opt := range options {
opt(opts)
}
connID, err := c.Connect(authToken, invitation, opts.connectOpts...)
if err != nil {
return nil, fmt.Errorf("failed to perform did connection : %w", err)
}
connRecord, err := c.connectionLookup.GetConnectionRecord(connID)
if err != nil {
return nil, fmt.Errorf("failed to lookup connection for propose presentation : %w", err)
}
opts = preparePresentProofOpts(connRecord, opts)
_, err = c.presentProofClient.SendProposePresentation(&presentproof.ProposePresentation{}, connRecord.MyDID,
opts.from)
if err != nil {
return nil, fmt.Errorf("failed to propose presentation from wallet: %w", err)
}
ctx, cancel := context.WithTimeout(context.Background(), opts.timeout)
defer cancel()
return c.waitForRequestPresentation(ctx, connRecord)
}
// PresentProof sends message present proof message from wallet to relying party.
// https://w3c-ccg.github.io/universal-wallet-interop-spec/#presentproof
//
// Currently Supporting
// [0454-present-proof-v2](https://github.com/hyperledger/aries-rfcs/tree/master/features/0454-present-proof-v2)
//
// Args:
// - authToken: authorization for performing operation.
// - thID: thread ID (action ID) of request presentation.
// - presentProofFrom: presentation to be sent.
//
// Returns:
// - error if operation fails.
//
// TODO: wait for acknowledgement option to be added.
func (c *Wallet) PresentProof(authToken, thID string, presentProofFrom PresentProofFrom) error {
presFrom := &presentProofOpts{}
presentProofFrom(presFrom)
var presentation interface{}
if presFrom.presentation != nil {
presentation = presFrom.presentation
} else {
presentation = presFrom.rawPresentation
}
return c.presentProofClient.AcceptRequestPresentation(thID, &presentproof.Presentation{
Type: presentproofSvc.PresentationMsgType,
PresentationsAttach: []decorator.Attachment{{
ID: uuid.New().String(),
MimeType: presentProofMimeType,
Data: decorator.AttachmentData{
JSON: presentation,
},
}},
}, nil)
}
//nolint: funlen,gocyclo
func (c *Wallet) resolveOptionsToPresent(auth string, credentials ...ProveOptions) (*verifiable.Presentation, error) {
var allCredentials []*verifiable.Credential
opts := &proveOpts{}
for _, opt := range credentials {
opt(opts)
}
for _, id := range opts.storedCredentials {
raw, err := c.contents.Get(auth, id, Credential)
if err != nil {
return nil, err
}
// proof check is disabled while resolving credentials from store. A wallet UI may or may not choose to
// show credentials as verified. If a wallet implementation chooses to show credentials as 'verified' it
// may to call 'wallet.Verify()' for each credential being presented.
// (More details can be found in issue #2677).
credential, err := verifiable.ParseCredential(raw, verifiable.WithDisabledProofCheck(),
verifiable.WithJSONLDDocumentLoader(c.jsonldDocumentLoader))
if err != nil {
return nil, err
}
allCredentials = append(allCredentials, credential)
}
for _, raw := range opts.rawCredentials {
// proof check is disabled while resolving credentials from raw bytes. A wallet UI may or may not choose to
// show credentials as verified. If a wallet implementation chooses to show credentials as 'verified' it
// may to call 'wallet.Verify()' for each credential being presented.
// (More details can be found in issue #2677).
credential, err := verifiable.ParseCredential(raw, verifiable.WithDisabledProofCheck(),
verifiable.WithJSONLDDocumentLoader(c.jsonldDocumentLoader))
if err != nil {
return nil, err
}
allCredentials = append(allCredentials, credential)
}
if len(opts.credentials) > 0 {
allCredentials = append(allCredentials, opts.credentials...)
}
if opts.presentation != nil {
opts.presentation.AddCredentials(allCredentials...)
return opts.presentation, nil
} else if len(opts.rawPresentation) > emptyRawLength {
vp, err := verifiable.ParsePresentation(opts.rawPresentation, verifiable.WithPresDisabledProofCheck(),
verifiable.WithPresJSONLDDocumentLoader(c.jsonldDocumentLoader))
if err != nil {
return nil, err
}
vp.AddCredentials(allCredentials...)
return vp, nil
}
return verifiable.NewPresentation(verifiable.WithCredentials(allCredentials...))
}
func (c *Wallet) resolveCredentialToDerive(auth string, credential CredentialToDerive) (*verifiable.Credential, error) {
opts := &deriveOpts{}
credential(opts)
if opts.credential != nil {
return opts.credential, nil
}
if len(opts.rawCredential) > 0 {
// proof check is disabled while resolving credentials from store. A wallet UI may or may not choose to
// show credentials as verified. If a wallet implementation chooses to show credentials as 'verified' it
// may to call 'wallet.Verify()' for each credential being presented.
// (More details can be found in issue #2677).
return verifiable.ParseCredential(opts.rawCredential, verifiable.WithDisabledProofCheck(),
verifiable.WithJSONLDDocumentLoader(c.jsonldDocumentLoader))
}
if opts.credentialID != "" {
raw, err := c.contents.Get(auth, opts.credentialID, Credential)
if err != nil {
return nil, err
}
// proof check is disabled while resolving credentials from store. A wallet UI may or may not choose to
// show credentials as verified. If a wallet implementation chooses to show credentials as 'verified' it
// may to call 'wallet.Verify()' for each credential being presented.
// (More details can be found in issue #2677).
return verifiable.ParseCredential(raw, verifiable.WithDisabledProofCheck(),
verifiable.WithJSONLDDocumentLoader(c.jsonldDocumentLoader))
}
return nil, errors.New("invalid request to derive credential")
}
func (c *Wallet) verifyCredential(authToken string, credential json.RawMessage) (bool, error) {
_, err := verifiable.ParseCredential(credential, verifiable.WithPublicKeyFetcher(
verifiable.NewVDRKeyResolver(newContentBasedVDR(authToken, c.vdr, c.contents)).PublicKeyFetcher(),
), verifiable.WithJSONLDDocumentLoader(c.jsonldDocumentLoader))
if err != nil {
return false, fmt.Errorf("credential verification failed: %w", err)
}
return true, nil
}
func (c *Wallet) verifyPresentation(authToken string, presentation json.RawMessage) (bool, error) {
vp, err := verifiable.ParsePresentation(presentation, verifiable.WithPresPublicKeyFetcher(
verifiable.NewVDRKeyResolver(newContentBasedVDR(authToken, c.vdr, c.contents)).PublicKeyFetcher(),
), verifiable.WithPresJSONLDDocumentLoader(c.jsonldDocumentLoader))
if err != nil {
return false, fmt.Errorf("presentation verification failed: %w", err)
}
// verify proof of each credential
for _, cred := range vp.Credentials() {
vc, err := json.Marshal(cred)
if err != nil {
return false, fmt.Errorf("failed to read credentials from presentation: %w", err)
}
_, err = c.verifyCredential(authToken, vc)
if err != nil {
return false, fmt.Errorf("presentation verification failed: %w", err)
}
}
return true, nil
}
func (c *Wallet) addLinkedDataProof(authToken string, p provable, opts *ProofOptions,
relationship did.VerificationRelationship) error {
s, err := newKMSSigner(authToken, c.walletCrypto, opts)
if err != nil {
return err
}
var signatureSuite signer.SignatureSuite
switch opts.ProofType {
case Ed25519Signature2018:
signatureSuite = ed25519signature2018.New(suite.WithSigner(s))
case JSONWebSignature2020:
signatureSuite = jsonwebsignature2020.New(suite.WithSigner(s))
case BbsBlsSignature2020:
addContext(p, bbsContext)
signatureSuite = bbsblssignature2020.New(suite.WithSigner(s))
default:
return fmt.Errorf("unsupported signature type '%s'", opts.ProofType)
}
signingCtx := &verifiable.LinkedDataProofContext{
VerificationMethod: opts.VerificationMethod,
SignatureRepresentation: *opts.ProofRepresentation,
SignatureType: opts.ProofType,
Suite: signatureSuite,
Created: opts.Created,
Domain: opts.Domain,
Challenge: opts.Challenge,
Purpose: supportedRelationships[relationship],
}
err = p.AddLinkedDataProof(signingCtx, jsonld.WithDocumentLoader(c.jsonldDocumentLoader))
if err != nil {
return fmt.Errorf("failed to add linked data proof: %w", err)
}
return nil
}
func (c *Wallet) validateProofOption(authToken string, opts *ProofOptions, method did.VerificationRelationship) error {
if opts == nil || opts.Controller == "" {
return errors.New("invalid proof option, 'controller' is required")
}
resolvedDoc, err := newContentBasedVDR(authToken, c.vdr, c.contents).Resolve(opts.Controller)
if err != nil {
return err
}
err = c.validateVerificationMethod(resolvedDoc.DIDDocument, opts, method)
if err != nil {
return err
}
if opts.ProofRepresentation == nil {
opts.ProofRepresentation = &defaultSignatureRepresentation
}
if opts.ProofType == "" {
opts.ProofType = Ed25519Signature2018
}
return nil
}
func (c *Wallet) validateVerificationMethod(didDoc *did.Doc, opts *ProofOptions,
relationship did.VerificationRelationship) error {
vms := didDoc.VerificationMethods(relationship)[relationship]
for _, vm := range vms {
if opts.VerificationMethod == "" {
opts.VerificationMethod = vm.VerificationMethod.ID
return nil
}
if opts.VerificationMethod == vm.VerificationMethod.ID {
return nil
}
}
return fmt.Errorf("unable to find '%s' for given verification method", supportedRelationships[relationship])
}
// currently correlating response action by connection due to limitation in current present proof V1 implementation.
func (c *Wallet) waitForRequestPresentation(ctx context.Context, record *connection.Record) (*service.DIDCommMsgMap, error) { //nolint: lll
done := make(chan *service.DIDCommMsgMap)
go func() {
for {
actions, err := c.presentProofClient.Actions()
if err != nil {
continue
}
if len(actions) > 0 {
for _, action := range actions {
if action.MyDID == record.MyDID && action.TheirDID == record.TheirDID {
done <- &action.Msg
return
}
}
}
select {
default:
time.Sleep(retryDelay)
case <-ctx.Done():
return
}
}
}()
select {
case msg := <-done:
return msg, nil
case <-ctx.Done():