-
Notifications
You must be signed in to change notification settings - Fork 0
/
keys.go
331 lines (284 loc) · 8.28 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
package cmd
import (
"bytes"
"encoding/json"
"fmt"
"io"
"strings"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/spf13/cobra"
"go.uber.org/zap"
"golang.org/x/term"
)
const (
flagCoinType = "coin-type"
defaultCoinType uint32 = sdk.CoinType
)
// keysCmd represents the keys command
func keysCmd(a *appState) *cobra.Command {
// flagAccountPrefix allows the user to override the prefix for a given account.
// Scoped to keysCmd so that concurrent test runs don't encounter a data race.
var flagAccountPrefix string
cmd := &cobra.Command{
Use: "keys",
Aliases: []string{"k"},
Short: "manage keys held by the relayer for each chain",
}
cmd.AddCommand(
keysAddCmd(a),
keysRestoreCmd(a),
keysDeleteCmd(a),
keysListCmd(a),
keysShowCmd(a, &flagAccountPrefix),
keysExportCmd(a),
)
return cmd
}
// keysAddCmd respresents the `keys add` command
func keysAddCmd(a *appState) *cobra.Command {
cmd := &cobra.Command{
Use: "add [name]",
Aliases: []string{"a"},
Short: "adds a key to the keychain associated with a particular chain",
Long: "if no name is passed, 'default' is used",
Args: cobra.RangeArgs(0, 1),
Example: strings.TrimSpace(fmt.Sprintf(`
$ %s keys add
$ %s keys add test_key
$ %s k a osmo_key --chain osmosis`, appName, appName, appName)),
RunE: func(cmd *cobra.Command, args []string) error {
cl := a.GetDefaultClient()
var keyName string
if len(args) == 0 {
keyName = cl.Config.Key
} else {
keyName = args[0]
}
if cl.KeyExists(keyName) {
return errKeyExists(keyName)
}
coinType, err := cmd.Flags().GetUint32(flagCoinType)
if err != nil {
return err
}
ko, err := cl.AddKey(keyName, coinType)
if err != nil {
return err
}
// Not calling writeJSON because this is one case that does not use indentation.
// (Was that intentional?)
enc := json.NewEncoder(cmd.OutOrStdout())
enc.SetEscapeHTML(false)
if err := enc.Encode(&ko); err != nil {
return err
}
return nil
},
}
cmd.Flags().Uint32(flagCoinType, defaultCoinType, "coin type number for HD derivation")
return cmd
}
// keysRestoreCmd respresents the `keys add` command
func keysRestoreCmd(a *appState) *cobra.Command {
cmd := &cobra.Command{
Use: "restore [name]",
Aliases: []string{"r"},
Short: "restores a mnemonic to the keychain associated with a particular chain",
Args: cobra.ExactArgs(1),
Example: strings.TrimSpace(fmt.Sprintf(`
$ %s keys restore --chain ibc-0 testkey
$ %s k r --chain ibc-1 faucet-key`, appName, appName)),
RunE: func(cmd *cobra.Command, args []string) error {
cl := a.GetDefaultClient()
keyName := args[0]
if cl.KeyExists(keyName) {
return errKeyExists(keyName)
}
mnemonic, err := readMnemonic(cmd.InOrStdin(), cmd.ErrOrStderr())
if err != nil {
// Can happen when there is an issue with the terminal.
return fmt.Errorf("failed to read mnemonic: %w", err)
}
coinType, err := cmd.Flags().GetUint32(flagCoinType)
if err != nil {
return err
}
address, err := cl.RestoreKey(keyName, string(mnemonic), coinType)
if err != nil {
return err
}
fmt.Fprintln(cmd.OutOrStdout(), address)
return nil
},
}
cmd.Flags().Uint32(flagCoinType, defaultCoinType, "coin type number for HD derivation")
return cmd
}
// readMnemonic reads a password in terminal mode if stdin is a terminal,
// otherwise it returns all of stdin with the trailing newline removed.
func readMnemonic(stdin io.Reader, stderr io.Writer) ([]byte, error) {
type fder interface {
Fd() uintptr
}
if f, ok := stdin.(fder); ok {
fmt.Fprint(stderr, "Enter mnemonic 🔑: ")
mnemonic, err := term.ReadPassword(int(f.Fd()))
fmt.Fprintln(stderr)
return mnemonic, err
}
in, err := io.ReadAll(stdin)
if err != nil {
return nil, err
}
return bytes.TrimSuffix(in, []byte("\n")), nil
}
// keysDeleteCmd represents the `keys delete` command.
func keysDeleteCmd(a *appState) *cobra.Command {
cmd := &cobra.Command{
Use: "delete [name]",
Aliases: []string{"d"},
Short: "deletes a key from the keychain associated with a particular chain",
Args: cobra.ExactArgs(1),
Example: strings.TrimSpace(fmt.Sprintf(`
$ %s keys delete ibc-0 -y
$ %s keys delete ibc-1 key2 -y
$ %s k d ibc-2 testkey`, appName, appName, appName)),
RunE: func(cmd *cobra.Command, args []string) error {
cl := a.GetDefaultClient()
chainName := cl.Config.ChainID
keyName := args[0]
if !cl.KeyExists(keyName) {
return errKeyDoesntExist(keyName)
}
if skip, _ := cmd.Flags().GetBool("skip"); !skip {
fmt.Fprintf(cmd.OutOrStdout(), "Are you sure you want to delete key(%s) from chain(%s)? (Y/n)\n", keyName, chainName)
if !askForConfirmation(a.Log, cmd) {
return nil
}
}
if err := cl.DeleteKey(keyName); err != nil {
panic(err)
}
fmt.Fprintf(cmd.OutOrStdout(), "key %s deleted\n", keyName)
return nil
},
}
return skipConfirm(cmd, a.Viper)
}
func askForConfirmation(log *zap.Logger, cmd *cobra.Command) bool {
var response string
_, err := fmt.Fscanln(cmd.InOrStdin(), &response)
if err != nil {
log.Fatal("Failed to read input", zap.Error(err))
}
switch strings.ToLower(response) {
case "y", "yes":
return true
case "n", "no":
return false
default:
fmt.Fprintln(cmd.OutOrStdout(), "please type (y)es or (n)o and then press enter")
return askForConfirmation(log, cmd)
}
}
// keysListCmd respresents the `keys list` command
func keysListCmd(a *appState) *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Aliases: []string{"l"},
Short: "lists keys from the keychain associated with a particular chain",
Args: cobra.NoArgs,
Example: strings.TrimSpace(fmt.Sprintf(`
$ %s keys list ibc-0
$ %s k l ibc-1`, appName, appName)),
RunE: func(cmd *cobra.Command, args []string) error {
cl := a.GetDefaultClient()
info, err := cl.ListAddresses()
if err != nil {
return err
}
if len(info) == 0 {
fmt.Fprintln(cmd.ErrOrStderr(), "WARNING: no keys found")
return nil
}
for key, val := range info {
fmt.Fprintf(cmd.OutOrStdout(), "key(%s) -> %s\n", key, val)
}
return nil
},
}
return cmd
}
// keysShowCmd respresents the `keys show` command
func keysShowCmd(a *appState, flagAccountPrefix *string) *cobra.Command {
cmd := &cobra.Command{
Use: "show [name]",
Aliases: []string{"s"},
Short: "shows a key from the keychain associated with a particular chain",
Long: "if no name is passed, name in config is used",
Args: cobra.RangeArgs(0, 1),
Example: strings.TrimSpace(fmt.Sprintf(`
$ %s keys show ibc-0
$ %s keys show ibc-1 key2
$ %s k s ibc-2 testkey`, appName, appName, appName)),
RunE: func(cmd *cobra.Command, args []string) error {
cl := a.GetDefaultClient()
var keyName string
if len(args) == 0 {
keyName = cl.Config.Key
} else {
keyName = args[0]
}
if !cl.KeyExists(keyName) {
return errKeyDoesntExist(keyName)
}
if *flagAccountPrefix != "" {
cl.Config.AccountPrefix = *flagAccountPrefix
}
address, err := cl.ShowAddress(keyName)
if err != nil {
return err
}
fmt.Fprintln(cmd.OutOrStdout(), address)
return nil
},
}
cmd.Flags().StringVar(flagAccountPrefix, "prefix", "", "Encode the key with the user specified prefix")
return cmd
}
type KeyEnumeration struct {
KeyName string `json:"key_name"`
Addresses map[string]string `json:"addresses"`
}
// keysExportCmd respresents the `keys export` command
func keysExportCmd(a *appState) *cobra.Command {
cmd := &cobra.Command{
Use: "export [name]",
Aliases: []string{"e"},
Short: "exports a privkey from the keychain associated with a particular chain",
Args: cobra.ExactArgs(1),
Example: strings.TrimSpace(fmt.Sprintf(`
$ %s keys export ibc-0 testkey
$ %s k e ibc-2 testkey`, appName, appName)),
RunE: func(cmd *cobra.Command, args []string) error {
cl := a.GetDefaultClient()
keyName := args[0]
if !cl.KeyExists(keyName) {
return errKeyDoesntExist(keyName)
}
info, err := cl.ExportPrivKeyArmor(keyName)
if err != nil {
return err
}
fmt.Println(info)
return nil
},
}
return cmd
}
func errKeyExists(name string) error {
return fmt.Errorf("a key with name %s already exists", name)
}
func errKeyDoesntExist(name string) error {
return fmt.Errorf("a key with name %s doesn't exist", name)
}