-
Notifications
You must be signed in to change notification settings - Fork 128
/
chain_node.go
1249 lines (1073 loc) · 37 KB
/
chain_node.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 cosmos
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"hash/fnv"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/avast/retry-go/v4"
tmjson "github.com/tendermint/tendermint/libs/json"
"github.com/tendermint/tendermint/p2p"
rpcclient "github.com/tendermint/tendermint/rpc/client"
rpchttp "github.com/tendermint/tendermint/rpc/client/http"
coretypes "github.com/tendermint/tendermint/rpc/core/types"
libclient "github.com/tendermint/tendermint/rpc/jsonrpc/client"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/types"
authTx "github.com/cosmos/cosmos-sdk/x/auth/tx"
paramsutils "github.com/cosmos/cosmos-sdk/x/params/client/utils"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
dockerclient "github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
"github.com/strangelove-ventures/interchaintest/v3/ibc"
"github.com/strangelove-ventures/interchaintest/v3/internal/blockdb"
"github.com/strangelove-ventures/interchaintest/v3/internal/dockerutil"
"github.com/strangelove-ventures/interchaintest/v3/testutil"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
)
// ChainNode represents a node in the test network that is being created
type ChainNode struct {
VolumeName string
Index int
Chain ibc.Chain
Validator bool
NetworkID string
DockerClient *dockerclient.Client
Client rpcclient.Client
TestName string
Image ibc.DockerImage
lock sync.Mutex
log *zap.Logger
containerLifecycle *dockerutil.ContainerLifecycle
// Ports set during StartContainer.
hostRPCPort string
hostGRPCPort string
}
func NewChainNode(log *zap.Logger, validator bool, chain *CosmosChain, dockerClient *dockerclient.Client, networkID string, testName string, image ibc.DockerImage, index int) *ChainNode {
tn := &ChainNode{
log: log,
Validator: validator,
Chain: chain,
DockerClient: dockerClient,
NetworkID: networkID,
TestName: testName,
Image: image,
Index: index,
}
tn.containerLifecycle = dockerutil.NewContainerLifecycle(log, dockerClient, tn.Name())
return tn
}
// ChainNodes is a collection of ChainNode
type ChainNodes []*ChainNode
const (
valKey = "validator"
blockTime = 2 // seconds
p2pPort = "26656/tcp"
rpcPort = "26657/tcp"
grpcPort = "9090/tcp"
apiPort = "1317/tcp"
privValPort = "1234/tcp"
)
var (
sentryPorts = nat.PortSet{
nat.Port(p2pPort): {},
nat.Port(rpcPort): {},
nat.Port(grpcPort): {},
nat.Port(apiPort): {},
nat.Port(privValPort): {},
}
)
// NewClient creates and assigns a new Tendermint RPC client to the ChainNode
func (tn *ChainNode) NewClient(addr string) error {
httpClient, err := libclient.DefaultHTTPClient(addr)
if err != nil {
return err
}
httpClient.Timeout = 10 * time.Second
rpcClient, err := rpchttp.NewWithClient(addr, "/websocket", httpClient)
if err != nil {
return err
}
tn.Client = rpcClient
return nil
}
// CliContext creates a new Cosmos SDK client context
func (tn *ChainNode) CliContext() client.Context {
cfg := tn.Chain.Config()
return client.Context{
Client: tn.Client,
ChainID: cfg.ChainID,
InterfaceRegistry: cfg.EncodingConfig.InterfaceRegistry,
Input: os.Stdin,
Output: os.Stdout,
OutputFormat: "json",
LegacyAmino: cfg.EncodingConfig.Amino,
TxConfig: cfg.EncodingConfig.TxConfig,
}
}
// Name of the test node container
func (tn *ChainNode) Name() string {
var nodeType string
if tn.Validator {
nodeType = "val"
} else {
nodeType = "fn"
}
return fmt.Sprintf("%s-%s-%d-%s", tn.Chain.Config().ChainID, nodeType, tn.Index, dockerutil.SanitizeContainerName(tn.TestName))
}
// hostname of the test node container
func (tn *ChainNode) HostName() string {
return dockerutil.CondenseHostName(tn.Name())
}
func (tn *ChainNode) GenesisFileContent(ctx context.Context) ([]byte, error) {
gen, err := tn.ReadFile(ctx, "config/genesis.json")
if err != nil {
return nil, fmt.Errorf("getting genesis.json content: %w", err)
}
return gen, nil
}
func (tn *ChainNode) OverwriteGenesisFile(ctx context.Context, content []byte) error {
err := tn.WriteFile(ctx, content, "config/genesis.json")
if err != nil {
return fmt.Errorf("overwriting genesis.json: %w", err)
}
return nil
}
func (tn *ChainNode) copyGentx(ctx context.Context, destVal *ChainNode) error {
nid, err := tn.NodeID(ctx)
if err != nil {
return fmt.Errorf("getting node ID: %w", err)
}
relPath := fmt.Sprintf("config/gentx/gentx-%s.json", nid)
gentx, err := tn.ReadFile(ctx, relPath)
if err != nil {
return fmt.Errorf("getting gentx content: %w", err)
}
err = destVal.WriteFile(ctx, gentx, relPath)
if err != nil {
return fmt.Errorf("overwriting gentx: %w", err)
}
return nil
}
type PrivValidatorKey struct {
Type string `json:"type"`
Value string `json:"value"`
}
type PrivValidatorKeyFile struct {
Address string `json:"address"`
PubKey PrivValidatorKey `json:"pub_key"`
PrivKey PrivValidatorKey `json:"priv_key"`
}
// Bind returns the home folder bind point for running the node
func (tn *ChainNode) Bind() []string {
return []string{fmt.Sprintf("%s:%s", tn.VolumeName, tn.HomeDir())}
}
func (tn *ChainNode) HomeDir() string {
return path.Join("/var/cosmos-chain", tn.Chain.Config().Name)
}
// SetTestConfig modifies the config to reasonable values for use within interchaintest.
func (tn *ChainNode) SetTestConfig(ctx context.Context) error {
c := make(testutil.Toml)
// Set Log Level to info
c["log_level"] = "info"
p2p := make(testutil.Toml)
// Allow p2p strangeness
p2p["allow_duplicate_ip"] = true
p2p["addr_book_strict"] = false
c["p2p"] = p2p
consensus := make(testutil.Toml)
blockT := (time.Duration(blockTime) * time.Second).String()
consensus["timeout_commit"] = blockT
consensus["timeout_propose"] = blockT
c["consensus"] = consensus
rpc := make(testutil.Toml)
// Enable public RPC
rpc["laddr"] = "tcp://0.0.0.0:26657"
c["rpc"] = rpc
if err := testutil.ModifyTomlConfigFile(
ctx,
tn.logger(),
tn.DockerClient,
tn.TestName,
tn.VolumeName,
"config/config.toml",
c,
); err != nil {
return err
}
a := make(testutil.Toml)
a["minimum-gas-prices"] = tn.Chain.Config().GasPrices
grpc := make(testutil.Toml)
// Enable public GRPC
grpc["address"] = "0.0.0.0:9090"
a["grpc"] = grpc
return testutil.ModifyTomlConfigFile(
ctx,
tn.logger(),
tn.DockerClient,
tn.TestName,
tn.VolumeName,
"config/app.toml",
a,
)
}
// SetPeers modifies the config persistent_peers for a node
func (tn *ChainNode) SetPeers(ctx context.Context, peers string) error {
c := make(testutil.Toml)
p2p := make(testutil.Toml)
// Set peers
p2p["persistent_peers"] = peers
c["p2p"] = p2p
return testutil.ModifyTomlConfigFile(
ctx,
tn.logger(),
tn.DockerClient,
tn.TestName,
tn.VolumeName,
"config/config.toml",
c,
)
}
func (tn *ChainNode) Height(ctx context.Context) (uint64, error) {
res, err := tn.Client.Status(ctx)
if err != nil {
return 0, fmt.Errorf("tendermint rpc client status: %w", err)
}
height := res.SyncInfo.LatestBlockHeight
return uint64(height), nil
}
// FindTxs implements blockdb.BlockSaver.
func (tn *ChainNode) FindTxs(ctx context.Context, height uint64) ([]blockdb.Tx, error) {
h := int64(height)
var eg errgroup.Group
var blockRes *coretypes.ResultBlockResults
var block *coretypes.ResultBlock
eg.Go(func() (err error) {
blockRes, err = tn.Client.BlockResults(ctx, &h)
return err
})
eg.Go(func() (err error) {
block, err = tn.Client.Block(ctx, &h)
return err
})
if err := eg.Wait(); err != nil {
return nil, err
}
interfaceRegistry := tn.Chain.Config().EncodingConfig.InterfaceRegistry
txs := make([]blockdb.Tx, 0, len(block.Block.Txs)+2)
for i, tx := range block.Block.Txs {
var newTx blockdb.Tx
newTx.Data = []byte(fmt.Sprintf(`{"data":"%s"}`, hex.EncodeToString(tx)))
sdkTx, err := decodeTX(interfaceRegistry, tx)
if err != nil {
tn.logger().Info("Failed to decode tx", zap.Uint64("height", height), zap.Error(err))
continue
}
b, err := encodeTxToJSON(interfaceRegistry, sdkTx)
if err != nil {
tn.logger().Info("Failed to marshal tx to json", zap.Uint64("height", height), zap.Error(err))
continue
}
newTx.Data = b
rTx := blockRes.TxsResults[i]
newTx.Events = make([]blockdb.Event, len(rTx.Events))
for j, e := range rTx.Events {
attrs := make([]blockdb.EventAttribute, len(e.Attributes))
for k, attr := range e.Attributes {
attrs[k] = blockdb.EventAttribute{
Key: string(attr.Key),
Value: string(attr.Value),
}
}
newTx.Events[j] = blockdb.Event{
Type: e.Type,
Attributes: attrs,
}
}
txs = append(txs, newTx)
}
if len(blockRes.BeginBlockEvents) > 0 {
beginBlockTx := blockdb.Tx{
Data: []byte(`{"data":"begin_block","note":"this is a transaction artificially created for debugging purposes"}`),
}
beginBlockTx.Events = make([]blockdb.Event, len(blockRes.BeginBlockEvents))
for i, e := range blockRes.BeginBlockEvents {
attrs := make([]blockdb.EventAttribute, len(e.Attributes))
for j, attr := range e.Attributes {
attrs[j] = blockdb.EventAttribute{
Key: string(attr.Key),
Value: string(attr.Value),
}
}
beginBlockTx.Events[i] = blockdb.Event{
Type: e.Type,
Attributes: attrs,
}
}
txs = append(txs, beginBlockTx)
}
if len(blockRes.EndBlockEvents) > 0 {
endBlockTx := blockdb.Tx{
Data: []byte(`{"data":"end_block","note":"this is a transaction artificially created for debugging purposes"}`),
}
endBlockTx.Events = make([]blockdb.Event, len(blockRes.EndBlockEvents))
for i, e := range blockRes.EndBlockEvents {
attrs := make([]blockdb.EventAttribute, len(e.Attributes))
for j, attr := range e.Attributes {
attrs[j] = blockdb.EventAttribute{
Key: string(attr.Key),
Value: string(attr.Value),
}
}
endBlockTx.Events[i] = blockdb.Event{
Type: e.Type,
Attributes: attrs,
}
}
txs = append(txs, endBlockTx)
}
return txs, nil
}
// TxCommand is a helper to retrieve a full command for broadcasting a tx
// with the chain node binary.
func (tn *ChainNode) TxCommand(keyName string, command ...string) []string {
command = append([]string{"tx"}, command...)
var gasPriceFound, gasAdjustmentFound = false, false
for i := 0; i < len(command); i++ {
if command[i] == "--gas-prices" {
gasPriceFound = true
}
if command[i] == "--gas-adjustment" {
gasAdjustmentFound = true
}
}
if !gasPriceFound {
command = append(command, "--gas-prices", tn.Chain.Config().GasPrices)
}
if !gasAdjustmentFound {
command = append(command, "--gas-adjustment", fmt.Sprint(tn.Chain.Config().GasAdjustment))
}
return tn.NodeCommand(append(command,
"--from", keyName,
"--keyring-backend", keyring.BackendTest,
"--output", "json",
"-y",
)...)
}
// ExecTx executes a transaction, waits for 2 blocks if successful, then returns the tx hash.
func (tn *ChainNode) ExecTx(ctx context.Context, keyName string, command ...string) (string, error) {
tn.lock.Lock()
defer tn.lock.Unlock()
stdout, _, err := tn.Exec(ctx, tn.TxCommand(keyName, command...), nil)
if err != nil {
return "", err
}
output := CosmosTx{}
err = json.Unmarshal([]byte(stdout), &output)
if err != nil {
return "", err
}
if output.Code != 0 {
return output.TxHash, fmt.Errorf("transaction failed with code %d: %s", output.Code, output.RawLog)
}
if err := testutil.WaitForBlocks(ctx, 2, tn); err != nil {
return "", err
}
return output.TxHash, nil
}
// NodeCommand is a helper to retrieve a full command for a chain node binary.
// when interactions with the RPC endpoint are necessary.
// For example, if chain node binary is `gaiad`, and desired command is `gaiad keys show key1`,
// pass ("keys", "show", "key1") for command to return the full command.
// Will include additional flags for node URL, home directory, and chain ID.
func (tn *ChainNode) NodeCommand(command ...string) []string {
command = tn.BinCommand(command...)
return append(command,
"--node", fmt.Sprintf("tcp://%s:26657", tn.HostName()),
"--chain-id", tn.Chain.Config().ChainID,
)
}
// BinCommand is a helper to retrieve a full command for a chain node binary.
// For example, if chain node binary is `gaiad`, and desired command is `gaiad keys show key1`,
// pass ("keys", "show", "key1") for command to return the full command.
// Will include additional flags for home directory and chain ID.
func (tn *ChainNode) BinCommand(command ...string) []string {
command = append([]string{tn.Chain.Config().Bin}, command...)
return append(command,
"--home", tn.HomeDir(),
)
}
// ExecBin is a helper to execute a command for a chain node binary.
// For example, if chain node binary is `gaiad`, and desired command is `gaiad keys show key1`,
// pass ("keys", "show", "key1") for command to execute the command against the node.
// Will include additional flags for home directory and chain ID.
func (tn *ChainNode) ExecBin(ctx context.Context, command ...string) ([]byte, []byte, error) {
return tn.Exec(ctx, tn.BinCommand(command...), nil)
}
// QueryCommand is a helper to retrieve the full query command. For example,
// if chain node binary is gaiad, and desired command is `gaiad query gov params`,
// pass ("gov", "params") for command to return the full command with all necessary
// flags to query the specific node.
func (tn *ChainNode) QueryCommand(command ...string) []string {
command = append([]string{"query"}, command...)
return tn.NodeCommand(append(command,
"--output", "json",
)...)
}
// ExecQuery is a helper to execute a query command. For example,
// if chain node binary is gaiad, and desired command is `gaiad query gov params`,
// pass ("gov", "params") for command to execute the query against the node.
// Returns response in json format.
func (tn *ChainNode) ExecQuery(ctx context.Context, command ...string) ([]byte, []byte, error) {
return tn.Exec(ctx, tn.QueryCommand(command...), nil)
}
// CondenseMoniker fits a moniker into the cosmos character limit for monikers.
// If the moniker already fits, it is returned unmodified.
// Otherwise, the middle is truncated, and a hash is appended to the end
// in case the only unique data was in the middle.
func CondenseMoniker(m string) string {
if len(m) <= stakingtypes.MaxMonikerLength {
return m
}
// Get the hash suffix, a 32-bit uint formatted in base36.
// fnv32 was chosen because a 32-bit number ought to be sufficient
// as a distinguishing suffix, and it will be short enough so that
// less of the middle will be truncated to fit in the character limit.
// It's also non-cryptographic, not that this function will ever be a bottleneck in tests.
h := fnv.New32()
h.Write([]byte(m))
suffix := "-" + strconv.FormatUint(uint64(h.Sum32()), 36)
wantLen := stakingtypes.MaxMonikerLength - len(suffix)
// Half of the want length, minus 2 to account for half of the ... we add in the middle.
keepLen := (wantLen / 2) - 2
return m[:keepLen] + "..." + m[len(m)-keepLen:] + suffix
}
// InitHomeFolder initializes a home folder for the given node
func (tn *ChainNode) InitHomeFolder(ctx context.Context) error {
tn.lock.Lock()
defer tn.lock.Unlock()
_, _, err := tn.ExecBin(ctx,
"init", CondenseMoniker(tn.Name()),
"--chain-id", tn.Chain.Config().ChainID,
)
return err
}
// WriteFile accepts file contents in a byte slice and writes the contents to
// the docker filesystem. relPath describes the location of the file in the
// docker volume relative to the home directory
func (tn *ChainNode) WriteFile(ctx context.Context, content []byte, relPath string) error {
fw := dockerutil.NewFileWriter(tn.logger(), tn.DockerClient, tn.TestName)
return fw.WriteFile(ctx, tn.VolumeName, relPath, content)
}
// CopyFile adds a file from the host filesystem to the docker filesystem
// relPath describes the location of the file in the docker volume relative to
// the home directory
func (tn *ChainNode) CopyFile(ctx context.Context, srcPath, dstPath string) error {
content, err := os.ReadFile(srcPath)
if err != nil {
return err
}
return tn.WriteFile(ctx, content, dstPath)
}
// ReadFile reads the contents of a single file at the specified path in the docker filesystem.
// relPath describes the location of the file in the docker volume relative to the home directory.
func (tn *ChainNode) ReadFile(ctx context.Context, relPath string) ([]byte, error) {
fr := dockerutil.NewFileRetriever(tn.logger(), tn.DockerClient, tn.TestName)
gen, err := fr.SingleFileContent(ctx, tn.VolumeName, relPath)
if err != nil {
return nil, fmt.Errorf("failed to read file at %s: %w", relPath, err)
}
return gen, nil
}
// CreateKey creates a key in the keyring backend test for the given node
func (tn *ChainNode) CreateKey(ctx context.Context, name string) error {
tn.lock.Lock()
defer tn.lock.Unlock()
_, _, err := tn.ExecBin(ctx,
"keys", "add", name,
"--coin-type", tn.Chain.Config().CoinType,
"--keyring-backend", keyring.BackendTest,
)
return err
}
// RecoverKey restores a key from a given mnemonic.
func (tn *ChainNode) RecoverKey(ctx context.Context, keyName, mnemonic string) error {
command := []string{
"sh",
"-c",
fmt.Sprintf(`echo %q | %s keys add %s --recover --keyring-backend %s --coin-type %s --home %s --output json`, mnemonic, tn.Chain.Config().Bin, keyName, keyring.BackendTest, tn.Chain.Config().CoinType, tn.HomeDir()),
}
tn.lock.Lock()
defer tn.lock.Unlock()
_, _, err := tn.Exec(ctx, command, nil)
return err
}
// AddGenesisAccount adds a genesis account for each key
func (tn *ChainNode) AddGenesisAccount(ctx context.Context, address string, genesisAmount []types.Coin) error {
amount := ""
for i, coin := range genesisAmount {
if i != 0 {
amount += ","
}
amount += fmt.Sprintf("%d%s", coin.Amount.Int64(), coin.Denom)
}
tn.lock.Lock()
defer tn.lock.Unlock()
// Adding a genesis account should complete instantly,
// so use a 1-minute timeout to more quickly detect if Docker has locked up.
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
var command []string
if tn.Chain.Config().UsingNewGenesisCommand {
command = append(command, "genesis")
}
command = append(command, "add-genesis-account", address, amount)
_, _, err := tn.ExecBin(ctx, command...)
return err
}
// Gentx generates the gentx for a given node
func (tn *ChainNode) Gentx(ctx context.Context, name string, genesisSelfDelegation types.Coin) error {
tn.lock.Lock()
defer tn.lock.Unlock()
var command []string
if tn.Chain.Config().UsingNewGenesisCommand {
command = append(command, "genesis")
}
command = append(command, "gentx", valKey, fmt.Sprintf("%d%s", genesisSelfDelegation.Amount.Int64(), genesisSelfDelegation.Denom),
"--keyring-backend", keyring.BackendTest,
"--chain-id", tn.Chain.Config().ChainID)
_, _, err := tn.ExecBin(ctx, command...)
return err
}
// CollectGentxs runs collect gentxs on the node's home folders
func (tn *ChainNode) CollectGentxs(ctx context.Context) error {
command := []string{tn.Chain.Config().Bin}
if tn.Chain.Config().UsingNewGenesisCommand {
command = append(command, "genesis")
}
command = append(command, "collect-gentxs", "--home", tn.HomeDir())
tn.lock.Lock()
defer tn.lock.Unlock()
_, _, err := tn.Exec(ctx, command, nil)
return err
}
type CosmosTx struct {
TxHash string `json:"txhash"`
Code int `json:"code"`
RawLog string `json:"raw_log"`
}
func (tn *ChainNode) SendIBCTransfer(
ctx context.Context,
channelID string,
keyName string,
amount ibc.WalletAmount,
options ibc.TransferOptions,
) (string, error) {
command := []string{
"ibc-transfer", "transfer", "transfer", channelID,
amount.Address, fmt.Sprintf("%d%s", amount.Amount, amount.Denom),
}
if options.Timeout != nil {
if options.Timeout.NanoSeconds > 0 {
command = append(command, "--packet-timeout-timestamp", fmt.Sprint(options.Timeout.NanoSeconds))
} else if options.Timeout.Height > 0 {
command = append(command, "--packet-timeout-height", fmt.Sprintf("0-%d", options.Timeout.Height))
}
}
if options.Memo != "" {
command = append(command, "--memo", options.Memo)
}
return tn.ExecTx(ctx, keyName, command...)
}
func (tn *ChainNode) SendFunds(ctx context.Context, keyName string, amount ibc.WalletAmount) error {
_, err := tn.ExecTx(ctx,
keyName, "bank", "send", keyName,
amount.Address, fmt.Sprintf("%d%s", amount.Amount, amount.Denom),
)
return err
}
type InstantiateContractAttribute struct {
Value string `json:"value"`
}
type InstantiateContractEvent struct {
Attributes []InstantiateContractAttribute `json:"attributes"`
}
type InstantiateContractLog struct {
Events []InstantiateContractEvent `json:"event"`
}
type InstantiateContractResponse struct {
Logs []InstantiateContractLog `json:"log"`
}
type QueryContractResponse struct {
Contracts []string `json:"contracts"`
}
type CodeInfo struct {
CodeID string `json:"code_id"`
}
type CodeInfosResponse struct {
CodeInfos []CodeInfo `json:"code_infos"`
}
// StoreContract takes a file path to smart contract and stores it on-chain. Returns the contracts code id.
func (tn *ChainNode) StoreContract(ctx context.Context, keyName string, fileName string) (string, error) {
_, file := filepath.Split(fileName)
err := tn.CopyFile(ctx, fileName, file)
if err != nil {
return "", fmt.Errorf("writing contract file to docker volume: %w", err)
}
if _, err := tn.ExecTx(ctx, keyName, "wasm", "store", path.Join(tn.HomeDir(), file), "--gas", "auto"); err != nil {
return "", err
}
err = testutil.WaitForBlocks(ctx, 5, tn.Chain)
if err != nil {
return "", fmt.Errorf("wait for blocks: %w", err)
}
stdout, _, err := tn.ExecQuery(ctx, "wasm", "list-code", "--reverse")
if err != nil {
return "", err
}
res := CodeInfosResponse{}
if err := json.Unmarshal([]byte(stdout), &res); err != nil {
return "", err
}
return res.CodeInfos[0].CodeID, nil
}
func (tn *ChainNode) getTransaction(clientCtx client.Context, txHash string) (*types.TxResponse, error) {
// Retry because sometimes the tx is not committed to state yet.
var txResp *types.TxResponse
err := retry.Do(func() error {
var err error
txResp, err = authTx.QueryTx(clientCtx, txHash)
return err
},
// retry for total of 3 seconds
retry.Attempts(15),
retry.Delay(200*time.Millisecond),
retry.DelayType(retry.FixedDelay),
retry.LastErrorOnly(true),
)
return txResp, err
}
// InstantiateContract takes a code id for a smart contract and initialization message and returns the instantiated contract address.
func (tn *ChainNode) InstantiateContract(ctx context.Context, keyName string, codeID string, initMessage string, needsNoAdminFlag bool, extraExecTxArgs ...string) (string, error) {
command := []string{"wasm", "instantiate", codeID, initMessage, "--label", "wasm-contract"}
command = append(command, extraExecTxArgs...)
if needsNoAdminFlag {
command = append(command, "--no-admin")
}
txHash, err := tn.ExecTx(ctx, keyName, command...)
if err != nil {
return "", err
}
txResp, err := tn.getTransaction(tn.CliContext(), txHash)
if err != nil {
return "", fmt.Errorf("failed to get transaction %s: %w", txHash, err)
}
if txResp.Code != 0 {
return "", fmt.Errorf("error in transaction (code: %d): %s", txResp.Code, txResp.RawLog)
}
stdout, _, err := tn.ExecQuery(ctx, "wasm", "list-contract-by-code", codeID)
if err != nil {
return "", err
}
contactsRes := QueryContractResponse{}
if err := json.Unmarshal([]byte(stdout), &contactsRes); err != nil {
return "", err
}
contractAddress := contactsRes.Contracts[len(contactsRes.Contracts)-1]
return contractAddress, nil
}
// ExecuteContract executes a contract transaction with a message using it's address.
func (tn *ChainNode) ExecuteContract(ctx context.Context, keyName string, contractAddress string, message string) (txHash string, err error) {
return tn.ExecTx(ctx, keyName,
"wasm", "execute", contractAddress, message,
)
}
// QueryContract performs a smart query, taking in a query struct and returning a error with the response struct populated.
func (tn *ChainNode) QueryContract(ctx context.Context, contractAddress string, queryMsg any, response any) error {
query, err := json.Marshal(queryMsg)
if err != nil {
return err
}
stdout, _, err := tn.ExecQuery(ctx, "wasm", "contract-state", "smart", contractAddress, string(query))
if err != nil {
return err
}
err = json.Unmarshal([]byte(stdout), response)
return err
}
// StoreClientContract takes a file path to a client smart contract and stores it on-chain. Returns the contracts code id.
func (tn *ChainNode) StoreClientContract(ctx context.Context, keyName string, fileName string) (string, error) {
content, err := os.ReadFile(fileName)
if err != nil {
return "", err
}
_, file := filepath.Split(fileName)
err = tn.WriteFile(ctx, content, file)
if err != nil {
return "", fmt.Errorf("writing contract file to docker volume: %w", err)
}
_, err = tn.ExecTx(ctx, keyName, "ibc-wasm", "store-code", path.Join(tn.HomeDir(), file), "--gas", "auto")
if err != nil {
return "", err
}
codeHashByte32 := sha256.Sum256(content)
codeHash := hex.EncodeToString(codeHashByte32[:])
//return stdout, nil
return codeHash, nil
}
// QueryClientContractCode performs a query with the contract codeHash as the input and code as the output
func (tn *ChainNode) QueryClientContractCode(ctx context.Context, codeHash string, response any) error {
stdout, _, err := tn.ExecQuery(ctx, "ibc-wasm", "code", codeHash)
if err != nil {
return err
}
err = json.Unmarshal([]byte(stdout), response)
return err
}
// VoteOnProposal submits a vote for the specified proposal.
func (tn *ChainNode) VoteOnProposal(ctx context.Context, keyName string, proposalID string, vote string) error {
_, err := tn.ExecTx(ctx, keyName,
"gov", "vote",
proposalID, vote, "--gas", "auto",
)
return err
}
// QueryProposal returns the state and details of a governance proposal.
func (tn *ChainNode) QueryProposal(ctx context.Context, proposalID string) (*ProposalResponse, error) {
stdout, _, err := tn.ExecQuery(ctx, "gov", "proposal", proposalID)
if err != nil {
return nil, err
}
var proposal ProposalResponse
err = json.Unmarshal(stdout, &proposal)
if err != nil {
return nil, err
}
return &proposal, nil
}
// SubmitProposal submits a gov v1 proposal to the chain.
func (tn *ChainNode) SubmitProposal(ctx context.Context, keyName string, prop TxProposalv1) (string, error) {
// Write msg to container
file := "proposal.json"
propJson, err := json.MarshalIndent(prop, "", " ")
if err != nil {
return "", err
}
fw := dockerutil.NewFileWriter(tn.logger(), tn.DockerClient, tn.TestName)
if err := fw.WriteFile(ctx, tn.VolumeName, file, propJson); err != nil {
return "", fmt.Errorf("writing contract file to docker volume: %w", err)
}
command := []string{
"gov", "submit-proposal",
path.Join(tn.HomeDir(), file), "--gas", "auto",
}
return tn.ExecTx(ctx, keyName, command...)
}
// UpgradeProposal submits a software-upgrade governance proposal to the chain.
func (tn *ChainNode) UpgradeProposal(ctx context.Context, keyName string, prop SoftwareUpgradeProposal) (string, error) {
command := []string{
"gov", "submit-proposal",
"software-upgrade", prop.Name,
"--upgrade-height", strconv.FormatUint(prop.Height, 10),
"--title", prop.Title,
"--description", prop.Description,
"--deposit", prop.Deposit,
}
if prop.Info != "" {
command = append(command, "--upgrade-info", prop.Info)
}
return tn.ExecTx(ctx, keyName, command...)
}
// TextProposal submits a text governance proposal to the chain.
func (tn *ChainNode) TextProposal(ctx context.Context, keyName string, prop TextProposal) (string, error) {
command := []string{
"gov", "submit-proposal",
"--type", "text",
"--title", prop.Title,
"--description", prop.Description,
"--deposit", prop.Deposit,
}
if prop.Expedited {
command = append(command, "--is-expedited=true")
}
return tn.ExecTx(ctx, keyName, command...)
}
// ParamChangeProposal submits a param change proposal to the chain, signed by keyName.
func (tn *ChainNode) ParamChangeProposal(ctx context.Context, keyName string, prop *paramsutils.ParamChangeProposalJSON) (string, error) {
content, err := json.Marshal(prop)
if err != nil {
return "", err
}
hash := sha256.Sum256(content)
proposalFilename := fmt.Sprintf("%x.json", hash)
err = tn.WriteFile(ctx, content, proposalFilename)
if err != nil {
return "", fmt.Errorf("writing param change proposal: %w", err)
}
proposalPath := filepath.Join(tn.HomeDir(), proposalFilename)
command := []string{
"gov", "submit-proposal",
"param-change",
proposalPath,
}
return tn.ExecTx(ctx, keyName, command...)
}
// QueryParam returns the state and details of a subspace param.
func (tn *ChainNode) QueryParam(ctx context.Context, subspace, key string) (*ParamChange, error) {
stdout, _, err := tn.ExecQuery(ctx, "params", "subspace", subspace, key)
if err != nil {
return nil, err
}
var param ParamChange
err = json.Unmarshal(stdout, ¶m)
if err != nil {
return nil, err
}
return ¶m, nil
}
// DumpContractState dumps the state of a contract at a block height.
func (tn *ChainNode) DumpContractState(ctx context.Context, contractAddress string, height int64) (*DumpContractStateResponse, error) {
stdout, _, err := tn.ExecQuery(ctx,
"wasm", "contract-state", "all", contractAddress,
"--height", fmt.Sprint(height),
)
if err != nil {
return nil, err
}
res := new(DumpContractStateResponse)
if err := json.Unmarshal([]byte(stdout), res); err != nil {
return nil, err
}
return res, nil
}
func (tn *ChainNode) ExportState(ctx context.Context, height int64) (string, error) {
tn.lock.Lock()
defer tn.lock.Unlock()
stdout, stderr, err := tn.ExecBin(ctx, "export", "--height", fmt.Sprint(height))