forked from algorand/go-algorand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaccount.go
1501 lines (1297 loc) · 53.7 KB
/
account.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
// Copyright (C) 2019-2021 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"bufio"
"encoding/base64"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"github.com/spf13/cobra"
"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/crypto/passphrase"
generatedV2 "github.com/algorand/go-algorand/daemon/algod/api/server/v2/generated"
algodAcct "github.com/algorand/go-algorand/data/account"
"github.com/algorand/go-algorand/data/basics"
"github.com/algorand/go-algorand/data/transactions"
"github.com/algorand/go-algorand/libgoal"
"github.com/algorand/go-algorand/protocol"
"github.com/algorand/go-algorand/util"
"github.com/algorand/go-algorand/util/db"
)
var (
accountAddress string
walletName string
defaultAccountName string
defaultAccount bool
unencryptedWallet bool
online bool
accountName string
transactionFee uint64
statusChangeLease string
statusChangeTxFile string
roundFirstValid uint64
roundLastValid uint64
keyDilution uint64
threshold uint8
partKeyOutDir string
partKeyFile string
partKeyDeleteInput bool
partkeyCompat bool
importDefault bool
mnemonic string
dumpOutFile string
listAccountInfo bool
)
func init() {
accountCmd.AddCommand(newCmd)
accountCmd.AddCommand(deleteCmd)
accountCmd.AddCommand(listCmd)
accountCmd.AddCommand(renameCmd)
accountCmd.AddCommand(infoCmd)
accountCmd.AddCommand(balanceCmd)
accountCmd.AddCommand(rewardsCmd)
accountCmd.AddCommand(changeOnlineCmd)
accountCmd.AddCommand(addParticipationKeyCmd)
accountCmd.AddCommand(installParticipationKeyCmd)
accountCmd.AddCommand(listParticipationKeysCmd)
accountCmd.AddCommand(importCmd)
accountCmd.AddCommand(exportCmd)
accountCmd.AddCommand(importRootKeysCmd)
accountCmd.AddCommand(accountMultisigCmd)
accountCmd.AddCommand(markNonparticipatingCmd)
accountMultisigCmd.AddCommand(newMultisigCmd)
accountMultisigCmd.AddCommand(deleteMultisigCmd)
accountMultisigCmd.AddCommand(infoMultisigCmd)
accountCmd.AddCommand(renewParticipationKeyCmd)
accountCmd.AddCommand(renewAllParticipationKeyCmd)
accountCmd.AddCommand(partkeyInfoCmd)
accountCmd.AddCommand(dumpCmd)
// Wallet to be used for the account operation
accountCmd.PersistentFlags().StringVarP(&walletName, "wallet", "w", "", "Set the wallet to be used for the selected operation")
// Account Flag
accountCmd.Flags().StringVarP(&defaultAccountName, "default", "f", "", "Set the account with this name to be the default account")
// New Account flag
newCmd.Flags().BoolVarP(&defaultAccount, "default", "f", false, "Set this account as the default one")
// Delete account flag
deleteCmd.Flags().StringVarP(&accountAddress, "address", "a", "", "Address of account to delete")
deleteCmd.MarkFlagRequired("address")
// New Multisig account flag
newMultisigCmd.Flags().Uint8VarP(&threshold, "threshold", "T", 1, "Number of signatures required to spend from this address")
newMultisigCmd.MarkFlagRequired("threshold")
// Delete multisig account flag
deleteMultisigCmd.Flags().StringVarP(&accountAddress, "address", "a", "", "Address of multisig account to delete")
deleteMultisigCmd.MarkFlagRequired("address")
// Lookup info for multisig account flag
infoMultisigCmd.Flags().StringVarP(&accountAddress, "address", "a", "", "Address of multisig account to look up")
infoMultisigCmd.MarkFlagRequired("address")
// Account list flags
listCmd.Flags().BoolVar(&listAccountInfo, "info", false, "Include additional information about each account's assets and applications")
// Info flags
infoCmd.Flags().StringVarP(&accountAddress, "address", "a", "", "Account address to look up (required)")
infoCmd.MarkFlagRequired("address")
// Balance flags
balanceCmd.Flags().StringVarP(&accountAddress, "address", "a", "", "Account address to retrieve balance (required)")
balanceCmd.MarkFlagRequired("address")
// Rewards flags
rewardsCmd.Flags().StringVarP(&accountAddress, "address", "a", "", "Account address to retrieve rewards (required)")
rewardsCmd.MarkFlagRequired("address")
// changeOnlineStatus flags
changeOnlineCmd.Flags().StringVarP(&accountAddress, "address", "a", "", "Account address to change (required if no -partkeyfile)")
changeOnlineCmd.Flags().StringVarP(&partKeyFile, "partkeyfile", "", "", "Participation key file (required if no -account)")
changeOnlineCmd.Flags().BoolVarP(&online, "online", "o", true, "Set this account to online or offline")
changeOnlineCmd.Flags().Uint64VarP(&transactionFee, "fee", "f", 0, "The Fee to set on the status change transaction (defaults to suggested fee)")
changeOnlineCmd.Flags().Uint64VarP(&firstValid, "firstRound", "", 0, "")
changeOnlineCmd.Flags().Uint64VarP(&firstValid, "firstvalid", "", 0, "FirstValid for the status change transaction (0 for current)")
changeOnlineCmd.Flags().Uint64VarP(&numValidRounds, "validRounds", "", 0, "")
changeOnlineCmd.Flags().Uint64VarP(&numValidRounds, "validrounds", "v", 0, "The validity period for the status change transaction")
changeOnlineCmd.Flags().Uint64Var(&lastValid, "lastvalid", 0, "The last round where the transaction may be committed to the ledger")
changeOnlineCmd.Flags().StringVarP(&statusChangeLease, "lease", "x", "", "Lease value (base64, optional): no transaction may also acquire this lease until lastvalid")
changeOnlineCmd.Flags().StringVarP(&statusChangeTxFile, "txfile", "t", "", "Write status change transaction to this file")
changeOnlineCmd.Flags().BoolVarP(&noWaitAfterSend, "no-wait", "N", false, "Don't wait for transaction to commit")
changeOnlineCmd.Flags().MarkDeprecated("firstRound", "use --firstvalid instead")
changeOnlineCmd.Flags().MarkDeprecated("validRounds", "use --validrounds instead")
// addParticipationKey flags
addParticipationKeyCmd.Flags().StringVarP(&accountAddress, "address", "a", "", "Account to associate with the generated partkey")
addParticipationKeyCmd.MarkFlagRequired("address")
addParticipationKeyCmd.Flags().Uint64VarP(&roundFirstValid, "roundFirstValid", "", 0, "The first round for which the generated partkey will be valid")
addParticipationKeyCmd.MarkFlagRequired("roundFirstValid")
addParticipationKeyCmd.Flags().Uint64VarP(&roundLastValid, "roundLastValid", "", 0, "The last round for which the generated partkey will be valid")
addParticipationKeyCmd.MarkFlagRequired("roundLastValid")
addParticipationKeyCmd.Flags().StringVarP(&partKeyOutDir, "outdir", "o", "", "Save participation key file to specified output directory to (for offline creation)")
addParticipationKeyCmd.Flags().Uint64VarP(&keyDilution, "keyDilution", "", 0, "Key dilution for two-level participation keys")
// installParticipationKey flags
installParticipationKeyCmd.Flags().StringVar(&partKeyFile, "partkey", "", "Participation key file to install")
installParticipationKeyCmd.MarkFlagRequired("partkey")
installParticipationKeyCmd.Flags().BoolVar(&partKeyDeleteInput, "delete-input", false, "Acknowledge that installpartkey will delete the input key file")
// listpartkey flags
listParticipationKeysCmd.Flags().BoolVarP(&partkeyCompat, "compatibility", "c", false, "Print output in compatibility mode. This option will be removed in a future release, please use REST API for tooling.")
// partkeyinfo flags
partkeyInfoCmd.Flags().BoolVarP(&partkeyCompat, "compatibility", "c", false, "Print output in compatibility mode. This option will be removed in a future release, please use REST API for tooling.")
// import flags
importCmd.Flags().BoolVarP(&importDefault, "default", "f", false, "Set this account as the default one")
importCmd.Flags().StringVarP(&mnemonic, "mnemonic", "m", "", "Mnemonic to import (will prompt otherwise)")
// export flags
exportCmd.Flags().StringVarP(&accountAddress, "address", "a", "", "Address of account to export")
exportCmd.MarkFlagRequired("address")
// importRootKeys flags
importRootKeysCmd.Flags().BoolVarP(&unencryptedWallet, "unencrypted-wallet", "u", false, "Import into the default unencrypted wallet, potentially creating it")
// renewParticipationKeyCmd
renewParticipationKeyCmd.Flags().StringVarP(&accountAddress, "address", "a", "", "Account address to update (required)")
renewParticipationKeyCmd.MarkFlagRequired("address")
renewParticipationKeyCmd.Flags().Uint64VarP(&transactionFee, "fee", "f", 0, "The Fee to set on the status change transaction (defaults to suggested fee)")
renewParticipationKeyCmd.Flags().Uint64VarP(&roundLastValid, "roundLastValid", "", 0, "The last round for which the generated partkey will be valid")
renewParticipationKeyCmd.MarkFlagRequired("roundLastValid")
renewParticipationKeyCmd.Flags().Uint64VarP(&keyDilution, "keyDilution", "", 0, "Key dilution for two-level participation keys")
renewParticipationKeyCmd.Flags().BoolVarP(&noWaitAfterSend, "no-wait", "N", false, "Don't wait for transaction to commit")
// renewAllParticipationKeyCmd
renewAllParticipationKeyCmd.Flags().Uint64VarP(&transactionFee, "fee", "f", 0, "The Fee to set on the status change transactions (defaults to suggested fee)")
renewAllParticipationKeyCmd.Flags().Uint64VarP(&roundLastValid, "roundLastValid", "", 0, "The last round for which the generated partkeys will be valid")
renewAllParticipationKeyCmd.MarkFlagRequired("roundLastValid")
renewAllParticipationKeyCmd.Flags().Uint64VarP(&keyDilution, "keyDilution", "", 0, "Key dilution for two-level participation keys")
renewAllParticipationKeyCmd.Flags().BoolVarP(&noWaitAfterSend, "no-wait", "N", false, "Don't wait for transaction to commit")
// markNonparticipatingCmd flags
markNonparticipatingCmd.Flags().StringVarP(&accountAddress, "address", "a", "", "Account address to change")
markNonparticipatingCmd.MarkFlagRequired("address")
markNonparticipatingCmd.Flags().Uint64VarP(&transactionFee, "fee", "f", 0, "The Fee to set on the status change transaction (defaults to suggested fee)")
markNonparticipatingCmd.Flags().Uint64VarP(&firstValid, "firstRound", "", 0, "")
markNonparticipatingCmd.Flags().Uint64VarP(&firstValid, "firstvalid", "", 0, "FirstValid for the status change transaction (0 for current)")
markNonparticipatingCmd.Flags().Uint64VarP(&numValidRounds, "validRounds", "", 0, "")
markNonparticipatingCmd.Flags().Uint64VarP(&numValidRounds, "validrounds", "v", 0, "The validity period for the status change transaction")
markNonparticipatingCmd.Flags().Uint64Var(&lastValid, "lastvalid", 0, "The last round where the transaction may be committed to the ledger")
markNonparticipatingCmd.Flags().StringVarP(&statusChangeTxFile, "txfile", "t", "", "Write status change transaction to this file, rather than posting to network")
markNonparticipatingCmd.Flags().BoolVarP(&noWaitAfterSend, "no-wait", "N", false, "Don't wait for transaction to commit")
markNonparticipatingCmd.Flags().MarkDeprecated("firstRound", "use --firstvalid instead")
markNonparticipatingCmd.Flags().MarkDeprecated("validRounds", "use --validrounds instead")
dumpCmd.Flags().StringVarP(&dumpOutFile, "outfile", "o", "", "Save balance record to specified output file")
dumpCmd.Flags().StringVarP(&accountAddress, "address", "a", "", "Account address to retrieve balance (required)")
balanceCmd.MarkFlagRequired("address")
}
func scLeaseBytes(cmd *cobra.Command) (leaseBytes [32]byte) {
if cmd.Flags().Changed("lease") {
leaseBytesRaw, err := base64.StdEncoding.DecodeString(statusChangeLease)
if err != nil {
reportErrorf(malformedLease, lease, err)
}
if len(leaseBytesRaw) != 32 {
reportErrorf(malformedLease, lease, fmt.Errorf("lease length %d != 32", len(leaseBytesRaw)))
}
copy(leaseBytes[:], leaseBytesRaw)
}
return
}
var accountCmd = &cobra.Command{
Use: "account",
Short: "Control and manage Algorand accounts",
Long: `Collection of commands to support the creation and management of accounts / wallets tied to a specific Algorand node instance.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, args []string) {
accountList := makeAccountsList(ensureSingleDataDir())
// Update the default account
if defaultAccountName != "" {
// If the name doesn't exist, return an error
if !accountList.isTaken(defaultAccountName) {
reportErrorf(errorNameDoesntExist, defaultAccountName)
}
// Set the account with this name to be default
accountList.setDefault(defaultAccountName)
reportInfof(infoSetAccountToDefault, defaultAccountName)
os.Exit(0)
}
// Return the help text
cmd.HelpFunc()(cmd, args)
},
}
var accountMultisigCmd = &cobra.Command{
Use: "multisig",
Short: "Control and manage multisig accounts",
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, args []string) {
// Return the help text
cmd.HelpFunc()(cmd, args)
},
}
var renameCmd = &cobra.Command{
Use: "rename [old name] [new name]",
Short: "Change the human-friendly name of an account",
Long: `Change the human-friendly name of an account. This is a local-only name, it is not stored on the network.`,
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
accountList := makeAccountsList(ensureSingleDataDir())
oldName := args[0]
newName := args[1]
// If not valid name, return an error
if ok, err := isValidName(newName); !ok {
reportErrorln(err)
}
// If the old name isn't in use, return an error
if !accountList.isTaken(oldName) {
reportErrorf(errorNameDoesntExist, oldName)
}
// If the new name isn't available, return an error
if accountList.isTaken(newName) {
reportErrorf(errorNameAlreadyTaken, newName)
}
// Otherwise, rename
accountList.rename(oldName, newName)
reportInfof(infoRenamedAccount, oldName, newName)
},
}
var newCmd = &cobra.Command{
Use: "new",
Short: "Create a new account",
Long: `Coordinates the creation of a new account with KMD. The name specified here is stored in a local configuration file and is only used by goal when working against that specific node instance.`,
Args: cobra.RangeArgs(0, 1),
Run: func(cmd *cobra.Command, args []string) {
accountList := makeAccountsList(ensureSingleDataDir())
// Choose an account name
if len(args) == 0 {
accountName = accountList.getUnnamed()
} else {
accountName = args[0]
}
// If not valid name, return an error
if ok, err := isValidName(accountName); !ok {
reportErrorln(err)
}
// Ensure the user's name choice isn't taken
if accountList.isTaken(accountName) {
reportErrorf(errorNameAlreadyTaken, accountName)
}
dataDir := ensureSingleDataDir()
// Get a wallet handle
wh := ensureWalletHandle(dataDir, walletName)
// Generate a new address in the default wallet
client := ensureKmdClient(dataDir)
genAddr, err := client.GenerateAddress(wh)
if err != nil {
reportErrorf(errorRequestFail, err)
}
// Add account to list
accountList.addAccount(accountName, genAddr)
// Set account to default if required
if defaultAccount {
accountList.setDefault(accountName)
}
reportInfof(infoCreatedNewAccount, genAddr)
},
}
var deleteCmd = &cobra.Command{
Use: "delete",
Short: "Delete an account",
Long: `Delete the indicated account. The key management daemon will no longer know about this account, although the account will still exist on the network.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, args []string) {
dataDir := ensureSingleDataDir()
accountList := makeAccountsList(dataDir)
client := ensureKmdClient(dataDir)
wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)
err := client.DeleteAccount(wh, pw, accountAddress)
if err != nil {
reportErrorf(errorRequestFail, err)
}
accountList.removeAccount(accountAddress)
},
}
var newMultisigCmd = &cobra.Command{
Use: "new [address 1] [address 2]...",
Short: "Create a new multisig account",
Long: `Create a new multisig account from a list of existing non-multisig addresses`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
dataDir := ensureSingleDataDir()
accountList := makeAccountsList(dataDir)
// Get a wallet handle to the default wallet
client := ensureKmdClient(dataDir)
// Get a wallet handle
wh := ensureWalletHandle(dataDir, walletName)
// Detect duplicate PKs
duplicateDetector := make(map[string]int)
for _, addrStr := range args {
duplicateDetector[addrStr]++
}
duplicatesDetected := false
for _, counter := range duplicateDetector {
if counter > 1 {
duplicatesDetected = true
break
}
}
if duplicatesDetected {
reportWarnln(warnMultisigDuplicatesDetected)
}
// Generate a new address in the default wallet
addr, err := client.CreateMultisigAccount(wh, threshold, args)
if err != nil {
reportErrorf(errorRequestFail, err)
}
// Add account to list
accountList.addAccount(accountList.getUnnamed(), addr)
reportInfof(infoCreatedNewAccount, addr)
},
}
var deleteMultisigCmd = &cobra.Command{
Use: "delete",
Short: "Delete a multisig account",
Long: `Delete a multisig account. Like ordinary account delete, the local node will no longer know about the account, but it may still exist on the network.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, args []string) {
dataDir := ensureSingleDataDir()
accountList := makeAccountsList(dataDir)
client := ensureKmdClient(dataDir)
wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)
err := client.DeleteMultisigAccount(wh, pw, accountAddress)
if err != nil {
reportErrorf(errorRequestFail, err)
}
accountList.removeAccount(accountAddress)
},
}
var infoMultisigCmd = &cobra.Command{
Use: "info",
Short: "Print information about a multisig account",
Long: `Print information about a multisig account, such as its Algorand multisig version, or the number of keys needed to validate a transaction from the multisig account.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, args []string) {
dataDir := ensureSingleDataDir()
client := ensureKmdClient(dataDir)
wh := ensureWalletHandle(dataDir, walletName)
multisigInfo, err := client.LookupMultisigAccount(wh, accountAddress)
if err != nil {
reportErrorf(errorRequestFail, err)
}
fmt.Printf("Version: %d\n", multisigInfo.Version)
fmt.Printf("Threshold: %d\n", multisigInfo.Threshold)
fmt.Printf("Public keys:\n")
for _, pk := range multisigInfo.PKs {
fmt.Printf(" %s\n", pk)
}
},
}
var listCmd = &cobra.Command{
Use: "list",
Short: "Show the list of Algorand accounts on this machine",
Long: `Show the list of Algorand accounts on this machine. Indicates whether the account is [offline] or [online], and if the account is the default account for goal. Also displays account information with --info.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, args []string) {
dataDir := ensureSingleDataDir()
accountList := makeAccountsList(dataDir)
// Get a wallet handle to the specified wallet
wh := ensureWalletHandle(dataDir, walletName)
// List the addresses in the wallet
client := ensureKmdClient(dataDir)
addrs, err := client.ListAddressesWithInfo(wh)
if err != nil {
reportErrorf(errorRequestFail, err)
}
// Special response if there are no addresses
if len(addrs) == 0 {
reportInfoln(infoNoAccounts)
os.Exit(0)
}
accountInfoError := false
// For each address, request information about it from algod
for _, addr := range addrs {
response, _ := client.AccountInformationV2(addr.Addr)
// it's okay to proceed without algod info
// Display this information to the user
if addr.Multisig {
multisigInfo, err := client.LookupMultisigAccount(wh, addr.Addr)
if err != nil {
fmt.Println("multisig lookup err")
reportErrorf(errorRequestFail, err)
}
accountList.outputAccount(addr.Addr, response, &multisigInfo)
} else {
accountList.outputAccount(addr.Addr, response, nil)
}
if listAccountInfo {
hasError := printAccountInfo(client, addr.Addr, response)
accountInfoError = accountInfoError || hasError
}
}
if accountInfoError {
os.Exit(1)
}
},
}
var infoCmd = &cobra.Command{
Use: "info",
Short: "Retrieve information about the assets and applications belonging to the specified account",
Long: `Retrieve information about the assets and applications the specified account has created or opted into.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, args []string) {
dataDir := ensureSingleDataDir()
client := ensureAlgodClient(dataDir)
response, err := client.AccountInformationV2(accountAddress)
if err != nil {
reportErrorf(errorRequestFail, err)
}
hasError := printAccountInfo(client, accountAddress, response)
if hasError {
os.Exit(1)
}
},
}
func printAccountInfo(client libgoal.Client, address string, account generatedV2.Account) bool {
var createdAssets []generatedV2.Asset
if account.CreatedAssets != nil {
createdAssets = make([]generatedV2.Asset, len(*account.CreatedAssets))
for i, asset := range *account.CreatedAssets {
createdAssets[i] = asset
}
sort.Slice(createdAssets, func(i, j int) bool {
return createdAssets[i].Index < createdAssets[j].Index
})
}
var heldAssets []generatedV2.AssetHolding
if account.Assets != nil {
heldAssets = make([]generatedV2.AssetHolding, len(*account.Assets))
for i, assetHolding := range *account.Assets {
heldAssets[i] = assetHolding
}
sort.Slice(heldAssets, func(i, j int) bool {
return heldAssets[i].AssetId < heldAssets[j].AssetId
})
}
var createdApps []generatedV2.Application
if account.CreatedApps != nil {
createdApps = make([]generatedV2.Application, len(*account.CreatedApps))
for i, app := range *account.CreatedApps {
createdApps[i] = app
}
sort.Slice(createdApps, func(i, j int) bool {
return createdApps[i].Id < createdApps[j].Id
})
}
var optedInApps []generatedV2.ApplicationLocalState
if account.AppsLocalState != nil {
optedInApps = make([]generatedV2.ApplicationLocalState, len(*account.AppsLocalState))
for i, appLocalState := range *account.AppsLocalState {
optedInApps[i] = appLocalState
}
sort.Slice(optedInApps, func(i, j int) bool {
return optedInApps[i].Id < optedInApps[j].Id
})
}
report := &strings.Builder{}
errorReport := &strings.Builder{}
hasError := false
fmt.Fprintln(report, "Created Assets:")
if len(createdAssets) == 0 {
fmt.Fprintln(report, "\t<none>")
}
for _, createdAsset := range createdAssets {
name := "<unnamed>"
if createdAsset.Params.Name != nil {
_, name = unicodePrintable(*createdAsset.Params.Name)
}
units := "units"
if createdAsset.Params.UnitName != nil {
_, units = unicodePrintable(*createdAsset.Params.UnitName)
}
total := assetDecimalsFmt(createdAsset.Params.Total, uint32(createdAsset.Params.Decimals))
url := ""
if createdAsset.Params.Url != nil {
_, safeURL := unicodePrintable(*createdAsset.Params.Url)
url = fmt.Sprintf(", %s", safeURL)
}
fmt.Fprintf(report, "\tID %d, %s, supply %s %s%s\n", createdAsset.Index, name, total, units, url)
}
fmt.Fprintln(report, "Held Assets:")
if len(heldAssets) == 0 {
fmt.Fprintln(report, "\t<none>")
}
for _, assetHolding := range heldAssets {
assetParams, err := client.AssetInformationV2(assetHolding.AssetId)
if err != nil {
hasError = true
fmt.Fprintf(errorReport, "Error: Unable to retrieve asset information for asset %d referred to by account %s: %v\n", assetHolding.AssetId, address, err)
fmt.Fprintf(report, "\tID %d, error\n", assetHolding.AssetId)
}
amount := assetDecimalsFmt(assetHolding.Amount, uint32(assetParams.Params.Decimals))
assetName := "<unnamed>"
if assetParams.Params.Name != nil {
_, assetName = unicodePrintable(*assetParams.Params.Name)
}
unitName := "units"
if assetParams.Params.UnitName != nil {
_, unitName = unicodePrintable(*assetParams.Params.UnitName)
}
frozen := ""
if assetHolding.IsFrozen {
frozen = " (frozen)"
}
fmt.Fprintf(report, "\tID %d, %s, balance %s %s%s\n", assetHolding.AssetId, assetName, amount, unitName, frozen)
}
fmt.Fprintln(report, "Created Apps:")
if len(createdApps) == 0 {
fmt.Fprintln(report, "\t<none>")
}
for _, app := range createdApps {
allocatedInts := uint64(0)
allocatedBytes := uint64(0)
if app.Params.GlobalStateSchema != nil {
allocatedInts = app.Params.GlobalStateSchema.NumUint
allocatedBytes = app.Params.GlobalStateSchema.NumByteSlice
}
usedInts := uint64(0)
usedBytes := uint64(0)
if app.Params.GlobalState != nil {
for _, value := range *app.Params.GlobalState {
if basics.TealType(value.Value.Type) == basics.TealUintType {
usedInts++
} else {
usedBytes++
}
}
}
extraPages := ""
if app.Params.ExtraProgramPages != nil && *app.Params.ExtraProgramPages != 0 {
plural := ""
if *app.Params.ExtraProgramPages != 1 {
plural = "s"
}
extraPages = fmt.Sprintf(", %d extra page%s", *app.Params.ExtraProgramPages, plural)
}
fmt.Fprintf(report, "\tID %d%s, global state used %d/%d uints, %d/%d byte slices\n", app.Id, extraPages, usedInts, allocatedInts, usedBytes, allocatedBytes)
}
fmt.Fprintln(report, "Opted In Apps:")
if len(optedInApps) == 0 {
fmt.Fprintln(report, "\t<none>")
}
for _, localState := range optedInApps {
allocatedInts := localState.Schema.NumUint
allocatedBytes := localState.Schema.NumByteSlice
usedInts := uint64(0)
usedBytes := uint64(0)
if localState.KeyValue != nil {
for _, value := range *localState.KeyValue {
if basics.TealType(value.Value.Type) == basics.TealUintType {
usedInts++
} else {
usedBytes++
}
}
}
fmt.Fprintf(report, "\tID %d, local state used %d/%d uints, %d/%d byte slices\n", localState.Id, usedInts, allocatedInts, usedBytes, allocatedBytes)
}
if hasError {
fmt.Fprint(os.Stderr, errorReport.String())
}
fmt.Print(report.String())
return hasError
}
var balanceCmd = &cobra.Command{
Use: "balance",
Short: "Retrieve the balances for the specified account",
Long: `Retrieve the balance record for the specified account. Algo balance is displayed in microAlgos.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, args []string) {
dataDir := ensureSingleDataDir()
client := ensureAlgodClient(dataDir)
response, err := client.AccountInformation(accountAddress)
if err != nil {
reportErrorf(errorRequestFail, err)
}
fmt.Printf("%v microAlgos\n", response.Amount)
},
}
var dumpCmd = &cobra.Command{
Use: "dump",
Short: "Dump the balance record for the specified account",
Long: `Dump the balance record for the specified account to terminal as JSON or to a file as MessagePack.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, args []string) {
dataDir := ensureSingleDataDir()
client := ensureAlgodClient(dataDir)
rawAddress, err := basics.UnmarshalChecksumAddress(accountAddress)
if err != nil {
reportErrorf(errorParseAddr, err)
}
accountData, err := client.AccountData(accountAddress)
if err != nil {
reportErrorf(errorRequestFail, err)
}
br := basics.BalanceRecord{Addr: rawAddress, AccountData: accountData}
if len(dumpOutFile) > 0 {
data := protocol.Encode(&br)
writeFile(dumpOutFile, data, 0644)
} else {
data := protocol.EncodeJSONStrict(&br)
fmt.Println(string(data))
}
},
}
var rewardsCmd = &cobra.Command{
Use: "rewards",
Short: "Retrieve the rewards for the specified account",
Long: `Retrieve the rewards for the specified account, including pending rewards. Units displayed are microAlgos.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, args []string) {
dataDir := ensureSingleDataDir()
client := ensureAlgodClient(dataDir)
response, err := client.AccountInformation(accountAddress)
if err != nil {
reportErrorf(errorRequestFail, err)
}
fmt.Printf("%v microAlgos\n", response.Rewards)
},
}
var changeOnlineCmd = &cobra.Command{
Use: "changeonlinestatus",
Short: "Change online status for the specified account",
Long: `Change online status for the specified account. Set online should be 1 to set online, 0 to set offline. The broadcast transaction will be valid for a limited number of rounds. goal will provide the TXID of the transaction if successful. Going online requires that the given account has a valid participation key. If the participation key is specified using --partkeyfile, you must separately install the participation key from that file using "goal account installpartkey".`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, args []string) {
checkTxValidityPeriodCmdFlags(cmd)
if accountAddress == "" && partKeyFile == "" {
fmt.Printf("Must specify one of --address or --partkeyfile\n")
os.Exit(1)
}
if partKeyFile != "" && !online {
fmt.Printf("Going offline does not support --partkeyfile\n")
os.Exit(1)
}
dataDir := ensureSingleDataDir()
var client libgoal.Client
if statusChangeTxFile != "" {
// writing out a txn, don't need kmd
client = ensureAlgodClient(dataDir)
} else {
client = ensureFullClient(dataDir)
}
var part *algodAcct.Participation
if partKeyFile != "" {
partdb, err := db.MakeErasableAccessor(partKeyFile)
if err != nil {
fmt.Printf("Cannot open partkey %s: %v\n", partKeyFile, err)
os.Exit(1)
}
partkey, err := algodAcct.RestoreParticipation(partdb)
if err != nil {
fmt.Printf("Cannot load partkey %s: %v\n", partKeyFile, err)
os.Exit(1)
}
part = &partkey.Participation
if accountAddress == "" {
accountAddress = part.Parent.String()
}
}
firstTxRound, lastTxRound, err := client.ComputeValidityRounds(firstValid, lastValid, numValidRounds)
if err != nil {
reportErrorf(err.Error())
}
err = changeAccountOnlineStatus(
accountAddress, part, online, statusChangeTxFile, walletName,
firstTxRound, lastTxRound, transactionFee, scLeaseBytes(cmd), dataDir, client,
)
if err != nil {
reportErrorf(err.Error())
}
},
}
func changeAccountOnlineStatus(acct string, part *algodAcct.Participation, goOnline bool, txFile string, wallet string, firstTxRound, lastTxRound, fee uint64, leaseBytes [32]byte, dataDir string, client libgoal.Client) error {
// Generate an unsigned online/offline tx
var utx transactions.Transaction
var err error
if goOnline {
utx, err = client.MakeUnsignedGoOnlineTx(acct, part, firstTxRound, lastTxRound, fee, leaseBytes)
} else {
utx, err = client.MakeUnsignedGoOfflineTx(acct, firstTxRound, lastTxRound, fee, leaseBytes)
}
if err != nil {
return err
}
if txFile != "" {
return writeTxnToFile(client, false, dataDir, wallet, utx, txFile)
}
// Sign & broadcast the transaction
wh, pw := ensureWalletHandleMaybePassword(dataDir, wallet, true)
txid, err := client.SignAndBroadcastTransaction(wh, pw, utx)
if err != nil {
return fmt.Errorf(errorOnlineTX, err)
}
fmt.Printf("Transaction id for status change transaction: %s\n", txid)
if noWaitAfterSend {
fmt.Println("Note: status will not change until transaction is finalized")
return nil
}
_, err = waitForCommit(client, txid, lastTxRound)
return err
}
var addParticipationKeyCmd = &cobra.Command{
Use: "addpartkey",
Short: "Generate a participation key for the specified account",
Long: `Generate a participation key for the specified account. This participation key can then be used for going online and participating in consensus.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, args []string) {
dataDir := ensureSingleDataDir()
if partKeyOutDir != "" && !util.IsDir(partKeyOutDir) {
reportErrorf(errorDirectoryNotExist, partKeyOutDir)
}
// Generate a participation keys database and install it
client := ensureFullClient(dataDir)
_, _, err := client.GenParticipationKeysTo(accountAddress, roundFirstValid, roundLastValid, keyDilution, partKeyOutDir)
if err != nil {
reportErrorf(errorRequestFail, err)
}
fmt.Println("Participation key generation successful")
},
}
var installParticipationKeyCmd = &cobra.Command{
Use: "installpartkey",
Short: "Install a participation key",
Long: `Install a participation key from a partkey file. Intended for use with participation key files generated by "algokey part generate". Does not change the online status of an account or register the participation key; use "goal account changeonlinestatus" for doing so. Deletes input key file on successful install to ensure forward security.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, args []string) {
if !partKeyDeleteInput {
fmt.Println(
`The installpartkey command deletes the input participation file on
successful installation. Please acknowledge this by passing the
"--delete-input" flag to the installpartkey command. You can make
a copy of the input file if needed, but please keep in mind that
participation keys must be securely deleted for each round, to ensure
forward security. Storing old participation keys compromises overall
system security.
No --delete-input flag specified, exiting without installing key.`)
os.Exit(1)
}
dataDir := ensureSingleDataDir()
client := ensureAlgodClient(dataDir)
_, _, err := client.InstallParticipationKeys(partKeyFile)
if err != nil {
reportErrorf(errorRequestFail, err)
}
fmt.Println("Participation key installed successfully")
},
}
var renewParticipationKeyCmd = &cobra.Command{
Use: "renewpartkey",
Short: "Renew an account's participation key",
Long: `Generate a participation key for the specified account and issue the necessary transaction to register it.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, args []string) {
dataDir := ensureSingleDataDir()
client := ensureAlgodClient(dataDir)
currentRound, err := client.CurrentRound()
if err != nil {
reportErrorf(errorRequestFail, err)
}
params, err := client.SuggestedParams()
if err != nil {
reportErrorf(errorRequestFail, err)
}
proto := config.Consensus[protocol.ConsensusVersion(params.ConsensusVersion)]
if roundLastValid <= (currentRound + proto.MaxTxnLife) {
reportErrorf(errLastRoundInvalid, currentRound)
}
// Make sure we don't already have a partkey valid for (or after) specified roundLastValid
parts, err := client.ListParticipationKeyFiles()
if err != nil {
reportErrorf(errorRequestFail, err)
}
for _, part := range parts {
if part.Address().String() == accountAddress {
if part.LastValid >= basics.Round(roundLastValid) {
reportErrorf(errExistingPartKey, roundLastValid, part.LastValid)
}
}
}
err = generateAndRegisterPartKey(accountAddress, currentRound, roundLastValid, transactionFee, scLeaseBytes(cmd), keyDilution, walletName, dataDir, client)
if err != nil {
reportErrorf(err.Error())
}
},
}
func generateAndRegisterPartKey(address string, currentRound, lastValidRound uint64, fee uint64, leaseBytes [32]byte, dilution uint64, wallet string, dataDir string, client libgoal.Client) error {
// Generate a participation keys database and install it
part, keyPath, err := client.GenParticipationKeysTo(address, currentRound, lastValidRound, dilution, "")
if err != nil {
return fmt.Errorf(errorRequestFail, err)
}
fmt.Printf(" Generated participation key for %s (Valid %d - %d)\n", address, currentRound, lastValidRound)
// Now register it as our new online participation key
goOnline := true
txFile := ""
err = changeAccountOnlineStatus(address, &part, goOnline, txFile, wallet, currentRound, lastValidRound, fee, leaseBytes, dataDir, client)
if err != nil {
os.Remove(keyPath)
fmt.Fprintf(os.Stderr, " Error registering keys - deleting newly-generated key file: %s\n", keyPath)
}
return err
}
var renewAllParticipationKeyCmd = &cobra.Command{
Use: "renewallpartkeys",
Short: "Renew all existing participation keys",
Long: `Generate new participation keys for all existing accounts with participation keys and issue the necessary transactions to register them.`,
Args: validateNoPosArgsFn,
Run: func(cmd *cobra.Command, args []string) {
onDataDirs(func(dataDir string) {
fmt.Printf("Renewing participation keys in %s...\n", dataDir)
err := renewPartKeysInDir(dataDir, roundLastValid, transactionFee, scLeaseBytes(cmd), keyDilution, walletName)
if err != nil {
fmt.Fprintf(os.Stderr, " Error: %s\n", err)
}
})
},
}
func renewPartKeysInDir(dataDir string, lastValidRound uint64, fee uint64, leaseBytes [32]byte, dilution uint64, wallet string) error {
client := ensureAlgodClient(dataDir)
// Build list of accounts to renew from all accounts with part keys present