-
Notifications
You must be signed in to change notification settings - Fork 5
/
method.go
84 lines (65 loc) · 2.16 KB
/
method.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
/*
Copyright Gen Digital Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package operationparser
import (
"encoding/json"
"errors"
"strings"
"github.com/trustbloc/sidetree-go/pkg/api/operation"
"github.com/trustbloc/sidetree-go/pkg/canonicalizer"
"github.com/trustbloc/sidetree-go/pkg/encoder"
"github.com/trustbloc/sidetree-go/pkg/versions/1_0/model"
)
const (
longFormSeparator = ":"
didSeparator = ":"
)
// ParseDID inspects resolution request and returns:
// - did and create request in case of long form resolution
// - just did in case of short form resolution (common scenario).
func (p *Parser) ParseDID(namespace, shortOrLongFormDID string) (string, []byte, error) {
var err error
withoutNamespace := strings.ReplaceAll(shortOrLongFormDID, namespace+didSeparator, "")
posLongFormSeparator := strings.Index(withoutNamespace, longFormSeparator)
if posLongFormSeparator == -1 {
// there is short form did
return shortOrLongFormDID, nil, nil
}
// long form format: '<namespace>:<unique-portion>:Base64url(JCS({suffix-data, delta}))'
endOfDIDPos := strings.LastIndex(shortOrLongFormDID, longFormSeparator)
did := shortOrLongFormDID[0:endOfDIDPos]
longFormDID := shortOrLongFormDID[endOfDIDPos+1:]
createRequest, err := parseInitialState(longFormDID)
if err != nil {
return "", nil, err
}
createRequestBytes, err := canonicalizer.MarshalCanonical(createRequest)
if err != nil {
return "", nil, err
}
// return did and initial state
return did, createRequestBytes, nil
}
// parse initial state will get create request from encoded initial value.
func parseInitialState(initialState string) (*model.CreateRequest, error) {
decodedJCS, err := encoder.DecodeString(initialState)
if err != nil {
return nil, err
}
var createRequest model.CreateRequest
err = json.Unmarshal(decodedJCS, &createRequest)
if err != nil {
return nil, err
}
expected, err := canonicalizer.MarshalCanonical(createRequest)
if err != nil {
return nil, err
}
if encoder.EncodeToString(expected) != initialState {
return nil, errors.New("initial state is not valid")
}
createRequest.Operation = operation.TypeCreate
return &createRequest, nil
}