forked from hyperledger-archives/aries-framework-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
states.go
868 lines (704 loc) · 24.2 KB
/
states.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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package didexchange
import (
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/btcsuite/btcutil/base58"
"github.com/google/uuid"
"github.com/mitchellh/mapstructure"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/didcomm/common/model"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/didcomm/common/service"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/didcomm/protocol/decorator"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/didcomm/protocol/mediator"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/doc/did"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/doc/signature/suite"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/doc/signature/suite/ed25519signature2018"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/doc/signature/verifier"
vdrapi "github.com/Universal-Health-Chain/aries-framework-go/pkg/framework/aries/api/vdr"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/kms"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/kms/localkms"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/storage"
connectionstore "github.com/Universal-Health-Chain/aries-framework-go/pkg/store/connection"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/vdr"
)
const (
stateNameNoop = "noop"
stateNameNull = "null"
// StateIDInvited marks the invited phase of the did-exchange protocol.
StateIDInvited = "invited"
// StateIDRequested marks the requested phase of the did-exchange protocol.
StateIDRequested = "requested"
// StateIDResponded marks the responded phase of the did-exchange protocol.
StateIDResponded = "responded"
// StateIDCompleted marks the completed phase of the did-exchange protocol.
StateIDCompleted = "completed"
// StateIDAbandoned marks the abandoned phase of the did-exchange protocol.
StateIDAbandoned = "abandoned"
ackStatusOK = "ok"
didCommServiceType = "did-communication"
didMethod = "peer"
timestamplen = 8
)
var errVerKeyNotFound = errors.New("verkey not found")
// state action for network call.
type stateAction func() error
// The did-exchange protocol's state.
type state interface {
// Name of this state.
Name() string
// Whether this state allows transitioning into the next state.
CanTransitionTo(next state) bool
// ExecuteInbound this state, returning a followup state to be immediately executed as well.
// The 'noOp' state should be returned if the state has no followup.
ExecuteInbound(msg *stateMachineMsg, thid string, ctx *context) (connRecord *connectionstore.Record,
state state, action stateAction, err error)
}
// Returns the state towards which the protocol will transition to if the msgType is processed.
func stateFromMsgType(msgType string) (state, error) {
switch msgType {
case InvitationMsgType, oobMsgType:
return &invited{}, nil
case RequestMsgType:
return &requested{}, nil
case ResponseMsgType:
return &responded{}, nil
case AckMsgType:
return &completed{}, nil
default:
return nil, fmt.Errorf("unrecognized msgType: %s", msgType)
}
}
// Returns the state representing the name.
func stateFromName(name string) (state, error) {
switch name {
case stateNameNoop:
return &noOp{}, nil
case stateNameNull:
return &null{}, nil
case StateIDInvited:
return &invited{}, nil
case StateIDRequested:
return &requested{}, nil
case StateIDResponded:
return &responded{}, nil
case StateIDCompleted:
return &completed{}, nil
case StateIDAbandoned:
return &abandoned{}, nil
default:
return nil, fmt.Errorf("invalid state name %s", name)
}
}
type noOp struct {
}
func (s *noOp) Name() string {
return stateNameNoop
}
func (s *noOp) CanTransitionTo(_ state) bool {
return false
}
func (s *noOp) ExecuteInbound(_ *stateMachineMsg, thid string, ctx *context) (*connectionstore.Record,
state, stateAction, error) {
return nil, nil, nil, errors.New("cannot execute no-op")
}
// null state.
type null struct {
}
func (s *null) Name() string {
return stateNameNull
}
func (s *null) CanTransitionTo(next state) bool {
return StateIDInvited == next.Name() || StateIDRequested == next.Name()
}
func (s *null) ExecuteInbound(msg *stateMachineMsg, thid string, ctx *context) (*connectionstore.Record,
state, stateAction, error) {
return &connectionstore.Record{}, &noOp{}, nil, nil
}
// invited state.
type invited struct {
}
func (s *invited) Name() string {
return StateIDInvited
}
func (s *invited) CanTransitionTo(next state) bool {
return StateIDRequested == next.Name()
}
func (s *invited) ExecuteInbound(msg *stateMachineMsg, _ string, _ *context) (*connectionstore.Record,
state, stateAction, error) {
if msg.Type() != InvitationMsgType && msg.Type() != oobMsgType {
return nil, nil, nil, fmt.Errorf("illegal msg type %s for state %s", msg.Type(), s.Name())
}
return msg.connRecord, &requested{}, func() error { return nil }, nil
}
// requested state.
type requested struct {
}
func (s *requested) Name() string {
return StateIDRequested
}
func (s *requested) CanTransitionTo(next state) bool {
return StateIDResponded == next.Name()
}
func (s *requested) ExecuteInbound(msg *stateMachineMsg, thid string, ctx *context) (*connectionstore.Record,
state, stateAction, error) {
switch msg.Type() {
case oobMsgType:
action, record, err := ctx.handleInboundOOBInvitation(msg, thid, msg.options)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to handle inbound oob invitation : %w", err)
}
return record, &noOp{}, action, nil
case InvitationMsgType:
invitation := &Invitation{}
err := msg.Decode(invitation)
if err != nil {
return nil, nil, nil, fmt.Errorf("JSON unmarshalling of invitation: %w", err)
}
action, connRecord, err := ctx.handleInboundInvitation(invitation, thid, msg.options, msg.connRecord)
if err != nil {
return nil, nil, nil, fmt.Errorf("handle inbound invitation: %w", err)
}
return connRecord, &noOp{}, action, nil
case RequestMsgType:
return msg.connRecord, &responded{}, func() error { return nil }, nil
default:
return nil, nil, nil, fmt.Errorf("illegal msg type %s for state %s", msg.Type(), s.Name())
}
}
// responded state.
type responded struct {
}
func (s *responded) Name() string {
return StateIDResponded
}
func (s *responded) CanTransitionTo(next state) bool {
return StateIDCompleted == next.Name()
}
func (s *responded) ExecuteInbound(msg *stateMachineMsg, thid string, ctx *context) (*connectionstore.Record,
state, stateAction, error) {
switch msg.Type() {
case RequestMsgType:
request := &Request{}
err := msg.Decode(request)
if err != nil {
return nil, nil, nil, fmt.Errorf("JSON unmarshalling of request: %w", err)
}
action, connRecord, err := ctx.handleInboundRequest(request, msg.options, msg.connRecord)
if err != nil {
return nil, nil, nil, fmt.Errorf("handle inbound request: %w", err)
}
return connRecord, &noOp{}, action, nil
case ResponseMsgType:
return msg.connRecord, &completed{}, func() error { return nil }, nil
default:
return nil, nil, nil, fmt.Errorf("illegal msg type %s for state %s", msg.Type(), s.Name())
}
}
// completed state.
type completed struct {
}
func (s *completed) Name() string {
return StateIDCompleted
}
func (s *completed) CanTransitionTo(next state) bool {
return false
}
func (s *completed) ExecuteInbound(msg *stateMachineMsg, thid string, ctx *context) (*connectionstore.Record,
state, stateAction, error) {
switch msg.Type() {
case ResponseMsgType:
response := &Response{}
err := msg.Decode(response)
if err != nil {
return nil, nil, nil, fmt.Errorf("JSON unmarshalling of response: %w", err)
}
action, connRecord, err := ctx.handleInboundResponse(response)
if err != nil {
return nil, nil, nil, fmt.Errorf("handle inbound response: %w", err)
}
return connRecord, &noOp{}, action, nil
case AckMsgType:
action := func() error { return nil }
return msg.connRecord, &noOp{}, action, nil
default:
return nil, nil, nil, fmt.Errorf("illegal msg type %s for state %s", msg.Type(), s.Name())
}
}
// abandoned state.
type abandoned struct {
}
func (s *abandoned) Name() string {
return StateIDAbandoned
}
func (s *abandoned) CanTransitionTo(next state) bool {
return false
}
func (s *abandoned) ExecuteInbound(msg *stateMachineMsg, thid string, ctx *context) (*connectionstore.Record,
state, stateAction, error) {
return nil, nil, nil, errors.New("not implemented")
}
func (ctx *context) handleInboundOOBInvitation(
msg *stateMachineMsg, thid string, options *options) (stateAction, *connectionstore.Record, error) {
myDID, conn, err := ctx.getDIDDocAndConnection(getPublicDID(options), getRouterConnections(options))
if err != nil {
return nil, nil, fmt.Errorf("handleInboundOOBInvitation - failed to get diddoc and connection: %w", err)
}
msg.connRecord.MyDID = myDID.ID
msg.connRecord.ThreadID = thid
oobInvitation := OOBInvitation{}
err = msg.Decode(&oobInvitation)
if err != nil {
return nil, nil, fmt.Errorf("failed to decode oob invitation: %w", err)
}
request := &Request{
Type: RequestMsgType,
ID: thid,
Label: oobInvitation.MyLabel,
Connection: conn,
Thread: &decorator.Thread{
ID: thid,
PID: msg.connRecord.ParentThreadID,
},
}
svc, err := ctx.getServiceBlock(&oobInvitation)
if err != nil {
return nil, nil, fmt.Errorf("failed to get service block: %w", err)
}
dest := &service.Destination{
RecipientKeys: svc.RecipientKeys,
ServiceEndpoint: svc.ServiceEndpoint,
RoutingKeys: svc.RoutingKeys,
}
recipientKey, err := recipientKey(myDID)
if err != nil {
return nil, nil, fmt.Errorf("handle inbound OOBInvitation: %w", err)
}
return func() error {
logger.Debugf("dispatching outbound request on thread: %+v", request.Thread)
return ctx.outboundDispatcher.Send(request, recipientKey, dest)
}, msg.connRecord, nil
}
func (ctx *context) handleInboundInvitation(invitation *Invitation, thid string, options *options,
connRec *connectionstore.Record) (stateAction, *connectionstore.Record, error) {
// create a destination from invitation
destination, err := ctx.getDestination(invitation)
if err != nil {
return nil, nil, err
}
// get did document that will be used in exchange request
didDoc, conn, err := ctx.getDIDDocAndConnection(getPublicDID(options), getRouterConnections(options))
if err != nil {
return nil, nil, err
}
pid := invitation.ID
if connRec.Implicit {
pid = invitation.DID
}
request := &Request{
Type: RequestMsgType,
ID: thid,
Label: getLabel(options),
Connection: conn,
Thread: &decorator.Thread{
PID: pid,
},
}
connRec.MyDID = request.Connection.DID
senderKey, err := recipientKey(didDoc)
if err != nil {
return nil, nil, fmt.Errorf("handle inbound invitation: %w", err)
}
return func() error {
return ctx.outboundDispatcher.Send(request, senderKey, destination)
}, connRec, nil
}
func (ctx *context) handleInboundRequest(request *Request, options *options,
connRec *connectionstore.Record) (stateAction, *connectionstore.Record, error) {
requestDidDoc, err := ctx.resolveDidDocFromConnection(request.Connection)
if err != nil {
return nil, nil, fmt.Errorf("resolve did doc from exchange request connection: %w", err)
}
// get did document that will be used in exchange response
// (my did doc)
responseDidDoc, connection, err := ctx.getDIDDocAndConnection(getPublicDID(options), getRouterConnections(options))
if err != nil {
return nil, nil, err
}
// prepare connection signature
encodedConnectionSignature, err := ctx.prepareConnectionSignature(connection, request.Thread.PID)
if err != nil {
return nil, nil, err
}
// prepare the response
response := &Response{
Type: ResponseMsgType,
ID: uuid.New().String(),
Thread: &decorator.Thread{
ID: request.ID,
},
ConnectionSignature: encodedConnectionSignature,
}
connRec.TheirDID = request.Connection.DID
connRec.MyDID = connection.DID
connRec.TheirLabel = request.Label
destination, err := service.CreateDestination(requestDidDoc)
if err != nil {
return nil, nil, err
}
senderVerKey, err := recipientKey(responseDidDoc)
if err != nil {
return nil, nil, fmt.Errorf("handle inbound request: %w", err)
}
// send exchange response
return func() error {
return ctx.outboundDispatcher.Send(response, senderVerKey, destination)
}, connRec, nil
}
func getPublicDID(options *options) string {
if options == nil {
return ""
}
return options.publicDID
}
func getRouterConnections(options *options) []string {
if options == nil {
return nil
}
return options.routerConnections
}
// returns the label given in the options, otherwise an empty string.
func getLabel(options *options) string {
if options == nil {
return ""
}
return options.label
}
func (ctx *context) getDestination(invitation *Invitation) (*service.Destination, error) {
if invitation.DID != "" {
return service.GetDestination(invitation.DID, ctx.vdRegistry)
}
return &service.Destination{
RecipientKeys: invitation.RecipientKeys,
ServiceEndpoint: invitation.ServiceEndpoint,
RoutingKeys: invitation.RoutingKeys,
}, nil
}
// nolint: funlen,gocyclo
func (ctx *context) getDIDDocAndConnection(pubDID string, routerConnections []string) (*did.Doc, *Connection, error) {
if pubDID != "" {
logger.Debugf("using public did[%s] for connection", pubDID)
docResolution, err := ctx.vdRegistry.Resolve(pubDID)
if err != nil {
return nil, nil, fmt.Errorf("resolve public did[%s]: %w", pubDID, err)
}
err = ctx.connectionStore.SaveDIDFromDoc(docResolution.DIDDocument)
if err != nil {
return nil, nil, err
}
return docResolution.DIDDocument, &Connection{DID: docResolution.DIDDocument.ID}, nil
}
logger.Debugf("creating new '%s' did for connection", didMethod)
var services []did.Service
for _, connID := range routerConnections {
// get the route configs (pass empty service endpoint, as default service endpoint added in VDR)
serviceEndpoint, routingKeys, err := mediator.GetRouterConfig(ctx.routeSvc, connID, "")
if err != nil {
return nil, nil, fmt.Errorf("did doc - fetch router config: %w", err)
}
services = append(services, did.Service{ServiceEndpoint: serviceEndpoint, RoutingKeys: routingKeys})
}
if len(services) == 0 {
services = append(services, did.Service{})
}
// by default use peer did
docResolution, err := ctx.vdRegistry.Create(
didMethod, &did.Doc{Service: services},
)
if err != nil {
return nil, nil, fmt.Errorf("create %s did: %w", didMethod, err)
}
if len(routerConnections) != 0 {
svc, ok := did.LookupService(docResolution.DIDDocument, didCommServiceType)
if ok {
for _, recKey := range svc.RecipientKeys {
for _, connID := range routerConnections {
// TODO https://github.com/hyperledger/aries-framework-go/issues/1105 Support to Add multiple
// recKeys to the Router
if err = mediator.AddKeyToRouter(ctx.routeSvc, connID, recKey); err != nil {
return nil, nil, fmt.Errorf("did doc - add key to the router: %w", err)
}
}
}
}
}
err = ctx.connectionStore.SaveDIDFromDoc(docResolution.DIDDocument)
if err != nil {
return nil, nil, err
}
connection := &Connection{
DID: docResolution.DIDDocument.ID,
DIDDoc: docResolution.DIDDocument,
}
return docResolution.DIDDocument, connection, nil
}
func (ctx *context) resolveDidDocFromConnection(conn *Connection) (*did.Doc, error) {
didDoc := conn.DIDDoc
if didDoc == nil {
// did content was not provided; resolve
docResolution, err := ctx.vdRegistry.Resolve(conn.DID)
if err != nil {
return nil, err
}
return docResolution.DIDDocument, err
}
didMethod, err := vdr.GetDidMethod(didDoc.ID)
if err != nil {
return nil, err
}
// store provided did document
_, err = ctx.vdRegistry.Create(didMethod, didDoc, vdrapi.WithOption("store", true))
if err != nil {
return nil, fmt.Errorf("failed to store provided did document: %w", err)
}
return didDoc, nil
}
// Encode the connection and convert to Connection Signature as per the spec:
// https://github.com/hyperledger/aries-rfcs/tree/master/features/0023-did-exchange
func (ctx *context) prepareConnectionSignature(connection *Connection,
invitationID string) (*ConnectionSignature, error) {
logger.Debugf("connection=%+v invitationID=%s", connection, invitationID)
connAttributeBytes, err := json.Marshal(connection)
if err != nil {
return nil, fmt.Errorf("failed to marshal connection: %w", err)
}
now := getEpochTime()
timestampBuf := make([]byte, timestamplen)
binary.BigEndian.PutUint64(timestampBuf, uint64(now))
concatenateSignData := append(timestampBuf, connAttributeBytes...)
pubKey, err := ctx.getVerKey(invitationID)
if err != nil {
return nil, fmt.Errorf("failed to get verkey: %w", err)
}
signingKID, err := localkms.CreateKID(base58.Decode(pubKey), kms.ED25519Type)
if err != nil {
return nil, fmt.Errorf("prepareConnectionSignature: failed to generate KID from public key: %w", err)
}
kh, err := ctx.kms.Get(signingKID)
if err != nil {
return nil, fmt.Errorf("prepareConnectionSignature: failed to get key handle: %w", err)
}
// TODO: Replace with signed attachments issue-626
signature, err := ctx.crypto.Sign(concatenateSignData, kh)
if err != nil {
return nil, fmt.Errorf("sign response message: %w", err)
}
return &ConnectionSignature{
Type: "https://didcomm.org/signature/1.0/ed25519Sha512_single",
SignedData: base64.URLEncoding.EncodeToString(concatenateSignData),
SignVerKey: base64.URLEncoding.EncodeToString(base58.Decode(pubKey)),
Signature: base64.URLEncoding.EncodeToString(signature),
}, nil
}
func (ctx *context) handleInboundResponse(response *Response) (stateAction, *connectionstore.Record, error) {
ack := &model.Ack{
Type: AckMsgType,
ID: uuid.New().String(),
Status: ackStatusOK,
Thread: &decorator.Thread{
ID: response.Thread.ID,
},
}
nsThID, err := connectionstore.CreateNamespaceKey(myNSPrefix, ack.Thread.ID)
if err != nil {
return nil, nil, err
}
connRecord, err := ctx.connectionStore.GetConnectionRecordByNSThreadID(nsThID)
if err != nil {
return nil, nil, fmt.Errorf("get connection record: %w", err)
}
conn, err := verifySignature(response.ConnectionSignature, connRecord.RecipientKeys[0])
if err != nil {
return nil, nil, err
}
connRecord.TheirDID = conn.DID
responseDidDoc, err := ctx.resolveDidDocFromConnection(conn)
if err != nil {
return nil, nil, fmt.Errorf("resolve did doc from exchange response connection: %w", err)
}
destination, err := service.CreateDestination(responseDidDoc)
if err != nil {
return nil, nil, fmt.Errorf("prepare destination from response did doc: %w", err)
}
docResolution, err := ctx.vdRegistry.Resolve(connRecord.MyDID)
if err != nil {
return nil, nil, fmt.Errorf("fetching did document: %w", err)
}
recKey, err := recipientKey(docResolution.DIDDocument)
if err != nil {
return nil, nil, fmt.Errorf("handle inbound response: %w", err)
}
return func() error {
return ctx.outboundDispatcher.Send(ack, recKey, destination)
}, connRecord, nil
}
// verifySignature verifies connection signature and returns connection.
func verifySignature(connSignature *ConnectionSignature, recipientKeys string) (*Connection, error) {
sigData, err := base64.URLEncoding.DecodeString(connSignature.SignedData)
if err != nil {
return nil, fmt.Errorf("decode signature data: %w", err)
}
if len(sigData) == 0 {
return nil, fmt.Errorf("missing or invalid signature data")
}
signature, err := base64.URLEncoding.DecodeString(connSignature.Signature)
if err != nil {
return nil, fmt.Errorf("decode signature: %w", err)
}
// The signature data must be used to verify against the invitation's recipientKeys for continuity.
pubKey := base58.Decode(recipientKeys)
// TODO: Replace with signed attachments issue-626
suiteVerifier := ed25519signature2018.NewPublicKeyVerifier()
signatureSuite := ed25519signature2018.New(suite.WithVerifier(suiteVerifier))
err = signatureSuite.Verify(&verifier.PublicKey{
Type: kms.ED25519,
Value: pubKey,
},
sigData, signature)
if err != nil {
return nil, fmt.Errorf("verify signature: %w", err)
}
// trimming the timestamp and delimiter - only taking out connection attribute bytes
if len(sigData) <= timestamplen {
return nil, fmt.Errorf("missing connection attribute bytes")
}
connBytes := sigData[timestamplen:]
conn := &Connection{}
err = json.Unmarshal(connBytes, conn)
if err != nil {
return nil, fmt.Errorf("JSON unmarshalling of connection: %w", err)
}
return conn, nil
}
func getEpochTime() int64 {
return time.Now().Unix()
}
func (ctx *context) getVerKey(invitationID string) (string, error) {
pubKey, err := ctx.getVerKeyFromOOBInvitation(invitationID)
if err != nil && !errors.Is(err, errVerKeyNotFound) {
return "", fmt.Errorf("failed to get my verkey from oob invitation: %w", err)
}
if err == nil {
return pubKey, nil
}
var invitation Invitation
if isDID(invitationID) {
invitation = Invitation{ID: invitationID, DID: invitationID}
} else {
err = ctx.connectionStore.GetInvitation(invitationID, &invitation)
if err != nil {
return "", fmt.Errorf("get invitation for signature: %w", err)
}
}
invPubKey, err := ctx.getInvitationRecipientKey(&invitation)
if err != nil {
return "", fmt.Errorf("get invitation recipient key: %w", err)
}
return invPubKey, nil
}
func (ctx *context) getInvitationRecipientKey(invitation *Invitation) (string, error) {
if invitation.DID != "" {
docResolution, err := ctx.vdRegistry.Resolve(invitation.DID)
if err != nil {
return "", fmt.Errorf("get invitation recipient key: %w", err)
}
recKey, err := recipientKey(docResolution.DIDDocument)
if err != nil {
return "", fmt.Errorf("getInvitationRecipientKey: %w", err)
}
return recKey, nil
}
return invitation.RecipientKeys[0], nil
}
func (ctx *context) getVerKeyFromOOBInvitation(invitationID string) (string, error) {
logger.Debugf("invitationID=%s", invitationID)
var invitation OOBInvitation
err := ctx.connectionStore.GetInvitation(invitationID, &invitation)
if errors.Is(err, storage.ErrDataNotFound) {
return "", errVerKeyNotFound
}
if err != nil {
return "", fmt.Errorf("failed to load oob invitation: %w", err)
}
if invitation.Type != oobMsgType {
return "", errVerKeyNotFound
}
pubKey, err := ctx.resolveVerKey(&invitation)
if err != nil {
return "", fmt.Errorf("failed to get my verkey: %w", err)
}
return pubKey, nil
}
func (ctx *context) getServiceBlock(i *OOBInvitation) (*did.Service, error) {
logger.Debugf("extracting service block from oobinvitation=%+v", i)
var block *did.Service
switch svc := i.Target.(type) {
case string:
docResolution, err := ctx.vdRegistry.Resolve(svc)
if err != nil {
return nil, fmt.Errorf("failed to resolve myDID=%s : %w", svc, err)
}
s, found := did.LookupService(docResolution.DIDDocument, didCommServiceType)
if !found {
return nil, fmt.Errorf(
"no valid service block found on myDID=%s with serviceType=%s",
svc, didCommServiceType)
}
block = s
case *did.Service:
block = svc
case map[string]interface{}:
var s did.Service
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{TagName: "json", Result: &s})
if err != nil {
return nil, fmt.Errorf("failed to initialize decoder : %w", err)
}
err = decoder.Decode(svc)
if err != nil {
return nil, fmt.Errorf("failed to decode service block : %w", err)
}
block = &s
default:
return nil, fmt.Errorf("unsupported target type: %+v", svc)
}
logger.Debugf("extracted service block=%+v", block)
return block, nil
}
func (ctx *context) resolveVerKey(i *OOBInvitation) (string, error) {
logger.Debugf("extracting verkey from oobinvitation=%+v", i)
svc, err := ctx.getServiceBlock(i)
if err != nil {
return "", fmt.Errorf("failed to get service block from oobinvitation : %w", err)
}
logger.Debugf("extracted verkey=%s", svc.RecipientKeys[0])
return svc.RecipientKeys[0], nil
}
func isDID(str string) bool {
const didPrefix = "did:"
return strings.HasPrefix(str, didPrefix)
}
// returns the did:key ID of the first element in the doc's destination RecipientKeys.
func recipientKey(doc *did.Doc) (string, error) {
dest, err := service.CreateDestination(doc)
if err != nil {
return "", fmt.Errorf("failed to create destination: %w", err)
}
return dest.RecipientKeys[0], nil
}