-
Notifications
You must be signed in to change notification settings - Fork 63
/
wallet_cmd.go
591 lines (515 loc) · 13 KB
/
wallet_cmd.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
package main
import (
"bufio"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"strings"
"github.com/filecoin-project/boost/cli/node"
"github.com/filecoin-project/boost/cmd"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/chain/types"
lcli "github.com/filecoin-project/lotus/cli"
"github.com/filecoin-project/lotus/lib/tablewriter"
"github.com/urfave/cli/v2"
)
var walletCmd = &cli.Command{
Name: "wallet",
Usage: "Manage wallets with Boost",
Subcommands: []*cli.Command{
walletNew,
walletList,
walletBalance,
walletExport,
walletImport,
walletGetDefault,
walletSetDefault,
walletDelete,
walletSign,
},
}
var walletNew = &cli.Command{
Name: "new",
Usage: "Generate a new key of the given type",
ArgsUsage: "[bls|secp256k1 (default secp256k1)]",
Action: func(cctx *cli.Context) error {
ctx := lcli.ReqContext(cctx)
n, err := node.Setup(cctx.String(cmd.FlagRepo.Name))
if err != nil {
return err
}
t := cctx.Args().First()
if t == "" {
t = "secp256k1"
}
nk, err := n.Wallet.WalletNew(ctx, types.KeyType(t))
if err != nil {
return err
}
if cctx.Bool("json") {
out := map[string]interface{}{
"address": nk.String(),
}
cmd.PrintJson(out) //nolint:errcheck
} else {
fmt.Println(nk.String())
}
return nil
},
}
var walletList = &cli.Command{
Name: "list",
Usage: "List wallet address",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "addr-only",
Usage: "Only print addresses",
Aliases: []string{"a"},
},
&cli.BoolFlag{
Name: "id",
Usage: "Output ID addresses",
Aliases: []string{"i"},
},
},
Action: func(cctx *cli.Context) error {
ctx := lcli.ReqContext(cctx)
n, err := node.Setup(cctx.String(cmd.FlagRepo.Name))
if err != nil {
return err
}
api, closer, err := lcli.GetGatewayAPI(cctx)
if err != nil {
return fmt.Errorf("cant setup gateway connection: %w", err)
}
defer closer()
afmt := NewAppFmt(cctx.App)
addrs, err := n.Wallet.WalletList(ctx)
if err != nil {
return err
}
// Assume an error means no default key is set
def, _ := n.Wallet.GetDefault()
// Map Keys. Corresponds to the standard tablewriter output
addressKey := "Address"
idKey := "ID"
balanceKey := "Balance"
marketKey := "market" // for json only
marketAvailKey := "Market(Avail)"
marketLockedKey := "Market(Locked)"
nonceKey := "Nonce"
defaultKey := "Default"
errorKey := "Error"
dataCapKey := "DataCap"
// One-to-one mapping between tablewriter keys and JSON keys
tableKeysToJsonKeys := map[string]string{
addressKey: strings.ToLower(addressKey),
idKey: strings.ToLower(idKey),
balanceKey: strings.ToLower(balanceKey),
marketKey: marketKey, // only in JSON
nonceKey: strings.ToLower(nonceKey),
defaultKey: strings.ToLower(defaultKey),
errorKey: strings.ToLower(errorKey),
dataCapKey: strings.ToLower(dataCapKey),
}
// List of Maps whose keys are defined above. One row = one list element = one wallet
var wallets []map[string]interface{}
for _, addr := range addrs {
if cctx.Bool("addr-only") {
afmt.Println(addr.String())
} else {
a, err := api.StateGetActor(ctx, addr, types.EmptyTSK)
if err != nil {
if !strings.Contains(err.Error(), "actor not found") {
wallet := map[string]interface{}{
addressKey: addr,
errorKey: err,
}
wallets = append(wallets, wallet)
continue
}
a = &types.Actor{
Balance: big.Zero(),
}
}
wallet := map[string]interface{}{
addressKey: addr,
balanceKey: types.FIL(a.Balance),
nonceKey: a.Nonce,
}
if cctx.Bool("json") {
if addr == def {
wallet[defaultKey] = true
} else {
wallet[defaultKey] = false
}
} else {
if addr == def {
wallet[defaultKey] = "X"
}
}
if cctx.Bool("id") {
id, err := api.StateLookupID(ctx, addr, types.EmptyTSK)
if err != nil {
wallet[idKey] = "n/a"
} else {
wallet[idKey] = id
}
}
mbal, err := api.StateMarketBalance(ctx, addr, types.EmptyTSK)
if err == nil {
marketAvailValue := types.FIL(types.BigSub(mbal.Escrow, mbal.Locked))
marketLockedValue := types.FIL(mbal.Locked)
// structure is different for these particular keys so we have to distinguish the cases here
if cctx.Bool("json") {
wallet[marketKey] = map[string]interface{}{
"available": marketAvailValue,
"locked": marketLockedValue,
}
} else {
wallet[marketAvailKey] = marketAvailValue
wallet[marketLockedKey] = marketLockedValue
}
}
dcap, err := api.StateVerifiedClientStatus(ctx, addr, types.EmptyTSK)
if err == nil {
wallet[dataCapKey] = dcap
if !cctx.Bool("json") && dcap == nil {
wallet[dataCapKey] = "X"
}
} else {
wallet[dataCapKey] = "n/a"
if cctx.Bool("json") {
wallet[dataCapKey] = nil
}
}
wallets = append(wallets, wallet)
}
}
if !cctx.Bool("addr-only") {
if cctx.Bool("json") {
// get a new list of wallets with json keys instead of tablewriter keys
var jsonWallets []map[string]interface{}
for _, wallet := range wallets {
jsonWallet := make(map[string]interface{})
for k, v := range wallet {
jsonWallet[tableKeysToJsonKeys[k]] = v
}
jsonWallets = append(jsonWallets, jsonWallet)
}
// then return this!
return cmd.PrintJson(jsonWallets)
} else {
// Init the tablewriter's columns
tw := tablewriter.New(
tablewriter.Col(addressKey),
tablewriter.Col(idKey),
tablewriter.Col(balanceKey),
tablewriter.Col(marketAvailKey),
tablewriter.Col(marketLockedKey),
tablewriter.Col(nonceKey),
tablewriter.Col(defaultKey),
tablewriter.NewLineCol(errorKey))
// populate it with content
for _, wallet := range wallets {
tw.Write(wallet)
}
// return the corresponding string
return tw.Flush(os.Stdout)
}
}
return nil
},
}
var walletBalance = &cli.Command{
Name: "balance",
Usage: "Get account balance",
ArgsUsage: "[address]",
Action: func(cctx *cli.Context) error {
ctx := lcli.ReqContext(cctx)
n, err := node.Setup(cctx.String(cmd.FlagRepo.Name))
if err != nil {
return err
}
api, closer, err := lcli.GetGatewayAPI(cctx)
if err != nil {
return fmt.Errorf("cant setup gateway connection: %w", err)
}
defer closer()
afmt := NewAppFmt(cctx.App)
var addr address.Address
if cctx.Args().First() != "" {
addr, err = address.NewFromString(cctx.Args().First())
} else {
addr, err = n.Wallet.GetDefault()
}
if err != nil {
return err
}
balance, err := api.WalletBalance(ctx, addr)
if err != nil {
return err
}
if balance.Equals(types.NewInt(0)) {
warningMessage := "may display 0 if chain sync in progress"
if cctx.Bool("json") {
out := map[string]interface{}{
"balance": types.FIL(balance),
"warning": warningMessage,
}
return cmd.PrintJson(out)
} else {
afmt.Printf(fmt.Sprintf("%s (warning: %s)\n", types.FIL(balance), warningMessage))
}
} else {
if cctx.Bool("json") {
out := map[string]interface{}{
"balance": types.FIL(balance),
}
return cmd.PrintJson(out)
} else {
afmt.Printf("%s\n", types.FIL(balance))
}
}
return nil
},
}
var walletExport = &cli.Command{
Name: "export",
Usage: "export keys",
ArgsUsage: "[address]",
Action: func(cctx *cli.Context) error {
ctx := lcli.ReqContext(cctx)
n, err := node.Setup(cctx.String(cmd.FlagRepo.Name))
if err != nil {
return err
}
afmt := NewAppFmt(cctx.App)
if !cctx.Args().Present() {
err := fmt.Errorf("must specify key to export")
return err
}
addr, err := address.NewFromString(cctx.Args().First())
if err != nil {
return err
}
ki, err := n.Wallet.WalletExport(ctx, addr)
if err != nil {
return err
}
b, err := json.Marshal(ki)
if err != nil {
return err
}
if cctx.Bool("json") {
out := map[string]interface{}{
"key": hex.EncodeToString(b),
}
return cmd.PrintJson(out)
} else {
afmt.Println(hex.EncodeToString(b))
}
return nil
},
}
var walletImport = &cli.Command{
Name: "import",
Usage: "import keys",
ArgsUsage: "[<path> (optional, will read from stdin if omitted)]",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "format",
Usage: "specify input format for key",
Value: "hex-lotus",
},
&cli.BoolFlag{
Name: "as-default",
Usage: "import the given key as your new default key",
},
},
Action: func(cctx *cli.Context) error {
ctx := lcli.ReqContext(cctx)
n, err := node.Setup(cctx.String(cmd.FlagRepo.Name))
if err != nil {
return err
}
var inpdata []byte
if !cctx.Args().Present() || cctx.Args().First() == "-" {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter private key: ")
indata, err := reader.ReadBytes('\n')
if err != nil {
return err
}
inpdata = indata
} else {
fdata, err := os.ReadFile(cctx.Args().First())
if err != nil {
return err
}
inpdata = fdata
}
var ki types.KeyInfo
switch cctx.String("format") {
case "hex-lotus":
data, err := hex.DecodeString(strings.TrimSpace(string(inpdata)))
if err != nil {
return err
}
if err := json.Unmarshal(data, &ki); err != nil {
return err
}
case "json-lotus":
if err := json.Unmarshal(inpdata, &ki); err != nil {
return err
}
case "gfc-json":
var f struct {
KeyInfo []struct {
PrivateKey []byte
SigType int
}
}
if err := json.Unmarshal(inpdata, &f); err != nil {
return fmt.Errorf("failed to parse go-filecoin key: %s", err)
}
gk := f.KeyInfo[0]
ki.PrivateKey = gk.PrivateKey
switch gk.SigType {
case 1:
ki.Type = types.KTSecp256k1
case 2:
ki.Type = types.KTBLS
default:
return fmt.Errorf("unrecognized key type: %d", gk.SigType)
}
default:
return fmt.Errorf("unrecognized format: %s", cctx.String("format"))
}
addr, err := n.Wallet.WalletImport(ctx, &ki)
if err != nil {
return err
}
if cctx.Bool("as-default") {
if err := n.Wallet.SetDefault(addr); err != nil {
return fmt.Errorf("failed to set default key: %w", err)
}
}
if cctx.Bool("json") {
out := map[string]interface{}{
"address": addr,
}
return cmd.PrintJson(out)
} else {
fmt.Printf("imported key %s successfully!\n", addr)
}
return nil
},
}
var walletGetDefault = &cli.Command{
Name: "default",
Usage: "Get default wallet address",
Aliases: []string{"get-default"},
Action: func(cctx *cli.Context) error {
n, err := node.Setup(cctx.String(cmd.FlagRepo.Name))
if err != nil {
return err
}
afmt := NewAppFmt(cctx.App)
addr, err := n.Wallet.GetDefault()
if err != nil {
return err
}
if cctx.Bool("json") {
out := map[string]interface{}{
"address": addr.String(),
}
return cmd.PrintJson(out)
} else {
afmt.Printf("%s\n", addr.String())
}
return nil
},
}
var walletSetDefault = &cli.Command{
Name: "set-default",
Usage: "Set default wallet address",
ArgsUsage: "[address]",
Action: func(cctx *cli.Context) error {
n, err := node.Setup(cctx.String(cmd.FlagRepo.Name))
if err != nil {
return err
}
if !cctx.Args().Present() {
return fmt.Errorf("must pass address to set as default")
}
addr, err := address.NewFromString(cctx.Args().First())
if err != nil {
return err
}
return n.Wallet.SetDefault(addr)
},
}
var walletDelete = &cli.Command{
Name: "delete",
Usage: "Delete an account from the wallet",
ArgsUsage: "<address> ",
Action: func(cctx *cli.Context) error {
ctx := lcli.ReqContext(cctx)
n, err := node.Setup(cctx.String(cmd.FlagRepo.Name))
if err != nil {
return err
}
if !cctx.Args().Present() || cctx.NArg() != 1 {
return fmt.Errorf("must specify address to delete")
}
addr, err := address.NewFromString(cctx.Args().First())
if err != nil {
return err
}
return n.Wallet.WalletDelete(ctx, addr)
},
}
var walletSign = &cli.Command{
Name: "sign",
Usage: "Sign a message",
ArgsUsage: "<signing address> <hexMessage>",
Action: func(cctx *cli.Context) error {
ctx := lcli.ReqContext(cctx)
n, err := node.Setup(cctx.String(cmd.FlagRepo.Name))
if err != nil {
return err
}
if !cctx.Args().Present() || cctx.NArg() != 2 {
return fmt.Errorf("must specify signing address and message to sign")
}
addr, err := address.NewFromString(cctx.Args().First())
if err != nil {
return err
}
msg, err := hex.DecodeString(cctx.Args().Get(1))
if err != nil {
return err
}
sig, err := n.Wallet.WalletSign(ctx, addr, msg, api.MsgMeta{Type: api.MTUnknown})
if err != nil {
return err
}
sigBytes := append([]byte{byte(sig.Type)}, sig.Data...)
if cctx.Bool("json") {
out := map[string]interface{}{
"signature": hex.EncodeToString(sigBytes),
}
err := cmd.PrintJson(out)
if err != nil {
return err
}
} else {
fmt.Println(hex.EncodeToString(sigBytes))
}
return nil
},
}