This repository has been archived by the owner on May 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 346
/
keys.go
375 lines (318 loc) · 11.5 KB
/
keys.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
package commands
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"os"
"time"
"github.com/howeyc/gopass"
"github.com/hyperledger/burrow/config"
"github.com/hyperledger/burrow/config/deployment"
"github.com/hyperledger/burrow/crypto"
"github.com/hyperledger/burrow/keys"
cli "github.com/jawher/mow.cli"
"google.golang.org/grpc"
)
// Keys runs as either client or server
func Keys(output Output) func(cmd *cli.Cmd) {
return func(cmd *cli.Cmd) {
keysHost := cmd.String(cli.StringOpt{
Name: "host",
Desc: "set the host for talking to the key daemon",
Value: keys.DefaultHost,
EnvVar: "BURROW_KEYS_HOST",
})
keysPort := cmd.String(cli.StringOpt{
Name: "port",
Desc: "set the port for key daemon",
Value: keys.DefaultPort,
EnvVar: "BURROW_KEYS_PORT",
})
grpcKeysClient := func(output Output) keys.KeysClient {
var opts []grpc.DialOption
opts = append(opts, grpc.WithInsecure())
conn, err := grpc.Dial(*keysHost+":"+*keysPort, opts...)
if err != nil {
output.Fatalf("Failed to connect to grpc server: %v", err)
}
return keys.NewKeysClient(conn)
}
cmd.Command("server", "run keys server", func(cmd *cli.Cmd) {
keysDir := cmd.StringOpt("dir", "", "specify the location of the directory containing key files")
badPerm := cmd.BoolOpt("allow-bad-perm", false, "Allow unix key file permissions to be readable other than user")
configOpt := cmd.StringOpt("c config", "", "Use the a specified burrow config file")
var conf *config.BurrowConfig
cmd.Before = func() {
var err error
conf, err = obtainDefaultConfig(*configOpt, "")
if err != nil {
output.Fatalf("Could not obtain config: %v", err)
}
}
cmd.Action = func() {
conf.Keys.AllowBadFilePermissions = *badPerm
if *keysDir != "" {
conf.Keys.KeysDirectory = *keysDir
}
server := keys.StandAloneServer(conf.Keys.KeysDirectory, conf.Keys.AllowBadFilePermissions)
address := fmt.Sprintf("%s:%s", *keysHost, *keysPort)
listener, err := net.Listen("tcp", address)
if err != nil {
output.Fatalf("Could not listen on %s: %v", address, err)
}
err = server.Serve(listener)
if err != nil {
output.Fatalf("Keys server terminated with error: %v", err)
}
}
})
cmd.Command("gen", "Generates a key using (insert crypto pkgs used)", func(cmd *cli.Cmd) {
noPassword := cmd.BoolOpt("n no-password", false, "don't use a password for this key")
keyType := cmd.StringOpt("t curvetype", "ed25519", "specify the curve type of key to create. Supports 'secp256k1' (ethereum), 'ed25519' (tendermint)")
keyName := cmd.StringOpt("name", "", "name of key to use")
cmd.Action = func() {
curve, err := crypto.CurveTypeFromString(*keyType)
if err != nil {
output.Fatalf("Unrecognised curve type %v", *keyType)
}
var password string
if !*noPassword {
fmt.Printf("Enter Password:")
pwd, err := gopass.GetPasswdMasked()
if err != nil {
os.Exit(1)
}
password = string(pwd)
}
c := grpcKeysClient(output)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := c.GenerateKey(ctx, &keys.GenRequest{Passphrase: password, CurveType: curve.String(), KeyName: *keyName})
if err != nil {
output.Fatalf("failed to generate key: %v", err)
}
fmt.Printf("%v\n", resp.GetAddress())
}
})
cmd.Command("hash", "hash <some data>", func(cmd *cli.Cmd) {
hashType := cmd.StringOpt("t type", keys.DefaultHashType, "specify the hash function to use")
hexByte := cmd.BoolOpt("hex", false, "the input should be hex decoded to bytes first")
msg := cmd.StringArg("MSG", "", "message to hash")
cmd.Action = func() {
var message []byte
var err error
if *hexByte {
message, err = hex.DecodeString(*msg)
if err != nil {
output.Fatalf("failed to hex decode message: %v", err)
}
} else {
message = []byte(*msg)
}
c := grpcKeysClient(output)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := c.Hash(ctx, &keys.HashRequest{Hashtype: *hashType, Message: message})
if err != nil {
output.Fatalf("failed to get public key: %v", err)
}
fmt.Printf("%v\n", resp.GetHash())
}
})
cmd.Command("export", "Export a key to tendermint format", func(cmd *cli.Cmd) {
keyName := cmd.StringOpt("name", "", "name of key to use")
keyAddr := cmd.StringOpt("addr", "", "address of key to use")
passphrase := cmd.StringOpt("passphrase", "", "passphrase for encrypted key")
keyTemplate := cmd.StringOpt("t template", deployment.DefaultKeysExportFormat, "template for export key")
cmd.Action = func() {
c := grpcKeysClient(output)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := c.Export(ctx, &keys.ExportRequest{Passphrase: *passphrase, Name: *keyName, Address: *keyAddr})
if err != nil {
output.Fatalf("failed to export key: %v", err)
}
addr, err := crypto.AddressFromBytes(resp.GetAddress())
if err != nil {
output.Fatalf("failed to convert address: %v", err)
}
key := deployment.Key{
Name: *keyName,
CurveType: resp.GetCurveType(),
Address: addr,
PublicKey: resp.GetPublickey(),
PrivateKey: resp.GetPrivatekey(),
}
str, err := key.Dump(*keyTemplate)
if err != nil {
output.Fatalf("failed to template key: %v", err)
}
fmt.Printf("%s\n", str)
}
})
cmd.Command("import", "import <priv key> | /path/to/keyfile | <key json>", func(cmd *cli.Cmd) {
curveType := cmd.StringOpt("t curvetype", "ed25519", "specify the curve type of key to create. Supports 'secp256k1' (ethereum), 'ed25519' (tendermint)")
noPassword := cmd.BoolOpt("n no-password", false, "don't use a password for this key")
key := cmd.StringArg("KEY", "", "private key, filename, or raw json")
cmd.Action = func() {
var password string
if !*noPassword {
fmt.Printf("Enter Password:")
pwd, err := gopass.GetPasswdMasked()
if err != nil {
os.Exit(1)
}
password = string(pwd)
}
var privKeyBytes []byte
fileContents, err := ioutil.ReadFile(*key)
if err == nil {
*key = string(fileContents)
}
c := grpcKeysClient(output)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if (*key)[:1] == "{" {
resp, err := c.ImportJSON(ctx, &keys.ImportJSONRequest{JSON: *key})
if err != nil {
output.Fatalf("failed to import json key: %v", err)
}
fmt.Printf("%s\n", resp.GetAddress())
} else {
privKeyBytes, err = hex.DecodeString(*key)
if err != nil {
output.Fatalf("failed to hex decode key: %s", *key)
}
resp, err := c.Import(ctx, &keys.ImportRequest{Passphrase: password, KeyBytes: privKeyBytes, CurveType: *curveType})
if err != nil {
output.Fatalf("failed to import json key: %v", err)
}
fmt.Printf("%s\n", resp.GetAddress())
}
}
})
cmd.Command("pub", "public key", func(cmd *cli.Cmd) {
name := cmd.StringOpt("name", "", "name of key to use")
addr := cmd.StringOpt("addr", "", "address of key to use")
cmd.Action = func() {
c := grpcKeysClient(output)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := c.PublicKey(ctx, &keys.PubRequest{Name: *name, Address: *addr})
if err != nil {
output.Fatalf("failed to get public key: %v", err)
}
fmt.Printf("%X\n", resp.GetPublicKey())
}
})
cmd.Command("sign", "sign <some data>", func(cmd *cli.Cmd) {
name := cmd.StringOpt("name", "", "name of key to use")
addr := cmd.StringOpt("addr", "", "address of key to use")
msg := cmd.StringArg("MSG", "", "message to sign")
passphrase := cmd.StringOpt("passphrase", "", "passphrase for encrypted key")
cmd.Action = func() {
message, err := hex.DecodeString(*msg)
if err != nil {
output.Fatalf("failed to hex decode message: %v", err)
}
c := grpcKeysClient(output)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := c.Sign(ctx, &keys.SignRequest{Passphrase: *passphrase, Name: *name, Address: *addr, Message: message})
if err != nil {
output.Fatalf("failed to get public key: %v", err)
}
fmt.Printf("%X\n", resp.GetSignature().Signature)
}
})
cmd.Command("verify", "verify <some data> <sig> <pubkey>", func(cmd *cli.Cmd) {
curveTypeOpt := cmd.StringOpt("t curvetype", "ed25519", "specify the curve type of key to create. Supports 'secp256k1' (ethereum), 'ed25519' (tendermint)")
msg := cmd.StringArg("MSG", "", "hash/message to check")
sig := cmd.StringArg("SIG", "", "signature")
pub := cmd.StringArg("PUBLIC", "", "public key")
cmd.Action = func() {
message, err := hex.DecodeString(*msg)
if err != nil {
output.Fatalf("failed to hex decode message: %v", err)
}
curveType, err := crypto.CurveTypeFromString(*curveTypeOpt)
if err != nil {
output.Fatalf("invalid curve type: %v", err)
}
signatureBytes, err := hex.DecodeString(*sig)
if err != nil {
output.Fatalf("failed to hex decode signature: %v", err)
}
signature, err := crypto.SignatureFromBytes(signatureBytes, curveType)
if err != nil {
output.Fatalf("could not form signature: %v", err)
}
publickey, err := hex.DecodeString(*pub)
if err != nil {
output.Fatalf("failed to hex decode publickey: %v", err)
}
c := grpcKeysClient(output)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err = c.Verify(ctx, &keys.VerifyRequest{
PublicKey: publickey,
Signature: signature,
Message: message,
})
if err != nil {
output.Fatalf("failed to verify: %v", err)
}
output.Printf("true\n")
}
})
cmd.Command("name", "add key name to addr", func(cmd *cli.Cmd) {
keyname := cmd.StringArg("NAME", "", "name of key to use")
addr := cmd.StringArg("ADDR", "", "address of key to use")
cmd.Action = func() {
c := grpcKeysClient(output)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := c.AddName(ctx, &keys.AddNameRequest{Keyname: *keyname, Address: *addr})
if err != nil {
output.Fatalf("failed to add name to addr: %v", err)
}
}
})
cmd.Command("list", "list keys", func(cmd *cli.Cmd) {
name := cmd.StringOpt("name", "", "name or address of key to use")
cmd.Action = func() {
c := grpcKeysClient(output)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := c.List(ctx, &keys.ListRequest{KeyName: *name})
if err != nil {
output.Fatalf("failed to list key: %v", err)
}
printKeys := resp.Key
if printKeys == nil {
printKeys = make([]*keys.KeyID, 0)
}
bs, err := json.MarshalIndent(printKeys, "", " ")
if err != nil {
output.Fatalf("failed to json encode keys: %v", err)
}
fmt.Printf("%s\n", string(bs))
}
})
cmd.Command("rm", "rm key name", func(cmd *cli.Cmd) {
name := cmd.StringArg("NAME", "", "key to remove")
cmd.Action = func() {
c := grpcKeysClient(output)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := c.RemoveName(ctx, &keys.RemoveNameRequest{KeyName: *name})
if err != nil {
output.Fatalf("failed to remove key: %v", err)
}
}
})
}
}