summaryrefslogtreecommitdiff
path: root/cmd/goal/account.go
blob: 3d8fc0ca15e891bfa3610fa8f25d0494c23ca239 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
// Copyright (C) 2019-2022 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)
	}

	fmt.Fprintf(report, "Minimum Balance:\t%v microAlgos\n", account.MinBalance)

	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)

		reportInfof("Please standby while generating keys. This might take a few minutes...")

		var err error
		participationGen := func() {
			_, _, err = client.GenParticipationKeysTo(accountAddress, roundFirstValid, roundLastValid, keyDilution, partKeyOutDir)
		}

		util.RunFuncWithSpinningCursor(participationGen)
		if err != nil {
			reportErrorf(errorRequestFail, err)
		}

		reportInfof("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)
		}
		txRoundLastValid := currentRound + proto.MaxTxnLife

		// 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, txRoundLastValid, transactionFee, scLeaseBytes(cmd), keyDilution, walletName, dataDir, client)
		if err != nil {
			reportErrorf(err.Error())
		}
	},
}

func generateAndRegisterPartKey(address string, currentRound, keyLastValidRound, txLastValidRound uint64, fee uint64, leaseBytes [32]byte, dilution uint64, wallet string, dataDir string, client libgoal.Client) error {
	// Generate a participation keys database and install it
	var part algodAcct.Participation
	var keyPath string
	var err error
	genFunc := func() {
		part, keyPath, err = client.GenParticipationKeysTo(address, currentRound, keyLastValidRound, dilution, "")
		if err != nil {
			err = fmt.Errorf(errorRequestFail, err)
		}
		fmt.Printf("  Generated participation key for %s (Valid %d - %d)\n", address, currentRound, keyLastValidRound)
	}
	fmt.Println("Generated participation key please standby...")
	util.RunFuncWithSpinningCursor(genFunc)
	if err != nil {
		return err
	}

	// Now register it as our new online participation key
	goOnline := true
	txFile := ""
	err = changeAccountOnlineStatus(address, &part, goOnline, txFile, wallet, currentRound, txLastValidRound, 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
	parts, err := client.ListParticipationKeyFiles()
	if err != nil {
		return fmt.Errorf(errorRequestFail, err)
	}
	renewAccounts := make(map[basics.Address]algodAcct.Participation)
	for _, part := range parts {
		if existing, has := renewAccounts[part.Address()]; has {
			if existing.LastValid >= part.LastValid {
				// We already saw a partkey that expires later
				continue
			}
		}
		renewAccounts[part.Address()] = part
	}

	currentRound, err := client.CurrentRound()
	if err != nil {
		return fmt.Errorf(errorRequestFail, err)
	}

	params, err := client.SuggestedParams()
	if err != nil {
		return fmt.Errorf(errorRequestFail, err)
	}
	proto := config.Consensus[protocol.ConsensusVersion(params.ConsensusVersion)]

	if lastValidRound <= (currentRound + proto.MaxTxnLife) {
		return fmt.Errorf(errLastRoundInvalid, currentRound)
	}
	txLastValidRound := currentRound + proto.MaxTxnLife

	var anyErrors bool

	// Now go through each account and if it doesn't have a part key that's valid
	// at least through lastValidRound, generate a new key and register it.
	// Make sure we don't already have a partkey valid for (or after) specified roundLastValid
	for _, renewPart := range renewAccounts {
		if renewPart.LastValid >= basics.Round(lastValidRound) {
			fmt.Printf("  Skipping account %s: Already has a part key valid beyond %d (currently %d)\n", renewPart.Address(), lastValidRound, renewPart.LastValid)
			continue
		}

		// If the account's latest partkey expired before the current round, don't automatically renew and instead instruct the user to explicitly renew it.
		if renewPart.LastValid < basics.Round(lastValidRound) {
			fmt.Printf("  Skipping account %s: This account has part keys that have expired.  Please renew this account explicitly using 'renewpartkey'\n", renewPart.Address())
			continue
		}

		address := renewPart.Address().String()
		err = generateAndRegisterPartKey(address, currentRound, lastValidRound, txLastValidRound, fee, leaseBytes, dilution, wallet, dataDir, client)
		if err != nil {
			fmt.Fprintf(os.Stderr, "  Error renewing part key for account %s: %v\n", address, err)
			anyErrors = true
		}
	}
	if anyErrors {
		return fmt.Errorf("one or more renewal attempts had errors")
	}
	return nil
}

func maxRound(current uint64, next *uint64) uint64 {
	if next != nil && *next > current {
		return *next
	}
	return current
}

func uintToStr(number uint64) string {
	return fmt.Sprintf("%d", number)
}

// legacyListParticipationKeysCommand prints key information in the same
// format as earlier versions of goal. Some users are using this information
// in scripts and need some extra time to migrate to the REST API.
// DEPRECATED
func legacyListParticipationKeysCommand() {
	dataDir := ensureSingleDataDir()

	client := ensureGoalClient(dataDir, libgoal.DynamicClient)
	parts, err := client.ListParticipationKeyFiles()
	if err != nil {
		reportErrorf(errorRequestFail, err)
	}

	var filenames []string
	for fn := range parts {
		filenames = append(filenames, fn)
	}
	sort.Strings(filenames)

	rowFormat := "%-10s\t%-80s\t%-60s\t%12s\t%12s\t%12s\n"
	fmt.Printf(rowFormat, "Registered", "Filename", "Parent address", "First round", "Last round", "First key")
	for _, fn := range filenames {
		onlineInfoStr := "unknown"
		onlineAccountInfo, err := client.AccountInformation(parts[fn].Address().GetUserAddress())
		if err == nil {
			votingBytes := parts[fn].Voting.OneTimeSignatureVerifier
			vrfBytes := parts[fn].VRF.PK
			if onlineAccountInfo.Participation != nil &&
				(string(onlineAccountInfo.Participation.ParticipationPK) == string(votingBytes[:])) &&
				(string(onlineAccountInfo.Participation.VRFPK) == string(vrfBytes[:])) &&
				(onlineAccountInfo.Participation.VoteFirst == uint64(parts[fn].FirstValid)) &&
				(onlineAccountInfo.Participation.VoteLast == uint64(parts[fn].LastValid)) &&
				(onlineAccountInfo.Participation.VoteKeyDilution == parts[fn].KeyDilution) {
				onlineInfoStr = "yes"
			} else {
				onlineInfoStr = "no"
			}
		}
		// it's okay to proceed without algod info
		first, last := parts[fn].ValidInterval()
		fmt.Printf(rowFormat, onlineInfoStr, fn, parts[fn].Address().GetUserAddress(),
			fmt.Sprintf("%d", first),
			fmt.Sprintf("%d", last),
			fmt.Sprintf("%d.%d", parts[fn].Voting.FirstBatch, parts[fn].Voting.FirstOffset))
	}
}

var listParticipationKeysCmd = &cobra.Command{
	Use:   "listpartkeys",
	Short: "List participation keys summary",
	Long:  `List all participation keys tracked by algod along with summary of additional information. For detailed key information use 'partkeyinfo'.`,
	Args:  validateNoPosArgsFn,
	Run: func(cmd *cobra.Command, args []string) {
		if partkeyCompat {
			legacyListParticipationKeysCommand()
			return
		}
		dataDir := ensureSingleDataDir()

		client := ensureGoalClient(dataDir, libgoal.DynamicClient)
		parts, err := client.ListParticipationKeys()
		if err != nil {
			reportErrorf(errorRequestFail, err)
		}

		// Squeezed this into 77 characters.
		rowFormat := "%-10s  %-11s  %-15s  %10s  %11s  %10s\n"
		fmt.Printf(rowFormat, "Registered", "Account", "ParticipationID", "Last Used", "First round", "Last round")
		for _, part := range parts {
			onlineInfoStr := "unknown"
			onlineAccountInfo, err := client.AccountInformation(part.Address)
			if err == nil {
				votingBytes := part.Key.VoteParticipationKey
				vrfBytes := part.Key.SelectionParticipationKey
				if onlineAccountInfo.Participation != nil &&
					(string(onlineAccountInfo.Participation.ParticipationPK) == string(votingBytes[:])) &&
					(string(onlineAccountInfo.Participation.VRFPK) == string(vrfBytes[:])) &&
					(onlineAccountInfo.Participation.VoteFirst == part.Key.VoteFirstValid) &&
					(onlineAccountInfo.Participation.VoteLast == part.Key.VoteLastValid) &&
					(onlineAccountInfo.Participation.VoteKeyDilution == part.Key.VoteKeyDilution) {
					onlineInfoStr = "yes"
				} else {
					onlineInfoStr = "no"
				}

				/*
					// PKI TODO: We could avoid querying the account with something like this.
					//       One problem is that it doesn't account for multiple keys on the same
					//       account, so we'd still need to query the round.
					if part.EffectiveFirstValid != nil && part.EffectiveLastValid < currentRound {
						onlineInfoStr = "yes"
					} else {
						onlineInfoStr = "no"
					}
				*/

				// it's okay to proceed without algod info
				lastUsed := maxRound(0, part.LastVote)
				lastUsed = maxRound(lastUsed, part.LastBlockProposal)
				lastUsed = maxRound(lastUsed, part.LastStateProof)
				lastUsedString := "N/A"
				if lastUsed != 0 {
					lastUsedString = uintToStr(lastUsed)
				}
				fmt.Printf(rowFormat,
					onlineInfoStr,
					fmt.Sprintf("%s...%s", part.Address[:4], part.Address[len(part.Address)-4:]),
					fmt.Sprintf("%s...", part.Id[:8]),
					lastUsedString,
					uintToStr(part.Key.VoteFirstValid),
					uintToStr(part.Key.VoteLastValid))
			}
		}
	},
}

var importCmd = &cobra.Command{
	Use:   "import",
	Short: "Import an account key from mnemonic",
	Long:  "Import an account key from a mnemonic generated by the export command or by algokey (NOT a mnemonic from the goal wallet command). The imported account will be listed alongside your wallet-generated accounts, but will not be tied to your wallet.",
	Run: func(cmd *cobra.Command, args []string) {
		dataDir := ensureSingleDataDir()
		accountList := makeAccountsList(dataDir)
		// 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)
		}

		client := ensureKmdClient(dataDir)
		wh := ensureWalletHandle(dataDir, walletName)
		//wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)

		if mnemonic == "" {
			fmt.Println(infoRecoveryPrompt)
			reader := bufio.NewReader(os.Stdin)
			resp, err := reader.ReadString('\n')
			resp = strings.TrimSpace(resp)
			if err != nil {
				reportErrorf(errorFailedToReadResponse, err)
			}
			mnemonic = resp
		}
		var key []byte
		key, err := passphrase.MnemonicToKey(mnemonic)
		if err != nil {
			reportErrorf(errorBadMnemonic, err)
		}

		importedKey, err := client.ImportKey(wh, key)
		if err != nil {
			reportErrorf(errorRequestFail, err)
		} else {
			reportInfof(infoImportedKey, importedKey.Address)

			accountList.addAccount(accountName, importedKey.Address)
			if importDefault {
				accountList.setDefault(accountName)
			}
		}
	},
}

var exportCmd = &cobra.Command{
	Use:   "export",
	Short: "Export an account key for use with account import",
	Long:  "Export an account mnemonic seed, for use with account import. This exports the seed for a single account and should NOT be confused with the wallet mnemonic.",
	Run: func(cmd *cobra.Command, args []string) {
		dataDir := ensureSingleDataDir()
		client := ensureKmdClient(dataDir)

		wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)
		passwordString := string(pw)

		response, err := client.ExportKey(wh, passwordString, accountAddress)

		if err != nil {
			reportErrorf(errorRequestFail, err)
		}

		seed, err := crypto.SecretKeyToSeed(response.PrivateKey)

		if err != nil {
			reportErrorf(errorSeedConversion, accountAddress, err)
		}

		privKeyAsMnemonic, err := passphrase.KeyToMnemonic(seed[:])

		if err != nil {
			reportErrorf(errorMnemonicConversion, accountAddress, err)
		}

		reportInfof(infoExportedKey, accountAddress, privKeyAsMnemonic)
	},
}

var importRootKeysCmd = &cobra.Command{
	Use:   "importrootkey",
	Short: "Import .rootkey files from the data directory into a kmd wallet",
	Long:  "Import .rootkey files from the data directory into a kmd wallet. This is analogous to using the import command with an account seed mnemonic: the imported account will be displayed alongside your wallet-derived accounts, but will not be tied to your wallet mnemonic.",
	Args:  validateNoPosArgsFn,
	Run: func(cmd *cobra.Command, args []string) {
		dataDir := ensureSingleDataDir()
		// Generate a participation keys database and install it
		client := ensureKmdClient(dataDir)

		genID, err := client.GenesisID()
		if err != nil {
			return
		}

		keyDir := filepath.Join(dataDir, genID)
		files, err := ioutil.ReadDir(keyDir)
		if err != nil {
			return
		}

		// For each of these files
		cnt := 0
		for _, info := range files {
			var handle db.Accessor

			// If it can't be a participation key database, skip it
			if !config.IsRootKeyFilename(info.Name()) {
				continue
			}

			filename := info.Name()

			// Fetch a handle to this database
			handle, err = db.MakeErasableAccessor(filepath.Join(keyDir, filename))
			if err != nil {
				// Couldn't open it, skip it
				continue
			}

			// Fetch an account.Participation from the database
			root, err := algodAcct.RestoreRoot(handle)
			handle.Close()
			if err != nil {
				// Couldn't read it, skip it
				continue
			}

			secretKey := root.Secrets().SK

			// Determine which wallet to import into
			var wh []byte
			if unencryptedWallet {
				wh, err = client.GetUnencryptedWalletHandle()
				if err != nil {
					reportErrorf(errorRequestFail, err)
				}
			} else {
				wh = ensureWalletHandle(dataDir, walletName)
			}

			resp, err := client.ImportKey(wh, secretKey[:])
			if err != nil {
				// If error is 'like' "key already exists", treat as warning and not an error
				if strings.Contains(err.Error(), "key already exists") {
					reportWarnf(errorRequestFail, err.Error()+"\n > Key File: "+filename)
				} else {
					reportErrorf(errorRequestFail, err)
				}
			} else {
				// Count the number of keys imported
				cnt++
				reportInfof(infoImportedKey, resp.Address)
			}
		}

		// Provide feedback on how many keys were imported
		plural := "s"
		if cnt == 1 {
			plural = ""
		}
		reportInfof(infoImportedNKeys, cnt, plural)
	},
}

func strOrNA(value *uint64) string {
	if value == nil {
		return "N/A"
	}
	return uintToStr(*value)
}

// legacyPartkeyInfoCommand prints key information in the same
// format as earlier versions of goal. Some users are using this information
// in scripts and need some extra time to migrate to alternatives.
// DEPRECATED
func legacyPartkeyInfoCommand() {
	type partkeyInfo struct {
		_struct         struct{}                        `codec:",omitempty,omitemptyarray"`
		Address         string                          `codec:"acct"`
		FirstValid      basics.Round                    `codec:"first"`
		LastValid       basics.Round                    `codec:"last"`
		VoteID          crypto.OneTimeSignatureVerifier `codec:"vote"`
		SelectionID     crypto.VRFVerifier              `codec:"sel"`
		VoteKeyDilution uint64                          `codec:"voteKD"`
	}

	onDataDirs(func(dataDir string) {
		fmt.Printf("Dumping participation key info from %s...\n", dataDir)
		client := ensureGoalClient(dataDir, libgoal.DynamicClient)

		// 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 filename, part := range parts {
			fmt.Println("------------------------------------------------------------------")
			info := partkeyInfo{
				Address:         part.Address().String(),
				FirstValid:      part.FirstValid,
				LastValid:       part.LastValid,
				VoteID:          part.VotingSecrets().OneTimeSignatureVerifier,
				SelectionID:     part.VRFSecrets().PK,
				VoteKeyDilution: part.KeyDilution,
			}
			infoString := protocol.EncodeJSON(&info)
			fmt.Printf("File: %s\n%s\n", filename, string(infoString))
		}
	})
}

var partkeyInfoCmd = &cobra.Command{
	Use:   "partkeyinfo",
	Short: "Output details about all available part keys",
	Long:  `Output details about all available part keys in the specified data directory(ies), such as key validity period.`,
	Args:  validateNoPosArgsFn,
	Run: func(cmd *cobra.Command, args []string) {
		if partkeyCompat {
			legacyPartkeyInfoCommand()
			return
		}

		onDataDirs(func(dataDir string) {
			fmt.Printf("Dumping participation key info from %s...\n", dataDir)
			client := ensureAlgodClient(dataDir)

			// Make sure we don't already have a partkey valid for (or after) specified roundLastValid
			parts, err := client.ListParticipationKeys()
			if err != nil {
				reportErrorf(errorRequestFail, err)
			}

			for _, part := range parts {
				fmt.Println()
				fmt.Printf("Participation ID:          %s\n", part.Id)
				fmt.Printf("Parent address:            %s\n", part.Address)
				fmt.Printf("Last vote round:           %s\n", strOrNA(part.LastVote))
				fmt.Printf("Last block proposal round: %s\n", strOrNA(part.LastBlockProposal))
				// PKI TODO: enable with state proof support.
				//fmt.Printf("Last state proof round:    %s\n", strOrNA(part.LastStateProof))
				fmt.Printf("Effective first round:     %s\n", strOrNA(part.EffectiveFirstValid))
				fmt.Printf("Effective last round:      %s\n", strOrNA(part.EffectiveLastValid))
				fmt.Printf("First round:               %d\n", part.Key.VoteFirstValid)
				fmt.Printf("Last round:                %d\n", part.Key.VoteLastValid)
				fmt.Printf("Key dilution:              %d\n", part.Key.VoteKeyDilution)
				fmt.Printf("Selection key:             %s\n", base64.StdEncoding.EncodeToString(part.Key.SelectionParticipationKey))
				fmt.Printf("Voting key:                %s\n", base64.StdEncoding.EncodeToString(part.Key.VoteParticipationKey))
				if part.Key.StateProofKey != nil {
					fmt.Printf("State proof key:           %s\n", base64.StdEncoding.EncodeToString(*part.Key.StateProofKey))
				}
			}
		})
	},
}

var markNonparticipatingCmd = &cobra.Command{
	Use:   "marknonparticipating",
	Short: "Permanently mark an account as not participating (i.e. offline and earns no rewards)",
	Long:  "Permanently mark an account as not participating (as opposed to Online or Offline). Once marked, the account can never go online or offline, it is forever nonparticipating, and it will never earn rewards on its balance.",
	Args:  validateNoPosArgsFn,
	Run: func(cmd *cobra.Command, args []string) {

		checkTxValidityPeriodCmdFlags(cmd)

		dataDir := ensureSingleDataDir()
		client := ensureFullClient(dataDir)
		firstTxRound, lastTxRound, err := client.ComputeValidityRounds(firstValid, lastValid, numValidRounds)
		if err != nil {
			reportErrorf(errorConstructingTX, err)
		}
		utx, err := client.MakeUnsignedBecomeNonparticipatingTx(accountAddress, firstTxRound, lastTxRound, transactionFee)
		if err != nil {
			reportErrorf(errorConstructingTX, err)
		}

		if statusChangeTxFile != "" {
			err = writeTxnToFile(client, false, dataDir, walletName, utx, statusChangeTxFile)
			if err != nil {
				reportErrorf(fileWriteError, statusChangeTxFile, err)
			}
			return
		}

		// Sign & broadcast the transaction
		wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)
		txid, err := client.SignAndBroadcastTransaction(wh, pw, utx)
		if err != nil {
			reportErrorf(errorOnlineTX, err)
		}
		fmt.Printf("Transaction id for mark-nonparticipating transaction: %s\n", txid)

		if noWaitAfterSend {
			fmt.Println("Note: status will not change until transaction is finalized")
			return
		}

		_, err = waitForCommit(client, txid, lastTxRound)
		if err != nil {
			reportErrorf("error waiting for transaction to be committed: %v", err)
		}
	},
}