-
Notifications
You must be signed in to change notification settings - Fork 2
/
keychain.go
342 lines (290 loc) · 9.2 KB
/
keychain.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
package archethic
import (
"bufio"
"bytes"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/hmac"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
)
type Keychain struct {
Seed []byte
Version uint8
Services map[string]Service
AuthorizedPublicKeys [][]byte
}
type Service struct {
DerivationPath string `json:"derivationPath"`
Curve Curve `json:"curve"`
HashAlgo HashAlgo `json:"hashAlgo"`
}
type DID struct {
Context []string `json:"@context"`
Id string `json:"id"`
Authentication []string `json:"authentication"`
VerificationMethod []DIDKeyMaterial `json:"verificationMethod"`
}
type DIDKeyMaterial struct {
Id string `json:"id"`
KeyType string `json:"type"`
PublicKeyJwk map[string]string `json:"publicKeyJwk"`
Controller string `json:"controller"`
}
func (s Service) toBytes() []byte {
buf := make([]byte, 0)
buf = append(buf, byte(len(s.DerivationPath)))
buf = append(buf, []byte(s.DerivationPath)...)
buf = append(buf, byte(s.Curve))
buf = append(buf, byte(s.HashAlgo))
return buf
}
// NewKeychain instanciates a new Keychain struct
func NewKeychain(seed []byte) *Keychain {
return &Keychain{
Seed: seed,
Version: 1,
Services: map[string]Service{
"uco": {
DerivationPath: "m/650'/0/0",
Curve: P256,
HashAlgo: SHA256,
},
},
}
}
func (k *Keychain) AddService(name string, derivationPath string, curve Curve, hashAlgo HashAlgo) {
k.Services[name] = Service{
DerivationPath: derivationPath,
Curve: curve,
HashAlgo: hashAlgo,
}
}
func (k *Keychain) RemoveService(name string) {
delete(k.Services, name)
}
func (k *Keychain) AddAuthorizedPublicKey(publicKey []byte) {
k.AuthorizedPublicKeys = append(k.AuthorizedPublicKeys, publicKey)
}
func (k *Keychain) RemoveAuthorizedPublicKey(publicKey []byte) {
for i, key := range k.AuthorizedPublicKeys {
if bytes.Equal(key, publicKey) {
k.AuthorizedPublicKeys = append(k.AuthorizedPublicKeys[:i], k.AuthorizedPublicKeys[i+1:]...)
return
}
}
}
func (k Keychain) ToDID() (*DID, error) {
address, err := DeriveAddress(k.Seed, 0, P256, SHA256)
if err != nil {
return nil, err
}
authentications := make([]string, 0)
verificationMethods := make([]DIDKeyMaterial, 0)
for serviceName, service := range k.Services {
splittedPath := strings.Split(service.DerivationPath, "/")
for i := 0; i < len(splittedPath); i++ {
splittedPath[i] = strings.ReplaceAll(splittedPath[i], "'", "")
purpose := splittedPath[i]
if purpose == "650" {
publicKey, _, err := DeriveArchethicKeypair(k.Seed, service.DerivationPath, 0, service.Curve)
if err != nil {
return nil, err
}
publicKeyJwk, err := KeyToJWK(publicKey, serviceName)
if err != nil {
return nil, err
}
verificationMethods = append(verificationMethods, DIDKeyMaterial{
Id: fmt.Sprintf("did:archethic:%x#%s", address, serviceName),
KeyType: "JsonWebKey2020",
PublicKeyJwk: publicKeyJwk,
Controller: fmt.Sprintf("did:archethic:%x", address),
})
authentications = append(authentications, fmt.Sprintf("did:archethic:%x#%s", address, serviceName))
}
}
}
return &DID{
Context: []string{
"https://www.w3.org/ns/did/v1",
},
Id: fmt.Sprintf("did:archethic:%x", address),
Authentication: authentications,
VerificationMethod: verificationMethods,
}, nil
}
func (d DID) ToJSON() []byte {
json, _ := json.Marshal(d)
return json
}
func KeyToJWK(publicKey []byte, keyId string) (map[string]string, error) {
curveID := publicKey[0]
keyBytes := publicKey[2:]
switch Curve(curveID) {
case ED25519:
key := ed25519.PublicKey(keyBytes)
return map[string]string{
"kty": "OKP",
"crv": "Ed25519",
"x": pointToBase64Url(key),
"kid": keyId,
}, nil
case P256:
curve := elliptic.P256()
pubKeyX, pubKeyY := elliptic.Unmarshal(curve, keyBytes)
if pubKeyX == nil || pubKeyY == nil {
return nil, errors.New("can't unmarshall public key")
}
publicKey := ecdsa.PublicKey{Curve: curve, X: pubKeyX, Y: pubKeyY}
return map[string]string{
"kty": "EC",
"crv": "P256",
"x": pointToBase64Url(publicKey.X.Bytes()),
"y": pointToBase64Url(publicKey.Y.Bytes()),
"kid": keyId,
}, nil
default:
return nil, errors.New("unsupported elliptic curve")
}
}
func pointToBase64Url(p []byte) string {
buf := base64.StdEncoding.EncodeToString(p)
r1 := regexp.MustCompile(`/\+/g`)
r2 := regexp.MustCompile(`/\//g`)
r3 := regexp.MustCompile(`/=+$/g`)
buf = r1.ReplaceAllString(buf, "_")
buf = r2.ReplaceAllString(buf, "_")
buf = r3.ReplaceAllString(buf, "")
return buf
}
func (k Keychain) toBytes() []byte {
buf := make([]byte, 0)
version := make([]byte, 4)
binary.BigEndian.PutUint32(version, uint32(k.Version))
buf = append(buf, version...)
buf = append(buf, byte(len(k.Seed)))
buf = append(buf, k.Seed...)
buf = append(buf, byte(len(k.Services)))
for name, service := range k.Services {
buf = append(buf, byte(len(name)))
buf = append(buf, []byte(name)...)
buf = append(buf, service.toBytes()...)
}
return buf
}
func (k Keychain) DeriveKeypair(serviceName string, index uint8) ([]byte, []byte, error) {
return k.DeriveKeypairWithSuffix(serviceName, index, "")
}
func (k Keychain) DeriveKeypairWithSuffix(serviceName string, index uint8, pathSuffix string) ([]byte, []byte, error) {
service, ok := k.Services[serviceName]
if !ok {
return nil, nil, errors.New("service doesn't exists in the keychain")
}
return DeriveArchethicKeypairWithSuffix(k.Seed, service.DerivationPath, index, service.Curve, pathSuffix)
}
func DeriveArchethicKeypair(seed []byte, derivationPath string, index uint8, curve Curve) ([]byte, []byte, error) {
return DeriveArchethicKeypairWithSuffix(seed, derivationPath, index, curve, "")
}
func DeriveArchethicKeypairWithSuffix(seed []byte, derivationPath string, index uint8, curve Curve, pathSuffix string) ([]byte, []byte, error) {
extendedSeed := deriveServiceSeed(seed, derivationPath, index, pathSuffix)
if isPathWithIndex(derivationPath) {
return GenerateDeterministicKeypair(extendedSeed, curve, KEYCHAIN_ORIGIN_ID)
} else {
return DeriveKeypair(extendedSeed, uint32(index), curve)
}
}
func isPathWithIndex(derivationPath string) bool {
return strings.Count(derivationPath, "/") == 3
}
func deriveServiceSeed(seed []byte, derivationPath string, index uint8, pathSuffix string) []byte {
h := sha256.New()
h.Write([]byte(replaceDerivationPathIndex(derivationPath, pathSuffix, index)))
hashedPath := h.Sum(nil)
hm := hmac.New(sha512.New, seed)
hm.Write(hashedPath)
extendedSeed := hm.Sum(nil)
return extendedSeed[:32]
}
func replaceDerivationPathIndex(derivationPath string, pathSuffix string, index uint8) string {
if isPathWithIndex(derivationPath) {
splitted := strings.Split(derivationPath, "/")
splitted[2] = splitted[2] + pathSuffix
splitted[3] = strconv.FormatUint(uint64(index), 10)
return strings.Join(splitted, "/")
} else {
return derivationPath + pathSuffix
}
}
func DecodeKeychain(binaryInput []byte) *Keychain {
byteReader := bufio.NewReader(bytes.NewReader(binaryInput))
version := make([]byte, 4)
byteReader.Read(version)
versionInt := uint8(version[3])
seedSize, _ := byteReader.ReadByte()
seed := make([]byte, seedSize)
byteReader.Read(seed)
nbServices, _ := byteReader.ReadByte()
k := &Keychain{
Seed: seed,
Version: versionInt,
Services: make(map[string]Service),
}
for i := 0; i < int(nbServices); i++ {
serviceNameLength, _ := byteReader.ReadByte()
serviceName := make([]byte, serviceNameLength)
byteReader.Read(serviceName)
derivationPathLength, _ := byteReader.ReadByte()
derivationPath := make([]byte, derivationPathLength)
byteReader.Read(derivationPath)
curveID, _ := byteReader.ReadByte()
hashAlgoID, _ := byteReader.ReadByte()
k.AddService(string(serviceName), string(derivationPath), Curve(curveID), HashAlgo(hashAlgoID))
}
return k
}
func (k Keychain) DeriveAddress(serviceName string, index uint8) ([]byte, error) {
service, ok := k.Services[serviceName]
if !ok {
return nil, errors.New("service doesn't exists in the keychain")
}
publicKey, _, err := DeriveArchethicKeypair(k.Seed, service.DerivationPath, index, service.Curve)
if err != nil {
return nil, err
}
hashedPublicKey, err := Hash(publicKey, service.HashAlgo)
if err != nil {
return nil, err
}
result := make([]byte, 0)
result = append(result, byte(service.Curve))
result = append(result, hashedPublicKey...)
return result, nil
}
func (k Keychain) BuildTransaction(transaction *TransactionBuilder, serviceName string, index uint8) error {
pubKey, privKey, err := k.DeriveKeypair(serviceName, index)
if err != nil {
return err
}
address, err := k.DeriveAddress(serviceName, index+1)
if err != nil {
return err
}
transaction.SetAddress(address)
payloadForPreviousSignature := transaction.previousSignaturePayload()
previousSignature, err := Sign(privKey, payloadForPreviousSignature)
if err != nil {
return err
}
transaction.SetPreviousSignatureAndPreviousPublicKey(previousSignature, pubKey)
return nil
}