forked from hyperledger-archives/aries-framework-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
826 lines (672 loc) · 19.9 KB
/
service.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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package introduce
import (
"encoding/json"
"errors"
"fmt"
"sort"
"time"
"github.com/google/uuid"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/common/log"
"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/outofband"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/storage"
)
const (
// Introduce protocol name.
Introduce = "introduce"
// IntroduceSpec defines the introduce spec.
IntroduceSpec = "https://didcomm.org/introduce/1.0/"
// ProposalMsgType defines the introduce proposal message type.
ProposalMsgType = IntroduceSpec + "proposal"
// RequestMsgType defines the introduce request message type.
RequestMsgType = IntroduceSpec + "request"
// ResponseMsgType defines the introduce response message type.
ResponseMsgType = IntroduceSpec + "response"
// AckMsgType defines the introduce ack message type.
AckMsgType = IntroduceSpec + "ack"
// ProblemReportMsgType defines the introduce problem-report message type.
ProblemReportMsgType = IntroduceSpec + "problem-report"
// stateOOBRequested the outofband protocol state name to determine specific event.
stateOOBRequested = "requested"
)
const (
maxIntroducees = 2
participantsKey = "participants_%s_%s"
stateNameKey = "state_name_"
transitionalPayloadKey = "transitionalPayload_%s"
metadataKey = "metadata_%s"
jsonMetadata = "_internal_metadata"
)
var (
logger = log.New("aries-framework/introduce/service")
errProtocolStopped = errors.New("protocol was stopped")
)
// customError is a wrapper to determine custom error against internal error.
type customError struct{ error }
// Recipient keeps information needed for the service
// 'To' field is needed for the proposal message
// 'MyDID' and 'TheirDID' fields are needed for sending messages e.g report-problem, proposal, ack etc.
type Recipient struct {
To *To `json:"to"`
Goal string `json:"goal"`
GoalCode string `json:"goal_code"`
MyDID string `json:"my_did,omitempty"`
TheirDID string `json:"their_did,omitempty"`
}
// Action contains helpful information about action.
type Action struct {
// Protocol instance ID
PIID string
Msg service.DIDCommMsgMap
MyDID string
TheirDID string
}
// transitionalPayload keeps payload needed for Continue function to proceed with the action.
type transitionalPayload struct {
Action
StateName string
}
// metaData type to store data for internal usage.
type metaData struct {
transitionalPayload
state state
msgClone service.DIDCommMsg
participants []*participant
rejected bool
inbound bool
saveMetadata func(msg service.DIDCommMsgMap, thID string) error
// err is used to determine whether callback was stopped
// e.g the user received an action event and executes Stop(err) function
// in that case `err` is equal to `err` which was passing to Stop function
err error
}
// Service for introduce protocol.
type Service struct {
service.Action
service.Message
store storage.Store
callbacks chan *metaData
oobEvent chan service.StateMsg
messenger service.Messenger
}
// Provider contains dependencies for the DID exchange protocol and is typically created by using aries.Context().
type Provider interface {
Messenger() service.Messenger
StorageProvider() storage.Provider
Service(id string) (interface{}, error)
}
// New returns introduce service.
func New(p Provider) (*Service, error) {
store, err := p.StorageProvider().OpenStore(Introduce)
if err != nil {
return nil, err
}
oobSvc, err := p.Service(outofband.Name)
if err != nil {
return nil, fmt.Errorf("load the %s service: %w", outofband.Name, err)
}
oobService, ok := oobSvc.(service.Event)
if !ok {
return nil, fmt.Errorf("cast service to service.Event")
}
svc := &Service{
messenger: p.Messenger(),
store: store,
callbacks: make(chan *metaData),
oobEvent: make(chan service.StateMsg),
}
if err = oobService.RegisterMsgEvent(svc.oobEvent); err != nil {
return nil, fmt.Errorf("oob register msg event: %w", err)
}
// start the listener
go svc.startInternalListener()
return svc, nil
}
// startInternalListener listens to messages in gochannel for callback messages from clients.
func (s *Service) startInternalListener() {
for {
select {
case msg := <-s.callbacks:
// if no error or it was rejected do handle
if msg.err == nil || msg.rejected {
msg.err = s.handle(msg)
}
// no error - continue
if msg.err == nil {
continue
}
msg.state = &abandoning{Code: codeInternalError}
logInternalError(msg.err)
if err := s.handle(msg); err != nil {
logger.Errorf("listener handle: %s", err)
}
case event := <-s.oobEvent:
if err := s.OOBMessageReceived(event); err != nil {
logger.Errorf("listener oob message received: %s", err)
}
}
}
}
func logInternalError(err error) {
if _, ok := err.(customError); !ok {
logger.Errorf("go to abandoning: %v", err)
}
}
func getPIID(msg service.DIDCommMsgMap) (string, error) {
piID := msg.Metadata()[metaPIID]
if piID, ok := piID.(string); ok && piID != "" {
return piID, nil
}
return threadID(msg)
}
func threadID(msg service.DIDCommMsgMap) (string, error) {
if pthID := msg.ParentThreadID(); pthID != "" {
return pthID, nil
}
thID, err := msg.ThreadID()
if errors.Is(err, service.ErrThreadIDNotFound) {
msg["@id"] = uuid.New().String()
return msg["@id"].(string), nil
}
return thID, err
}
func (s *Service) doHandle(msg service.DIDCommMsg, outbound bool) (*metaData, error) {
msgMap := msg.Clone()
piID, err := getPIID(msgMap)
if err != nil {
return nil, fmt.Errorf("piID: %w", err)
}
stateName, err := s.currentStateName(piID)
if err != nil {
return nil, fmt.Errorf("currentStateName: %w", err)
}
current := stateFromName(stateName)
next, err := nextState(msgMap, outbound)
if err != nil {
return nil, fmt.Errorf("nextState: %w", err)
}
if !current.CanTransitionTo(next) {
return nil, fmt.Errorf("invalid state transition: %s -> %s", current.Name(), next.Name())
}
return &metaData{
transitionalPayload: transitionalPayload{
StateName: next.Name(),
Action: Action{
Msg: msg.Clone(),
PIID: piID,
},
},
saveMetadata: s.saveMetadata,
state: next,
msgClone: msgMap.Clone(),
}, nil
}
// OOBMessageReceived is used to finish the state machine
// the function should be called by the out-of-band service after receiving an oob message.
func (s *Service) OOBMessageReceived(msg service.StateMsg) error {
if msg.StateID != stateOOBRequested || msg.Type != service.PostState || msg.Msg.ParentThreadID() == "" {
return nil
}
// NOTE: the message is being used internally.
// Do not modify the payload such as ID and Thread.
_, err := s.HandleInbound(service.NewDIDCommMsgMap(&model.Ack{
Type: AckMsgType,
ID: uuid.New().String(),
Thread: &decorator.Thread{ID: msg.Msg.ParentThreadID()},
}), "internal", "internal")
return err
}
// HandleInbound handles inbound message (introduce protocol).
func (s *Service) HandleInbound(msg service.DIDCommMsg, myDID, theirDID string) (string, error) {
aEvent := s.ActionEvent()
// throw error if there is no action event registered for inbound messages
if aEvent == nil {
return "", errors.New("no clients are registered to handle the message")
}
if err := s.populateMetadata(msg.(service.DIDCommMsgMap)); err != nil {
return "", fmt.Errorf("populate metadata: %w", err)
}
md, err := s.doHandle(msg, false)
if err != nil {
return "", fmt.Errorf("doHandle: %w", err)
}
// sets inbound payload
md.inbound = true
md.MyDID = myDID
md.TheirDID = theirDID
// trigger action event based on message type for inbound messages
if canTriggerActionEvents(msg) {
err = s.saveTransitionalPayload(md.PIID, md.transitionalPayload)
if err != nil {
return "", fmt.Errorf("save transitional payload: %w", err)
}
aEvent <- s.newDIDCommActionMsg(md)
return md.PIID, nil
}
// if no action event is triggered, continue the execution
return md.PIID, s.handle(md)
}
// HandleOutbound handles outbound message (introduce protocol).
func (s *Service) HandleOutbound(msg service.DIDCommMsg, myDID, theirDID string) (string, error) {
md, err := s.doHandle(msg, true)
if err != nil {
return "", fmt.Errorf("doHandle: %w", err)
}
// sets outbound payload
md.MyDID = myDID
md.TheirDID = theirDID
return md.PIID, s.handle(md)
}
// sendMsgEvents triggers the message events.
func (s *Service) sendMsgEvents(md *metaData, stateID string, stateType service.StateMsgType) {
// trigger the message events
for _, handler := range s.MsgEvents() {
handler <- service.StateMsg{
ProtocolName: Introduce,
Type: stateType,
Msg: md.msgClone,
StateID: stateID,
Properties: newEventProps(md),
}
}
}
// newDIDCommActionMsg creates new DIDCommAction message.
func (s *Service) newDIDCommActionMsg(md *metaData) service.DIDCommAction {
// create the message for the channel
// trigger the registered action event
actionStop := func(err error) {
// if introducee received Proposal rejected must be true
if md.Msg.Type() == ProposalMsgType {
md.rejected = true
}
md.err = err
s.processCallback(md)
}
return service.DIDCommAction{
ProtocolName: Introduce,
Message: md.msgClone,
Continue: func(opt interface{}) {
if fn, ok := opt.(Opt); ok {
fn(md.Msg.Metadata())
}
if md.Msg.Type() == RequestMsgType {
if md.Msg.Metadata()[metaRecipients] == nil {
md.err = errors.New("no recipients")
}
}
if err := s.deleteTransitionalPayload(md.PIID); err != nil {
logger.Errorf("delete transitional payload", err)
}
s.processCallback(md)
},
Stop: func(err error) {
if err == nil {
err = errProtocolStopped
}
actionStop(customError{error: err})
},
Properties: newEventProps(md),
}
}
// ActionContinue allows proceeding with the action by the piID.
func (s *Service) ActionContinue(piID string, opt Opt) error {
tPayload, err := s.getTransitionalPayload(piID)
if err != nil {
return fmt.Errorf("get transitional payload: %w", err)
}
md := &metaData{
transitionalPayload: *tPayload,
state: stateFromName(tPayload.StateName),
msgClone: tPayload.Msg.Clone(),
inbound: true,
saveMetadata: s.saveMetadata,
}
if opt != nil {
opt(md.Msg.Metadata())
}
if md.Msg.Type() == RequestMsgType {
if md.Msg.Metadata()[metaRecipients] == nil {
return errors.New("no recipients")
}
}
if err := s.deleteTransitionalPayload(md.PIID); err != nil {
logger.Errorf("delete transitional payload", err)
}
s.processCallback(md)
return nil
}
// ActionStop allows stopping the action by the piID.
func (s *Service) ActionStop(piID string, cErr error) error {
tPayload, err := s.getTransitionalPayload(piID)
if err != nil {
return fmt.Errorf("get transitional payload: %w", err)
}
md := &metaData{
transitionalPayload: *tPayload,
state: stateFromName(tPayload.StateName),
msgClone: tPayload.Msg.Clone(),
inbound: true,
saveMetadata: s.saveMetadata,
}
if err := s.deleteTransitionalPayload(md.PIID); err != nil {
return fmt.Errorf("delete transitional payload: %w", err)
}
// if introducee received Proposal rejected must be true
if md.Msg.Type() == ProposalMsgType {
md.rejected = true
}
if cErr == nil {
cErr = errProtocolStopped
}
md.err = customError{error: cErr}
s.processCallback(md)
return nil
}
func (s *Service) processCallback(msg *metaData) {
// pass the callback data to internal channel. This is created to unblock consumer go routine and wrap the callback
// channel internally.
s.callbacks <- msg
}
func nextState(msg service.DIDCommMsg, outbound bool) (state, error) {
switch msg.Type() {
case RequestMsgType:
if outbound {
return &requesting{}, nil
}
return &arranging{}, nil
case ProposalMsgType:
if outbound {
return &arranging{}, nil
}
return &deciding{}, nil
case ResponseMsgType:
return &arranging{}, nil
case ProblemReportMsgType:
return &abandoning{}, nil
case AckMsgType:
return &done{}, nil
default:
return nil, fmt.Errorf("unrecognized msgType: %s", msg.Type())
}
}
func (s *Service) currentStateName(piID string) (string, error) {
src, err := s.store.Get(stateNameKey + piID)
if errors.Is(err, storage.ErrDataNotFound) {
return stateNameStart, nil
}
return string(src), err
}
// Actions returns actions for the async usage.
func (s *Service) Actions() ([]Action, error) {
records := s.store.Iterator(
fmt.Sprintf(transitionalPayloadKey, ""),
fmt.Sprintf(transitionalPayloadKey, storage.EndKeySuffix),
)
defer records.Release()
var actions []Action
for records.Next() {
if records.Error() != nil {
return nil, records.Error()
}
var action Action
if err := json.Unmarshal(records.Value(), &action); err != nil {
return nil, fmt.Errorf("unmarshal: %w", err)
}
actions = append(actions, action)
}
return actions, nil
}
func (s *Service) deleteTransitionalPayload(id string) error {
return s.store.Delete(fmt.Sprintf(transitionalPayloadKey, id))
}
func (s *Service) saveTransitionalPayload(id string, data transitionalPayload) error {
src, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("marshal transitional payload: %w", err)
}
return s.store.Put(fmt.Sprintf(transitionalPayloadKey, id), src)
}
func (s *Service) getTransitionalPayload(id string) (*transitionalPayload, error) {
src, err := s.store.Get(fmt.Sprintf(transitionalPayloadKey, id))
if err != nil {
return nil, fmt.Errorf("store get: %w", err)
}
t := &transitionalPayload{}
err = json.Unmarshal(src, t)
if err != nil {
return nil, fmt.Errorf("unmarshal transitional payload: %w", err)
}
return t, err
}
func (s *Service) saveStateName(piID, stateName string) error {
return s.store.Put(stateNameKey+piID, []byte(stateName))
}
// nolint: gocyclo
// stateFromName returns the state by given name.
func stateFromName(name string) state {
switch name {
case stateNameNoop:
return &noOp{}
case stateNameStart:
return &start{}
case stateNameDone:
return &done{}
case stateNameArranging:
return &arranging{}
case stateNameDelivering:
return &delivering{}
case stateNameConfirming:
return &confirming{}
case stateNameAbandoning:
return &abandoning{}
case stateNameRequesting:
return &requesting{}
case stateNameDeciding:
return &deciding{}
case stateNameWaiting:
return &waiting{}
default:
return &noOp{}
}
}
// canTriggerActionEvents checks if the incoming message can trigger an action event.
func canTriggerActionEvents(msg service.DIDCommMsg) bool {
switch msg.Type() {
case ProposalMsgType, RequestMsgType, ProblemReportMsgType:
return true
}
return false
}
func isNoOp(s state) bool {
_, ok := s.(*noOp)
return ok
}
// isSkipProposal is a helper function to determine whether this is skip proposal or not.
func isSkipProposal(md *metaData) bool {
if md.Msg.Metadata()[metaSkipProposal] == nil {
return false
}
return md.Msg.Metadata()[metaSkipProposal].(bool)
}
func (s *Service) handle(md *metaData) error {
if err := s.saveResponse(md); err != nil {
return err
}
var (
current = md.state
actions []stateAction
stateName string
)
for !isNoOp(current) {
stateName = current.Name()
next, action, err := s.execute(current, md)
if err != nil {
return fmt.Errorf("execute: %w", err)
}
actions = append(actions, action)
if !isNoOp(next) && !current.CanTransitionTo(next) {
return fmt.Errorf("invalid state transition: %s --> %s", current.Name(), next.Name())
}
current = next
}
if err := s.saveStateName(md.PIID, stateName); err != nil {
return fmt.Errorf("failed to persist state %s: %w", stateName, err)
}
for _, action := range actions {
if err := action(); err != nil {
return err
}
}
return nil
}
func contextOOBMessage(msg service.DIDCommMsg) map[string]interface{} {
var oobMsg map[string]interface{}
switch v := msg.Metadata()[metaOOBMessage].(type) {
case service.DIDCommMsgMap:
oobMsg = v.Clone()
for k := range v.Metadata() {
delete(oobMsg, k)
}
case map[string]interface{}:
oobMsg = v
}
return oobMsg
}
type participant struct {
OOBMessage map[string]interface{}
Approve bool
Message service.DIDCommMsgMap
MyDID string
TheirDID string
ThreadID string
CreatedAt time.Time
}
func (s *Service) saveResponse(md *metaData) error {
// ignore if message is not response
if md.Msg.Type() != ResponseMsgType {
return nil
}
// checks whether response was already handled
for _, p := range md.participants {
if p.Message.ID() == md.Msg.ID() {
return nil
}
}
r := Response{}
if err := md.Msg.Decode(&r); err != nil {
return err
}
thID, err := md.Msg.ThreadID()
if err != nil {
return fmt.Errorf("threadID: %w", err)
}
err = s.saveParticipant(md.PIID, &participant{
OOBMessage: r.OOBMessage,
Approve: r.Approve,
Message: md.Msg,
MyDID: md.MyDID,
TheirDID: md.TheirDID,
ThreadID: thID,
CreatedAt: time.Now(),
})
if err != nil {
return fmt.Errorf("save participant: %w", err)
}
md.participants, err = s.getParticipants(md.PIID)
return err
}
func (s *Service) saveParticipant(piID string, p *participant) error {
src, err := json.Marshal(p)
if err != nil {
return fmt.Errorf("marshal: %w", err)
}
return s.store.Put(fmt.Sprintf(participantsKey, piID, uuid.New().String()), src)
}
func (s *Service) getParticipants(piID string) ([]*participant, error) {
records := s.store.Iterator(fmt.Sprintf(participantsKey, piID, ""),
fmt.Sprintf(participantsKey, piID, storage.EndKeySuffix))
defer records.Release()
var participants []*participant
for records.Next() {
if records.Error() != nil {
return nil, records.Error()
}
var participant *participant
if err := json.Unmarshal(records.Value(), &participant); err != nil {
return nil, fmt.Errorf("unmarshal: %w", err)
}
participants = append(participants, participant)
}
sort.Slice(participants, func(i, j int) bool {
return participants[i].CreatedAt.UnixNano() < participants[j].CreatedAt.UnixNano()
})
return participants, nil
}
func (s *Service) execute(next state, md *metaData) (state, stateAction, error) {
md.state = next
s.sendMsgEvents(md, next.Name(), service.PreState)
defer s.sendMsgEvents(md, next.Name(), service.PostState)
var (
followup state
err error
action func() error
)
if md.inbound {
followup, action, err = next.ExecuteInbound(s.messenger, md)
} else {
followup, action, err = next.ExecuteOutbound(s.messenger, md)
}
if err != nil {
return nil, nil, fmt.Errorf("execute state %s %w", next.Name(), err)
}
return followup, action, nil
}
func (s *Service) populateMetadata(msg service.DIDCommMsgMap) error {
thID, err := msg.ThreadID()
if err != nil {
return fmt.Errorf("threadID: %w", err)
}
rec, err := s.store.Get(fmt.Sprintf(metadataKey, thID))
if errors.Is(err, storage.ErrDataNotFound) {
return nil
}
if err != nil {
return fmt.Errorf("get record: %w", err)
}
res := map[string]interface{}{}
err = json.Unmarshal(rec, &res)
if err != nil {
return fmt.Errorf("get record: %w", err)
}
msg[jsonMetadata] = res
return nil
}
func (s *Service) saveMetadata(msg service.DIDCommMsgMap, thID string) error {
metadata := msg.Metadata()
if len(metadata) == 0 {
return nil
}
src, err := json.Marshal(metadata)
if err != nil {
return fmt.Errorf("marshal: %w", err)
}
return s.store.Put(fmt.Sprintf(metadataKey, thID), src)
}
// Name returns service name.
func (s *Service) Name() string {
return Introduce
}
// Accept msg checks the msg type.
func (s *Service) Accept(msgType string) bool {
switch msgType {
case ProposalMsgType, RequestMsgType, ResponseMsgType, AckMsgType, ProblemReportMsgType:
return true
}
return false
}