-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.go
1394 lines (1199 loc) · 37.2 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"cosmossdk.io/math"
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/spf13/cobra"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
)
// global vars
var (
// config file - expected to be in the present working directory
defaultLocalConfigFile = "config.toml"
defaultGlobalConfigFile = ".multisig/config.toml"
// files for signing - we use these filenames in the local working directory and in the remote bucket
unsignedJSON = "unsigned.json"
signedJSON = "signed.json"
signDataJSON = "signdata.json"
)
// SignData Data we need for signers to sign a tx (eg. without access to a node)
type SignData struct {
Account int `json:"account"`
Sequence int `json:"sequence"`
ChainID string `json:"chain-id"`
Description string `json:"description"`
}
func main() {
// cmds defined in cmd.go
err := rootCmd.Execute()
if err != nil {
log.Fatal(err)
}
}
func cmdDelete(cobraCmd *cobra.Command, args []string) error {
chainName := args[0]
keyName := args[1]
conf, err := loadConfig(flagConfigPath)
if err != nil {
return err
}
txIndex := flagTxIndex
txDir := filepath.Join(chainName, keyName, fmt.Sprintf("%d", txIndex))
err = deleteAllFilesInPath(txDir, conf)
if err != nil {
return err
}
return nil
}
// Generates a [binary] `tx distribution withdraw-all-rewards` transaction
func cmdWithdraw(cmd *cobra.Command, args []string) error {
chainName := args[0]
keyName := args[1]
conf, err := loadConfig(flagConfigPath)
if err != nil {
return err
}
chain, found := conf.GetChain(chainName)
if !found {
return fmt.Errorf("chain %s not found in config", chainName)
}
key, found := conf.GetKey(keyName)
if !found {
return fmt.Errorf("key %s not found in config", keyName)
}
nodeAddress := chain.Node
if flagNode != "" {
nodeAddress = flagNode
}
binary := chain.Binary
address, err := bech32ify(key.Address, chain.Prefix)
if err != nil {
return err
}
// Get fees
fees, err := getFeesParameter(cmd)
if err != nil {
return err
}
// [binary] tx distribution withdraw-all-rewards
cmdArgs := []string{"tx", "distribution", "withdraw-all-rewards",
"--from", address,
"--fees", fmt.Sprintf("%s%s", fees.Amount.String(), fees.Denom),
"--gas", fmt.Sprintf("%d", getGas(conf)),
"--generate-only",
"--chain-id", fmt.Sprintf("%s", chain.ID),
}
if nodeAddress != "" {
cmdArgs = append(cmdArgs, "--node", nodeAddress)
}
execCmd := exec.Command(binary, cmdArgs...)
fmt.Println(execCmd)
unsignedBytes, err := execCmd.CombinedOutput()
if err != nil {
fmt.Println("-----------------------------------------------------------------")
fmt.Println("call failed")
fmt.Println("-----------------------------------------------------------------")
fmt.Println(execCmd)
fmt.Println(string(unsignedBytes))
return err
}
fmt.Println(string(unsignedBytes))
return pushTx(chainName, keyName, unsignedBytes, cmd)
}
// Generates a [binary] `tx staking delegate` transaction
func cmdDelegate(cmd *cobra.Command, args []string) error {
chainName := args[0]
keyName := args[1]
validator := args[2]
amount := args[3]
conf, err := loadConfig(flagConfigPath)
if err != nil {
return err
}
chain, found := conf.GetChain(chainName)
if !found {
return fmt.Errorf("chain %s not found in config", chainName)
}
key, found := conf.GetKey(keyName)
if !found {
return fmt.Errorf("key %s not found in config", keyName)
}
// Use denom from flag if specified, if not, then try
// to retrieve it from the config, if not in the config
// try to retrieve from the chain registry.
var denom string
isDenomSet := cmd.Flags().Changed("denom")
if isDenomSet {
denom = flagDenom
} else {
denom, err = getDenom(conf, chainName)
if err != nil {
return fmt.Errorf("denom not found in config or chain registry: %s", err)
}
}
nodeAddress := chain.Node
if flagNode != "" {
nodeAddress = flagNode
}
binary := chain.Binary
address, err := bech32ify(key.Address, chain.Prefix)
if err != nil {
return err
}
// Safe check for amount
amountDecCoin, err := sdk.ParseDecCoin(amount)
if err != nil {
return fmt.Errorf("error parsing the amount to delegate, plesae specify amount and denom, e.g. 100uatom")
}
// Get fees
fees, err := getFeesParameter(cmd)
if err != nil {
return err
}
// Check if amount + fee < available balance
balance, err := getAccountBalance(address, denom, chain)
if err != nil {
fmt.Println("error getting account balance, skipping check to validate enough balance to delegate")
} else {
amountFee := amountDecCoin.Add(fees)
if sdk.NewDecFromBigInt(balance.BigInt()).RoundInt().LT(amountFee.Amount.RoundInt()) {
return fmt.Errorf("the balance available (%s) is less than the amount (%s) plus the fee (%s), transaction will fail", balance, balance.String(), amountFee.Amount.RoundInt().String())
}
}
cmdArgs := []string{"tx", "staking", "delegate",
validator,
amount,
"--from", address,
"--fees", fmt.Sprintf("%s%s", fees.Amount.String(), fees.Denom),
"--gas", fmt.Sprintf("%d", getGas(conf)),
"--generate-only",
"--chain-id", fmt.Sprintf("%s", chain.ID),
}
if nodeAddress != "" {
cmdArgs = append(cmdArgs, "--node", nodeAddress)
}
execCmd := exec.Command(binary, cmdArgs...)
fmt.Println(execCmd)
unsignedBytes, err := execCmd.CombinedOutput()
if err != nil {
fmt.Println("-----------------------------------------------------------------")
fmt.Println("call failed")
fmt.Println("-----------------------------------------------------------------")
fmt.Println(execCmd)
fmt.Println(string(unsignedBytes))
return err
}
fmt.Println(string(unsignedBytes))
return pushTx(chainName, keyName, unsignedBytes, cmd)
}
func cmdClaimValidator(cmd *cobra.Command, args []string) error {
chainName := args[0]
keyName := args[1]
valAddress := args[2]
conf, err := loadConfig(flagConfigPath)
if err != nil {
return err
}
chain, found := conf.GetChain(chainName)
if !found {
return fmt.Errorf("chain %s not found in config", chainName)
}
key, found := conf.GetKey(keyName)
if !found {
return fmt.Errorf("key %s not found in config", keyName)
}
nodeAddress := chain.Node
if flagNode != "" {
nodeAddress = flagNode
}
binary := chain.Binary
address, err := bech32ify(key.Address, chain.Prefix)
if err != nil {
return err
}
// Get fees
fees, err := getFeesParameter(cmd)
if err != nil {
return err
}
// [binary] tx distribution withdraw-rewards [validator-addr]
cmdArgs := []string{"tx", "distribution", "withdraw-rewards",
valAddress,
"--commission",
"--from", address,
"--fees", fmt.Sprintf("%s%s", fees.Amount.String(), fees.Denom),
"--gas", fmt.Sprintf("%d", getGas(conf)),
"--generate-only",
"--chain-id", fmt.Sprintf("%s", chain.ID),
}
if nodeAddress != "" {
cmdArgs = append(cmdArgs, "--node", nodeAddress)
}
// Append keyring if specified in the config
if conf.KeyringBackend != "" {
cmdArgs = append(cmdArgs, "--keyring-backend", conf.KeyringBackend)
}
execCmd := exec.Command(binary, cmdArgs...)
fmt.Println(execCmd)
unsignedBytes, err := execCmd.CombinedOutput()
if err != nil {
fmt.Println("-----------------------------------------------------------------")
fmt.Println("call failed")
fmt.Println("-----------------------------------------------------------------")
fmt.Println(execCmd)
fmt.Println(string(unsignedBytes))
return err
}
fmt.Println(string(unsignedBytes))
return pushTx(chainName, keyName, unsignedBytes, cmd)
}
func cmdGrantAuthz(cmd *cobra.Command, args []string) error {
chainName := args[0]
keyName := args[1]
grantee := args[2]
msgType := args[3]
// Parse message-type parameter and generate proper tx msg-type
// Only support the messages we need for now (withdraw, delegate, commission, vote)
var cosmosMsg string
switch msgType {
case "withdraw":
cosmosMsg = "/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward"
case "delegate":
cosmosMsg = "/cosmos.staking.v1beta1.MsgDelegate"
case "commission":
cosmosMsg = "/cosmos.distribution.v1beta1.MsgWithdrawValidatorCommission"
case "vote":
cosmosMsg = "/cosmos.gov.v1beta1.MsgVote"
case "unbond":
cosmosMsg = "/cosmos.staking.v1beta1.MsgUndelegate"
case "redelegate":
cosmosMsg = "/cosmos.staking.v1beta1.MsgBeginRedelegate"
default:
return fmt.Errorf("message type %s not supported", msgType)
}
daysToExpiration := args[4]
expiration, err := strconv.Atoi(daysToExpiration)
if err != nil {
return fmt.Errorf("invalid days to expiration %s. Only specify the number of days to expire e.g. 30 (for 30 days)", daysToExpiration)
}
// Expiration from days to timestamp
expireTimestamp := time.Now().AddDate(0, 0, expiration).Unix()
conf, err := loadConfig(flagConfigPath)
if err != nil {
return err
}
chain, found := conf.GetChain(chainName)
if !found {
return fmt.Errorf("chain %s not found in config", chainName)
}
key, found := conf.GetKey(keyName)
if !found {
return fmt.Errorf("key %s not found in config", keyName)
}
nodeAddress := chain.Node
if flagNode != "" {
nodeAddress = flagNode
}
binary := chain.Binary
address, err := bech32ify(key.Address, chain.Prefix)
if err != nil {
return err
}
// Get fees
fees, err := getFeesParameter(cmd)
if err != nil {
return err
}
// gaiad tx authz grant
cmdArgs := []string{"tx", "authz", "grant", grantee, "generic",
"--expiration", fmt.Sprintf("%d", expireTimestamp),
"--msg-type", cosmosMsg,
"--from", address,
"--fees", fmt.Sprintf("%s%s", fees.Amount.String(), fees.Denom),
"--gas", fmt.Sprintf("%d", getGas(conf)),
"--generate-only",
"--chain-id", fmt.Sprintf("%s", chain.ID),
}
if nodeAddress != "" {
cmdArgs = append(cmdArgs, "--node", nodeAddress)
}
execCmd := exec.Command(binary, cmdArgs...)
fmt.Println(execCmd)
unsignedBytes, err := execCmd.CombinedOutput()
if err != nil {
fmt.Println("-----------------------------------------------------------------")
fmt.Println("call failed")
fmt.Println("-----------------------------------------------------------------")
fmt.Println(execCmd)
fmt.Println(string(unsignedBytes))
return err
}
fmt.Println(string(unsignedBytes))
return pushTx(chainName, keyName, unsignedBytes, cmd)
}
func cmdRevokeAuthz(cmd *cobra.Command, args []string) error {
chainName := args[0]
keyName := args[1]
grantee := args[2]
msgType := args[3]
// Parse message-type parameter and generate proper tx msg-type
// Only support the messages we need for now (withdraw, delegate, commission, vote)
var cosmosMsg string
switch msgType {
case "withdraw":
cosmosMsg = "/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward"
case "delegate":
cosmosMsg = "/cosmos.staking.v1beta1.MsgDelegate"
case "commission":
cosmosMsg = "/cosmos.distribution.v1beta1.MsgWithdrawValidatorCommission"
case "vote":
cosmosMsg = "/cosmos.gov.v1beta1.MsgVote"
case "unbond":
cosmosMsg = "/cosmos.staking.v1beta1.MsgUndelegate"
case "redelegate":
cosmosMsg = "/cosmos.staking.v1beta1.MsgBeginRedelegate"
default:
return fmt.Errorf("message type %s not supported", msgType)
}
conf, err := loadConfig(flagConfigPath)
if err != nil {
return err
}
chain, found := conf.GetChain(chainName)
if !found {
return fmt.Errorf("chain %s not found in config", chainName)
}
key, found := conf.GetKey(keyName)
if !found {
return fmt.Errorf("key %s not found in config", keyName)
}
nodeAddress := chain.Node
if flagNode != "" {
nodeAddress = flagNode
}
binary := chain.Binary
address, err := bech32ify(key.Address, chain.Prefix)
if err != nil {
return err
}
// Get fees
fees, err := getFeesParameter(cmd)
if err != nil {
return err
}
// gaiad tx authz grant
cmdArgs := []string{"tx", "authz", "revoke", grantee, cosmosMsg,
"--from", address,
"--fees", fmt.Sprintf("%s%s", fees.Amount.String(), fees.Denom),
"--gas", fmt.Sprintf("%d", getGas(conf)),
"--generate-only",
"--chain-id", fmt.Sprintf("%s", chain.ID),
}
if nodeAddress != "" {
cmdArgs = append(cmdArgs, "--node", nodeAddress)
}
execCmd := exec.Command(binary, cmdArgs...)
fmt.Println(execCmd)
unsignedBytes, err := execCmd.CombinedOutput()
if err != nil {
fmt.Println("-----------------------------------------------------------------")
fmt.Println("call failed")
fmt.Println("-----------------------------------------------------------------")
fmt.Println(execCmd)
fmt.Println(string(unsignedBytes))
return err
}
fmt.Println(string(unsignedBytes))
return pushTx(chainName, keyName, unsignedBytes, cmd)
}
func cmdVote(cmd *cobra.Command, args []string) error {
chainName := args[0]
keyName := args[1]
propID := args[2]
voteOption := args[3]
conf, err := loadConfig(flagConfigPath)
if err != nil {
return err
}
chain, found := conf.GetChain(chainName)
if !found {
return fmt.Errorf("chain %s not found in config", chainName)
}
key, found := conf.GetKey(keyName)
if !found {
return fmt.Errorf("key %s not found in config", keyName)
}
nodeAddress := chain.Node
if flagNode != "" {
nodeAddress = flagNode
}
binary := chain.Binary
address, err := bech32ify(key.Address, chain.Prefix)
if err != nil {
return err
}
// Get fees
fees, err := getFeesParameter(cmd)
if err != nil {
return err
}
// gaiad tx gov vote <prop id> <option> --from <from> --generate-only
cmdArgs := []string{"tx", "gov", "vote", propID, voteOption,
"--from", address,
"--fees", fmt.Sprintf("%s%s", fees.Amount.String(), fees.Denom),
"--gas", fmt.Sprintf("%d", getGas(conf)),
"--generate-only",
"--chain-id", fmt.Sprintf("%s", chain.ID),
}
if nodeAddress != "" {
cmdArgs = append(cmdArgs, "--node", nodeAddress)
}
execCmd := exec.Command(binary, cmdArgs...)
fmt.Println(execCmd)
unsignedBytes, err := execCmd.CombinedOutput()
if err != nil {
fmt.Println("-----------------------------------------------------------------")
fmt.Println("call failed")
fmt.Println("-----------------------------------------------------------------")
fmt.Println(execCmd)
fmt.Println(string(unsignedBytes))
return err
}
fmt.Println(string(unsignedBytes))
return pushTx(chainName, keyName, unsignedBytes, cmd)
}
func cmdPush(cmd *cobra.Command, args []string) error {
txFile := args[0]
chainName := args[1]
keyName := args[2]
unsignedBytes, err := os.ReadFile(txFile)
if err != nil {
return err
}
conf, err := loadConfig(flagConfigPath)
if err != nil {
return err
}
// Logic to emit a warning if the denoms don't match
denomInJson, err2 := parseDenomFromJson(unsignedBytes)
if err2 == nil {
denomConfig, err := getDenom(conf, chainName)
if err == nil {
if denomInJson != denomConfig {
fmt.Printf("WARNING: Denom '%s' in the unsigned json is different from the denom '%s' in the config or registry!\n", denomInJson, denomConfig)
}
}
}
return pushTx(chainName, keyName, unsignedBytes, cmd)
}
func pushTx(chainName, keyName string, unsignedTxBytes []byte, cmd *cobra.Command) error {
if flagForce && flagAdditional {
return fmt.Errorf("cannot specify both --force and --additional")
}
conf, err := loadConfig(flagConfigPath)
if err != nil {
return err
}
chain, found := conf.GetChain(chainName)
if !found {
return fmt.Errorf("chain %s not found in config", chainName)
}
key, found := conf.GetKey(keyName)
if !found {
return fmt.Errorf("key %s not found in config", keyName)
}
//-----------------------------------
// find account and sequence numbers
// either from a node and/or from CLI
//------------------------------------
nodeAddress := chain.Node
if flagNode != "" {
nodeAddress = flagNode
}
isAccSet := cmd.Flags().Changed("account")
isSeqSet := cmd.Flags().Changed("sequence")
// if both account and sequence are not set, the node must be set in the config or CLI
noAccOrSeq := !(isAccSet && isSeqSet)
noNode := nodeAddress == ""
if noAccOrSeq && noNode {
fmt.Println("if the --account and --sequence are not provided, a node must be specified in the config or with --node")
return nil
}
var (
accountNum int
sequenceNum int
)
// if both account and sequence are not set, get them from the node
if noAccOrSeq {
var err2 error
httpClient := NewHttpClient()
nodeInfo, err2 := GetNodeInfo(chain, httpClient)
if err2 != nil {
return err2
}
sdkVersion, err2 := parseSdkVersionFromJson(nodeInfo)
if err2 != nil {
return err2
}
binary := chain.Binary
address, err2 := bech32ify(key.Address, chain.Prefix)
if err2 != nil {
return err2
}
accountNum, sequenceNum, err2 = getAccSeq(binary, address, nodeAddress, sdkVersion)
if err2 != nil {
return err2
}
}
// if the acc or seq flags are set, overwrite the node
if isAccSet {
accountNum = flagAccount
}
if isSeqSet {
sequenceNum = flagSequence
}
txDir := filepath.Join(chainName, keyName)
sess := awsSession(conf.AWS)
// check if a file already exists
files, err := awsListFilesInDir(sess, conf.AWS, chainName, keyName)
if err != nil {
return err
}
// if there is already files there, and we don't specify -f or -x, return
if len(files) > 0 && !(flagForce || flagAdditional) {
return fmt.Errorf("files already exist for %s/%s. Use -f to force overwrite or -x to add additional txs", chainName, keyName)
} else if len(files) == 0 && (flagForce || flagAdditional) {
return fmt.Errorf("path %s/%s is empty, Cannot specify --force or --additional", chainName, keyName)
}
// now, either:
// it is empty, so push files
// it is not empty, overwrite files (--force)
// it is not empty, add additional files (--additional)
// we always start paths with 0, to support multiple txs per chain/key pair
N := 0
// if we're pushing additional files, figure out what the highest number is and increment,
// and add that to the sequence number
if flagAdditional {
// figure out what highest number in the files is
// files should be either "filename.json" or "n/filename.json"
for _, fullPathFile := range files {
f := strings.TrimPrefix(fullPathFile, txDir+"/")
spl := strings.Split(f, "/")
if len(spl) == 1 {
continue
}
nString := spl[0]
n, err := strconv.Atoi(nString)
if err != nil {
return fmt.Errorf("failed to read number after %s in path %s", txDir, fullPathFile)
}
if n > N {
N = n
}
}
N += 1
if !isSeqSet {
sequenceNum += N
}
}
txDir = filepath.Join(txDir, fmt.Sprintf("%d", N))
// Delete existing files in the path
err = deleteAllFilesInPath(txDir, conf)
if err != nil {
return err
}
// create and marshal the sign data
signData := SignData{
Account: accountNum,
Sequence: sequenceNum,
ChainID: chain.ID,
Description: flagDescription,
}
signDataBytes, err := json.Marshal(signData)
if err != nil {
return err
}
// upload the unsigned tx
if err := awsUpload(sess, conf.AWS, txDir, unsignedJSON, unsignedTxBytes); err != nil {
return err
}
// upload the sign data
if err := awsUpload(sess, conf.AWS, txDir, signDataJSON, signDataBytes); err != nil {
return err
}
fmt.Printf("pushed %s and %s files to %s\n", unsignedJSON, signedJSON, txDir)
return nil
}
func cmdSign(cobraCmd *cobra.Command, args []string) error {
/*
fetch the unsigned tx and signdata
display the tx and sign data and ask for confirmation from the user
run the appropriate tx sign command with the right binary using the unsigned tx and metadata
upload the signature to the right bucket
*/
chainName := args[0]
keyName := args[1]
from := flagFrom
txIndex := flagTxIndex
conf, err := loadConfig(flagConfigPath)
if err != nil {
return err
}
chain, found := conf.GetChain(chainName)
if !found {
return fmt.Errorf("chain %s not found in config", chainName)
}
key, found := conf.GetKey(keyName)
if !found {
return fmt.Errorf("key %s not found in config", keyName)
}
txDir := filepath.Join(chainName, keyName, fmt.Sprintf("%d", txIndex))
sess := awsSession(conf.AWS)
downloader := s3manager.NewDownloader(sess)
// Make a file for the unsigned.json, download it
unsignedFile, err := os.CreateTemp("", "temp")
if err != nil {
return err
}
defer func(name string) {
_ = os.Remove(name)
}(unsignedFile.Name())
unsignedPath := filepath.Join(txDir, unsignedJSON)
numBytes, err := downloader.Download(unsignedFile,
&s3.GetObjectInput{
Bucket: aws.String(conf.AWS.Bucket),
Key: aws.String(unsignedPath),
})
if err != nil {
return err
}
_ = numBytes
// Make a file for sign data, download it
signDataFile, err := os.CreateTemp("", "temp")
if err != nil {
return err
}
defer func(name string) {
_ = os.Remove(name)
}(signDataFile.Name())
signDataPath := filepath.Join(txDir, signDataJSON)
numBytes, err = downloader.Download(signDataFile,
&s3.GetObjectInput{
Bucket: aws.String(conf.AWS.Bucket),
Key: aws.String(signDataPath),
})
if err != nil {
return err
}
_ = numBytes
// TODO: pretty print and confirm the unsigned tx
unsignedBytes, _ := io.ReadAll(unsignedFile)
signDataBytes, _ := io.ReadAll(signDataFile)
fmt.Println("You are signing the following tx:")
fmt.Println(string(unsignedBytes))
fmt.Println("With the following sign data:")
fmt.Println(string(signDataBytes))
var signData SignData
if err := json.Unmarshal(signDataBytes, &signData); err != nil {
return err
}
address, err := bech32ify(key.Address, chain.Prefix)
if err != nil {
return err
}
binary := chain.Binary
accNum := fmt.Sprintf("%d", signData.Account)
seqNum := fmt.Sprintf("%d", signData.Sequence)
chainID := signData.ChainID
unsignedFileName := unsignedFile.Name()
backend := conf.KeyringBackend
user := conf.User
// gaiad tx sign unsigned.json --multisig <address> --from <from> --account-number <acc> --sequence <seq> --chain-id <id> --offline
cmdArgs := []string{"tx", "sign", unsignedFileName, "--multisig", address, "--from", from,
"--account-number", accNum, "--sequence", seqNum, "--chain-id", chainID,
"--sign-mode", "amino-json",
"--offline",
}
cmdArgs = append(cmdArgs, "--keyring-backend", backend)
if flagHomePath != "" {
cmdArgs = append(cmdArgs, "--home", flagHomePath)
}
cmd := exec.Command(binary, cmdArgs...)
b, err := cmd.CombinedOutput()
if err != nil {
fmt.Println("-----------------------------------------------------------------")
fmt.Println("call failed")
fmt.Println("-----------------------------------------------------------------")
fmt.Println(cmd)
fmt.Println(string(b))
return err
}
fmt.Println(cmd)
fmt.Println(string(b))
// upload the signature as <user>.json
if err := awsUpload(sess, conf.AWS, txDir, fmt.Sprintf("%s.json", user), b); err != nil {
return err
}
return nil
}
func cmdBroadcast(cobraCmd *cobra.Command, args []string) error {
chainName := args[0]
keyName := args[1]
conf, err := loadConfig(flagConfigPath)
if err != nil {
return err
}
chain, found := conf.GetChain(chainName)
if !found {
return fmt.Errorf("chain %s not found in config", chainName)
}
key, found := conf.GetKey(keyName)
if !found {
return fmt.Errorf("key %s not found in config", keyName)
}
txIndex := flagTxIndex
txDir := filepath.Join(chainName, keyName, fmt.Sprintf("%d", txIndex))
sess := awsSession(conf.AWS)
svc := s3.New(sess)
// list all items in bucket
resp, err := svc.ListObjectsV2(&s3.ListObjectsV2Input{Bucket: aws.String(conf.AWS.Bucket)})
if err != nil {
return err
}
//--------------------------------
// txIndex specified must be smallest index for this chainName/keyName pair,
// otherwise error
files, err := awsListFilesInDir(sess, conf.AWS, chainName, keyName)
if err != nil {
return err
}
// see if any indices are smaller than txIndex, and if so, quit
for _, fullPathFile := range files {
dirPrefix := filepath.Join(chainName, keyName)
f := strings.TrimPrefix(fullPathFile, dirPrefix+"/")
spl := strings.Split(f, "/")
if len(spl) == 1 {
continue
}
nString := spl[0]
n, err := strconv.Atoi(nString)
if err != nil {
return fmt.Errorf("failed to read number after %s in path %s", txDir, fullPathFile)
}
if n < txIndex {
return fmt.Errorf("found index %d smaller than specified txIndex %d. txs must be broadcast in order", n, txIndex)
}
}
//--------------------------------
fileNames := []string{}
for _, item := range resp.Contents {
itemKey := *item.Key
if strings.HasPrefix(itemKey, txDir) && !strings.HasSuffix(itemKey, "/") {
base := filepath.Base(itemKey)
// sanity check
if len(base) == 0 {
return fmt.Errorf("%s had empty base", itemKey)
}
fileNames = append(fileNames, base)
}
}
for _, f := range fileNames {
fmt.Println(f)
_, err := awsDownload(sess, conf.AWS, txDir, f)
if err != nil {
return err
}
}
// get the names of the signatures (everything except unsigned.json and signdata.json)
sigFileNames := []string{}
for _, f := range fileNames {
if f == unsignedJSON || f == signDataJSON {
continue
}
sigFileNames = append(sigFileNames, f)
}
// TODO: add this to the key config so its not hardcoded to 2.
// can default to 2 tho
threshold := 2
if len(sigFileNames) < threshold {
return fmt.Errorf("Insufficient signatures for broadcast. Requires %d, got %d", threshold, len(sigFileNames))
}
// read and unmarshal the sign data
signDataBytes, err := os.ReadFile(signDataJSON)
if err != nil {
return err
}
var signData SignData
if err := json.Unmarshal(signDataBytes, &signData); err != nil {
return err
}
// setup for the `tx multisign` command
binary := chain.Binary
accNum := fmt.Sprintf("%d", signData.Account)
seqNum := fmt.Sprintf("%d", signData.Sequence)
chainID := signData.ChainID
unsignedFileName := unsignedJSON
backend := conf.KeyringBackend