This repository has been archived by the owner on Jul 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
walletcmd.go
1272 lines (1135 loc) · 42.2 KB
/
walletcmd.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 client
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math/big"
"os"
"strconv"
"text/tabwriter"
"github.com/bgentry/speakeasy"
"github.com/spf13/cobra"
"github.com/threefoldtech/rivine/modules"
"github.com/threefoldtech/rivine/pkg/api"
clipkg "github.com/threefoldtech/rivine/pkg/cli"
"github.com/threefoldtech/rivine/types"
)
func createWalletCmd(cli *CommandLineClient) *WalletCommand {
walletCmd := &walletCmd{cli: cli}
// create root explore command and all subs
var (
rootCmd = &cobra.Command{
Use: "wallet",
Short: "Perform wallet actions",
Long: "Generate a new address, send coins to another wallet, or view info about the wallet.",
Run: Wrap(walletCmd.balanceCmd),
}
blockStakeStatCmd = &cobra.Command{
Use: "blockstakestat",
Short: "Get the stats of the blockstake",
Long: "Gives all the statistical info of the blockstake.",
Run: Wrap(walletCmd.blockStakesStatsCmd),
}
addressCmd = &cobra.Command{
Use: "address",
Short: "Get a new wallet address",
Long: "Generate a new wallet address from the wallet's primary seed.",
Run: Wrap(walletCmd.addressCmd),
}
addressesCmd = &cobra.Command{
Use: "addresses",
Short: "List all addresses",
Long: "List all addresses that have been generated by the wallet",
Run: Wrap(walletCmd.addressesCmd),
}
initCmd = &cobra.Command{
Use: "init",
Short: "Initialize a new wallet",
Long: `Generate a new wallet from a randomly generated seed and by default encrypt it.`,
Run: Wrap(walletCmd.initCmd),
}
recoverCmd = &cobra.Command{
Use: "recover",
Short: "Recover a wallet",
Long: `Recover a wallet from the given mnemonic, to be used as primary seed and by default encrypt it.`,
Run: Wrap(walletCmd.recoverCmd),
}
lockCmd = &cobra.Command{
Use: "lock",
Short: "Lock the wallet",
Long: "Lock the wallet, preventing further use",
Run: Wrap(walletCmd.lockCmd),
}
signTxCmd = &cobra.Command{
Use: "sign <txnjson>",
Short: "Sign inputs from the transaction",
Long: `Signs as much of the inputs transaction. Iterate over every input, and check if they can be signed
by any of the keys in the wallet.`,
Run: Wrap(walletCmd.signTxCmd),
}
seedsCmd = &cobra.Command{
Use: "seeds",
Short: "Retrieve information about your seeds",
Long: "Retrieves the current seed, how many addresses are remaining, and the rest of your seeds from the wallet",
Run: Wrap(walletCmd.seedsCmd),
}
balanceCmd = &cobra.Command{
Use: "balance",
Short: "View wallet balance",
Long: "View wallet balance, including confirmed and unconfirmed coins and blockstakes.",
Run: Wrap(walletCmd.balanceCmd),
}
listTransactionsCmd = &cobra.Command{
Use: "transactions",
Short: "View transactions",
Long: `View transactions related to addresses spendable by the wallet,
providing a net flow of coins and blockstakes for each transaction.`,
Run: Wrap(walletCmd.listTransactionsCmd),
}
unlockCmd = &cobra.Command{
Use: `unlock`,
Short: "Unlock the wallet",
Long: "Decrypt and load the wallet into memory",
Run: Wrap(walletCmd.unlockCmd),
}
loadCmd = &cobra.Command{
Use: "load",
Short: "Load something into the wallet",
// Run field is not set, as the load command itself is not a valid command.
// A subcommand must be provided.
}
loadSeedCmd = &cobra.Command{
Use: `seed`,
Short: "Load a seed into the wallet",
Long: "Uses the given password to create a new wallet with that as the primary seed",
Run: Wrap(walletCmd.loadSeedCmd),
}
sendCmd = &cobra.Command{
Use: "send",
Short: "Send either coins or blockstakes",
Long: "Send either coins or blockstakes",
// Run field is not set, as the load command itself is not a valid command.
// A subcommand must be provided.
}
sendCoinsCmd = &cobra.Command{
Use: "coins <dest>|<rawCondition> <amount> [<dest>|<rawCondition> <amount>]...",
Short: "Send coins one or multiple addresses.",
Long: `Send coins to one or multiple addresses.
Each 'dest' must be a 78-byte hexadecimal address (Unlock Hash),
instead of an unlockHash, you can also give a JSON-encoded UnlockCondition directly,
giving you more control and options over how exactly the block stake is to be unlocked.
Amounts have to be given expressed in the OneCoin unit, and without the unit of currency.
Decimals are possible and are to be expressed using English conventions.
Amounts have to be given expressed in the OneCoin unit, and without the unit of currency.
Decimals are possible and have to be defined using the decimal point.
The Minimum Miner Fee will be added on top of the total given amount automatically.
`,
Run: walletCmd.sendCoinsCmd,
}
sendBlockStakesCmd = &cobra.Command{
Use: "blockstakes <dest>|<rawCondition> <amount> [<dest>|<rawCondition> <amount>]..",
Short: "Send blockstakes to one or multiple addresses",
Long: `Send blockstakes to one or multiple addresses.
Each 'dest' must be a 78-byte hexadecimal address (Unlock Hash),
instead of an unlockHash, you can also give a JSON-encoded UnlockCondition directly,
giving you more control and options over how exactly the block stake is to be unlocked.
Amounts have to be given expressed in the OneCoin unit, and without the unit of currency.
Decimals are possible and have to be defined using the decimal point.
The Minimum Miner Fee will be added on top of the total given amount automatically.
`,
Run: walletCmd.sendBlockStakesCmd,
}
sendTxCmd = &cobra.Command{
Use: "transaction <txnjson>",
Short: "Publish a raw transaction",
Long: "Publish a raw transasction. The transaction must be given in json format. The inputs don't need to be related to the current wallet",
Run: Wrap(walletCmd.sendTxCmd),
}
listCmd = &cobra.Command{
Use: "list",
Short: "List either locked or unlocked unspent outputs",
// Run field is not set, as the list command itself is not a valid command.
// A subcommand must be provided.
}
listUnlockedCmd = &cobra.Command{
Use: "unlocked [address]",
Args: cobra.RangeArgs(0, 1),
Short: "List unlocked coin and blockstake outputs",
Long: `List all the unlocked coin and blockstake outputs that belong to this wallet.
If an address is given, only unspent unlocked outputs of the wallet linked to that address are shown.
`,
Run: walletCmd.listUnlockedCmd,
}
listLockedCmd = &cobra.Command{
Use: "locked [address]",
Args: cobra.RangeArgs(0, 1),
Short: "List locked coin and blockstake outputs",
Long: `List all the locked coin and blockstake outputs that belong to this wallet.
If an address is given, only unspent unlocked outputs of the wallet linked to that address are shown.
`,
Run: walletCmd.listLockedCmd,
}
createCmd = &cobra.Command{
Use: "create",
Short: "Create a coin or blockstake transaction",
// Run field is not set, as the create command itself is not a valid command.
// A subcommand must be provided.
}
createMultisigAddressesCmd = &cobra.Command{
Use: "multisigaddress <minsigsrequired> <address1> <address2> [<address>]...",
Short: "Create a multisig address",
Long: `Create a multisig address from the given addresses, which requires at least <minsigrequired>
signatures to unlock`,
Args: cobra.MinimumNArgs(3),
Run: walletCmd.createMultisigAddressesCmd,
}
createCoinTxCmd = &cobra.Command{
Use: "cointransaction <parentID>... <dest>|<rawCondition> <amount> [<dest>|<rawCondition> <amount>]...",
Short: "Create a new coin transaction",
Long: `Create a new coin transaction using the given parentID's and outputs.
The outputs can be given as a pair of value and a raw output condition (or
address, which resolved to a singlesignature condition).
Amounts have to be given expressed in the OneCoin unit, and without the unit of currency.
Decimals are possible and have to be defined using the decimal point.
The Minimum Miner Fee will be added on top of the total given amount automatically.
`,
Run: walletCmd.createCoinTxCmd,
}
createBlockStakeTxCmd = &cobra.Command{
Use: "blockstaketransaction <parentID>... <dest>|<rawCondition> <amount> [<dest>|<rawCondition> <amount>]...",
Short: "Create a new blockstake transaction",
Long: `Create a new blockstake transaction using the given parentID's and outputs.
The outputs can be given as a pair of value and a raw output condition (or
address, which resolved to a singlesignature condition).
Amounts have to be given expressed in the OneCoin unit, and without the unit of currency.
Decimals are possible and have to be defined using the decimal point.
The Minimum Miner Fee will be added on top of the total given amount automatically.
`,
Run: walletCmd.createBlockStakeTxCmd,
}
)
// define wallet command tree
rootCmd.AddCommand(
addressCmd,
addressesCmd,
initCmd,
recoverCmd,
lockCmd,
unlockCmd,
loadCmd,
seedsCmd,
sendCmd,
balanceCmd,
listTransactionsCmd,
blockStakeStatCmd,
listCmd,
createCmd,
signTxCmd)
sendCmd.AddCommand(
sendCoinsCmd,
sendBlockStakesCmd,
sendTxCmd)
loadCmd.AddCommand(loadSeedCmd)
listCmd.AddCommand(
listUnlockedCmd,
listLockedCmd)
createCmd.AddCommand(
createMultisigAddressesCmd,
createCoinTxCmd,
createBlockStakeTxCmd)
// define config of commands that have a config
initCmd.Flags().BoolVar(
&walletCmd.walletInitCfg.Plain,
"plain", false, "create a plain wallet, requiring no passphrase")
recoverCmd.Flags().BoolVar(
&walletCmd.walletRecoverCfg.Plain,
"plain", false, "Recover seed as a plain wallet, requiring no passphrase")
recoverCmd.Flags().StringVar(
&walletCmd.walletRecoverCfg.Seed,
"seed", "", "define the seed to be recovered as a flag instead of the STDIN")
loadSeedCmd.Flags().BoolVar(
&walletCmd.walletLoadSeedCfg.Plain,
"plain", false, "Load seed into a plain wallet, requiring no passphrase")
loadSeedCmd.Flags().StringVar(
&walletCmd.walletLoadSeedCfg.Seed,
"seed", "", "define the seed to be loaded as a flag instead of the STDIN")
// custom arbitrarydata flag
clipkg.ArbitraryDataFlagVar(sendCoinsCmd.Flags(), &walletCmd.sendCoinsCfg.Data,
"data", "optional arbitrary data (or description) to attach to transaction")
clipkg.ArbitraryDataFlagVar(sendBlockStakesCmd.Flags(), &walletCmd.sendBlockStakesCfg.Data,
"data", "optional arbitrary data (or description) to attach to transaction")
// other custom send coins flags
sendCoinsCmd.Flags().StringVar(
&walletCmd.sendCoinsCfg.RefundAddress,
"refund-address", "", "define a custom refund address")
sendCoinsCmd.Flags().BoolVar(
&walletCmd.sendCoinsCfg.RefundAddressNew,
"refund-address-new", false, "generate a new refund address if a refund needs to happen")
// other custom send blockstkars flags
sendBlockStakesCmd.Flags().StringVar(
&walletCmd.sendBlockStakesCfg.RefundAddress,
"refund-address", "", "define a custom refund address")
sendBlockStakesCmd.Flags().BoolVar(
&walletCmd.sendBlockStakesCfg.RefundAddressNew,
"refund-address-new", false, "generate a new refund address if a refund needs to happen")
// all addresses cmd flags
addressesCmd.Flags().BoolVarP(
&walletCmd.walletAddressesCfg.ShowIndices, "index", "i", false,
"prefix each address with its index")
// return root command
return &WalletCommand{
Command: rootCmd,
RootCmdSend: sendCmd,
RootCmdLoad: loadCmd,
RootCmdList: listCmd,
RootCmdCreate: createCmd,
}
}
// WalletCommand returns the Wallet Command as an extended cobra command,
// exposing its sub command groups directly as public properties.
type WalletCommand struct {
*cobra.Command
RootCmdSend *cobra.Command
RootCmdLoad *cobra.Command
RootCmdList *cobra.Command
RootCmdCreate *cobra.Command
}
type walletCmd struct {
cli *CommandLineClient
sendCoinsCfg struct {
Data []byte
RefundAddress string
RefundAddressNew bool
}
sendBlockStakesCfg struct {
Data []byte
RefundAddress string
RefundAddressNew bool
}
walletInitCfg struct {
Plain bool
}
walletRecoverCfg struct {
Plain bool
Seed string
}
walletLoadSeedCfg struct {
Plain bool
Seed string
}
walletAddressesCfg struct {
ShowIndices bool
}
}
// addressCmd fetches a new address from the wallet that will be able to
// receive coins.
func (walletCmd *walletCmd) addressCmd() {
addr := new(api.WalletAddressGET)
err := walletCmd.cli.GetWithResponse("/wallet/address", addr)
if err != nil {
clipkg.DieWithError("Could not generate new address:", err)
}
fmt.Printf("Created new address: %s\n", addr.Address)
}
// addressesCmd fetches the list of addresses that the wallet knows.
func (walletCmd *walletCmd) addressesCmd() {
addrs := new(api.WalletAddressesGET)
err := walletCmd.cli.GetWithResponse("/wallet/addresses", addrs)
if err != nil {
clipkg.DieWithError("Failed to fetch addresses:", err)
}
if !walletCmd.walletAddressesCfg.ShowIndices {
for _, addr := range addrs.Addresses {
fmt.Println(addr)
}
return
}
fmtStr := "%04d\t%s\r\n"
if len(addrs.Addresses) >= 10000 {
fmtStr = "%05d\t%s\r\n"
}
for idx, addr := range addrs.Addresses {
fmt.Printf(fmtStr, idx, addr.String())
}
}
// initCmd encrypts the wallet with the given password
func (walletCmd *walletCmd) initCmd() {
var er api.WalletInitPOST
var data string
if !walletCmd.walletInitCfg.Plain {
fmt.Println("You have to provide a passphrase!")
fmt.Println("If you have an existing mnemonic you can use the recover wallet command instead.")
passphrase, err := speakeasy.Ask("Wallet passphrase: ")
if err != nil {
clipkg.Die("Reading passphrase failed:", err)
}
if passphrase == "" {
clipkg.Die("passphrase is required and cannot be empty")
}
repassphrase, err := speakeasy.Ask("Reenter passphrase: ")
if err != nil {
clipkg.Die("Reading passphrase failed:", err)
}
if repassphrase != passphrase {
clipkg.Die("Given passphrases do not match !!")
}
data = fmt.Sprintf("passphrase=%s", passphrase)
}
err := walletCmd.cli.PostWithResponse("/wallet/init", data, &er)
if err != nil {
if walletCmd.walletInitCfg.Plain {
clipkg.DieWithError("Error when creating plain wallet:", err)
} else {
clipkg.DieWithError("Error when creating encrypted wallet:", err)
}
}
fmt.Printf("Mnemonic of primary seed:\n%s\n\n", er.PrimarySeed)
if !walletCmd.walletInitCfg.Plain {
fmt.Printf("Wallet encrypted with given passphrase\n")
}
}
// recoverCmd encrypts the wallet with the given password,
// recovering a wallet for the given menmeonic to be used as primary seed.
func (walletCmd *walletCmd) recoverCmd() {
var er api.WalletInitPOST
var data string
if !walletCmd.walletRecoverCfg.Plain {
fmt.Println("You have to provide a passphrase and existing mnemonic!")
fmt.Println("If you have no existing mnemonic use the init wallet command instead!")
passphrase, err := speakeasy.Ask("Wallet passphrase: ")
if err != nil {
clipkg.Die("Reading passphrase failed:", err)
}
if passphrase == "" {
clipkg.Die("passphrase is required and cannot be empty")
}
repassphrase, err := speakeasy.Ask("Reenter passphrase: ")
if err != nil {
clipkg.Die("Reading passphrase failed:", err)
}
if repassphrase != passphrase {
clipkg.Die("Given passphrases do not match !!")
}
data = fmt.Sprintf("passphrase=%s&", passphrase)
}
mnemonic := walletCmd.walletRecoverCfg.Seed
if mnemonic == "" {
var err error
mnemonic, err = speakeasy.Ask("Enter existing mnemonic to be used as primary seed: ")
if err != nil {
clipkg.Die("Reading mnemonic failed:", err)
}
}
seed, err := modules.InitialSeedFromMnemonic(mnemonic)
if err != nil {
clipkg.Die("Invalid mnemonic given:", err)
}
data += fmt.Sprintf("seed=%s", seed.String())
err = walletCmd.cli.PostWithResponse("/wallet/init", data, &er)
if err != nil {
if walletCmd.walletRecoverCfg.Plain {
clipkg.DieWithError("Error when creating plain wallet:", err)
} else {
clipkg.DieWithError("Error when creating encrypted wallet:", err)
}
}
if er.PrimarySeed != mnemonic {
clipkg.Die("Wallet was created, but returned primary seed mnemonic was unexpected:\n\n" + er.PrimarySeed)
}
fmt.Printf("Mnemonic of primary seed:\n%s\n\n", er.PrimarySeed)
if !walletCmd.walletRecoverCfg.Plain {
fmt.Printf("Wallet encrypted with given passphrase\n")
}
}
// loadSeedCmd adds a seed to the wallet's list of seeds
func (walletCmd *walletCmd) loadSeedCmd() {
var data string
if !walletCmd.walletLoadSeedCfg.Plain {
passphrase, err := speakeasy.Ask("Wallet passphrase: ")
if err != nil {
clipkg.Die("Reading passphrase failed:", err)
}
data = fmt.Sprintf("passphrase=%s&", passphrase)
}
seed := walletCmd.walletLoadSeedCfg.Seed
if seed == "" {
var err error
seed, err = speakeasy.Ask("Existing Mnemonic: ")
if err != nil {
clipkg.Die("Reading seed failed:", err)
}
}
data += fmt.Sprintf("mnemonic=%s", seed)
err := walletCmd.cli.Post("/wallet/seed", data)
if err != nil {
clipkg.DieWithError("Could not add seed:", err)
}
fmt.Println("Added Key")
}
// lockCmd locks the wallet
func (walletCmd *walletCmd) lockCmd() {
err := walletCmd.cli.Post("/wallet/lock", "")
if err != nil {
clipkg.DieWithError("Could not lock wallet:", err)
}
}
// seedsCmd returns the current seed {
func (walletCmd *walletCmd) seedsCmd() {
var seedInfo api.WalletSeedsGET
err := walletCmd.cli.GetWithResponse("/wallet/seeds", &seedInfo)
if err != nil {
clipkg.DieWithError("Error retrieving the current seed:", err)
}
fmt.Printf("Primary Seed: %s\n"+
"Addresses Remaining %d\n"+
"All Seeds:\n", seedInfo.PrimarySeed, seedInfo.AddressesRemaining)
for _, seed := range seedInfo.AllSeeds {
fmt.Println(seed)
}
}
// sendCoinsCmd sends siacoins to one or multiple destination addresses.
func (walletCmd *walletCmd) sendCoinsCmd(cmd *cobra.Command, args []string) {
currencyConvertor := walletCmd.cli.CreateCurrencyConvertor()
pairs, err := parsePairedOutputs(args, currencyConvertor.ParseCoinString)
if err != nil {
cmd.UsageFunc()(cmd)
clipkg.Die(err)
}
body := api.WalletCoinsPOST{
CoinOutputs: make([]types.CoinOutput, len(pairs)),
Data: []byte(walletCmd.sendCoinsCfg.Data),
}
for i, pair := range pairs {
body.CoinOutputs[i] = types.CoinOutput{
Value: pair.Value,
Condition: pair.Condition,
}
}
if walletCmd.sendCoinsCfg.RefundAddress != "" {
// use the specified address as the refund address if a refund has to happen
var uh types.UnlockHash
err = uh.LoadString(walletCmd.sendCoinsCfg.RefundAddress)
if err != nil {
clipkg.DieWithError("invalid refund address specified", err)
}
body.RefundAddress = &uh
} else if walletCmd.sendCoinsCfg.RefundAddressNew {
// ensure the daemon generates a new refund address if a refund needs to happen
body.GenerateRefundAddress = true
}
bytes, err := json.Marshal(&body)
if err != nil {
clipkg.Die("Failed to JSON Marshal the input body:", err)
}
var resp api.WalletCoinsPOSTResp
err = walletCmd.cli.PostWithResponse("/wallet/coins", string(bytes), &resp)
if err != nil {
clipkg.DieWithError("Could not send coins:", err)
}
fmt.Println("Succesfully sent coins as transaction " + resp.TransactionID.String())
for _, co := range body.CoinOutputs {
fmt.Printf("Sent %s to %s (using ConditionType %d)\n",
currencyConvertor.ToCoinStringWithUnit(co.Value), co.Condition.UnlockHash(),
co.Condition.ConditionType())
}
}
// sendBlockStakesCmd sends block stakes to one or multiple destination addresses.
func (walletCmd *walletCmd) sendBlockStakesCmd(cmd *cobra.Command, args []string) {
pairs, err := parsePairedOutputs(args, stringToBlockStakes)
if err != nil {
cmd.UsageFunc()(cmd)
clipkg.Die(err)
}
body := api.WalletBlockStakesPOST{
BlockStakeOutputs: make([]types.BlockStakeOutput, len(pairs)),
Data: []byte(walletCmd.sendBlockStakesCfg.Data),
}
for i, pair := range pairs {
body.BlockStakeOutputs[i] = types.BlockStakeOutput{
Value: pair.Value,
Condition: pair.Condition,
}
}
if walletCmd.sendBlockStakesCfg.RefundAddress != "" {
// use the specified address as the refund address if a refund has to happen
var uh types.UnlockHash
err = uh.LoadString(walletCmd.sendBlockStakesCfg.RefundAddress)
if err != nil {
clipkg.DieWithError("invalid refund address specified", err)
}
body.RefundAddress = &uh
} else if walletCmd.sendBlockStakesCfg.RefundAddressNew {
// ensure the daemon generates a new refund address if a refund needs to happen
body.GenerateRefundAddress = true
}
bytes, err := json.Marshal(&body)
if err != nil {
clipkg.Die("Failed to JSON Marshal the input body:", err)
}
var resp api.WalletBlockStakesPOSTResp
err = walletCmd.cli.PostWithResponse("/wallet/blockstakes", string(bytes), &resp)
if err != nil {
clipkg.DieWithError("Could not send block stakes:", err)
}
fmt.Println("Succesfully sent blockstakes as transaction " + resp.TransactionID.String())
for _, bo := range body.BlockStakeOutputs {
fmt.Printf("Sent %s BS to %s (using ConditionType %d)\n",
bo.Value, bo.Condition.UnlockHash(), bo.Condition.ConditionType())
}
}
type outputPair struct {
Condition types.UnlockConditionProxy
Value types.Currency
}
// parseCurrencyString takes the string representation of a currency value
type parseCurrencyString func(string) (types.Currency, error)
func stringToBlockStakes(input string) (types.Currency, error) {
bsv, err := strconv.ParseUint(input, 10, 64)
return types.NewCurrency64(bsv), err
}
func parsePairedOutputs(args []string, parseCurrency parseCurrencyString) (pairs []outputPair, err error) {
argn := len(args)
if argn < 2 {
err = errors.New("not enough arguments, at least 2 required")
return
}
if argn%2 != 0 {
err = errors.New("arguments have to be given in pairs of '<dest>|<rawCondition>'+'<value>'")
return
}
for i := 0; i < argn; i += 2 {
// parse value first, as it's the one without any possibility of ambiguity
var pair outputPair
pair.Value, err = parseCurrency(args[i+1])
if err != nil {
err = fmt.Errorf("failed to parse amount/value for output #%d: %v", i/2, err)
return
}
// try to parse it as an unlock hash
var uh types.UnlockHash
err = uh.LoadString(args[i])
if err == nil {
// parsing as an unlock hash was succesfull, store the pair and continue to the next pair
pair.Condition = types.NewCondition(types.NewUnlockHashCondition(uh))
pairs = append(pairs, pair)
continue
}
// try to parse it as a JSON-encoded unlock condition
err = pair.Condition.UnmarshalJSON([]byte(args[i]))
if err != nil {
err = fmt.Errorf("condition has to be UnlockHash or JSON-encoded UnlockCondition, output #%d's was neither", i/2)
return
}
pairs = append(pairs, pair)
}
return
}
// blockStakesStatsCmd gives all statistical info of blockstake
func (walletCmd *walletCmd) blockStakesStatsCmd() {
currencyConvertor := walletCmd.cli.CreateCurrencyConvertor()
bsstat := new(api.WalletBlockStakeStatsGET)
err := walletCmd.cli.GetWithResponse("/wallet/blockstakestats", bsstat)
if err != nil {
clipkg.DieWithError("Could not gen blockstake info:", err)
}
fmt.Printf("BlockStake stats:\n")
fmt.Printf("Total active Blockstake is %v\n", bsstat.TotalActiveBlockStake)
fmt.Printf("This account has %v Blockstake\n", bsstat.TotalBlockStake)
fmt.Printf("%v of last %v Blocks created (theoretically %v)\n", bsstat.TotalBCLast1000, bsstat.BlockCount, bsstat.TotalBCLast1000t)
fmt.Printf("containing %v fee \n",
currencyConvertor.ToCoinStringWithUnit(bsstat.TotalFeeLast1000))
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', tabwriter.AlignRight|tabwriter.Debug)
fmt.Fprintln(w, "state\t#BlockStake\tUTXO hash\t")
for i, BSstate := range bsstat.BlockStakeState {
state := "active"
if BSstate == 0 {
state = "not active"
}
fmt.Fprintf(w, "%v\t%v\t%v\t\n", state, bsstat.BlockStakeNumOf[i], bsstat.BlockStakeUTXOAddress[i])
}
w.Flush()
}
// balanceCmd retrieves and displays information about the wallet.
func (walletCmd *walletCmd) balanceCmd() {
currencyConvertor := walletCmd.cli.CreateCurrencyConvertor()
status := new(api.WalletGET)
err := walletCmd.cli.GetWithResponse("/wallet", status)
if err != nil {
clipkg.DieWithError("Could not get wallet status:", err)
}
encStatus := "Unencrypted"
if status.Encrypted {
encStatus = "Encrypted"
}
if !status.Unlocked {
clipkg.DieWithExitCode(clipkg.ExitCodeUsage, fmt.Sprintf(`Wallet status:
%v, Locked
Unlock the wallet to view balance
`, encStatus))
}
unconfirmedBalance := status.ConfirmedCoinBalance.Add(status.UnconfirmedIncomingCoins).Sub(status.UnconfirmedOutgoingCoins)
var delta string
if unconfirmedBalance.Cmp(status.ConfirmedCoinBalance) >= 0 {
delta = "+ " + currencyConvertor.ToCoinStringWithUnit(unconfirmedBalance.Sub(status.ConfirmedCoinBalance))
} else {
delta = "- " + currencyConvertor.ToCoinStringWithUnit(status.ConfirmedCoinBalance.Sub(unconfirmedBalance))
}
fmt.Printf(`Wallet status:
%s, Unlocked
Confirmed Balance: %v
Locked Balance: %v
Unconfirmed Delta: %v
BlockStakes: %v BS
`, encStatus, currencyConvertor.ToCoinStringWithUnit(status.ConfirmedCoinBalance),
currencyConvertor.ToCoinStringWithUnit(status.ConfirmedLockedCoinBalance),
delta, status.BlockStakeBalance)
if !status.LockedBlockStakeBalance.IsZero() {
fmt.Printf("Locked BlockStakes: %v BS\n", status.LockedBlockStakeBalance)
}
if len(status.MultiSigWallets) > 0 {
fmt.Println()
fmt.Println("Multisig Wallets:")
}
for _, wallet := range status.MultiSigWallets {
// Print separator
fmt.Println()
fmt.Println("==============================================================================")
fmt.Println()
unconfirmedBalance := wallet.ConfirmedCoinBalance.Add(wallet.UnconfirmedIncomingCoins).Sub(wallet.UnconfirmedOutgoingCoins)
var coindelta string
if unconfirmedBalance.Cmp(wallet.ConfirmedCoinBalance) >= 0 {
coindelta = "+ " + currencyConvertor.ToCoinStringWithUnit(unconfirmedBalance.Sub(wallet.ConfirmedCoinBalance))
} else {
coindelta = "- " + currencyConvertor.ToCoinStringWithUnit(wallet.ConfirmedCoinBalance.Sub(unconfirmedBalance))
}
unconfirmedBlockStakeBalance := wallet.ConfirmedBlockStakeBalance.Add(wallet.UnconfirmedIncomingBlockStakes).Sub(wallet.UnconfirmedOutgoingBlockStakes)
var bsdelta string
if unconfirmedBlockStakeBalance.Cmp(wallet.ConfirmedBlockStakeBalance) >= 0 {
bsdelta = "+ " + unconfirmedBalance.Sub(wallet.ConfirmedBlockStakeBalance).String()
} else {
bsdelta = "- " + wallet.ConfirmedBlockStakeBalance.Sub(unconfirmedBlockStakeBalance).String()
}
fmt.Printf("%v\n", wallet.Address)
fmt.Printf("Confirmed Balance: %v\n", currencyConvertor.ToCoinStringWithUnit(wallet.ConfirmedCoinBalance))
if !wallet.ConfirmedLockedCoinBalance.IsZero() {
fmt.Printf("Locked Balance: %v\n", currencyConvertor.ToCoinStringWithUnit(wallet.ConfirmedLockedCoinBalance))
}
if wallet.UnconfirmedIncomingCoins.Cmp(wallet.UnconfirmedOutgoingCoins) != 0 {
fmt.Printf("Unconfirmed Delta: %v\n", coindelta)
}
if !wallet.ConfirmedBlockStakeBalance.IsZero() {
fmt.Printf("BlockStakes: %v BS\n", wallet.ConfirmedBlockStakeBalance)
}
if !wallet.ConfirmedLockedBlockStakeBalance.IsZero() {
fmt.Printf("Locked BlockStakes: %v BS\n", wallet.ConfirmedLockedBlockStakeBalance)
}
if wallet.UnconfirmedIncomingBlockStakes.Cmp(wallet.UnconfirmedOutgoingBlockStakes) != 0 {
fmt.Printf("Unconfirmed blockstake delta: %v BS\n", bsdelta)
}
fmt.Println()
fmt.Println("Possible signatories:")
for _, uh := range wallet.Owners {
fmt.Println(uh)
}
fmt.Println()
fmt.Println("Minimum signatures required:", wallet.MinSigs)
}
}
// listTransactionsCmd lists all of the transactions related to the wallet,
// providing a net flow of siacoins and siafunds for each.
func (walletCmd *walletCmd) listTransactionsCmd() {
wtg := new(api.WalletTransactionsGET)
err := walletCmd.cli.GetWithResponse("/wallet/transactions?startheight=0&endheight=10000000", wtg)
if err != nil {
clipkg.DieWithError("Could not fetch transaction history:", err)
}
multiSigWalletTxns := make(map[types.UnlockHash][]modules.ProcessedTransaction)
txns := append(wtg.ConfirmedTransactions, wtg.UnconfirmedTransactions...)
if len(txns) == 0 {
fmt.Println("This wallet has no transaction related to it.")
return
}
fmt.Println(" [height] [transaction id] [net coins] [net blockstakes]")
for _, txn := range txns {
var relatedMultiSigUnlockHashes []types.UnlockHash
// Determine the number of outgoing siacoins and siafunds.
var outgoingSiacoins types.Currency
var outgoingBlockStakes types.Currency
var rootWalletOwned bool
for _, input := range txn.Inputs {
if input.FundType == types.SpecifierCoinInput && input.WalletAddress {
rootWalletOwned = true
outgoingSiacoins = outgoingSiacoins.Add(input.Value)
}
if input.FundType == types.SpecifierBlockStakeInput && input.WalletAddress {
rootWalletOwned = true
outgoingBlockStakes = outgoingBlockStakes.Add(input.Value)
}
if input.RelatedAddress.Type == types.UnlockTypeMultiSig {
relatedMultiSigUnlockHashes = append(relatedMultiSigUnlockHashes, input.RelatedAddress)
}
}
// Determine the number of incoming siacoins and siafunds.
var incomingSiacoins types.Currency
var incomingBlockStakes types.Currency
for _, output := range txn.Outputs {
if output.FundType == types.SpecifierMinerPayout {
rootWalletOwned = true
incomingSiacoins = incomingSiacoins.Add(output.Value)
}
if output.FundType == types.SpecifierCoinOutput && output.WalletAddress {
rootWalletOwned = true
incomingSiacoins = incomingSiacoins.Add(output.Value)
}
if output.FundType == types.SpecifierBlockStakeOutput && output.WalletAddress {
rootWalletOwned = true
incomingBlockStakes = incomingBlockStakes.Add(output.Value)
}
if output.RelatedAddress.Type == types.UnlockTypeMultiSig {
relatedMultiSigUnlockHashes = append(relatedMultiSigUnlockHashes, output.RelatedAddress)
}
}
// Remember the txn to print it in case there are related special conditions
for _, uh := range relatedMultiSigUnlockHashes {
multiSigWalletTxns[uh] = append(multiSigWalletTxns[uh], txn)
}
// Only print here if there is a direct relation to the root wallet
if !rootWalletOwned {
continue
}
// Convert the siacoins to a float.
incomingSiacoinsFloat, _ := new(big.Rat).SetFrac(incomingSiacoins.Big(), walletCmd.cli.Config.CurrencyUnits.OneCoin.Big()).Float64()
outgoingSiacoinsFloat, _ := new(big.Rat).SetFrac(outgoingSiacoins.Big(), walletCmd.cli.Config.CurrencyUnits.OneCoin.Big()).Float64()
// Print the results.
if txn.ConfirmationHeight < 1e9 {
fmt.Printf("%12v", txn.ConfirmationHeight-1)
} else {
fmt.Printf(" unconfirmed")
}
fmt.Printf("%67v%15.2f %s", txn.TransactionID, incomingSiacoinsFloat-outgoingSiacoinsFloat, walletCmd.cli.Config.CurrencyCoinUnit)
incomingBlockStakeBigInt := incomingBlockStakes.Big()
outgoingBlockStakeBigInt := outgoingBlockStakes.Big()
fmt.Printf("%14s BS\n", new(big.Int).Sub(incomingBlockStakeBigInt, outgoingBlockStakeBigInt).String())
}
if len(multiSigWalletTxns) > 0 {
for uh, txns := range multiSigWalletTxns {
for _, txn := range txns {
fmt.Println()
fmt.Println("=====================================================================================================================")
fmt.Println()
fmt.Println("Wallet Address:", uh)
fmt.Println()
fmt.Println(" [height] [transaction/block id] [net coins] [net blockstakes]")
// Determine the number of outgoing siacoins and siafunds.
var outgoingSiacoins types.Currency
var outgoingBlockStakes types.Currency
for _, input := range txn.Inputs {
if input.FundType == types.SpecifierCoinInput && input.RelatedAddress.Cmp(uh) == 0 {
outgoingSiacoins = outgoingSiacoins.Add(input.Value)
}
if input.FundType == types.SpecifierBlockStakeInput && input.RelatedAddress.Cmp(uh) == 0 {
outgoingBlockStakes = outgoingBlockStakes.Add(input.Value)
}
}
// Determine the number of incoming siacoins and siafunds.
var incomingSiacoins types.Currency
var incomingBlockStakes types.Currency
for _, output := range txn.Outputs {
if output.FundType == types.SpecifierMinerPayout {
incomingSiacoins = incomingSiacoins.Add(output.Value)
}
if output.FundType == types.SpecifierCoinOutput && output.RelatedAddress.Cmp(uh) == 0 {
incomingSiacoins = incomingSiacoins.Add(output.Value)
}
if output.FundType == types.SpecifierBlockStakeOutput && output.RelatedAddress.Cmp(uh) == 0 {
incomingBlockStakes = incomingBlockStakes.Add(output.Value)
}
}
// Convert the siacoins to a float.
incomingSiacoinsFloat, _ := new(big.Rat).SetFrac(incomingSiacoins.Big(),
walletCmd.cli.Config.CurrencyUnits.OneCoin.Big()).Float64()
outgoingSiacoinsFloat, _ := new(big.Rat).SetFrac(outgoingSiacoins.Big(),
walletCmd.cli.Config.CurrencyUnits.OneCoin.Big()).Float64()
// Print the results.
if txn.ConfirmationHeight < 1e9 {
fmt.Printf("%12v", txn.ConfirmationHeight-1)
} else {
fmt.Printf(" unconfirmed")
}
fmt.Printf("%67v%15.2f %s", txn.TransactionID, incomingSiacoinsFloat-outgoingSiacoinsFloat,
walletCmd.cli.Config.CurrencyCoinUnit)
incomingBlockStakeBigInt := incomingBlockStakes.Big()
outgoingBlockStakeBigInt := outgoingBlockStakes.Big()
fmt.Printf("%14s BS\n", new(big.Int).Sub(incomingBlockStakeBigInt, outgoingBlockStakeBigInt).String())
}
}
}
}
// unlockCmd unlocks a saved wallet
func (walletCmd *walletCmd) unlockCmd() {
password, err := speakeasy.Ask("Wallet password: ")
if err != nil {
clipkg.Die("Reading password failed:", err)
}
fmt.Println("Unlocking the wallet. This may take several minutes...")
qs := fmt.Sprintf("passphrase=%s", password)
err = walletCmd.cli.Post("/wallet/unlock", qs)
if err != nil {
clipkg.DieWithError("Could not unlock wallet:", err)
}
fmt.Println("Wallet unlocked")
}
// sendTxCmd sends commits a transaction in json format
// to the transaction pool
func (walletCmd *walletCmd) sendTxCmd(txnjson string) {
var resp api.TransactionPoolPOST
err := walletCmd.cli.PostWithResponse("/transactionpool/transactions", txnjson, &resp)
if err != nil {
clipkg.DieWithError("Could not publish transaction:", err)
}
fmt.Println("Transaction published, transaction id:", resp.TransactionID)
}
func (walletCmd *walletCmd) listUnlockedCmd(_ *cobra.Command, args []string) {
currencyConvertor := walletCmd.cli.CreateCurrencyConvertor()
var (
err error