forked from hyperledger-aries/aries-framework-go-ext
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
642 lines (510 loc) · 16.6 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
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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
// Package sidetree implements sidetree client
package sidetree
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/hyperledger/aries-framework-go/pkg/common/log"
docdid "github.com/hyperledger/aries-framework-go/pkg/doc/did"
"github.com/trustbloc/sidetree-core-go/pkg/commitment"
"github.com/trustbloc/sidetree-core-go/pkg/hashing"
"github.com/trustbloc/sidetree-core-go/pkg/patch"
"github.com/trustbloc/sidetree-core-go/pkg/util/pubkey"
"github.com/trustbloc/sidetree-core-go/pkg/versions/1_0/client"
"github.com/hyperledger/aries-framework-go-ext/component/vdr/sidetree/doc"
"github.com/hyperledger/aries-framework-go-ext/component/vdr/sidetree/option/create"
"github.com/hyperledger/aries-framework-go-ext/component/vdr/sidetree/option/deactivate"
"github.com/hyperledger/aries-framework-go-ext/component/vdr/sidetree/option/recovery"
"github.com/hyperledger/aries-framework-go-ext/component/vdr/sidetree/option/update"
)
const (
defaultHashAlgorithm = 18
)
var logger = log.New("aries-framework-ext/vdr/sidetree/client") //nolint: gochecknoglobals
type authTokenProvider interface {
AuthToken() (string, error)
}
// Client sidetree client.
type Client struct {
client *http.Client
authToken string
authTokenProvider authTokenProvider
sendRequest func(req []byte, getEndpoints func() ([]string, error)) ([]byte, error)
}
// New return sidetree client.
func New(opts ...Option) *Client {
c := &Client{client: &http.Client{}}
c.sendRequest = c.defaultSendRequest
// Apply options
for _, opt := range opts {
opt(c)
}
return c
}
// CreateDID create did doc.
func (c *Client) CreateDID(opts ...create.Option) (*docdid.DocResolution, error) { //
createDIDOpts := &create.Opts{MultiHashAlgorithm: defaultHashAlgorithm}
// Apply options
for _, opt := range opts {
opt(createDIDOpts)
}
err := validateCreateReq(createDIDOpts)
if err != nil {
return nil, err
}
req, err := buildCreateRequest(createDIDOpts.MultiHashAlgorithm, createDIDOpts)
if err != nil {
return nil, fmt.Errorf("failed to build sidetree request: %w", err)
}
responseBytes, err := c.sendRequest(req, createDIDOpts.GetEndpoints)
if err != nil {
return nil, fmt.Errorf("failed to send create sidetree request: %w", err)
}
documentResolution, err := docdid.ParseDocumentResolution(responseBytes)
if err != nil {
if !errors.Is(err, docdid.ErrDIDDocumentNotExist) {
return nil, fmt.Errorf("failed to parse document resolution: %w", err)
}
logger.Warnf("failed to parse document resolution %w", err)
} else {
return documentResolution, nil
}
didDoc, err := docdid.ParseDocument(responseBytes)
if err != nil {
return nil, fmt.Errorf("failed to parse did document: %w", err)
}
return &docdid.DocResolution{DIDDocument: didDoc}, nil
}
// UpdateDID update did doc.
func (c *Client) UpdateDID(did string, opts ...update.Option) error {
updateDIDOpts := &update.Opts{MultiHashAlgorithm: defaultHashAlgorithm}
// Apply options
for _, opt := range opts {
opt(updateDIDOpts)
}
err := validateUpdateReq(updateDIDOpts)
if err != nil {
return err
}
req, err := c.buildUpdateRequest(did, updateDIDOpts.MultiHashAlgorithm, updateDIDOpts)
if err != nil {
return fmt.Errorf("failed to build update request: %w", err)
}
_, err = c.sendRequest(req, updateDIDOpts.GetEndpoints)
if err != nil {
return fmt.Errorf("failed to send update did request: %w", err)
}
return nil
}
// RecoverDID recover did doc.
func (c *Client) RecoverDID(did string, opts ...recovery.Option) error {
recoverDIDOpts := &recovery.Opts{MultiHashAlgorithm: defaultHashAlgorithm}
// Apply options
for _, opt := range opts {
opt(recoverDIDOpts)
}
err := validateRecoverReq(recoverDIDOpts)
if err != nil {
return err
}
req, err := buildRecoverRequest(did, recoverDIDOpts.MultiHashAlgorithm, recoverDIDOpts)
if err != nil {
return fmt.Errorf("failed to build sidetree request: %w", err)
}
_, err = c.sendRequest(req, recoverDIDOpts.GetEndpoints)
if err != nil {
return fmt.Errorf("failed to send recover sidetree request: %w", err)
}
return err
}
// DeactivateDID deactivate did doc.
func (c *Client) DeactivateDID(did string, opts ...deactivate.Option) error {
deactivateDIDOpts := &deactivate.Opts{}
// Apply options
for _, opt := range opts {
opt(deactivateDIDOpts)
}
err := validateDeactivateReq(deactivateDIDOpts)
if err != nil {
return err
}
req, err := buildDeactivateRequest(did, deactivateDIDOpts)
if err != nil {
return fmt.Errorf("failed to build sidetree request: %w", err)
}
_, err = c.sendRequest(req, deactivateDIDOpts.GetEndpoints)
if err != nil {
return fmt.Errorf("failed to send deactivate sidetree request: %w", err)
}
return err
}
func validateCreateReq(createDIDOpts *create.Opts) error {
if createDIDOpts.RecoveryPublicKey == nil {
return fmt.Errorf("recovery public key is required")
}
if createDIDOpts.UpdatePublicKey == nil {
return fmt.Errorf("update public key is required")
}
return nil
}
func validateUpdateReq(updateDIDOpts *update.Opts) error {
if updateDIDOpts.Signer == nil {
return fmt.Errorf("signer is required")
}
if updateDIDOpts.NextUpdatePublicKey == nil {
return fmt.Errorf("next update public key is required")
}
if updateDIDOpts.OperationCommitment == "" {
return fmt.Errorf("operation commitment is required")
}
return nil
}
func validateRecoverReq(recoverDIDOpts *recovery.Opts) error {
if recoverDIDOpts.NextRecoveryPublicKey == nil {
return fmt.Errorf("next recovery public key is required")
}
if recoverDIDOpts.NextUpdatePublicKey == nil {
return fmt.Errorf("next update public key is required")
}
if recoverDIDOpts.Signer == nil {
return fmt.Errorf("signer is required")
}
if recoverDIDOpts.OperationCommitment == "" {
return fmt.Errorf("operation commitment is required")
}
return nil
}
func validateDeactivateReq(deactivateDIDOpts *deactivate.Opts) error {
if deactivateDIDOpts.Signer == nil {
return fmt.Errorf("signer is required")
}
if deactivateDIDOpts.OperationCommitment == "" {
return fmt.Errorf("operation commitment is required")
}
return nil
}
// buildCreateRequest request builder for sidetree public DID creation.
func buildCreateRequest(multiHashAlgorithm uint, createDIDOpts *create.Opts) ([]byte, error) {
didDoc := &doc.Doc{
PublicKey: createDIDOpts.PublicKeys,
Service: createDIDOpts.Services,
AlsoKnownAs: createDIDOpts.AlsoKnownAs,
}
docBytes, err := didDoc.JSONBytes()
if err != nil {
return nil, fmt.Errorf("failed to get document bytes : %w", err)
}
recoveryKey, err := pubkey.GetPublicKeyJWK(createDIDOpts.RecoveryPublicKey)
if err != nil {
return nil, fmt.Errorf("failed to get recovery key : %w", err)
}
updateKey, err := pubkey.GetPublicKeyJWK(createDIDOpts.UpdatePublicKey)
if err != nil {
return nil, fmt.Errorf("failed to get update key : %w", err)
}
recoveryCommitment, err := commitment.GetCommitment(recoveryKey, multiHashAlgorithm)
if err != nil {
return nil, err
}
updateCommitment, err := commitment.GetCommitment(updateKey, multiHashAlgorithm)
if err != nil {
return nil, err
}
createRequestInfo := &client.CreateRequestInfo{
OpaqueDocument: string(docBytes),
RecoveryCommitment: recoveryCommitment,
UpdateCommitment: updateCommitment,
MultihashCode: multiHashAlgorithm,
}
if createDIDOpts.AnchorOrigin != "" {
createRequestInfo.AnchorOrigin = createDIDOpts.AnchorOrigin
}
req, err := client.NewCreateRequest(createRequestInfo)
if err != nil {
return nil, fmt.Errorf("failed to create sidetree request: %w", err)
}
return req, nil
}
// buildUpdateRequest request builder for sidetree public DID update.
func (c *Client) buildUpdateRequest(did string, multiHashAlgorithm uint,
updateDIDOpts *update.Opts) ([]byte, error) {
nextUpdateKey, err := pubkey.GetPublicKeyJWK(updateDIDOpts.NextUpdatePublicKey)
if err != nil {
return nil, fmt.Errorf("failed to get next update key : %w", err)
}
nextUpdateCommitment, err := commitment.GetCommitment(nextUpdateKey, multiHashAlgorithm)
if err != nil {
return nil, err
}
patches, err := createUpdatePatches(updateDIDOpts)
if err != nil {
return nil, err
}
didSuffix, err := getUniqueSuffix(did)
if err != nil {
return nil, err
}
multihashCode, err := hashing.GetMultihashCode(updateDIDOpts.OperationCommitment)
if err != nil {
return nil, err
}
rv, err := commitment.GetRevealValue(updateDIDOpts.Signer.PublicKeyJWK(), uint(multihashCode))
if err != nil {
return nil, err
}
return client.NewUpdateRequest(&client.UpdateRequestInfo{
DidSuffix: didSuffix,
RevealValue: rv,
UpdateCommitment: nextUpdateCommitment,
UpdateKey: updateDIDOpts.Signer.PublicKeyJWK(),
Patches: patches,
MultihashCode: multiHashAlgorithm,
Signer: updateDIDOpts.Signer,
})
}
// buildRecoverRequest request builder for sidetree public DID recovery.
func buildRecoverRequest(did string, multiHashAlgorithm uint, recoverDIDOpts *recovery.Opts) ([]byte, error) {
didDoc := &doc.Doc{
PublicKey: recoverDIDOpts.PublicKeys,
Service: recoverDIDOpts.Services,
AlsoKnownAs: recoverDIDOpts.AlsoKnownAs,
}
docBytes, err := didDoc.JSONBytes()
if err != nil {
return nil, fmt.Errorf("failed to get document bytes : %w", err)
}
nextRecoveryCommitment, nextUpdateCommitment, err := getCommitment(multiHashAlgorithm, recoverDIDOpts)
if err != nil {
return nil, err
}
didSuffix, err := getUniqueSuffix(did)
if err != nil {
return nil, err
}
multihashCode, err := hashing.GetMultihashCode(recoverDIDOpts.OperationCommitment)
if err != nil {
return nil, err
}
rv, err := commitment.GetRevealValue(recoverDIDOpts.Signer.PublicKeyJWK(), uint(multihashCode))
if err != nil {
return nil, err
}
recoverRequestInfo := &client.RecoverRequestInfo{
DidSuffix: didSuffix, RevealValue: rv, OpaqueDocument: string(docBytes),
RecoveryCommitment: nextRecoveryCommitment, UpdateCommitment: nextUpdateCommitment,
MultihashCode: multiHashAlgorithm, Signer: recoverDIDOpts.Signer,
RecoveryKey: recoverDIDOpts.Signer.PublicKeyJWK(),
}
if recoverDIDOpts.AnchorOrigin != "" {
recoverRequestInfo.AnchorOrigin = recoverDIDOpts.AnchorOrigin
}
req, err := client.NewRecoverRequest(recoverRequestInfo)
if err != nil {
return nil, fmt.Errorf("failed to create sidetree request: %w", err)
}
return req, nil
}
// buildDeactivateRequest request builder for sidetree public DID deactivate.
func buildDeactivateRequest(did string, deactivateDIDOpts *deactivate.Opts) ([]byte, error) {
didSuffix, err := getUniqueSuffix(did)
if err != nil {
return nil, err
}
multihashCode, err := hashing.GetMultihashCode(deactivateDIDOpts.OperationCommitment)
if err != nil {
return nil, err
}
rv, err := commitment.GetRevealValue(deactivateDIDOpts.Signer.PublicKeyJWK(), uint(multihashCode))
if err != nil {
return nil, err
}
return client.NewDeactivateRequest(&client.DeactivateRequestInfo{
DidSuffix: didSuffix,
RevealValue: rv,
RecoveryKey: deactivateDIDOpts.Signer.PublicKeyJWK(),
Signer: deactivateDIDOpts.Signer,
})
}
func (c *Client) defaultSendRequest(req []byte, getEndpoints func() ([]string, error)) ([]byte, error) {
if getEndpoints == nil {
return nil, fmt.Errorf("sidetree get endpoints func is required")
}
endpoints, err := getEndpoints()
if err != nil {
return nil, fmt.Errorf("sidetree get endpoints: %w", err)
}
// TODO add logic for using different sidetree endpoint
// for now will use the first one
endpointURL := endpoints[0]
httpReq, err := http.NewRequestWithContext(context.Background(),
http.MethodPost, endpointURL, bytes.NewReader(req))
if err != nil {
return nil, fmt.Errorf("failed to create http request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
authToken := c.authToken
if c.authTokenProvider != nil {
v, errToken := c.authTokenProvider.AuthToken()
if errToken != nil {
return nil, errToken
}
authToken = "Bearer " + v
}
if authToken != "" {
httpReq.Header.Add("Authorization", authToken)
}
resp, err := c.client.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer closeResponseBody(resp.Body)
responseBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response : %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("got unexpected response from %s status '%d' body %s",
endpointURL, resp.StatusCode, responseBytes)
}
return responseBytes, nil
}
func createUpdatePatches(updateDIDOpts *update.Opts) ([]patch.Patch, error) { //nolint: gocyclo
var patches []patch.Patch
if len(updateDIDOpts.RemoveAlsoKnownAs) != 0 {
p, err := createRemoveAlsoKnownAsPatch(updateDIDOpts)
if err != nil {
return nil, err
}
patches = append(patches, p)
}
if len(updateDIDOpts.RemovePublicKeys) != 0 {
p, err := createRemovePublicKeysPatch(updateDIDOpts)
if err != nil {
return nil, err
}
patches = append(patches, p)
}
if len(updateDIDOpts.RemoveServices) != 0 {
p, err := createRemoveServicesPatch(updateDIDOpts)
if err != nil {
return nil, err
}
patches = append(patches, p)
}
if len(updateDIDOpts.AddAlsoKnownAs) != 0 {
p, err := createAddAlsoKnownAsPatch(updateDIDOpts)
if err != nil {
return nil, err
}
patches = append(patches, p)
}
if len(updateDIDOpts.AddServices) != 0 {
p, err := createAddServicesPatch(updateDIDOpts)
if err != nil {
return nil, err
}
patches = append(patches, p)
}
if len(updateDIDOpts.AddPublicKeys) != 0 {
p, err := createAddPublicKeysPatch(updateDIDOpts)
if err != nil {
return nil, err
}
patches = append(patches, p)
}
return patches, nil
}
func createRemovePublicKeysPatch(updateDIDOpts *update.Opts) (patch.Patch, error) {
removePubKeys, err := json.Marshal(updateDIDOpts.RemovePublicKeys)
if err != nil {
return nil, err
}
return patch.NewRemovePublicKeysPatch(string(removePubKeys))
}
func createRemoveServicesPatch(updateDIDOpts *update.Opts) (patch.Patch, error) {
removeServices, err := json.Marshal(updateDIDOpts.RemoveServices)
if err != nil {
return nil, err
}
return patch.NewRemoveServiceEndpointsPatch(string(removeServices))
}
func createRemoveAlsoKnownAsPatch(updateDIDOpts *update.Opts) (patch.Patch, error) {
removeAlsoKnownAs, err := json.Marshal(updateDIDOpts.RemoveAlsoKnownAs)
if err != nil {
return nil, err
}
return patch.NewRemoveAlsoKnownAs(string(removeAlsoKnownAs))
}
func createAddAlsoKnownAsPatch(updateDIDOpts *update.Opts) (patch.Patch, error) {
rawAlsoKnownAs := doc.PopulateRawAlsoKnownAs(updateDIDOpts.AddAlsoKnownAs)
addAlsoKnownAs, err := json.Marshal(rawAlsoKnownAs)
if err != nil {
return nil, err
}
return patch.NewAddAlsoKnownAs(string(addAlsoKnownAs))
}
func createAddServicesPatch(updateDIDOpts *update.Opts) (patch.Patch, error) {
rawServices, err := doc.PopulateRawServices(updateDIDOpts.AddServices)
if err != nil {
return nil, err
}
addServices, err := json.Marshal(rawServices)
if err != nil {
return nil, err
}
return patch.NewAddServiceEndpointsPatch(string(addServices))
}
func createAddPublicKeysPatch(updateDIDOpts *update.Opts) (patch.Patch, error) {
rawPublicKeys, err := doc.PopulateRawPublicKeys(updateDIDOpts.AddPublicKeys)
if err != nil {
return nil, err
}
addPublicKeys, err := json.Marshal(rawPublicKeys)
if err != nil {
return nil, err
}
return patch.NewAddPublicKeysPatch(string(addPublicKeys))
}
func getUniqueSuffix(id string) (string, error) {
p := strings.LastIndex(id, ":")
if p == -1 {
return "", fmt.Errorf("unique suffix not provided in id [%s]", id)
}
return id[p+1:], nil
}
func getCommitment(multiHashAlgorithm uint, recoverDIDOpts *recovery.Opts) (nextRecoveryCommitment string,
nextUpdateCommitment string, err error) {
nextRecoveryKey, err := pubkey.GetPublicKeyJWK(recoverDIDOpts.NextRecoveryPublicKey)
if err != nil {
return "", "", fmt.Errorf("failed to get next recovery key : %w", err)
}
nextUpdateKey, err := pubkey.GetPublicKeyJWK(recoverDIDOpts.NextUpdatePublicKey)
if err != nil {
return "", "", fmt.Errorf("failed to get next update key : %w", err)
}
nextRecoveryCommitment, err = commitment.GetCommitment(nextRecoveryKey, multiHashAlgorithm)
if err != nil {
return "", "", err
}
nextUpdateCommitment, err = commitment.GetCommitment(nextUpdateKey, multiHashAlgorithm)
if err != nil {
return "", "", err
}
return nextRecoveryCommitment, nextUpdateCommitment, nil
}
func closeResponseBody(respBody io.Closer) {
e := respBody.Close()
if e != nil {
logger.Errorf("Failed to close response body: %v", e)
}
}