/
vdr.go
386 lines (310 loc) · 9.71 KB
/
vdr.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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
// Package sidetreelongform implement long-form vdr
package sidetreelongform
import (
"crypto"
"crypto/ed25519"
"crypto/rand"
"encoding/json"
"fmt"
"strings"
"github.com/btcsuite/btcutil/base58"
jsonld "github.com/piprate/json-gold/ld"
"github.com/trustbloc/sidetree-go/pkg/document"
ld "github.com/trustbloc/did-go/doc/ld/documentloader"
ldstore "github.com/trustbloc/did-go/doc/ld/store"
docdid "github.com/trustbloc/did-go/doc/did"
"github.com/trustbloc/did-go/legacy/mem"
vdrapi "github.com/trustbloc/did-go/vdr/api"
"github.com/trustbloc/sidetree-go/pkg/vdr/sidetreelongform/dochandler"
"github.com/trustbloc/sidetree-go/pkg/vdr/sidetreelongform/sidetree"
"github.com/trustbloc/sidetree-go/pkg/vdr/sidetreelongform/sidetree/doc"
"github.com/trustbloc/sidetree-go/pkg/vdr/sidetreelongform/sidetree/option/create"
)
const (
// UpdatePublicKeyOpt update public key opt.
UpdatePublicKeyOpt = "updatePublicKey"
// RecoveryPublicKeyOpt recovery public key opt.
RecoveryPublicKeyOpt = "recoveryPublicKey"
sha2_256 = 18
defaultDIDMethod = "ion"
// DIDAcceptOpt is DID accept option.
DIDAcceptOpt = "didAcceptOpt"
// VDRAcceptOpt is VDR accept option.
VDRAcceptOpt = "vdrAcceptOpt"
)
type sidetreeClient interface {
CreateDID(opts ...create.Option) (*docdid.DocResolution, error)
}
// VDR bloc.
type VDR struct {
method string
sidetreeDocHandler sidetreeDocumentHandler
sidetreeClient sidetreeClient
documentLoader jsonld.DocumentLoader
}
type sidetreeDocumentHandler interface {
ResolveDocument(longFormDID string, opts ...document.ResolutionOption) (*document.ResolutionResult, error)
ProcessOperation(operationBuffer []byte) (*document.ResolutionResult, error)
}
// New creates new long form VDR.
func New(opts ...Option) (*VDR, error) {
v := &VDR{method: defaultDIDMethod}
for _, opt := range opts {
opt(v)
}
if v.documentLoader == nil {
l, err := createJSONLDDocumentLoader()
if err != nil {
return nil, fmt.Errorf("failed to init default jsonld document loader: %w", err)
}
v.documentLoader = l
}
var err error
v.sidetreeDocHandler, err = dochandler.New(fmt.Sprintf("did:%s", v.method))
if err != nil {
return nil, err
}
v.sidetreeClient = sidetree.New(sidetree.WithSidetreeOperationRequestFnc(v.sendRequest))
return v, nil
}
type ldStoreProvider struct {
ContextStore ldstore.ContextStore
RemoteProviderStore ldstore.RemoteProviderStore
}
func (p *ldStoreProvider) JSONLDContextStore() ldstore.ContextStore {
return p.ContextStore
}
func (p *ldStoreProvider) JSONLDRemoteProviderStore() ldstore.RemoteProviderStore {
return p.RemoteProviderStore
}
func createJSONLDDocumentLoader() (jsonld.DocumentLoader, error) {
contextStore, err := ldstore.NewContextStore(mem.NewProvider())
if err != nil {
return nil, fmt.Errorf("create JSON-LD context store: %w", err)
}
remoteProviderStore, err := ldstore.NewRemoteProviderStore(mem.NewProvider())
if err != nil {
return nil, fmt.Errorf("create remote provider store: %w", err)
}
ldStore := &ldStoreProvider{
ContextStore: contextStore,
RemoteProviderStore: remoteProviderStore,
}
documentLoader, err := ld.NewDocumentLoader(ldStore)
if err != nil {
return nil, fmt.Errorf("new document loader: %w", err)
}
return documentLoader, nil
}
// Accept did method.
func (v *VDR) Accept(method string, opts ...vdrapi.DIDMethodOption) bool {
if method != v.method {
return false
}
// method is valid; now check additional info (if present)
acceptOpts := &vdrapi.DIDMethodOpts{Values: make(map[string]interface{})}
// apply options
for _, opt := range opts {
opt(acceptOpts)
}
// vdr accept option can be provided as additional clue for choosing (or rejecting) VDR
vdrAcceptObj, ok := acceptOpts.Values[VDRAcceptOpt]
if ok {
vdrAccept, strOk := vdrAcceptObj.(string)
if strOk {
return vdrAccept == "long-form"
}
}
// DID accept option is always provided by registry for read, update and deactivate.
didObj, ok := acceptOpts.Values[DIDAcceptOpt]
if ok {
did, strOk := didObj.(string)
if strOk {
didParts := strings.Split(did, ":")
return len(didParts) > 3
}
}
return false
}
// Close vdr.
func (v *VDR) Close() error {
return nil
}
// Create did doc.
//
//nolint:gocyclo,funlen
func (v *VDR) Create(did *docdid.Doc,
opts ...vdrapi.DIDMethodOption) (*docdid.DocResolution, error) {
didMethodOpts := &vdrapi.DIDMethodOpts{Values: make(map[string]interface{})}
// Apply options
for _, opt := range opts {
opt(didMethodOpts)
}
createOpt := make([]create.Option, 0)
// get keys
if didMethodOpts.Values[UpdatePublicKeyOpt] == nil {
updateKey, _, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, fmt.Errorf("creating default update key: %w", err)
}
didMethodOpts.Values[UpdatePublicKeyOpt] = updateKey
}
updatePublicKey, ok := didMethodOpts.Values[UpdatePublicKeyOpt].(crypto.PublicKey)
if !ok {
return nil, fmt.Errorf("upatePublicKey is not crypto.PublicKey")
}
if didMethodOpts.Values[RecoveryPublicKeyOpt] == nil {
recoveryKey, _, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, fmt.Errorf("creating default recovery key: %w", err)
}
didMethodOpts.Values[RecoveryPublicKeyOpt] = recoveryKey
}
recoveryPublicKey, ok := didMethodOpts.Values[RecoveryPublicKeyOpt].(crypto.PublicKey)
if !ok {
return nil, fmt.Errorf("recoveryPublicKey is not crypto.PublicKey")
}
// get also known as
for i := range did.AlsoKnownAs {
createOpt = append(createOpt, create.WithAlsoKnownAs(did.AlsoKnownAs[i]))
}
// get services
for i := range did.Service {
createOpt = append(createOpt, create.WithService(&did.Service[i]))
}
// get verification method
pks, err := getSidetreePublicKeys(did)
if err != nil {
return nil, err
}
for k := range pks {
createOpt = append(createOpt, create.WithPublicKey(pks[k].publicKey))
}
createOpt = append(createOpt,
create.WithMultiHashAlgorithm(sha2_256),
create.WithUpdatePublicKey(updatePublicKey),
create.WithRecoveryPublicKey(recoveryPublicKey))
createdDID, err := v.sidetreeClient.CreateDID(createOpt...)
if err != nil {
return nil, err
}
return createdDID, nil
}
// Read long-form DID.
func (v *VDR) Read(longFormDID string, _ ...vdrapi.DIDMethodOption) (*docdid.DocResolution, error) {
resolutionResult, err := v.sidetreeDocHandler.ResolveDocument(longFormDID)
if err != nil {
return nil, err
}
resolutionResultBytes, err := json.Marshal(resolutionResult)
if err != nil {
return nil, err
}
documentResolution, err := docdid.ParseDocumentResolution(resolutionResultBytes)
if err != nil {
return nil, err
}
return &docdid.DocResolution{
DIDDocument: documentResolution.DIDDocument,
DocumentMetadata: documentResolution.DocumentMetadata,
Context: documentResolution.Context,
}, nil
}
// Update did doc.
func (v *VDR) Update(_ *docdid.Doc, _ ...vdrapi.DIDMethodOption) error {
return fmt.Errorf("not implemented")
}
// Deactivate did doc.
func (v *VDR) Deactivate(_ string, _ ...vdrapi.DIDMethodOption) error {
return fmt.Errorf("not implemented")
}
func (v *VDR) sendRequest(req []byte, _ sidetree.GetEndpointsFunc) ([]byte, error) {
didResolution, err := v.sidetreeDocHandler.ProcessOperation(req)
if err != nil {
return nil, err
}
return json.Marshal(didResolution)
}
type pk struct {
value []byte
publicKey *doc.PublicKey
}
func getSidetreePublicKeys(didDoc *docdid.Doc) (map[string]*pk, error) { //nolint:funlen,gocyclo
pksMap := make(map[string]*pk)
ver := make([]docdid.Verification, 0)
ver = append(ver, didDoc.Authentication...)
ver = append(ver, didDoc.AssertionMethod...)
ver = append(ver, didDoc.CapabilityDelegation...)
ver = append(ver, didDoc.CapabilityInvocation...)
ver = append(ver, didDoc.KeyAgreement...)
for _, v := range ver {
var purpose string
switch v.Relationship { //nolint: exhaustive
case docdid.Authentication:
purpose = doc.KeyPurposeAuthentication
case docdid.AssertionMethod:
purpose = doc.KeyPurposeAssertionMethod
case docdid.CapabilityDelegation:
purpose = doc.KeyPurposeCapabilityDelegation
case docdid.CapabilityInvocation:
purpose = doc.KeyPurposeCapabilityInvocation
case docdid.KeyAgreement:
purpose = doc.KeyPurposeKeyAgreement
default:
return nil, fmt.Errorf("vm relationship %d not supported", v.Relationship)
}
s := strings.Split(v.VerificationMethod.ID, "#")
id := s[0]
if len(s) > 1 {
id = s[1]
}
value, ok := pksMap[id]
if ok {
value.publicKey.Purposes = append(value.publicKey.Purposes, purpose)
continue
}
switch {
case v.VerificationMethod.JSONWebKey() != nil:
pksMap[id] = &pk{
publicKey: &doc.PublicKey{
ID: id,
Type: v.VerificationMethod.Type,
Purposes: []string{purpose},
JWK: *v.VerificationMethod.JSONWebKey(),
},
value: v.VerificationMethod.Value,
}
case v.VerificationMethod.Value != nil:
pksMap[id] = &pk{
publicKey: &doc.PublicKey{
ID: id,
Type: v.VerificationMethod.Type,
Purposes: []string{purpose},
B58Key: base58.Encode(v.VerificationMethod.Value),
},
value: v.VerificationMethod.Value,
}
default:
return nil, fmt.Errorf("verificationMethod needs either JSONWebKey or Base58 key")
}
}
return pksMap, nil
}
// Option configures the long-form vdr.
type Option func(opts *VDR)
// WithDocumentLoader overrides the default JSONLD document loader used when processing JSONLD DID Documents.
func WithDocumentLoader(l jsonld.DocumentLoader) Option {
return func(opts *VDR) {
opts.documentLoader = l
}
}
// WithDIDMethod overrides the default did method.
func WithDIDMethod(method string) Option {
return func(opts *VDR) {
opts.method = method
}
}