-
Notifications
You must be signed in to change notification settings - Fork 21
/
did.go
502 lines (423 loc) · 15.7 KB
/
did.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
// Package did is a set of tools to work with Decentralized Identifiers (DIDs) as described
// in the DID spec https://w3c-ccg.github.io/did-spec
package did
import (
"fmt"
"strings"
)
// A DID represents a parsed DID or a DID Reference
type DID struct {
// DID Method
// https://w3c-ccg.github.io/did-spec#dfn-did-method
Method string
// The specific-idstring component of a DID
ID string
// specific-idstring may be composed of multiple `:` separated idstrings
// did = "did:" method ":" specific-idstring
// specific-idstring = idstring *( ":" idstring )
IDStrings []string
// DID Path, the portion of a DID reference that follows the first forward slash character.
// https://w3c-ccg.github.io/did-spec/#dfn-did-path
Path string
// Path may be composed of multiple `/` separated segments
// did-path = segment-nz *( "/" segment )
PathSegments []string
// DID Fragment, the portion of a DID reference that follows the first hash sign character ("#")
// https://w3c-ccg.github.io/did-spec/#dfn-did-fragment
Fragment string
}
// the parsers internal state
type parser struct {
input string // input to the parser
currentIndex int // index in the input which the parser is currently processing
out *DID // the output DID that the parser will assemble as it steps through its state machine
err error // an error in the parser state machine
}
// a step in the parser state machine that returns the next step
type parserStep func() parserStep
// String encodes a DID struct into a valid DID string.
func (d *DID) String() string {
var buf strings.Builder
// write the did: prefix
buf.WriteString("did:") // nolint, returned error is always nil
if d.Method != "" {
// write method followed by a `:`
buf.WriteString(d.Method) // nolint, returned error is always nil
buf.WriteByte(':') // nolint, returned error is always nil
} else {
// if there is no Method, return an empty string
return ""
}
if d.ID != "" {
buf.WriteString(d.ID) // nolint, returned error is always nil
} else if len(d.IDStrings) > 0 {
// join IDStrings with a colon to make the ID
buf.WriteString(strings.Join(d.IDStrings[:], ":")) // nolint, returned error is always nil
} else {
// if there is no ID, return an empty string
return ""
}
if d.Path != "" {
// write a leading / and then Path
buf.WriteByte('/') // nolint, returned error is always nil
buf.WriteString(d.Path) // nolint, returned error is always nil
} else if len(d.PathSegments) > 0 {
// write a leading / and then PathSegments joined with / between them
buf.WriteByte('/') // nolint, returned error is always nil
buf.WriteString(strings.Join(d.PathSegments[:], "/")) // nolint, returned error is always nil
} else {
// add fragment only when there is no path
if d.Fragment != "" {
buf.WriteByte('#') // nolint, returned error is always nil
buf.WriteString(d.Fragment) // nolint, returned error is always nil
}
}
return buf.String()
}
// Parse parses the input string into a DID structure.
func Parse(input string) (*DID, error) {
// intialize the parser state
p := &parser{input: input, out: &DID{}}
// the parser state machine is implemented as a loop over parser steps
// steps increment p.currentIndex as they consume the input, each step returns the next step to run
// the state machine halts when one of the steps returns nil
//
// This design is based on this talk from Rob Pike, although the talk focuses on lexical scanning,
// the DID grammar is simple enough for us to combine lexing and parsing into one lexerless parse
// http://www.youtube.com/watch?v=HxaD_trXwRE
parserState := p.checkLength
for parserState != nil {
parserState = parserState()
}
// If one of the steps added an err to the parser state, exit. Return nil and the error.
err := p.err
if err != nil {
return nil, err
}
// join IDStrings with : to make up ID
p.out.ID = strings.Join(p.out.IDStrings[:], ":")
// join PathSegments with / to make up Path
p.out.Path = strings.Join(p.out.PathSegments[:], "/")
return p.out, nil
}
// checkLength is a parserStep that checks if the input length is atleast 7
// the grammar requires
// `did:` prefix (4 chars)
// + atleast one methodchar (1 char)
// + `:` (1 char)
// + atleast one idchar (1 char)
// i.e atleast 7 chars
// The current specification does not take a position on maximum length of a DID.
// https://w3c-ccg.github.io/did-spec/#upper-limits-on-did-character-length
func (p *parser) checkLength() parserStep {
inputLength := len(p.input)
if inputLength < 7 {
return p.errorf(inputLength, "input length is less than 7")
}
return p.parseScheme
}
// parseScheme is a parserStep that validates that the input begins with 'did:'
func (p *parser) parseScheme() parserStep {
currentIndex := 3 // 4 bytes in 'did:', i.e index 3
// the grammer requires `did:` prefix
if p.input[:currentIndex+1] != "did:" {
return p.errorf(currentIndex, "input does not begin with 'did:' prefix")
}
p.currentIndex = currentIndex
return p.parseMethod
}
// parseMethod is a parserStep that extracts the DID Method
// from the grammar:
// did = "did:" method ":" specific-idstring
// method = 1*methodchar
// methodchar = %x61-7A / DIGIT ; 61-7A is a-z in US-ASCII
func (p *parser) parseMethod() parserStep {
input := p.input
inputLength := len(input)
currentIndex := p.currentIndex + 1
startIndex := currentIndex
// parse method name
// loop over every byte following the ':' in 'did:' unlil the second ':'
// method is the string between the two ':'s
for {
if currentIndex == inputLength {
// we got to the end of the input and didn't find a second ':'
return p.errorf(currentIndex, "input does not have a second `:` marking end of method name")
}
// read the input character at currentIndex
char := input[currentIndex]
if char == ':' {
// we've found the second : in the input that marks the end of the method
if currentIndex == startIndex {
// return error is method is empty, ex- did::1234
return p.errorf(currentIndex, "method is empty")
}
break
}
// as per the grammer method can only be made of digits 0-9 or small letters a-z
if isNotDigit(char) && isNotSmallLetter(char) {
return p.errorf(currentIndex, "character is not a-z OR 0-9")
}
// move to the next char
currentIndex = currentIndex + 1
}
// set parser state
p.currentIndex = currentIndex
p.out.Method = input[startIndex:currentIndex]
// method is followed by specific-idstring, parse that next
return p.parseID
}
// parseID is a parserStep that extracts : separated idstrings that are part of a specific-idstring
// and adds them to p.out.IDStrings
// from the grammar:
// specific-idstring = idstring *( ":" idstring )
// idstring = 1*idchar
// idchar = ALPHA / DIGIT / "." / "-"
// p.out.IDStrings is later concatented by the Parse function before it returns.
func (p *parser) parseID() parserStep {
input := p.input
inputLength := len(input)
currentIndex := p.currentIndex + 1
startIndex := currentIndex
var next parserStep
for {
if currentIndex == inputLength {
// we've reached end of input, no next state
next = nil
break
}
char := input[currentIndex]
if char == ':' {
// encountered : input may have another idstring, parse ID again
next = p.parseID
break
}
if char == '/' {
// encountered / input may have a path following specific-idstring, parse that next
next = p.parsePath
break
}
if char == '#' {
// encountered # input may have a fragment following specific-idstring, parse that next
next = p.parseFragment
break
}
// make sure current char is a valid idchar
// idchar = ALPHA / DIGIT / "." / "-"
if isNotValidIDChar(char) {
return p.errorf(currentIndex, "byte is not ALPHA OR DIGIT OR '.' OR '-'")
}
// move to the next char
currentIndex = currentIndex + 1
}
if currentIndex == startIndex {
// idstring length is zero
// from the grammar:
// idstring = 1*idchar
// return error because idstring is empty, ex- did:a::123:456
return p.errorf(currentIndex, "idstring must be atleast one char long")
}
// set parser state
p.currentIndex = currentIndex
p.out.IDStrings = append(p.out.IDStrings, input[startIndex:currentIndex])
// return the next parser step
return next
}
// parsePath is a parserStep that extracts a DID Path from a DID Reference
// from the grammar:
// did-path = segment-nz *( "/" segment )
// segment = *pchar
// segment-nz = 1*pchar
// pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
// pct-encoded = "%" HEXDIG HEXDIG
// sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
func (p *parser) parsePath() parserStep {
input := p.input
inputLength := len(input)
currentIndex := p.currentIndex + 1
startIndex := currentIndex
var indexIncrement int
var next parserStep
var percentEncoded bool
for {
if currentIndex == inputLength {
next = nil
break
}
char := input[currentIndex]
if char == '/' {
next = p.parsePath
break
}
if char == '%' {
// a % must be followed by 2 hex digits
if (currentIndex+2 >= inputLength) ||
isNotHexDigit(input[currentIndex+1]) ||
isNotHexDigit(input[currentIndex+2]) {
return p.errorf(currentIndex, "% is not followed by 2 hex digits")
}
// if we got here, we're dealing with percent encoded char, jump three chars
percentEncoded = true
indexIncrement = 3
} else {
// not pecent encoded
percentEncoded = false
indexIncrement = 1
}
// pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
if !percentEncoded && isNotValidPathChar(char) {
return p.errorf(currentIndex, "character is not allowed in fragment")
}
// move to the next char
currentIndex = currentIndex + indexIncrement
}
if currentIndex == startIndex && len(p.out.PathSegments) == 0 {
// path segment length is zero
// first path segment must have atleast one character
// from the grammar
// did-path = segment-nz *( "/" segment )
return p.errorf(currentIndex, "first path segment must have atleast one character")
}
// update parser state
p.currentIndex = currentIndex
p.out.PathSegments = append(p.out.PathSegments, input[startIndex:currentIndex])
return next
}
// parseFragment is a parserStep that extracts a DID Fragment from a DID Reference
// from the grammar:
// did-fragment = *( pchar / "/" / "?" )
// pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
// pct-encoded = "%" HEXDIG HEXDIG
// sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
func (p *parser) parseFragment() parserStep {
input := p.input
inputLength := len(input)
currentIndex := p.currentIndex + 1
startIndex := currentIndex
var indexIncrement int
var percentEncoded bool
for {
if currentIndex == inputLength {
// we've reached the end of input
// it's ok for reference to be empty, so we don't need a check for that
// did-fragment = *( pchar / "/" / "?" )
break
}
char := input[currentIndex]
if char == '%' {
// a % must be followed by 2 hex digits
if (currentIndex+2 >= inputLength) ||
isNotHexDigit(input[currentIndex+1]) ||
isNotHexDigit(input[currentIndex+2]) {
return p.errorf(currentIndex, "% is not followed by 2 hex digits")
}
// if we got here, we're dealing with percent encoded char, jump three chars
percentEncoded = true
indexIncrement = 3
} else {
// not pecent encoded
percentEncoded = false
indexIncrement = 1
}
// did-fragment = *( pchar / "/" / "?" )
// pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
// isNotValidFragmentChar checks for all othe valid chars except pct-encoded
if !percentEncoded && isNotValidFragmentChar(char) {
return p.errorf(currentIndex, "character is not allowed in fragment")
}
// move to the next char
currentIndex = currentIndex + indexIncrement
}
// update parser state
p.currentIndex = currentIndex
p.out.Fragment = input[startIndex:currentIndex]
// no more parsing needed after a fragment,
// cause the state machine to exit by returning nil
return nil
}
// errorf is a parserStep that returns nil to cause the state machine to exit
// before returning it sets the currentIndex and err field in parser state
// other parser steps use this function to exit the state machine with an error
func (p *parser) errorf(index int, format string, args ...interface{}) parserStep {
p.currentIndex = index
p.err = fmt.Errorf(format, args)
return nil
}
// INLINABLE
// Calls to all functions below this point should be inlined by the go compiler
// See output of `go build -gcflags -m` to confirm
// isNotValidIDChar returns true if a byte is not allowed in a ID
// from the greammar:
// idchar = ALPHA / DIGIT / "." / "-"
func isNotValidIDChar(char byte) bool {
return isNotAlpha(char) && isNotDigit(char) && char != '.' && char != '-'
}
// isNotValidFragmentChar returns true if a byte is not allowed in a Fragment
// from the grammar:
// did-fragment = *( pchar / "/" / "?" )
// pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
// pct-encoded is not checked in this function
func isNotValidFragmentChar(char byte) bool {
return isNotValidPathChar(char) && char != '/' && char != '?'
}
// isNotValidPathChar returns true if a byte is not allowed in Path
// did-path = segment-nz *( "/" segment )
// segment = *pchar
// segment-nz = 1*pchar
// pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
// pct-encoded is not checked in this function
func isNotValidPathChar(char byte) bool {
return isNotUnreservedOrSubdelim(char) && char != ':' && char != '@'
}
// isNotUnreservedOrSubdelim returns true if a byte is not unreserved or sub-delims
// from the grammar:
// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
// sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
// https://tools.ietf.org/html/rfc3986#appendix-A
func isNotUnreservedOrSubdelim(char byte) bool {
switch char {
case '-', '.', '_', '~', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=':
return false
default:
if isNotAlpha(char) && isNotDigit(char) {
return true
}
return false
}
}
// isNotHexDigit returns true if a byte is not a digit between 0-9 or A-F or a-f
// in US-ASCII http://www.columbia.edu/kermit/ascii.html
// https://tools.ietf.org/html/rfc5234#appendix-B.1
func isNotHexDigit(char byte) bool {
// '\x41' is A, '\x46' is F
// '\x61' is a, '\x66' is f
return isNotDigit(char) && (char < '\x41' || char > '\x46') && (char < '\x61' || char > '\x66')
}
// isNotDigit returns true if a byte is not a digit between 0-9
// in US-ASCII http://www.columbia.edu/kermit/ascii.html
// https://tools.ietf.org/html/rfc5234#appendix-B.1
func isNotDigit(char byte) bool {
// '\x30' is digit 0, '\x39' is digit 9
return (char < '\x30' || char > '\x39')
}
// isNotAlpha returns true if a byte is not a big letter between A-Z or small letter between a-z
// https://tools.ietf.org/html/rfc5234#appendix-B.1
func isNotAlpha(char byte) bool {
return isNotSmallLetter(char) && isNotBigLetter(char)
}
// isNotBigLetter returns true if a byte is not a big letter between A-Z
// in US-ASCII http://www.columbia.edu/kermit/ascii.html
// https://tools.ietf.org/html/rfc5234#appendix-B.1
func isNotBigLetter(char byte) bool {
// '\x41' is big letter A, '\x5A' small letter Z
return (char < '\x41' || char > '\x5A')
}
// isNotSmallLetter returns true if a byte is not a small letter between a-z
// in US-ASCII http://www.columbia.edu/kermit/ascii.html
// https://tools.ietf.org/html/rfc5234#appendix-B.1
func isNotSmallLetter(char byte) bool {
// '\x61' is small letter a, '\x7A' small letter z
return (char < '\x61' || char > '\x7A')
}