/
accounts.go
467 lines (428 loc) · 12.3 KB
/
accounts.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
package cmd
import (
"context"
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"syscall"
"github.com/aergoio/aergo/v2/account/key"
"github.com/aergoio/aergo/v2/types"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
)
func init() {
accountCmd := &cobra.Command{
Use: "account [flags] subcommand",
Short: "Account command",
PersistentPreRun: preConnectAergo,
PersistentPostRun: disconnectAergo,
}
newCmd.Flags().StringVar(&pw, "password", "", "password (optional, will be asked on the terminal if not given)")
unlockCmd.Flags().StringVar(&address, "address", "", "address of account")
unlockCmd.MarkFlagRequired("address")
unlockCmd.Flags().StringVar(&pw, "password", "", "password (optional, will be asked on the terminal if not given)")
lockCmd.Flags().StringVar(&address, "address", "", "address of account")
lockCmd.MarkFlagRequired("address")
lockCmd.Flags().StringVar(&pw, "password", "", "password (optional, will be asked on the terminal if not given)")
importCmd.Flags().StringVar(&importFormat, "if", "", "Base58 import format string")
importCmd.Flags().StringVar(&pw, "password", "", "password used when exporting")
importCmd.Flags().StringVar(&to, "newpassword", "", "new password for storing account")
importCmd.Flags().StringVar(&importFilePath, "path", "", "path to import keystore file")
exportCmd.Flags().StringVar(&address, "address", "", "Address of account")
exportCmd.MarkFlagRequired("address")
exportCmd.Flags().BoolVar(&exportAsWif, "wif", false, "export as encrypted string instead of keystore format")
exportCmd.Flags().StringVar(&pw, "password", "", "password (optional, will be asked on the terminal if not given)")
voteCmd.Flags().StringVar(&address, "address", "", "account address of voter")
voteCmd.MarkFlagRequired("address")
voteCmd.Flags().StringVar(&to, "to", "", "json string array which has candidates, or input file path")
voteCmd.MarkFlagRequired("to")
voteCmd.Flags().StringVar(&voteId, "id", types.OpvoteBP.Cmd(), "id to vote (e.g. bpcount, stakingmin, gasprice, nameprice)")
voteCmd.Flags().StringVar(&pw, "password", "", "password (optional, will be asked on the terminal if not given)")
stakeCmd.Flags().StringVar(&address, "address", "", "account address")
stakeCmd.MarkFlagRequired("address")
stakeCmd.Flags().StringVar(&amount, "amount", "0", "amount to stake")
stakeCmd.MarkFlagRequired("amount")
stakeCmd.Flags().StringVar(&pw, "password", "", "password (optional, will be asked on the terminal if not given)")
unstakeCmd.Flags().StringVar(&address, "address", "", "account address")
unstakeCmd.MarkFlagRequired("address")
unstakeCmd.Flags().StringVar(&amount, "amount", "0", "amount to unstake")
unstakeCmd.MarkFlagRequired("amount")
unstakeCmd.Flags().StringVar(&pw, "password", "", "password (optional, will be asked on the terminal if not given)")
accountCmd.AddCommand(newCmd, listCmd, unlockCmd, lockCmd, importCmd, exportCmd, voteCmd, stakeCmd, unstakeCmd)
rootCmd.AddCommand(accountCmd)
}
var newCmd = &cobra.Command{
Use: "new [flags]",
Short: "Create new account in the node or cli",
Run: func(cmd *cobra.Command, args []string) {
var param types.Personal
var err error
if pw != "" {
param.Passphrase = pw
} else {
param.Passphrase, err = getPasswd(cmd, true)
if err != nil {
cmd.PrintErrf("Failed get password: %s\n", err.Error())
return
}
}
var msg *types.Account
var addr []byte
if rootConfig.KeyStorePath == "" {
msg, err = client.CreateAccount(context.Background(), ¶m)
if msg != nil {
addr = msg.GetAddress()
}
} else {
dataEnvPath := os.ExpandEnv(rootConfig.KeyStorePath)
ks := key.NewStore(dataEnvPath, 0)
defer ks.CloseStore()
addr, err = ks.CreateKey(param.Passphrase)
if err != nil {
cmd.PrintErrf("Failed: %s\n", err.Error())
return
}
}
if err != nil {
cmd.PrintErrf("Failed: %s\n", err.Error())
return
}
cmd.Println(types.EncodeAddress(addr))
},
}
var listCmd = &cobra.Command{
Use: "list [flags]",
Short: "Get account list in the node or cli",
Run: func(cmd *cobra.Command, args []string) {
var err error
var msg *types.AccountList
var addrs [][]byte
if rootConfig.KeyStorePath == "" {
msg, err = client.GetAccounts(context.Background(), &types.Empty{})
} else {
dataEnvPath := os.ExpandEnv(rootConfig.KeyStorePath)
ks := key.NewStore(dataEnvPath, 0)
defer ks.CloseStore()
addrs, err = ks.GetAddresses()
}
if err != nil {
cmd.PrintErrf("Failed: %s\n", err.Error())
return
}
out := fmt.Sprintf("%s", "[")
if msg != nil {
addresslist := msg.GetAccounts()
for _, a := range addresslist {
out = fmt.Sprintf("%s\"%s\", ", out, types.EncodeAddress(a.Address))
}
if addresslist != nil {
out = out[:len(out)-2]
}
} else if addrs != nil && len(addrs) > 0 {
for _, a := range addrs {
out = fmt.Sprintf("%s\"%s\", ", out, types.EncodeAddress(a))
}
out = out[:len(out)-2]
}
out = fmt.Sprintf("%s%s", out, "]")
cmd.Println(out)
},
}
var lockCmd = &cobra.Command{
Use: "lock [flags]",
Short: "Lock account in the node",
Run: func(cmd *cobra.Command, args []string) {
if rootConfig.KeyStorePath != "" {
cmd.PrintErrf("There is no lock on the local keystore.\n")
return
}
param, err := parsePersonalParam(cmd)
if err != nil {
cmd.PrintErrf("Failed: %s\n", err.Error())
return
}
msg, err := client.LockAccount(context.Background(), param)
if err != nil {
cmd.PrintErrf("Failed: %s\n", err.Error())
return
}
cmd.Println(types.EncodeAddress(msg.GetAddress()))
},
}
var unlockCmd = &cobra.Command{
Use: "unlock [flags]",
Short: "Unlock account in the node",
Run: func(cmd *cobra.Command, args []string) {
if rootConfig.KeyStorePath != "" {
cmd.PrintErrf("Local keystore do not need to be unlocked.\n")
return
}
param, err := parsePersonalParam(cmd)
msg, err := client.UnlockAccount(context.Background(), param)
if err != nil {
cmd.PrintErrf("Failed: %s\n", err.Error())
return
}
cmd.Println(types.EncodeAddress(msg.GetAddress()))
},
}
// import account using WIF (legacy)
func importWif(cmd *cobra.Command) ([]byte, error) {
var err error
var address []byte
importBuf, err := types.DecodePrivKey(importFormat)
if err != nil {
return nil, fmt.Errorf("failed to decode input: %s", err.Error())
}
wif := &types.ImportFormat{Wif: &types.SingleBytes{Value: importBuf}}
if pw != "" {
wif.Oldpass = pw
} else {
wif.Oldpass, err = getPasswd(cmd, false)
if err != nil {
return nil, err
}
}
if to != "" {
wif.Newpass = to
} else {
wif.Newpass = wif.Oldpass
}
if rootConfig.KeyStorePath == "" {
msg, errRemote := client.ImportAccount(context.Background(), wif)
address = msg.GetAddress()
if errRemote != nil {
return address, fmt.Errorf("node request returned error: %s", errRemote.Error())
}
} else {
dataEnvPath := os.ExpandEnv(rootConfig.KeyStorePath)
ks := key.NewStore(dataEnvPath, 0)
defer ks.CloseStore()
address, err = ks.ImportKey(importBuf, wif.Oldpass, wif.Newpass)
if err != nil {
return address, err
}
}
return address, nil
}
// import account using keystore
func importKeystore(cmd *cobra.Command) ([]byte, error) {
var err error
var address []byte
absPath, err := filepath.Abs(importFilePath)
if err != nil {
return nil, err
}
keystore, err := os.ReadFile(absPath)
if err != nil {
return nil, err
}
wif := &types.ImportFormat{Keystore: &types.SingleBytes{Value: keystore}}
if pw != "" {
wif.Oldpass = pw
} else {
wif.Oldpass, err = getPasswd(cmd, false)
if err != nil {
return nil, err
}
}
if to != "" {
wif.Newpass = to
} else {
wif.Newpass = wif.Oldpass
}
if rootConfig.KeyStorePath == "" {
msg, errRemote := client.ImportAccount(context.Background(), wif)
if errRemote != nil {
return nil, errRemote
}
address = msg.GetAddress()
} else {
dataEnvPath := os.ExpandEnv(rootConfig.KeyStorePath)
ks := key.NewStore(dataEnvPath, 0)
defer ks.CloseStore()
privateKey, err := key.LoadKeystore(keystore, wif.Oldpass)
if err != nil {
return nil, err
}
address, err = ks.AddKey(privateKey, wif.Newpass)
if err != nil {
return nil, err
}
}
return address, nil
}
var importCmd = &cobra.Command{
Use: "import [flags]",
Short: "Import account",
Run: func(cmd *cobra.Command, args []string) {
var address []byte
var err error
if importFormat != "" {
address, err = importWif(cmd)
} else if importFilePath != "" {
address, err = importKeystore(cmd)
} else {
cmd.Help()
}
if err != nil {
cmd.PrintErrln(err)
}
if address != nil {
cmd.Println(types.EncodeAddress(address))
}
},
}
// export account as WIF (legacy)
func exportWif(cmd *cobra.Command, param *types.Personal) ([]byte, error) {
if rootConfig.KeyStorePath == "" {
msg, err := client.ExportAccount(context.Background(), param)
if err != nil {
return nil, fmt.Errorf("node request returned error: %s", err.Error())
}
return msg.Value, nil
} else {
dataEnvPath := os.ExpandEnv(rootConfig.KeyStorePath)
ks := key.NewStore(dataEnvPath, 0)
defer ks.CloseStore()
wif, err := ks.ExportKey(param.Account.Address, param.Passphrase)
if err != nil {
return nil, err
}
return wif, nil
}
}
// export account as keystore
func exportKeystore(cmd *cobra.Command, param *types.Personal) ([]byte, error) {
if rootConfig.KeyStorePath == "" {
msg, err := client.ExportAccountKeystore(context.Background(), param)
if err != nil {
return nil, fmt.Errorf("node request returned error: %s", err.Error())
}
return msg.Value, nil
} else {
dataEnvPath := os.ExpandEnv(rootConfig.KeyStorePath)
ks := key.NewStore(dataEnvPath, 0)
defer ks.CloseStore()
privateKey, err := ks.GetKey(param.Account.Address, param.Passphrase)
if err != nil {
return nil, err
}
wif, err := key.GetKeystore(privateKey, param.Passphrase)
if err != nil {
return nil, err
}
return wif, nil
}
}
var exportCmd = &cobra.Command{
Use: "export [flags]",
Short: "Export account",
Run: func(cmd *cobra.Command, args []string) {
var result []byte
var err error
param, err := parsePersonalParam(cmd)
if err != nil {
cmd.PrintErr(err.Error())
return
}
if exportAsWif {
result, err = exportWif(cmd, param)
if result != nil {
cmd.Println(types.EncodePrivKey(result))
}
} else {
result, err = exportKeystore(cmd, param)
if result != nil {
cmd.Println(string(result))
}
}
if err != nil {
cmd.PrintErrln(err)
}
},
}
func parsePersonalParam(cmd *cobra.Command) (*types.Personal, error) {
var err error
param := &types.Personal{Account: &types.Account{}}
if address != "" {
param.Account.Address, err = types.DecodeAddress(address)
if err != nil {
return nil, err
}
if pw != "" {
param.Passphrase = pw
} else {
param.Passphrase, err = getPasswd(cmd, false)
if err != nil {
return nil, err
}
}
}
return param, nil
}
// Try to open /dev/tty for read/write, with stdin/stdout as fallback
// This is so we can use aergocli in a pipe and still read passwords from tty
func getTerminalReaderWriter() (struct {
io.Reader
io.Writer
}, int) {
path := "/dev/tty"
fallback := struct {
io.Reader
io.Writer
}{os.Stdin, os.Stdout}
in, err := os.Open(path)
if err != nil {
return fallback, 0
}
out, err := os.OpenFile(path, syscall.O_WRONLY, 0)
if err != nil {
return fallback, 0
}
return struct {
io.Reader
io.Writer
}{in, out}, int(out.Fd())
}
func getPasswd(cmd *cobra.Command, isNew bool) (string, error) {
screen, fd := getTerminalReaderWriter()
oldState, err := terminal.MakeRaw(fd)
if err != nil {
return "", err
}
defer terminal.Restore(0, oldState)
term := terminal.NewTerminal(screen, "")
password, err := term.ReadPassword("Enter password: ")
if err != nil {
return "", err
}
if len(password) == 0 {
return "", errors.New("empty password")
}
if isNew {
repeat, err := term.ReadPassword("Repeat password: ")
if err != nil {
return "", err
}
if password != repeat {
return "", errors.New("Passwords don't match")
}
}
return password, err
}
func preConnectAergo(cmd *cobra.Command, args []string) {
if rootConfig.KeyStorePath == "" {
connectAergo(cmd, args)
} else {
client = nil
}
if len(sock) > 0 {
if admClient = newAergoAdminClient(sock); admClient == nil {
log.Fatal("can't create admin connection")
}
}
}