forked from hyperledger-archives/aries-framework-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
443 lines (359 loc) · 13.8 KB
/
client.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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package didexchange
import (
"encoding/json"
"errors"
"fmt"
"github.com/btcsuite/btcutil/base58"
"github.com/google/uuid"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/didcomm/common/service"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/didcomm/protocol/didexchange"
"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/kms"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/storage"
"github.com/Universal-Health-Chain/aries-framework-go/pkg/store/connection"
)
const (
// InvitationMsgType defines the did-exchange invite message type.
InvitationMsgType = didexchange.InvitationMsgType
// RequestMsgType defines the did-exchange request message type.
RequestMsgType = didexchange.RequestMsgType
// ProtocolName is the framework's friendly name for the did exchange protocol.
ProtocolName = didexchange.DIDExchange
)
// ErrConnectionNotFound is returned when connection not found.
var ErrConnectionNotFound = errors.New("connection not found")
type options struct {
routerConnections []string
routerConnectionID string
}
func applyOptions(args ...Opt) *options {
opts := &options{}
for i := range args {
args[i](opts)
}
return opts
}
// Opt represents option function.
type Opt func(*options)
// InvOpt represents option for the CreateInvitation function.
type InvOpt Opt
// WithRouterConnectionID allows you to specify the router connection ID.
func WithRouterConnectionID(conn string) InvOpt {
return func(opts *options) {
opts.routerConnectionID = conn
}
}
// WithRouterConnections allows you to specify the router connections.
func WithRouterConnections(conns ...string) Opt {
return func(opts *options) {
for _, conn := range conns {
// filters out empty connections
if conn != "" {
opts.routerConnections = append(opts.routerConnections, conn)
}
}
}
}
// provider contains dependencies for the DID exchange protocol and is typically created by using aries.Context().
type provider interface {
Service(id string) (interface{}, error)
KMS() kms.KeyManager
ServiceEndpoint() string
StorageProvider() storage.Provider
ProtocolStateStorageProvider() storage.Provider
}
// Client enable access to didexchange api.
type Client struct {
service.Event
didexchangeSvc protocolService
routeSvc mediator.ProtocolService
kms kms.KeyManager
serviceEndpoint string
connectionStore *connection.Recorder
}
// protocolService defines DID Exchange service.
type protocolService interface {
// DIDComm service
service.DIDComm
// Accepts/Approves exchange request
AcceptExchangeRequest(connectionID, publicDID, label string, routerConnections []string) error
// Accepts/Approves exchange invitation
AcceptInvitation(connectionID, publicDID, label string, routerConnections []string) error
// CreateImplicitInvitation creates implicit invitation. Inviter DID is required, invitee DID is optional.
// If invitee DID is not provided new peer DID will be created for implicit invitation exchange request.
CreateImplicitInvitation(inviterLabel, inviterDID, inviteeLabel,
inviteeDID string, routerConnections []string) (string, error)
// CreateConnection saves the connection record.
CreateConnection(*connection.Record, *did.Doc) error
}
// New return new instance of didexchange client.
func New(ctx provider) (*Client, error) {
svc, err := ctx.Service(didexchange.DIDExchange)
if err != nil {
return nil, err
}
didexchangeSvc, ok := svc.(protocolService)
if !ok {
return nil, errors.New("cast service to DIDExchange Service failed")
}
s, err := ctx.Service(mediator.Coordination)
if err != nil {
return nil, err
}
routeSvc, ok := s.(mediator.ProtocolService)
if !ok {
return nil, errors.New("cast service to Route Service failed")
}
connectionStore, err := connection.NewRecorder(ctx)
if err != nil {
return nil, err
}
return &Client{
Event: didexchangeSvc,
didexchangeSvc: didexchangeSvc,
routeSvc: routeSvc,
kms: ctx.KMS(),
serviceEndpoint: ctx.ServiceEndpoint(),
connectionStore: connectionStore,
}, nil
}
// CreateInvitation creates an invitation. New key pair will be generated and base58 encoded public key will be
// used as basis for invitation. This invitation will be stored so client can cross reference this invitation during
// did exchange protocol.
func (c *Client) CreateInvitation(label string, args ...InvOpt) (*Invitation, error) {
opts := &options{}
for i := range args {
args[i](opts)
}
// TODO https://github.com/hyperledger/aries-framework-go/issues/623 'alias' should be passed as arg and persisted
// with connection record
_, sigPubKey, err := c.kms.CreateAndExportPubKeyBytes(kms.ED25519Type)
if err != nil {
return nil, fmt.Errorf("createInvitation: failed to extract public SigningKey bytes from handle:%w", err)
}
sigPubKeyB58 := base58.Encode(sigPubKey)
var (
serviceEndpoint = c.serviceEndpoint
routingKeys []string
)
if opts.routerConnectionID != "" {
// get the route configs
serviceEndpoint, routingKeys, err = mediator.GetRouterConfig(c.routeSvc,
opts.routerConnectionID, c.serviceEndpoint)
if err != nil {
return nil, fmt.Errorf("createInvitation: getRouterConfig: %w", err)
}
if err = mediator.AddKeyToRouter(c.routeSvc, opts.routerConnectionID, sigPubKeyB58); err != nil {
return nil, fmt.Errorf("createInvitation: AddKeyToRouter: %w", err)
}
}
invitation := &didexchange.Invitation{
ID: uuid.New().String(),
Label: label,
RecipientKeys: []string{sigPubKeyB58},
ServiceEndpoint: serviceEndpoint,
Type: didexchange.InvitationMsgType,
RoutingKeys: routingKeys,
}
err = c.connectionStore.SaveInvitation(invitation.ID, invitation)
if err != nil {
return nil, fmt.Errorf("createInvitation: failed to save invitation: %w", err)
}
return &Invitation{invitation}, nil
}
// CreateInvitationWithDID creates an invitation with specified public DID. This invitation will be stored
// so client can cross reference this invitation during did exchange protocol.
func (c *Client) CreateInvitationWithDID(label, publicDID string) (*Invitation, error) {
invitation := &didexchange.Invitation{
ID: uuid.New().String(),
Label: label,
DID: publicDID,
Type: didexchange.InvitationMsgType,
}
err := c.connectionStore.SaveInvitation(invitation.ID, invitation)
if err != nil {
return nil, fmt.Errorf("createInvitationWithDID: failed to save invitation with DID: %w", err)
}
return &Invitation{invitation}, nil
}
// HandleInvitation handle incoming invitation and returns the connectionID that can be used to query the state
// of did exchange protocol. Upon successful completion of did exchange protocol connection details will be used
// for securing communication between agents.
func (c *Client) HandleInvitation(invitation *Invitation) (string, error) {
payload, err := json.Marshal(invitation)
if err != nil {
return "", fmt.Errorf("handleInvitation: failed marshal invitation: %w", err)
}
msg, err := service.ParseDIDCommMsgMap(payload)
if err != nil {
return "", fmt.Errorf("handleInvitation: failed to create DIDCommMsg: %w", err)
}
connectionID, err := c.didexchangeSvc.HandleInbound(msg, "", "")
if err != nil {
return "", fmt.Errorf("handleInvitation: failed from didexchange service handle: %w", err)
}
return connectionID, nil
}
// TODO https://github.com/hyperledger/aries-framework-go/issues/754 - e.Continue v Explicit API call for action events
// AcceptInvitation accepts/approves exchange invitation. This call is not used if auto execute is setup
// for this client (see package example for more details about how to setup auto execute).
func (c *Client) AcceptInvitation(connectionID, publicDID, label string, args ...Opt) error {
opts := applyOptions(args...)
if err := c.didexchangeSvc.AcceptInvitation(connectionID, publicDID, label, opts.routerConnections); err != nil {
return fmt.Errorf("did exchange client - accept exchange invitation: %w", err)
}
return nil
}
// AcceptExchangeRequest accepts/approves exchange request. This call is not used if auto execute is setup
// for this client (see package example for more details about how to setup auto execute).
func (c *Client) AcceptExchangeRequest(connectionID, publicDID, label string, args ...Opt) error {
err := c.didexchangeSvc.AcceptExchangeRequest(connectionID, publicDID, label,
applyOptions(args...).routerConnections)
if err != nil {
return fmt.Errorf("did exchange client - accept exchange request: %w", err)
}
return nil
}
// CreateImplicitInvitation enables invitee to create and send an exchange request using inviter public DID.
func (c *Client) CreateImplicitInvitation(inviterLabel, inviterDID string, args ...Opt) (string, error) {
return c.didexchangeSvc.CreateImplicitInvitation(inviterLabel, inviterDID,
"", "", applyOptions(args...).routerConnections)
}
// CreateImplicitInvitationWithDID enables invitee to create implicit invitation using inviter and invitee public DID.
func (c *Client) CreateImplicitInvitationWithDID(inviter, invitee *DIDInfo) (string, error) {
if inviter == nil || invitee == nil {
return "", errors.New("missing inviter and/or invitee public DID(s)")
}
return c.didexchangeSvc.CreateImplicitInvitation(inviter.Label, inviter.DID, invitee.Label, invitee.DID, nil)
}
// QueryConnections queries connections matching given criteria(parameters).
func (c *Client) QueryConnections(request *QueryConnectionsParams) ([]*Connection, error) { //nolint: gocyclo
// TODO https://github.com/hyperledger/aries-framework-go/issues/655 - query all connections from all criteria and
// also results needs to be paged.
records, err := c.connectionStore.QueryConnectionRecords()
if err != nil {
return nil, fmt.Errorf("failed query connections: %w", err)
}
var result []*Connection
for _, record := range records {
if request.State != "" && request.State != record.State {
continue
}
if request.InvitationID != "" && request.InvitationID != record.InvitationID {
continue
}
if request.ParentThreadID != "" && request.ParentThreadID != record.ParentThreadID {
continue
}
if request.MyDID != "" && request.MyDID != record.MyDID {
continue
}
if request.TheirDID != "" && request.TheirDID != record.TheirDID {
continue
}
result = append(result, &Connection{Record: record})
}
return result, nil
}
// GetConnection fetches single connection record for given id.
func (c *Client) GetConnection(connectionID string) (*Connection, error) {
conn, err := c.connectionStore.GetConnectionRecord(connectionID)
if err != nil {
if errors.Is(err, storage.ErrDataNotFound) {
return nil, ErrConnectionNotFound
}
return nil, fmt.Errorf("cannot fetch state from store: connectionid=%s err=%s", connectionID, err)
}
return &Connection{
conn,
}, nil
}
// GetConnectionAtState fetches connection record for connection id at particular state.
func (c *Client) GetConnectionAtState(connectionID, stateID string) (*Connection, error) {
conn, err := c.connectionStore.GetConnectionRecordAtState(connectionID, stateID)
if err != nil {
if errors.Is(err, storage.ErrDataNotFound) {
return nil, ErrConnectionNotFound
}
return nil, fmt.Errorf("cannot fetch state from store: connectionid=%s err=%s", connectionID, err)
}
return &Connection{
conn,
}, nil
}
// CreateConnection creates a new connection between myDID and theirDID and returns the connectionID.
func (c *Client) CreateConnection(myDID string, theirDID *did.Doc, options ...ConnectionOption) (string, error) {
conn := &Connection{&connection.Record{
ConnectionID: uuid.New().String(),
State: connection.StateNameCompleted,
TheirDID: theirDID.ID,
MyDID: myDID,
Namespace: connection.MyNSPrefix,
}}
for i := range options {
options[i](conn)
}
destination, err := service.CreateDestination(theirDID)
if err != nil {
return "", fmt.Errorf("createConnection: failed to create destination: %w", err)
}
conn.ServiceEndPoint = destination.ServiceEndpoint
conn.RecipientKeys = destination.RecipientKeys
conn.RoutingKeys = destination.RoutingKeys
err = c.didexchangeSvc.CreateConnection(conn.Record, theirDID)
if err != nil {
return "", fmt.Errorf("createConnection: err: %w", err)
}
return conn.ConnectionID, nil
}
// RemoveConnection removes connection record for given id.
func (c *Client) RemoveConnection(connectionID string) error {
err := c.connectionStore.RemoveConnection(connectionID)
if err != nil {
return fmt.Errorf("cannot remove connection from the store: err=%w", err)
}
return nil
}
// ConnectionOption allows you to customize details of the connection record.
type ConnectionOption func(*Connection)
// WithTheirLabel sets TheirLabel on the connection record.
func WithTheirLabel(l string) ConnectionOption {
return func(c *Connection) {
c.TheirLabel = l
}
}
// WithThreadID sets ThreadID on the connection record.
func WithThreadID(thid string) ConnectionOption {
return func(c *Connection) {
c.ThreadID = thid
}
}
// WithParentThreadID sets ParentThreadID on the connection record.
func WithParentThreadID(pthid string) ConnectionOption {
return func(c *Connection) {
c.ParentThreadID = pthid
}
}
// WithInvitationID sets InvitationID on the connection record.
func WithInvitationID(id string) ConnectionOption {
return func(c *Connection) {
c.InvitationID = id
}
}
// WithInvitationDID sets InvitationDID on the connection record.
func WithInvitationDID(didID string) ConnectionOption {
return func(c *Connection) {
c.InvitationDID = didID
}
}
// WithImplicit sets Implicit on the connection record.
func WithImplicit(i bool) ConnectionOption {
return func(c *Connection) {
c.Implicit = i
}
}