-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
1047 lines (911 loc) · 24.6 KB
/
main.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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
crypto2 "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/crypto/blake2b"
"github.com/filecoin-project/firefly-wallet/db"
"github.com/filecoin-project/firefly-wallet/impl"
"github.com/filecoin-project/firefly-wallet/mnemonic"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/crypto"
"github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/chain/types"
lcli "github.com/filecoin-project/lotus/cli"
"github.com/filecoin-project/lotus/lib/tablewriter"
"github.com/filecoin-project/specs-actors/v5/actors/builtin"
"github.com/howeyc/gopass"
"github.com/mitchellh/go-homedir"
"github.com/syndtr/goleveldb/leveldb/errors"
"github.com/urfave/cli/v2"
"golang.org/x/xerrors"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
)
var localdb *db.LocalDb = nil
var localMnenoic []byte
var passwdValid = true
var passwd []byte
const NEXT = "next"
const encryptKey = "encryptText"
const repoENV = "LOTUS_WALLET_TOOL_PATH"
const defaultRepoPath = "~/.lotuswallettool"
const unRecoverIndex = -1 // 导入钱包地址index为0。
//const signKeyFile = "sign.txt"
//const filPath = "m/44'/461'/0'/0/"
type FilAddressInfo struct {
MinerId string
AddrType string
Index int
Address string
}
func getRepoPath() string {
repoPath := os.Getenv(repoENV)
if len(repoPath) == 0 {
repoPath = defaultRepoPath
}
repoPath, err := homedir.Expand(repoPath)
if err != nil {
fmt.Println("读取程序配置目录失败")
panic("读取程序配置目录失败")
}
return repoPath
}
func _initDb() error {
_, err := os.Stat(filepath.Join(getRepoPath(), "db"))
//if err != nil && os.IsNotExist(err) {
if err != nil {
os.RemoveAll(filepath.Join(getRepoPath(), "db"))
err := os.MkdirAll(filepath.Join(getRepoPath(), "db"), 0755)
if err != nil {
fmt.Printf("初始化程序创建数据库目录失败! err:%v\n", err)
return xerrors.Errorf("初始化程序创建数据库目录失败! err:%v\n", err)
}
}
localdb, err = db.Init(filepath.Join(getRepoPath(), "db"))
if err != nil {
fmt.Printf("初始化程序创建数据库失败! err:%v\n", err)
}
return err
}
func signMessage(msg []byte, addr address.Address) (*crypto.Signature, error) {
faiByte, err := localdb.Get(db.KeyAddr, addr.String())
if err != nil {
fmt.Println("db中读取钱包地址", addr.String())
return &crypto.Signature{}, err
//panic(err)
}
fai := FilAddressInfo{}
err = json.Unmarshal(faiByte, &fai)
if err != nil {
fmt.Printf("解析数据库信息是失败, err:%v\n", err)
return &crypto.Signature{}, err
}
//mb, err := msg.ToStorageBlock()
//if err != nil {
// fmt.Printf("序列化消息失败, err:%v", err)
// return &crypto.Signature{}, xerrors.Errorf("serializing message: %w", err)
//}
// 导入钱包地址签名
if fai.Index == unRecoverIndex {
sb, err := unRecoverAddrSign(msg, addr)
if err != nil {
fmt.Printf("签名失败,err: %v\n", err)
}
return sb, nil
} else {
// 派生钱包地址签名
sb, err := impl.Sign(msg, addr, string(localMnenoic), fai.Index)
if err != nil {
fmt.Printf("签名失败,err: %v\n", err)
}
return sb, nil
}
}
// 非派生钱包地址,即不可恢复钱包地址,签名
func unRecoverAddrSign(msg []byte, addr address.Address) (*crypto.Signature, error) {
encryptKey, err := localdb.Get(db.KeyPriKey, addr.String())
if err != nil {
fmt.Printf("从数据库读取钱包失败!,err: %v", err)
return &crypto.Signature{}, err
}
inpdata, err := mnemonic.Decrypt(encryptKey, passwd)
if err != nil {
fmt.Printf("读取私钥出错,err: %v", err)
return &crypto.Signature{}, err
}
var ki types.KeyInfo
data, err := hex.DecodeString(strings.TrimSpace(string(inpdata)))
if err != nil {
fmt.Println("输入的私钥格式不正确,解析出错!")
return &crypto.Signature{}, err
}
if err := json.Unmarshal(data, &ki); err != nil {
fmt.Println("输入的私钥格式不正确,序列化出错!")
return &crypto.Signature{}, err
}
var sb *crypto.Signature
switch ki.Type {
case types.KTSecp256k1:
b2sum := blake2b.Sum256(msg)
priKey, err := crypto2.ToECDSA(ki.PrivateKey)
if err != nil {
return nil, err
}
sig, err := crypto2.Sign(b2sum[:], priKey)
if err != nil {
fmt.Printf("签名消息失败,err:%v", err)
return &crypto.Signature{}, err
}
sb = &crypto.Signature{
Type: crypto.SigTypeSecp256k1,
Data: sig,
}
case types.KTBLS:
sb, err = impl.SignBls(ki.PrivateKey[:], msg)
if err != nil {
fmt.Printf("签名消息失败,err:%v", err)
return &crypto.Signature{}, err
}
default:
return nil, xerrors.Errorf("unsupported key type: %s", ki.Type)
}
return sb, nil
}
func _init() error {
if err := _initDb(); err != nil {
fmt.Printf("初始化DB失败,err: %v\n", err)
return err
}
encryptText, err := localdb.Get(db.KeyCommon, encryptKey)
if err != nil {
fmt.Printf("读取化DB失败,err: %v\n", err)
return err
}
//fmt.Println(string(encryptText))
passwd, err = getPassword()
if err != nil {
fmt.Printf("输入密码异常,err: %v\n", err)
return err
}
localMnenoic, err = mnemonic.Decrypt(encryptText, passwd)
if err != nil {
fmt.Printf("读取助记词失败,err: %v\n", err)
return err
}
if valid := impl.VerifyPassword(string(localMnenoic), 0); !valid {
return fmt.Errorf("密码错误!")
}
return nil
}
func main() {
local := []*cli.Command{
initCmd,
withdrawCmd,
sendCmd,
newAddressCmd,
exportAddressCmd,
listCmd,
importAddressCmd,
signCmd,
setOwnerCmd,
proposeChangeWorker,
//controlListCmd,
//controlSetCmd,
}
app := &cli.App{
Name: "萤火虫钱包管理工具",
Usage: "萤火虫钱包管理工具, 用于矿工提现,转账,签名,以及节点控制等功能",
Version: build.UserVersion(),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "db-dir",
Value: "./data",
},
},
Commands: local,
}
if err := app.Run(os.Args); err != nil {
os.Exit(1)
}
}
var exportAddressCmd = &cli.Command{
Name: "export-address",
Usage: "导出钱包私钥",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "address",
Usage: "导出地址",
},
},
Before: func(context *cli.Context) error {
if err := _init(); err != nil {
passwdValid = false
}
return nil
},
Action: func(cctx *cli.Context) error {
if !passwdValid || len(passwd) < 1 {
fmt.Println("密码错误.")
return fmt.Errorf("密码错误")
}
address := cctx.String("address")
if address == "" {
fmt.Println("address is empty")
return nil
}
faiByte, err := localdb.Get(db.KeyAddr, address)
if err != nil {
fmt.Printf("从数据库读取钱包失败!,err: %v", err)
return nil
}
fai := FilAddressInfo{}
err = json.Unmarshal(faiByte, &fai)
if err != nil {
fmt.Printf("反序列化数据(%v)失败!,err: %v", faiByte, err)
return nil
}
var privKey string
if fai.Index == unRecoverIndex {
encryptKey, err := localdb.Get(db.KeyPriKey, address)
if err != nil {
fmt.Printf("从数据库读取钱包失败!,err: %v", err)
return nil
}
inpdata, err := mnemonic.Decrypt(encryptKey, passwd)
if err != nil {
fmt.Printf("读取私钥出错,err: %v", err)
return nil
}
var ki types.KeyInfo
data, err := hex.DecodeString(strings.TrimSpace(string(inpdata)))
if err != nil {
fmt.Println("输入的私钥格式不正确,解析出错!")
return err
}
if err := json.Unmarshal(data, &ki); err != nil {
fmt.Println("输入的私钥格式不正确,序列化出错!")
return err
}
b, err := json.Marshal(ki)
if err != nil {
fmt.Println("序列化私钥出错,原因:", err.Error())
return err
}
privKey = hex.EncodeToString(b)
} else {
if strings.HasPrefix(fai.Address, "f3") || strings.HasPrefix(fai.Address, "t3") {
privKey, err = impl.ExportBlsAddress(string(localMnenoic), fai.Index)
if err != nil {
fmt.Printf("导出BLS钱包失败!,err: %v", err)
return nil
}
} else {
privKey, err = impl.ExportSecp256k1Address(string(localMnenoic), fai.Index)
if err != nil {
fmt.Printf("导出Secp256钱包失败!,err: %v", err)
return nil
}
}
}
fmt.Println(privKey)
return nil
},
}
var sendCmd = &cli.Command{
Name: "send",
Usage: "转账",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "from",
Usage: "转账源账户",
},
&cli.StringFlag{
Name: "to",
Usage: "转账目标账户",
},
&cli.StringFlag{
Name: "amount",
Usage: "转账金额",
},
},
Before: func(context *cli.Context) error {
if err := _init(); err != nil {
passwdValid = false
}
return nil
},
Action: func(cctx *cli.Context) error {
if !passwdValid {
fmt.Println("密码错误.")
return fmt.Errorf("密码错误")
}
if cctx.String("from") == "" || cctx.String("to") == "" || cctx.String("amount") == "" {
fmt.Println("必须指定--from,--to,--amount.")
return nil
}
api, closer, err := lcli.GetFullNodeAPI(cctx)
if err != nil {
fmt.Printf("连接FULLNODE_API_INFO api失败。%v\n", err)
return err
}
defer closer() //nolint:errcheck
ctx := lcli.ReqContext(cctx)
msg := &types.Message{}
msg.From, err = address.NewFromString(cctx.String("from"))
if err != nil {
fmt.Printf("解析转账源地址失败: %v", err)
return fmt.Errorf("failed to parse source address: %w\n", err)
}
msg.To, err = address.NewFromString(cctx.String("to"))
if err != nil {
fmt.Printf("解析转账目标地址失败: %v", err)
return fmt.Errorf("failed to parse target address: %w\n", err)
}
amount, err := types.ParseFIL(cctx.String("amount"))
if err != nil {
fmt.Printf("解析转账金额地址失败: %v\n", err)
return fmt.Errorf("解析转账金额失败: %v", err)
}
msg.Value = abi.TokenAmount(amount)
if strings.Compare(msg.From.String(), msg.To.String()) == 0 {
fmt.Printf("转入和转出地址相同\n")
return fmt.Errorf("转入和转出地址相同")
}
msg.Method = builtin.MethodSend
// 获取nonce
msg.Nonce, err = api.MpoolGetNonce(ctx, msg.From)
if err != nil {
fmt.Printf("读取获取消息池中的的nonce失败,err:%v\n", err)
a, err := api.StateGetActor(ctx, msg.From, types.EmptyTSK)
if err != nil {
fmt.Printf("读取获取链数据上的的nonce失败,err:%v\n", err)
return err
}
msg.Nonce = a.Nonce
}
msg, err = api.GasEstimateMessageGas(ctx, msg, nil, types.EmptyTSK)
if err != nil {
fmt.Printf("评估消息的gas费用失败, err:%v\n", err)
return xerrors.Errorf("GasEstimateMessageGas error: %w", err)
}
mb, err := msg.ToStorageBlock()
if err != nil {
fmt.Printf("序列化消息失败, err:%v", err)
return xerrors.Errorf("serializing message: %w", err)
}
// 签名
sb, err := signMessage(mb.Cid().Bytes(), msg.From)
if err != nil {
fmt.Printf("签名失败, err:%v\n", err)
return xerrors.Errorf("签名失败: %w", err)
}
// 推送消息
cid, err := api.MpoolPush(ctx, &types.SignedMessage{Message: *msg, Signature: *sb})
if err != nil {
fmt.Printf("推送消息上链失败,err:%v\n", err)
return err
}
fmt.Printf("Requested rewards withdrawal in message %s\n", cid.String())
return nil
},
}
var initCmd = &cli.Command{
Name: "init",
Usage: "初始化配置钱包助记词,用于后续签名,第一次使用本工具必须先执行此命令初始化。助记词会通过输入密码加密保存,后面启动无需再次输入助记词。只需输入密码即可。",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "key-file",
Usage: "指定助记词文件",
},
&cli.BoolFlag{
Name: "force",
Usage: "强制执行,当本地存在一个助记词加密文件,不允许再次初始化,指定--force命令,可以强制初始化,将覆盖之前的助记词加密文件。请谨慎操作。",
},
},
Before: func(context *cli.Context) error {
if err := _initDb(); err != nil {
passwdValid = false
}
return nil
},
Action: func(cctx *cli.Context) error {
if !passwdValid {
fmt.Println("密码错误.")
return fmt.Errorf("密码错误")
}
// 读取助记词
keyFileBytes, err := ioutil.ReadFile(cctx.String("key-file"))
if err != nil {
fmt.Printf("从 %s 读取助记词失败。原因: %v\n", cctx.String("key-file"), err.Error())
return nil
}
if keyExist(localdb) {
if cctx.Bool("force") {
fmt.Println("旧的助记词将被新的覆盖掉!")
} else {
fmt.Println("已经存在一个助记词,请勿重复初始化, 如果确认想更换助记词,请加--force命令")
return nil
}
}
// 输入密码
passwd, err := getPassword()
if err != nil {
return nil
}
fmt.Print("请再次输入密码:")
passwdRe, err := gopass.GetPasswdMasked()
if err != nil {
fmt.Printf("输入密码异常,%v\n", err)
return nil
}
if bytes.Compare(passwd, passwdRe) != 0 {
fmt.Printf("两次输入密码不一致,%v\n", err)
return nil
}
// 加密助记词
if err := encryptAndSaveKey(keyFileBytes, passwd, localdb); err != nil {
fmt.Printf("加密保存助记词失败!err: %v\n", err)
return err
}
encryptText, err := localdb.Get(db.KeyCommon, encryptKey)
if err != nil {
fmt.Printf("读取化DB失败,err: %v\n", err)
return err
}
localMnenoic, err = mnemonic.Decrypt(encryptText, passwd)
if err != nil {
fmt.Printf("读取助记词失败,err: %v\n", err)
return err
}
// 初始化创建一个钱包地址,用于后续验证密码使用
createAddress(false, false)
return nil
},
}
var newAddressCmd = &cli.Command{
Name: "new-address",
Usage: "创建一个新的钱包地址",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "bls",
Usage: "创建bls类型的钱包地址",
Value: false,
},
&cli.BoolFlag{
Name: "show-private-key",
Usage: "显示私钥",
Value: false,
Hidden: true,
},
},
Before: func(context *cli.Context) error {
if err := _init(); err != nil {
passwdValid = false
}
return nil
},
Action: func(context *cli.Context) error {
if !passwdValid {
fmt.Println("密码错误.")
return fmt.Errorf("密码错误")
}
showPK := context.Bool("show-private-key")
createAddress(showPK, context.Bool("bls"))
return nil
},
}
var importAddressCmd = &cli.Command{
Name: "import",
Usage: "导入钱包地址,注意:导入的钱包地址,因不是助记词派生的地址,无法通过助记词找回来。",
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",
},
},
Before: func(context *cli.Context) error {
if err := _init(); err != nil {
passwdValid = false
}
return nil
},
Action: func(cctx *cli.Context) error {
if !passwdValid || len(passwd) < 1 {
fmt.Println("密码错误.")
return fmt.Errorf("密码错误")
}
var inpdata []byte
if !cctx.Args().Present() || cctx.Args().First() == "-" {
reader := bufio.NewReader(os.Stdin)
fmt.Print("请输入私钥: ")
indata, err := reader.ReadBytes('\n')
if err != nil {
return err
}
inpdata = indata
} else {
fdata, err := ioutil.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 {
fmt.Println("输入的私钥格式不正确,解析出错!")
return err
}
if err := json.Unmarshal(data, &ki); err != nil {
fmt.Println("输入的私钥格式不正确,序列化出错!")
return err
}
case "json-lotus":
if err := json.Unmarshal(inpdata, &ki); err != nil {
fmt.Println("输入的json格式的私钥格式不正确,序列化出错!")
return err
}
case "gfc-json":
var f struct {
KeyInfo []struct {
PrivateKey []byte
SigType int
}
}
if err := json.Unmarshal(inpdata, &f); err != nil {
fmt.Println("输入的gfc格式的私钥格式不正确,序列化出错!")
return xerrors.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:
fmt.Println("解析私钥 信息失败,无法识别的私钥类型!!")
return fmt.Errorf("unrecognized key type: %d", gk.SigType)
}
default:
fmt.Println("解析私钥 信息失败,不识别的格式!!")
return fmt.Errorf("unrecognized format: %s", cctx.String("format"))
}
//api, closer, err := lcli.GetFullNodeAPI(cctx)
//if err != nil {
// fmt.Printf("连接FULLNODE_API_INFO api失败。%v\n", err)
// return err
//}
//defer closer()
//ctx := lcli.ReqContext(cctx)
// 解析出addr
key, err := impl.NewKey(&ki)
if err != nil {
fmt.Println("创建钱包地址失败 ,原因:", err.Error())
return err
}
filInfo := FilAddressInfo{Address: key.Address.String(), Index: unRecoverIndex, AddrType: string(key.Type)}
filInfoByte, err := json.Marshal(&filInfo)
if err != nil {
fmt.Println("序列化filInfo失败!")
return err
}
err = localdb.Add(db.KeyAddr, key.Address.String(), filInfoByte)
if err != nil {
fmt.Println("保存钱包地址到数据异常,原因:", err.Error())
return err
}
// 保存privateKey,到数据库
encryData, err := mnemonic.EncryptData(inpdata, passwd)
if err != nil {
fmt.Println("加密私钥失败!原因:", err.Error())
return err
}
err = localdb.Add(db.KeyPriKey, key.Address.String(), encryData)
if err != nil {
fmt.Println("保存钱包地址到数据异常,原因:", err.Error())
return err
}
fmt.Println("成功导入钱包:", key.Address.String())
return nil
},
}
var listCmd = &cli.Command{
Name: "list",
Usage: "展示钱包列表",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "addr-only",
Usage: "只展示钱包地址",
Aliases: []string{"a"},
},
&cli.BoolFlag{
Name: "id",
Usage: "展示actorID",
Aliases: []string{"i"},
},
&cli.BoolFlag{
Name: "market",
Usage: "展示market余额",
Aliases: []string{"m"},
},
},
Before: func(context *cli.Context) error {
if err := _init(); err != nil {
passwdValid = false
}
return nil
},
Action: func(cctx *cli.Context) error {
if !passwdValid {
fmt.Println("密码错误.")
return fmt.Errorf("密码错误")
}
api, closer, err := lcli.GetFullNodeAPI(cctx)
if err != nil {
fmt.Printf("连接FULLNODE_API_INFO api失败。%v\n", err)
return err
}
defer closer()
ctx := lcli.ReqContext(cctx)
//addrs, err := localWallet.WalletList(ctx)
addrs, err := localdb.GetAll(db.KeyAddr)
if err != nil {
fmt.Println("读取数据库获取钱包地址失败")
return err
}
// Assume an error means no default key is set
def, _ := api.WalletDefaultAddress(ctx)
tw := tablewriter.New(
tablewriter.Col("Address"),
tablewriter.Col("ID"),
tablewriter.Col("Balance"),
tablewriter.Col("Market(Avail)"),
tablewriter.Col("Market(Locked)"),
tablewriter.Col("Nonce"),
tablewriter.Col("Default"),
tablewriter.NewLineCol("Error"))
for _, a := range addrs {
fa := FilAddressInfo{}
json.Unmarshal([]byte(a), &fa)
addr, err := address.NewFromString(fa.Address)
if err != nil {
return err
}
if cctx.Bool("addr-only") {
fmt.Println(addr)
} else {
a, err := api.StateGetActor(ctx, addr, types.EmptyTSK)
if err != nil {
if !strings.Contains(err.Error(), "actor not found") {
tw.Write(map[string]interface{}{
"Address": addr,
"Error": err,
})
continue
}
a = &types.Actor{
Balance: big.Zero(),
}
}
row := map[string]interface{}{
"Address": addr,
"Balance": types.FIL(a.Balance),
"Nonce": a.Nonce,
}
if addr == def {
row["Default"] = "X"
}
if cctx.Bool("id") {
id, err := api.StateLookupID(ctx, addr, types.EmptyTSK)
if err != nil {
row["ID"] = "n/a"
} else {
row["ID"] = id
}
}
if cctx.Bool("market") {
mbal, err := api.StateMarketBalance(ctx, addr, types.EmptyTSK)
if err == nil {
row["Market(Avail)"] = types.FIL(types.BigSub(mbal.Escrow, mbal.Locked))
row["Market(Locked)"] = types.FIL(mbal.Locked)
}
}
tw.Write(row)
}
}
if !cctx.Bool("addr-only") {
return tw.Flush(os.Stdout)
}
return nil
},
}
var signCmd = &cli.Command{
Name: "sign",
Usage: "签名消息命令",
ArgsUsage: "<signing address> <hexMessage>",
Before: func(context *cli.Context) error {
if err := _init(); err != nil {
passwdValid = false
}
return nil
},
Action: func(cctx *cli.Context) error {
//api, closer, err := GetFullNodeAPI(cctx)
//if err != nil {
// return err
//}
//defer closer()
//ctx := ReqContext(cctx)
if !passwdValid {
fmt.Println("密码错误.")
return fmt.Errorf("密码错误")
}
if !cctx.Args().Present() || cctx.NArg() != 2 {
fmt.Println("必须指定签名钱包地址和要签名的消息")
return fmt.Errorf("必须指定签名钱包地址和要签名的消息")
}
addr, err := address.NewFromString(cctx.Args().First())
if err != nil {
fmt.Println("输入签名的钱包地址异常,", err)
return err
}
msg, err := hex.DecodeString(cctx.Args().Get(1))
if err != nil {
fmt.Println("解析要签名的内容异常,", err)
return err
}
sig, err := signMessage(msg, addr)
if err != nil {
return err
}
sigBytes := append([]byte{byte(sig.Type)}, sig.Data...)
fmt.Println(hex.EncodeToString(sigBytes))
return nil
},
}
func createAddress(show, bls bool) {
if bls {
// t3...
generateBlsFilAddress(show)
} else {
// t1....
generateFilAddress(show)
}
}
func getNextIndex() int {
strIndex, err := localdb.Get(db.KeyIndex, NEXT)
if err != nil {
if err != errors.ErrNotFound {
panic(err)
}
strIndex = []byte("0")
}
index, err := strconv.Atoi(string(strIndex))
if err != nil {
panic(err)
}
return index
}
func generateBlsFilAddress(showPK bool) {
index := getNextIndex()
filAddr, err := impl.CreateBlsFilAddress(string(localMnenoic), index)
if err != nil {
panic(err)
}
fai := FilAddressInfo{
Address: filAddr,
Index: index,
}
//fmt.Println(fai)
if showPK {
priKey, err := impl.ExportBlsAddress(string(localMnenoic), index)
if err != nil {
panic(err)
}
fmt.Println(priKey)
}
faiByte, err := json.Marshal(&fai)
fmt.Println(filAddr)
if err != nil {
panic(err)
}
err = localdb.Add(db.KeyAddr, filAddr, faiByte)
if err != nil {
panic(err)
}
err = localdb.Add(db.KeyIndex, NEXT, []byte(fmt.Sprintf("%d", index+1)))
if err != nil {
panic(err)
}
}
func generateFilAddress(showPK bool) {
mnenoic := string(localMnenoic)
index := getNextIndex()
filAddr, err := impl.CreateSecp256k1FilAddress(mnenoic, index)
if err != nil {
panic(err)
}
fai := FilAddressInfo{
Address: filAddr,
Index: index,
}
fmt.Println(filAddr)
if showPK {
priKey, err := impl.ExportSecp256k1Address(mnenoic, index)
if err != nil {
panic(err)
}
fmt.Println(priKey)
}
faiByte, err := json.Marshal(&fai)
if err != nil {
panic(err)
}
err = localdb.Add(db.KeyAddr, filAddr, faiByte)
if err != nil {
panic(err)
}
err = localdb.Add(db.KeyIndex, NEXT, []byte(fmt.Sprintf("%d", index+1)))
if err != nil {
panic(err)
}
}
func getPassword() ([]byte, error) {
var passwd []byte
var err error
fmt.Print("请输入密码(长度至少6位):")
for tryTime := 3; tryTime > 0; tryTime-- {