From cea56bb49d7e952068951788a7f5ef3109369ebe Mon Sep 17 00:00:00 2001 From: Dan Kanefsky <56059752+boojamya@users.noreply.github.com> Date: Tue, 24 Sep 2024 11:43:03 -0700 Subject: [PATCH 1/5] feat: add override arg to Go relayer's create-channel (#1266) --- ibc/relayer.go | 2 ++ relayer/rly/cosmos_relayer.go | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/ibc/relayer.go b/ibc/relayer.go index 0739f16df..6589796ef 100644 --- a/ibc/relayer.go +++ b/ibc/relayer.go @@ -216,6 +216,8 @@ type CreateChannelOptions struct { Order Order Version string + + Override bool // only implemented on Go Relayer } // DefaultChannelOpts returns the default settings for creating an ics20 fungible token transfer channel. diff --git a/relayer/rly/cosmos_relayer.go b/relayer/rly/cosmos_relayer.go index d6debbcf8..35a531beb 100644 --- a/relayer/rly/cosmos_relayer.go +++ b/relayer/rly/cosmos_relayer.go @@ -130,7 +130,7 @@ func (commander) AddKey(chainID, keyName, coinType, signingAlgorithm, homeDir st } func (commander) CreateChannel(pathName string, opts ibc.CreateChannelOptions, homeDir string) []string { - return []string{ + cmd := []string{ "rly", "tx", "channel", pathName, "--src-port", opts.SourcePortName, "--dst-port", opts.DestPortName, @@ -139,6 +139,10 @@ func (commander) CreateChannel(pathName string, opts ibc.CreateChannelOptions, h "--home", homeDir, } + if opts.Override { + cmd = append(cmd, "--override") + } + return cmd } func createClientOptsHelper(opts ibc.CreateClientOptions) []string { From 84fb92b01b782785b25912abe3aa51495b56a685 Mon Sep 17 00:00:00 2001 From: Steve <1848680+misko9@users.noreply.github.com> Date: Wed, 25 Sep 2024 12:16:27 -0600 Subject: [PATCH 2/5] feat(thorchain): v50 support, update bank's genesis supply when adding bond module balance (#1267) --- chain/thorchain/thornode.go | 48 +++++++++++++++++-- ...ochains.go => chainspec_exochains_test.go} | 0 ...orchain.go => chainspec_thorchain_test.go} | 2 +- .../thorchain/{helper.go => helper_test.go} | 0 .../thorchain/{setup.go => setup_test.go} | 0 5 files changed, 45 insertions(+), 5 deletions(-) rename examples/thorchain/{chainspec_exochains.go => chainspec_exochains_test.go} (100%) rename examples/thorchain/{chainspec_thorchain.go => chainspec_thorchain_test.go} (99%) rename examples/thorchain/{helper.go => helper_test.go} (100%) rename examples/thorchain/{setup.go => setup_test.go} (100%) diff --git a/chain/thorchain/thornode.go b/chain/thorchain/thornode.go index b7c8d9309..1e764e747 100644 --- a/chain/thorchain/thornode.go +++ b/chain/thorchain/thornode.go @@ -23,6 +23,7 @@ import ( rpchttp "github.com/cometbft/cometbft/rpc/client/http" coretypes "github.com/cometbft/cometbft/rpc/core/types" libclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" + sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" @@ -357,7 +358,7 @@ func (tn *ChainNode) SetTestConfig(ctx context.Context) error { // Enable public REST API api["enable"] = true - api["swagger"] = false + api["swagger"] = true api["address"] = "tcp://0.0.0.0:1317" api["enabled-unsafe-cors"] = true @@ -721,13 +722,13 @@ EOF stdout, _, err := tn.Exec(ctx, command, tn.Chain.Config().Env) if err != nil { - return err + return fmt.Errorf("create key sdtout:\n%s\n, error: %w", string(stdout), err) } if tn.Validator && tn.ValidatorMnemonic == "" { var createKeyOutput map[string]string if err := json.Unmarshal(stdout, &createKeyOutput); err != nil { - return err + return fmt.Errorf("unmarshal create key sdtout:\n%s\n, error: %w", string(stdout), err) } tn.ValidatorMnemonic = createKeyOutput["mnemonic"] @@ -1071,7 +1072,7 @@ func (tn *ChainNode) AddBondModule(ctx context.Context) error { Coins: []CoinBalance{ { Denom: "rune", - Amount: fmt.Sprintf("%d0000000000000", tn.Chain.(*Thorchain).NumValidators), + Amount: fmt.Sprintf("%d00000000", tn.Chain.(*Thorchain).NumValidators), }, }, } @@ -1095,6 +1096,45 @@ func (tn *ChainNode) AddBondModule(ctx context.Context) error { } } + // Now update bank's supply with new balance if on v50 + if tn.IsAboveSDK47(ctx) { + bankSupplyPath := "app_state.bank.supply" + splitPath = strings.Split(bankSupplyPath, ".") + path = make([]interface{}, len(splitPath)) + for i, component := range splitPath { + if v, err := strconv.Atoi(component); err == nil { + path[i] = v + } else { + path[i] = component + } + } + supplyI, err := dyno.GetSlice(g, path...) + if err != nil { + return fmt.Errorf("failed to get key %s in genesis json", bankSupplyPath) + } + + for i, coinI := range supplyI { + coin := coinI.(map[string]interface{}) + if coin["denom"].(string) == "rune" { + originalAmount, ok := sdkmath.NewIntFromString(coin["amount"].(string)) + if !ok { + return fmt.Errorf("failed to convert bank's supply of rune to sdk Int from string") + } + addAmount, ok := sdkmath.NewIntFromString(bondBalance.Coins[0].Amount) + if !ok { + return fmt.Errorf("failed to convert bond amount of rune to sdk Int from string") + } + coin["amount"] = originalAmount.Add(addAmount).String() + supplyI[i] = coin + break + } + } + + if err := dyno.Set(g, supplyI, path...); err != nil { + return fmt.Errorf("failed to set bank's new supply") + } + } + genbz, err = json.Marshal(g) if err != nil { return fmt.Errorf("failed to marshal genesis bytes to json: %w", err) diff --git a/examples/thorchain/chainspec_exochains.go b/examples/thorchain/chainspec_exochains_test.go similarity index 100% rename from examples/thorchain/chainspec_exochains.go rename to examples/thorchain/chainspec_exochains_test.go diff --git a/examples/thorchain/chainspec_thorchain.go b/examples/thorchain/chainspec_thorchain_test.go similarity index 99% rename from examples/thorchain/chainspec_thorchain.go rename to examples/thorchain/chainspec_thorchain_test.go index de750d711..4398e269e 100644 --- a/examples/thorchain/chainspec_thorchain.go +++ b/examples/thorchain/chainspec_thorchain_test.go @@ -30,7 +30,7 @@ func ThorchainDefaultChainSpec(testName string, numVals int, numFn int, ethRoute name := common.THORChain.String() // Must use this name for test chainImage := ibc.NewDockerImage("thorchain", "local", "1025:1025") genesisKVMods := []thorchain.GenesisKV{ - thorchain.NewGenesisKV("app_state.bank.params.default_send_enabled", false), // disable bank module transfers + thorchain.NewGenesisKV("app_state.bank.params.default_send_enabled", true), // disable bank module transfers thorchain.NewGenesisKV("app_state.thorchain.reserve", "22000000000000000"), // mint to reserve for mocknet (220M) thorchain.NewGenesisKV("app_state.thorchain.chain_contracts", []ChainContract{ { diff --git a/examples/thorchain/helper.go b/examples/thorchain/helper_test.go similarity index 100% rename from examples/thorchain/helper.go rename to examples/thorchain/helper_test.go diff --git a/examples/thorchain/setup.go b/examples/thorchain/setup_test.go similarity index 100% rename from examples/thorchain/setup.go rename to examples/thorchain/setup_test.go From 9ac38ccbef082d59502c7803d9f4cc8eaaedc92b Mon Sep 17 00:00:00 2001 From: Justin Tieri <37750742+jtieri@users.noreply.github.com> Date: Sun, 29 Sep 2024 14:42:13 -0500 Subject: [PATCH 3/5] ci: add new CI jobs and bring existing ones into compliance (#1233) --- .codespellrc | 3 +- .github/workflows/chores.yml | 35 ------ .github/workflows/codeql-analysis.yml | 61 ++++++++++ .github/workflows/lint.yml | 71 +++++++----- .github/workflows/markdown-link-check.yml | 11 ++ .github/workflows/release.yml | 4 +- .github/workflows/spell-check.yml | 24 ++++ .github/workflows/title-format.yml | 20 ++++ .golangci.yml | 69 ++++++++++++ blockdb/collect_test.go | 2 +- blockdb/messages_view_test.go | 6 +- blockdb/query_test.go | 9 +- blockdb/sql.go | 2 +- blockdb/tui/presenter/cosmos_message.go | 2 +- blockdb/tui/style.go | 4 +- chain/cosmos/08-wasm-types/client_state.go | 9 +- chain/cosmos/08-wasm-types/codec.go | 4 +- chain/cosmos/08-wasm-types/module.go | 8 +- chain/cosmos/08-wasm-types/msgs.go | 4 +- chain/cosmos/account_retriever.go | 2 +- chain/cosmos/address.go | 2 +- chain/cosmos/broadcaster.go | 7 +- chain/cosmos/chain_node.go | 104 +++++++++--------- chain/cosmos/codec.go | 16 +-- chain/cosmos/cosmos_chain.go | 90 +++++++-------- chain/cosmos/ics.go | 18 +-- chain/cosmos/module_auth.go | 23 ++-- chain/cosmos/module_authz.go | 4 +- chain/cosmos/module_bank.go | 14 +-- chain/cosmos/module_cosmwasm.go | 5 +- chain/cosmos/module_distribution.go | 20 ++-- chain/cosmos/module_gov.go | 5 +- chain/cosmos/module_slashing.go | 6 +- chain/cosmos/module_tokenfactory.go | 2 +- chain/cosmos/module_upgrade.go | 3 +- chain/cosmos/module_vesting.go | 3 +- chain/cosmos/node_test.go | 3 +- chain/cosmos/osmosis.go | 2 +- chain/cosmos/poll.go | 8 +- chain/cosmos/query.go | 3 +- chain/cosmos/sidecar.go | 7 +- chain/cosmos/types.go | 2 +- chain/cosmos/wallet.go | 15 ++- chain/cosmos/wasm/wasm.go | 6 +- chain/ethereum/ethererum_chain.go | 7 +- chain/ethereum/foundry/anvil_chain.go | 5 +- chain/ethereum/foundry/forge.go | 10 +- chain/ethereum/geth/default_configs.go | 6 +- chain/ethereum/geth/geth_chain.go | 18 +-- chain/ethereum/wallet.go | 6 +- chain/internal/tendermint/events_test.go | 3 +- chain/internal/tendermint/tendermint_node.go | 62 ++++++----- chain/penumbra/penumbra_app_node.go | 11 +- chain/penumbra/penumbra_chain.go | 18 +-- chain/penumbra/penumbra_client_node.go | 16 +-- chain/penumbra/penumbra_client_node_test.go | 5 +- chain/penumbra/wallet.go | 2 +- chain/polkadot/keys.go | 11 +- chain/polkadot/parachain_node.go | 18 +-- chain/polkadot/polkadot_chain.go | 37 ++++--- chain/polkadot/query.go | 5 +- chain/polkadot/relay_chain_node.go | 13 +-- chain/polkadot/ss58.go | 2 +- chain/polkadot/tx.go | 10 +- chain/polkadot/wallet.go | 4 +- chain/thorchain/account_retriever.go | 3 +- chain/thorchain/address.go | 3 +- chain/thorchain/api_query.go | 4 +- chain/thorchain/broadcaster.go | 7 +- chain/thorchain/codec.go | 11 +- chain/thorchain/common/chain.go | 10 +- chain/thorchain/module_bank.go | 14 +-- chain/thorchain/module_thorchain.go | 4 +- chain/thorchain/poll.go | 6 +- chain/thorchain/query.go | 3 +- chain/thorchain/sidecar.go | 7 +- chain/thorchain/thorchain.go | 68 ++++++------ chain/thorchain/thornode.go | 98 ++++++++--------- chain/thorchain/types.go | 42 +++---- chain/thorchain/wallet.go | 15 ++- chain/utxo/cli.go | 4 +- chain/utxo/default_configs.go | 4 +- chain/utxo/utxo_chain.go | 12 +- chain/utxo/wallet.go | 6 +- chainfactory.go | 9 +- chainset.go | 1 - cmd/interchaintest/interchaintest_test.go | 2 +- cmd/interchaintest/matrix_test.go | 3 +- conformance/flush.go | 6 +- conformance/relayersetup.go | 5 +- conformance/test.go | 8 +- contract/cosmwasm/compile.go | 2 +- contract/cosmwasm/rust_optimizer.go | 8 +- contract/cosmwasm/workspace_optimizer.go | 10 +- dockerutil/container_lifecycle.go | 3 +- dockerutil/file.go | 2 +- dockerutil/filewriter.go | 2 +- dockerutil/image_test.go | 2 +- dockerutil/keyring.go | 3 +- dockerutil/setup.go | 4 +- dockerutil/strings.go | 2 +- docs/CODE_OF_CONDUCT.md | 43 ++++++++ docs/envOptions.md | 2 +- examples/cosmos/chain_core_test.go | 2 - examples/cosmos/chain_genesis_stake_test.go | 1 - examples/cosmos/chain_miscellaneous_test.go | 1 - examples/cosmos/chain_param_change_test.go | 2 +- examples/cosmos/chain_upgrade_ibc_test.go | 2 +- examples/cosmos/cometmock_test.go | 1 - examples/cosmos/sdk_boundary_test.go | 12 +- examples/hyperspace/hyperspace_test.go | 2 +- examples/ibc/client_creation_test.go | 4 +- examples/ibc/ics_test.go | 1 - examples/ibc/learn_ibc_test.go | 3 +- examples/ibc/wasm/wasm_ibc_test.go | 1 - examples/ibc/wasm/wasm_icq_test.go | 43 ++++---- examples/penumbra/penumbra_ibc_test.go | 4 +- examples/polkadot/polkadot_chain_test.go | 2 +- .../polkadot/push_wasm_client_code_test.go | 47 ++++---- .../polkadot/substrate_cosmos_ibc_test.go | 18 +-- .../contracts/lib/forge-std/src/Vm.sol | 2 +- examples/thorchain/features/arb.go | 2 +- examples/thorchain/features/helpers.go | 2 - examples/thorchain/thorchain_test.go | 4 +- examples/utxo/start_test.go | 1 - ibc/chain.go | 3 +- ibc/packet.go | 5 +- ibc/relayer.go | 4 +- ibc/relayer_test.go | 3 +- ibc/types.go | 11 +- interchain.go | 3 +- interchain_builder.go | 5 +- interchain_test.go | 16 +-- interchaintest.go | 4 +- local-interchain/cmd/local-ic/interaction.go | 1 - local-interchain/cmd/local-ic/root.go | 6 +- local-interchain/interchain/genesis.go | 3 - .../interchain/handlers/chain_registry.go | 3 +- local-interchain/interchain/logs.go | 3 +- local-interchain/interchain/router/router.go | 1 - .../interchain/types/chain_builder.go | 4 +- .../interchain/types/chains_test.go | 1 - local-interchain/interchain/types/types.go | 6 +- mocktesting/t.go | 2 +- relayer/docker.go | 5 +- relayer/hermes/hermes_commander.go | 1 - relayer/hermes/hermes_relayer.go | 2 +- relayer/hermes/hermes_wallet.go | 4 +- relayer/hyperspace/hyperspace_commander.go | 42 +++---- relayer/hyperspace/hyperspace_config.go | 8 +- relayer/hyperspace/hyperspace_relayer.go | 3 +- relayer/hyperspace/wallet.go | 4 +- relayer/rly/cosmos_relayer.go | 3 +- relayer/rly/wallet.go | 4 +- test_setup.go | 2 +- test_user.go | 3 +- testutil/gzip.go | 2 +- testutil/poll_for_state.go | 6 +- 158 files changed, 995 insertions(+), 760 deletions(-) delete mode 100644 .github/workflows/chores.yml create mode 100644 .github/workflows/codeql-analysis.yml create mode 100644 .github/workflows/markdown-link-check.yml create mode 100644 .github/workflows/spell-check.yml create mode 100644 .github/workflows/title-format.yml create mode 100644 .golangci.yml create mode 100644 docs/CODE_OF_CONDUCT.md diff --git a/.codespellrc b/.codespellrc index e393c29a7..f2350b52f 100644 --- a/.codespellrc +++ b/.codespellrc @@ -1,5 +1,4 @@ [codespell] -skip = *.pulsar.go,*.pb.go,*.pb.gw.go,*.json,*.git,*.bin,*.sum,*.mod,query_test.go +skip = *.pulsar.go,*.pb.go,*.pb.gw.go,*.json,*.git,*.bin,*.sum,*.mod,query_test.go,*.sol ignore-words-list = usera,pres,crate -count = quiet-level = 3 \ No newline at end of file diff --git a/.github/workflows/chores.yml b/.github/workflows/chores.yml deleted file mode 100644 index 83c577016..000000000 --- a/.github/workflows/chores.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: chores - -on: - pull_request: - -jobs: - link-check: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: gaurav-nelson/github-action-markdown-link-check@1.0.15 - - typos: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - name: Run codespell - continue-on-error: true - run: | - # .codespellrc is used - sudo apt-get install codespell -y - codespell -w --config .codespellrc - exit $? - - pr-title-format: - name: Lint PR Title - permissions: - pull-requests: read - statuses: write - contents: read - runs-on: ubuntu-latest - steps: - - uses: amannn/action-semantic-pull-request@v5 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 000000000..bd9acccf4 --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,61 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +name: "CodeQL" + +on: + push: + branches: [ main ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ main ] + schedule: + - cron: '59 23 * * 5' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'go' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] + # Learn more: + # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main + + # Autobuild attempts to build any compiled languages. + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v3 + + # ✏️ If the Autobuild fails above, remove it and uncomment the following lines + # and modify them (or add more) to build your code. + + #- run: | + # make install + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 \ No newline at end of file diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 2a4ca6a4b..8f35b408e 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -1,41 +1,54 @@ -name: golangci-lint +# Lint the entire golang project. This workflow relies on the +# '.golangci.yml' file for its configuration settings. +name: Lint on: + push: + tags: + - v* + branches: + - master + - main pull_request: +permissions: + contents: read + +env: + GO_VERSION: 1.22 + jobs: + clippy-lint: + defaults: + run: + working-directory: local-interchain/rust/localic-std + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install stable with clippy and rustfmt + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + components: rustfmt, clippy + - name: Install clippy + run: rustup component add clippy + - name: Update + run: cargo update + - name: Run clippy + run: make lint + golangci: - name: lint + name: golangci-lint runs-on: ubuntu-latest steps: - uses: actions/setup-go@v5 with: - go-version: '1.21' - cache: false + go-version: ${{ env.GO_VERSION }} + - uses: actions/checkout@v4 + - name: golangci-lint - uses: golangci/golangci-lint-action@v4 + uses: golangci/golangci-lint-action@v6.1.0 with: - version: v1.54 - only-new-issues: true - args: --timeout=10m - - clippy-lint: - defaults: - run: - working-directory: local-interchain/rust/localic-std - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - name: Install stable with clippy and rustfmt - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: stable - components: rustfmt, clippy - - name: Install clippy - run: rustup component add clippy - - name: Update - run: cargo update - - name: Run clippy - run: make lint - + version: v1.57.2 + args: --timeout 15m \ No newline at end of file diff --git a/.github/workflows/markdown-link-check.yml b/.github/workflows/markdown-link-check.yml new file mode 100644 index 000000000..3daf692b8 --- /dev/null +++ b/.github/workflows/markdown-link-check.yml @@ -0,0 +1,11 @@ +name: Markdown Link Check + +on: + pull_request: + +jobs: + link-check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: gaurav-nelson/github-action-markdown-link-check@1.0.15 \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 70a261d78..40440e00e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,7 +5,7 @@ on: types: [created] env: - GO_VERSION: 1.21 + GO_VERSION: 1.21 jobs: release-static-binary: @@ -18,7 +18,7 @@ jobs: - name: Setup go ${{ env.GO_VERSION }} uses: actions/setup-go@v5 with: - go-version: ${{ env.GO_VERSION }} + go-version: ${{ env.GO_VERSION }} # NOTE: make install must not be statically linked to the MakeFileInstallDirectory - run: cd local-interchain && go mod tidy && IGNORE_STATIC_LINK=true make install diff --git a/.github/workflows/spell-check.yml b/.github/workflows/spell-check.yml new file mode 100644 index 000000000..96ef19cc4 --- /dev/null +++ b/.github/workflows/spell-check.yml @@ -0,0 +1,24 @@ +name: Spell Check + +on: + pull_request: + +jobs: + spellcheck: + name: Run codespell + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.x' + + - name: Install codespell + run: pip install codespell + + - name: Run codespell + run: codespell \ No newline at end of file diff --git a/.github/workflows/title-format.yml b/.github/workflows/title-format.yml new file mode 100644 index 000000000..b5e7d1a95 --- /dev/null +++ b/.github/workflows/title-format.yml @@ -0,0 +1,20 @@ +name: "Lint PR Title" + +on: + pull_request_target: + types: + - opened + - edited + - synchronize + +permissions: + pull-requests: read + +jobs: + main: + name: Validate PR title + runs-on: ubuntu-latest + steps: + - uses: amannn/action-semantic-pull-request@v5 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..2b13f2610 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,69 @@ +run: + timeout: 10m + tests: true + +# These linter checks can be modified on a per project basis. +# Simply remove them from the enable list to disable them. +linters: + disable-all: true + enable: + - asciicheck + - bidichk + - bodyclose + - decorder + - dupl + - dupword + - errcheck + - errchkjson + - errname + - exhaustive + - exportloopref + - forbidigo + - gci + - goconst + - gocritic + - godot + - gofumpt + - gosec + - gosimple + - gosmopolitan + - govet + - grouper + - ineffassign + - loggercheck + - misspell + - nilerr + - nilnil + - noctx + - staticcheck + - stylecheck + - testifylint + - thelper + - tparallel + - typecheck + - unconvert + - unparam + - unused + - usestdlibvars + - wastedassign + - whitespace + +linters-settings: + gci: + custom-order: true + sections: + - standard # Standard section: captures all standard packages. + - default # Default section: contains all imports that could not be matched to another section type. + - blank # blank imports + - dot # dot imports + - prefix(cosmossdk.io) + - prefix(github.com/cosmos) + - prefix(github.com/cosmos/cosmos-sdk) + - prefix(github.com/cometbft/cometbft) + - prefix(github.com/strangelove-ventures/interchaintest) + gosec: + excludes: + - G404 # disables checks on insecure random number source + +issues: + max-issues-per-linter: 0 \ No newline at end of file diff --git a/blockdb/collect_test.go b/blockdb/collect_test.go index 2a6159aae..f5106c8dd 100644 --- a/blockdb/collect_test.go +++ b/blockdb/collect_test.go @@ -59,7 +59,7 @@ func TestCollector_Collect(t *testing.T) { savedHeights = append(savedHeights, int(height)) savedTxs = append(savedTxs, txs) } - atomic.SwapInt64(¤tHeight, int64(height)) + atomic.SwapInt64(¤tHeight, height) return nil }) diff --git a/blockdb/messages_view_test.go b/blockdb/messages_view_test.go index 442c563a7..2b23a0a8d 100644 --- a/blockdb/messages_view_test.go +++ b/blockdb/messages_view_test.go @@ -9,8 +9,6 @@ import ( "path/filepath" "testing" - "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/types" "github.com/strangelove-ventures/interchaintest/v8" "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/relayer" @@ -18,6 +16,10 @@ import ( "github.com/strangelove-ventures/interchaintest/v8/testutil" "github.com/stretchr/testify/require" "go.uber.org/zap/zaptest" + + "cosmossdk.io/math" + + "github.com/cosmos/cosmos-sdk/types" ) func TestMessagesView(t *testing.T) { diff --git a/blockdb/query_test.go b/blockdb/query_test.go index d4c5d705c..5268ee7c5 100644 --- a/blockdb/query_test.go +++ b/blockdb/query_test.go @@ -2,20 +2,19 @@ package blockdb import ( "context" - _ "embed" "encoding/json" "strings" "testing" "time" "github.com/stretchr/testify/require" -) -var ( - //go:embed testdata/sample_txs.json - txsFixture []byte + _ "embed" ) +//go:embed testdata/sample_txs.json +var txsFixture []byte + func TestQuery_CurrentSchemaVersion(t *testing.T) { t.Parallel() diff --git a/blockdb/sql.go b/blockdb/sql.go index 75f4288c4..459ce9ada 100644 --- a/blockdb/sql.go +++ b/blockdb/sql.go @@ -17,7 +17,7 @@ import ( // Pass :memory: as databasePath for in-memory database. func ConnectDB(ctx context.Context, databasePath string) (*sql.DB, error) { if databasePath != ":memory:" { - if err := os.MkdirAll(filepath.Dir(databasePath), 0755); err != nil { + if err := os.MkdirAll(filepath.Dir(databasePath), 0o755); err != nil { return nil, err } } diff --git a/blockdb/tui/presenter/cosmos_message.go b/blockdb/tui/presenter/cosmos_message.go index 1f29a9a21..4da9cfb32 100644 --- a/blockdb/tui/presenter/cosmos_message.go +++ b/blockdb/tui/presenter/cosmos_message.go @@ -17,7 +17,7 @@ func (msg CosmosMessage) Height() string { return strconv.FormatInt(msg.Result.H // Index is the message's ordered position within the tx. func (msg CosmosMessage) Index() string { return strconv.Itoa(msg.Result.Index) } -// Type is a URI for the proto definition, e.g. /ibc.core.client.v1.MsgCreateClient +// Type is a URI for the proto definition, e.g. /ibc.core.client.v1.MsgCreateClient. func (msg CosmosMessage) Type() string { return msg.Result.Type } func (msg CosmosMessage) ClientChain() string { return msg.Result.ClientChainID.String } diff --git a/blockdb/tui/style.go b/blockdb/tui/style.go index 9a8a4eee1..9fd3f0c0a 100644 --- a/blockdb/tui/style.go +++ b/blockdb/tui/style.go @@ -8,6 +8,4 @@ const ( errorTextColor = tcell.ColorRed ) -var ( - textStyle = tcell.Style{}.Foreground(textColor) -) +var textStyle = tcell.Style{}.Foreground(textColor) diff --git a/chain/cosmos/08-wasm-types/client_state.go b/chain/cosmos/08-wasm-types/client_state.go index f607d6f80..bc5e91291 100644 --- a/chain/cosmos/08-wasm-types/client_state.go +++ b/chain/cosmos/08-wasm-types/client_state.go @@ -2,10 +2,12 @@ package types import ( storetypes "cosmossdk.io/store/types" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" + clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" // nolint:staticcheck "github.com/cosmos/ibc-go/v8/modules/core/exported" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" ) var _ exported.ClientState = (*ClientState)(nil) @@ -86,9 +88,8 @@ func (c ClientState) CheckForMisbehaviour(ctx sdk.Context, cdc codec.BinaryCodec return true } -// UpdateStateOnMisbehaviour should perform appropriate state changes on a client state given that misbehaviour has been detected and verified +// UpdateStateOnMisbehaviour should perform appropriate state changes on a client state given that misbehaviour has been detected and verified. func (c ClientState) UpdateStateOnMisbehaviour(ctx sdk.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, clientMsg exported.ClientMessage) { - } func (c ClientState) UpdateState(ctx sdk.Context, cdc codec.BinaryCodec, clientStore storetypes.KVStore, clientMsg exported.ClientMessage) []exported.Height { diff --git a/chain/cosmos/08-wasm-types/codec.go b/chain/cosmos/08-wasm-types/codec.go index 324016496..be73b5693 100644 --- a/chain/cosmos/08-wasm-types/codec.go +++ b/chain/cosmos/08-wasm-types/codec.go @@ -1,11 +1,11 @@ package types import ( + "github.com/cosmos/ibc-go/v8/modules/core/exported" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" - - "github.com/cosmos/ibc-go/v8/modules/core/exported" ) // RegisterInterfaces registers the tendermint concrete client-related diff --git a/chain/cosmos/08-wasm-types/module.go b/chain/cosmos/08-wasm-types/module.go index 013890c0e..11b8aa32e 100644 --- a/chain/cosmos/08-wasm-types/module.go +++ b/chain/cosmos/08-wasm-types/module.go @@ -3,14 +3,14 @@ package types import ( "encoding/json" + // grpc "github.com/cosmos/gogoproto/grpc". + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module" - - //grpc "github.com/cosmos/gogoproto/grpc" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" ) var _ module.AppModuleBasic = AppModuleBasic{} diff --git a/chain/cosmos/08-wasm-types/msgs.go b/chain/cosmos/08-wasm-types/msgs.go index efe7da1b3..bbe13ef1c 100644 --- a/chain/cosmos/08-wasm-types/msgs.go +++ b/chain/cosmos/08-wasm-types/msgs.go @@ -16,12 +16,12 @@ func NewMsgStoreCode(signer string, code []byte) *MsgStoreCode { } } -// ValidateBasic implements sdk.Msg +// ValidateBasic implements sdk.Msg. func (m MsgStoreCode) ValidateBasic() error { return nil } -// GetSigners implements sdk.Msg +// GetSigners implements sdk.Msg. func (m MsgStoreCode) GetSigners() []sdk.AccAddress { signer, err := sdk.AccAddressFromBech32(m.Signer) if err != nil { diff --git a/chain/cosmos/account_retriever.go b/chain/cosmos/account_retriever.go index 66b9f66cf..a814e5932 100644 --- a/chain/cosmos/account_retriever.go +++ b/chain/cosmos/account_retriever.go @@ -3,7 +3,6 @@ package cosmos import ( "context" "fmt" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "strconv" grpc "google.golang.org/grpc" @@ -12,6 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" grpctypes "github.com/cosmos/cosmos-sdk/types/grpc" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( diff --git a/chain/cosmos/address.go b/chain/cosmos/address.go index 121c021bb..fdb18359b 100644 --- a/chain/cosmos/address.go +++ b/chain/cosmos/address.go @@ -2,10 +2,10 @@ package cosmos import ( "errors" - "github.com/cosmos/cosmos-sdk/types/bech32" "strings" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/bech32" ) // AccAddressFromBech32 creates an AccAddress from a Bech32 string. diff --git a/chain/cosmos/broadcaster.go b/chain/cosmos/broadcaster.go index c30f19f2e..7dd7a8027 100644 --- a/chain/cosmos/broadcaster.go +++ b/chain/cosmos/broadcaster.go @@ -8,6 +8,9 @@ import ( "testing" "time" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/testutil" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" @@ -15,8 +18,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/testutil" ) type ClientContextOpt func(clientContext client.Context) client.Context @@ -216,13 +217,11 @@ func BroadcastTx(ctx context.Context, broadcaster *Broadcaster, broadcastingUser err = testutil.WaitForCondition(time.Second*30, time.Second*5, func() (bool, error) { var err error txBytes, err = broadcaster.GetTxResponseBytes(ctx, broadcastingUser) - if err != nil { return false, nil } return true, nil }) - if err != nil { return sdk.TxResponse{}, err } diff --git a/chain/cosmos/chain_node.go b/chain/cosmos/chain_node.go index 912c2a7fe..4db0c25a5 100644 --- a/chain/cosmos/chain_node.go +++ b/chain/cosmos/chain_node.go @@ -18,23 +18,13 @@ import ( "time" "github.com/avast/retry-go/v4" - tmjson "github.com/cometbft/cometbft/libs/json" - "github.com/cometbft/cometbft/p2p" - rpcclient "github.com/cometbft/cometbft/rpc/client" - rpchttp "github.com/cometbft/cometbft/rpc/client/http" - coretypes "github.com/cometbft/cometbft/rpc/core/types" - libclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - sdk "github.com/cosmos/cosmos-sdk/types" - authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" volumetypes "github.com/docker/docker/api/types/volume" dockerclient "github.com/docker/docker/client" "github.com/docker/go-connections/nat" + "github.com/strangelove-ventures/interchaintest/v8/blockdb" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" "golang.org/x/mod/semver" "golang.org/x/sync/errgroup" @@ -43,13 +33,25 @@ import ( icatypes "github.com/cosmos/ibc-go/v8/modules/apps/27-interchain-accounts/types" ccvclient "github.com/cosmos/interchain-security/v5/x/ccv/provider/client" - "github.com/strangelove-ventures/interchaintest/v8/blockdb" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testutil" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + sdk "github.com/cosmos/cosmos-sdk/types" + authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + tmjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/p2p" + rpcclient "github.com/cometbft/cometbft/rpc/client" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + coretypes "github.com/cometbft/cometbft/rpc/core/types" + libclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" ) -// ChainNode represents a node in the test network that is being created +// ChainNode represents a node in the test network that is being created. type ChainNode struct { VolumeName string Index int @@ -101,13 +103,13 @@ func NewChainNode(log *zap.Logger, validator bool, chain *CosmosChain, dockerCli return tn } -// WithPreStartNode sets the preStartNode function for the ChainNode +// WithPreStartNode sets the preStartNode function for the ChainNode. func (tn *ChainNode) WithPreStartNode(preStartNode func(*ChainNode)) *ChainNode { tn.preStartNode = preStartNode return tn } -// ChainNodes is a collection of ChainNode +// ChainNodes is a collection of ChainNode. type ChainNodes []*ChainNode const ( @@ -122,17 +124,15 @@ const ( cometMockRawPort = "22331" ) -var ( - sentryPorts = nat.PortMap{ - nat.Port(p2pPort): {}, - nat.Port(rpcPort): {}, - nat.Port(grpcPort): {}, - nat.Port(apiPort): {}, - nat.Port(privValPort): {}, - } -) +var sentryPorts = nat.PortMap{ + 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 +// 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 { @@ -201,7 +201,7 @@ func (tn *ChainNode) NewSidecarProcess( return nil } -// CliContext creates a new Cosmos SDK client context +// CliContext creates a new Cosmos SDK client context. func (tn *ChainNode) CliContext() client.Context { cfg := tn.Chain.Config() return client.Context{ @@ -217,7 +217,7 @@ func (tn *ChainNode) CliContext() client.Context { } } -// Name of the test node container +// Name of the test node container. func (tn *ChainNode) Name() string { return fmt.Sprintf("%s-%s-%d-%s", tn.Chain.Config().ChainID, tn.NodeType(), tn.Index, dockerutil.SanitizeContainerName(tn.TestName)) } @@ -234,12 +234,12 @@ func (tn *ChainNode) ContainerID() string { return tn.containerLifecycle.ContainerID() } -// hostname of the test node container +// hostname of the test node container. func (tn *ChainNode) HostName() string { return dockerutil.CondenseHostName(tn.Name()) } -// hostname of the comet mock container +// hostname of the comet mock container. func (tn *ChainNode) HostnameCometMock() string { return tn.cometHostname } @@ -312,7 +312,7 @@ type PrivValidatorKeyFile struct { PrivKey PrivValidatorKey `json:"priv_key"` } -// Bind returns the home folder bind point for running the node +// 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())} } @@ -398,7 +398,7 @@ func (tn *ChainNode) SetTestConfig(ctx context.Context) error { ) } -// SetPeers modifies the config persistent_peers for a node +// 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) @@ -507,7 +507,7 @@ func (tn *ChainNode) FindTxs(ctx context.Context, height int64) ([]blockdb.Tx, e // with the chain node binary. func (tn *ChainNode) TxCommand(keyName string, command ...string) []string { command = append([]string{"tx"}, command...) - var gasPriceFound, gasAdjustmentFound, gasFound, feesFound = false, false, false, false + gasPriceFound, gasAdjustmentFound, gasFound, feesFound := false, false, false, false for i := 0; i < len(command); i++ { if command[i] == "--gas-prices" { gasPriceFound = true @@ -673,7 +673,7 @@ func CondenseMoniker(m string) string { return m[:keepLen] + "..." + m[len(m)-keepLen:] + suffix } -// InitHomeFolder initializes a home folder for the given node +// InitHomeFolder initializes a home folder for the given node. func (tn *ChainNode) InitHomeFolder(ctx context.Context) error { tn.lock.Lock() defer tn.lock.Unlock() @@ -687,7 +687,7 @@ func (tn *ChainNode) InitHomeFolder(ctx context.Context) error { // 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 +// 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) @@ -695,7 +695,7 @@ func (tn *ChainNode) WriteFile(ctx context.Context, content []byte, relPath stri // 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 +// the home directory. func (tn *ChainNode) CopyFile(ctx context.Context, srcPath, dstPath string) error { content, err := os.ReadFile(srcPath) if err != nil { @@ -715,7 +715,7 @@ func (tn *ChainNode) ReadFile(ctx context.Context, relPath string) ([]byte, erro return gen, nil } -// CreateKey creates a key in the keyring backend test for the given node +// 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() @@ -768,7 +768,7 @@ func (tn *ChainNode) ICSVersion(ctx context.Context) string { return "" } -// AddGenesisAccount adds a genesis account for each key +// AddGenesisAccount adds a genesis account for each key. func (tn *ChainNode) AddGenesisAccount(ctx context.Context, address string, genesisAmount []sdk.Coin) error { amount := "" for i, coin := range genesisAmount { @@ -802,7 +802,7 @@ func (tn *ChainNode) AddGenesisAccount(ctx context.Context, address string, gene return err } -// Gentx generates the gentx for a given node +// Gentx generates the gentx for a given node. func (tn *ChainNode) Gentx(ctx context.Context, name string, genesisSelfDelegation sdk.Coin) error { tn.lock.Lock() defer tn.lock.Unlock() @@ -823,7 +823,7 @@ func (tn *ChainNode) Gentx(ctx context.Context, name string, genesisSelfDelegati return err } -// CollectGentxs runs collect gentxs on the node's home folders +// 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.IsAboveSDK47(ctx) { @@ -986,7 +986,6 @@ func (tn *ChainNode) GetBuildInformation(ctx context.Context) *BinaryBuildInform Replacement: r, ReplacementVersion: rV, } - } else { // Ex: "github.com/aaa/bbb@v0.0.0-20191008050251-8e49817e8af4" parent, version := getRepoAndVersion(dep) @@ -1015,7 +1014,7 @@ func (tn *ChainNode) GetBuildInformation(ctx context.Context) *BinaryBuildInform } } -// QueryClientContractCode performs a query with the contract codeHash as the input and code as the output +// 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 { @@ -1288,7 +1287,7 @@ func (tn *ChainNode) RemoveContainer(ctx context.Context) error { return tn.containerLifecycle.RemoveContainer(ctx) } -// InitValidatorFiles creates the node files and signs a genesis transaction +// InitValidatorFiles creates the node files and signs a genesis transaction. func (tn *ChainNode) InitValidatorGenTx( ctx context.Context, chainType *ibc.ChainConfig, @@ -1337,7 +1336,8 @@ func (tn *ChainNode) NodeID(ctx context.Context) (string, error) { // KeyBech32 retrieves the named key's address in bech32 format from the node. // bech is the bech32 prefix (acc|val|cons). If empty, defaults to the account key (same as "acc"). func (tn *ChainNode) KeyBech32(ctx context.Context, name string, bech string) (string, error) { - command := []string{tn.Chain.Config().Bin, "keys", "show", "--address", name, + command := []string{ + tn.Chain.Config().Bin, "keys", "show", "--address", name, "--home", tn.HomeDir(), "--keyring-backend", keyring.BackendTest, } @@ -1359,7 +1359,7 @@ func (tn *ChainNode) AccountKeyBech32(ctx context.Context, name string) (string, return tn.KeyBech32(ctx, name, "") } -// PeerString returns the string for connecting the nodes passed in +// PeerString returns the string for connecting the nodes passed in. func (nodes ChainNodes) PeerString(ctx context.Context) string { addrs := make([]string, len(nodes)) for i, n := range nodes { @@ -1381,7 +1381,7 @@ func (nodes ChainNodes) PeerString(ctx context.Context) string { return strings.Join(addrs, ",") } -// LogGenesisHashes logs the genesis hashes for the various nodes +// LogGenesisHashes logs the genesis hashes for the various nodes. func (nodes ChainNodes) LogGenesisHashes(ctx context.Context) error { for _, n := range nodes { gen, err := n.GenesisFileContent(ctx) @@ -1487,7 +1487,7 @@ func (tn *ChainNode) SendICABankTransfer(ctx context.Context, connectionID, from } // GetHostAddress returns the host-accessible url for a port in the container. -// This is useful for finding the url & random host port for ports exposed via ChainConfig.ExposeAdditionalPorts +// This is useful for finding the url & random host port for ports exposed via ChainConfig.ExposeAdditionalPorts. func (tn *ChainNode) GetHostAddress(ctx context.Context, portID string) (string, error) { ports, err := tn.containerLifecycle.GetHostPorts(ctx, portID) if err != nil { diff --git a/chain/cosmos/codec.go b/chain/cosmos/codec.go index b297d2729..d7065270d 100644 --- a/chain/cosmos/codec.go +++ b/chain/cosmos/codec.go @@ -1,7 +1,16 @@ package cosmos import ( + ibcwasm "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos/08-wasm-types" + "cosmossdk.io/x/upgrade" + + "github.com/cosmos/ibc-go/modules/capability" + transfer "github.com/cosmos/ibc-go/v8/modules/apps/transfer" + ibccore "github.com/cosmos/ibc-go/v8/modules/core" + ibctm "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" + ccvprovider "github.com/cosmos/interchain-security/v5/x/ccv/provider" + "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -20,13 +29,6 @@ import ( paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/cosmos/ibc-go/modules/capability" - - transfer "github.com/cosmos/ibc-go/v8/modules/apps/transfer" - ibccore "github.com/cosmos/ibc-go/v8/modules/core" - ibctm "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" - ccvprovider "github.com/cosmos/interchain-security/v5/x/ccv/provider" - ibcwasm "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos/08-wasm-types" ) func DefaultEncoding() testutil.TestEncodingConfig { diff --git a/chain/cosmos/cosmos_chain.go b/chain/cosmos/cosmos_chain.go index c493806ce..0d88ea1b2 100644 --- a/chain/cosmos/cosmos_chain.go +++ b/chain/cosmos/cosmos_chain.go @@ -13,20 +13,6 @@ import ( "strings" "sync" - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - paramsutils "github.com/cosmos/cosmos-sdk/x/params/client/utils" - clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" // nolint:staticcheck - chanTypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types" - ccvclient "github.com/cosmos/interchain-security/v5/x/ccv/provider/client" dockertypes "github.com/docker/docker/api/types" volumetypes "github.com/docker/docker/api/types/volume" "github.com/docker/docker/client" @@ -38,6 +24,23 @@ import ( "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" "golang.org/x/sync/errgroup" + + sdkmath "cosmossdk.io/math" + + clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" // nolint:staticcheck + chanTypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types" + ccvclient "github.com/cosmos/interchain-security/v5/x/ccv/provider/client" + + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/cosmos/cosmos-sdk/types" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + paramsutils "github.com/cosmos/cosmos-sdk/x/params/client/utils" ) // CosmosChain is a local docker testnet for a Cosmos SDK chain. @@ -72,7 +75,8 @@ func NewCosmosHeighlinerChainConfig(name string, gasPrices string, gasAdjustment float64, trustingPeriod string, - noHostMount bool) ibc.ChainConfig { + noHostMount bool, +) ibc.ChainConfig { return ibc.ChainConfig{ Type: "cosmos", Name: name, @@ -172,7 +176,7 @@ func (c *CosmosChain) AddFullNodes(ctx context.Context, configFileOverrides map[ for configFile, modifiedConfig := range configFileOverrides { modifiedToml, ok := modifiedConfig.(testutil.Toml) if !ok { - return fmt.Errorf("Provided toml override for file %s is of type (%T). Expected (DecodedToml)", configFile, modifiedConfig) + return fmt.Errorf("provided toml override for file %s is of type (%T). Expected (DecodedToml)", configFile, modifiedConfig) } if err := testutil.ModifyTomlConfigFile( ctx, @@ -195,12 +199,12 @@ func (c *CosmosChain) AddFullNodes(ctx context.Context, configFileOverrides map[ return eg.Wait() } -// Implements Chain interface +// Implements Chain interface. func (c *CosmosChain) Config() ibc.ChainConfig { return c.cfg } -// Implements Chain interface +// Implements Chain interface. func (c *CosmosChain) Initialize(ctx context.Context, testName string, cli *client.Client, networkID string) error { if err := c.initializeSidecars(ctx, testName, cli, networkID); err != nil { return err @@ -221,7 +225,7 @@ func (c *CosmosChain) Exec(ctx context.Context, cmd []string, env []string) (std return c.getFullNode().Exec(ctx, cmd, env) } -// Implements Chain interface +// Implements Chain interface. func (c *CosmosChain) GetRPCAddress() string { if c.Config().UsesCometMock() { return fmt.Sprintf("http://%s:22331", c.getFullNode().HostnameCometMock()) @@ -230,12 +234,12 @@ func (c *CosmosChain) GetRPCAddress() string { return fmt.Sprintf("http://%s:26657", c.getFullNode().HostName()) } -// Implements Chain interface +// Implements Chain interface. func (c *CosmosChain) GetAPIAddress() string { return fmt.Sprintf("http://%s:1317", c.getFullNode().HostName()) } -// Implements Chain interface +// Implements Chain interface. func (c *CosmosChain) GetGRPCAddress() string { return fmt.Sprintf("%s:9090", c.getFullNode().HostName()) } @@ -269,17 +273,17 @@ func (c *CosmosChain) HomeDir() string { return c.getFullNode().HomeDir() } -// Implements Chain interface +// Implements Chain interface. func (c *CosmosChain) CreateKey(ctx context.Context, keyName string) error { return c.getFullNode().CreateKey(ctx, keyName) } -// Implements Chain interface +// Implements Chain interface. func (c *CosmosChain) RecoverKey(ctx context.Context, keyName, mnemonic string) error { return c.getFullNode().RecoverKey(ctx, keyName, mnemonic) } -// Implements Chain interface +// Implements Chain interface. func (c *CosmosChain) GetAddress(ctx context.Context, keyName string) ([]byte, error) { b32Addr, err := c.getFullNode().AccountKeyBech32(ctx, keyName) if err != nil { @@ -291,7 +295,7 @@ func (c *CosmosChain) GetAddress(ctx context.Context, keyName string) ([]byte, e // BuildWallet will return a Cosmos wallet // If mnemonic != "", it will restore using that mnemonic -// If mnemonic == "", it will create a new key +// If mnemonic == "", it will create a new key. func (c *CosmosChain) BuildWallet(ctx context.Context, keyName string, mnemonic string) (ibc.Wallet, error) { if mnemonic != "" { if err := c.RecoverKey(ctx, keyName, mnemonic); err != nil { @@ -339,17 +343,17 @@ func (c *CosmosChain) BuildRelayerWallet(ctx context.Context, keyName string) (i return NewWallet(keyName, addrBytes, mnemonic, c.cfg), nil } -// Implements Chain interface +// Implements Chain interface. func (c *CosmosChain) SendFunds(ctx context.Context, keyName string, amount ibc.WalletAmount) error { return c.getFullNode().BankSend(ctx, keyName, amount) } -// Implements Chain interface +// Implements Chain interface. func (c *CosmosChain) SendFundsWithNote(ctx context.Context, keyName string, amount ibc.WalletAmount, note string) (string, error) { return c.getFullNode().BankSendWithNote(ctx, keyName, amount, note) } -// Implements Chain interface +// Implements Chain interface. func (c *CosmosChain) SendIBCTransfer( ctx context.Context, channelID string, @@ -432,7 +436,7 @@ func (c *CosmosChain) SendICATx(ctx context.Context, keyName, connectionID strin return node.SendICATx(ctx, keyName, connectionID, registry, msgs, icaTxMemo, encoding) } -// PushNewWasmClientProposal submits a new wasm client governance proposal to the chain +// PushNewWasmClientProposal submits a new wasm client governance proposal to the chain. func (c *CosmosChain) PushNewWasmClientProposal(ctx context.Context, keyName string, fileName string, prop TxProposalv1) (TxProposal, string, error) { tx := TxProposal{} content, err := os.ReadFile(fileName) @@ -553,7 +557,7 @@ func (c *CosmosChain) ExecuteContract(ctx context.Context, keyName string, contr return c.getFullNode().ExecuteContract(ctx, keyName, contractAddress, message, extraExecTxArgs...) } -// MigrateContract performs contract migration +// MigrateContract performs contract migration. func (c *CosmosChain) MigrateContract(ctx context.Context, keyName string, contractAddress string, codeID string, message string, extraExecTxArgs ...string) (res *types.TxResponse, err error) { return c.getFullNode().MigrateContract(ctx, keyName, contractAddress, codeID, message, extraExecTxArgs...) } @@ -573,13 +577,13 @@ func (c *CosmosChain) StoreClientContract(ctx context.Context, keyName string, f return c.getFullNode().StoreClientContract(ctx, keyName, fileName, extraExecTxArgs...) } -// QueryClientContractCode performs a query with the contract codeHash as the input and code as the output +// QueryClientContractCode performs a query with the contract codeHash as the input and code as the output. func (c *CosmosChain) QueryClientContractCode(ctx context.Context, codeHash string, response any) error { return c.getFullNode().QueryClientContractCode(ctx, codeHash, response) } // ExportState exports the chain state at specific height. -// Implements Chain interface +// Implements Chain interface. func (c *CosmosChain) ExportState(ctx context.Context, height int64) (string, error) { return c.getFullNode().ExportState(ctx, height) } @@ -737,7 +741,7 @@ func (c *CosmosChain) NewSidecarProcess( return nil } -// creates the test node objects required for bootstrapping tests +// creates the test node objects required for bootstrapping tests. func (c *CosmosChain) initializeChainNodes( ctx context.Context, testName string, @@ -809,7 +813,6 @@ func (c *CosmosChain) initializeSidecars( } return nil }) - } if err := eg.Wait(); err != nil { return err @@ -837,7 +840,7 @@ type ValidatorWithIntPower struct { PubKeyBase64 string } -// Bootstraps the chain and starts it from genesis +// Bootstraps the chain and starts it from genesis. func (c *CosmosChain) Start(testName string, ctx context.Context, additionalGenesisWallets ...ibc.WalletAmount) error { if c.cfg.InterchainSecurityConfig.ConsumerCopyProviderKey != nil && c.Provider == nil { return fmt.Errorf("don't set ConsumerCopyProviderKey if it's not a consumer chain") @@ -875,7 +878,7 @@ func (c *CosmosChain) Start(testName string, ctx context.Context, additionalGene for configFile, modifiedConfig := range configFileOverrides { modifiedToml, ok := modifiedConfig.(testutil.Toml) if !ok { - return fmt.Errorf("Provided toml override for file %s is of type (%T). Expected (DecodedToml)", configFile, modifiedConfig) + return fmt.Errorf("provided toml override for file %s is of type (%T). Expected (DecodedToml)", configFile, modifiedConfig) } if err := testutil.ModifyTomlConfigFile( ctx, @@ -907,7 +910,7 @@ func (c *CosmosChain) Start(testName string, ctx context.Context, additionalGene for configFile, modifiedConfig := range configFileOverrides { modifiedToml, ok := modifiedConfig.(testutil.Toml) if !ok { - return fmt.Errorf("Provided toml override for file %s is of type (%T). Expected (DecodedToml)", configFile, modifiedConfig) + return fmt.Errorf("provided toml override for file %s is of type (%T). Expected (DecodedToml)", configFile, modifiedConfig) } if err := testutil.ModifyTomlConfigFile( ctx, @@ -964,7 +967,6 @@ func (c *CosmosChain) Start(testName string, ctx context.Context, additionalGene } for _, wallet := range additionalGenesisWallets { - if err := validator0.AddGenesisAccount(ctx, wallet.Address, []types.Coin{{Denom: wallet.Denom, Amount: wallet.Amount}}); err != nil { return err } @@ -998,7 +1000,7 @@ func (c *CosmosChain) Start(testName string, ctx context.Context, additionalGene zap.String("chain", exportGenesisChain), zap.String("path", exportGenesis), ) - _ = os.WriteFile(exportGenesis, genbz, 0600) + _ = os.WriteFile(exportGenesis, genbz, 0o600) } chainNodes := c.Nodes() @@ -1069,12 +1071,12 @@ func (c *CosmosChain) Start(testName string, ctx context.Context, additionalGene return testutil.WaitForBlocks(ctx, 2, c.getFullNode()) } -// Height implements ibc.Chain +// Height implements ibc.Chain. func (c *CosmosChain) Height(ctx context.Context) (int64, error) { return c.getFullNode().Height(ctx) } -// Acknowledgements implements ibc.Chain, returning all acknowledgments in block at height +// Acknowledgements implements ibc.Chain, returning all acknowledgments in block at height. func (c *CosmosChain) Acknowledgements(ctx context.Context, height int64) ([]ibc.PacketAcknowledgement, error) { var acks []*chanTypes.MsgAcknowledgement err := RangeBlockMessages(ctx, c.cfg.EncodingConfig.InterfaceRegistry, c.getFullNode().Client, height, func(msg types.Msg) bool { @@ -1107,7 +1109,7 @@ func (c *CosmosChain) Acknowledgements(ctx context.Context, height int64) ([]ibc return ibcAcks, nil } -// Timeouts implements ibc.Chain, returning all timeouts in block at height +// Timeouts implements ibc.Chain, returning all timeouts in block at height. func (c *CosmosChain) Timeouts(ctx context.Context, height int64) ([]ibc.PacketTimeout, error) { var timeouts []*chanTypes.MsgTimeout err := RangeBlockMessages(ctx, c.cfg.EncodingConfig.InterfaceRegistry, c.getFullNode().Client, height, func(msg types.Msg) bool { @@ -1147,7 +1149,7 @@ func (c *CosmosChain) FindTxs(ctx context.Context, height int64) ([]blockdb.Tx, return fn.FindTxs(ctx, height) } -// StopAllNodes stops and removes all long running containers (validators and full nodes) +// StopAllNodes stops and removes all long running containers (validators and full nodes). func (c *CosmosChain) StopAllNodes(ctx context.Context) error { var eg errgroup.Group for _, n := range c.Nodes() { @@ -1264,7 +1266,7 @@ func (c *CosmosChain) VoteOnProposalAllValidators(ctx context.Context, proposalI } // GetTimeoutHeight returns a timeout height of 1000 blocks above the current block height. -// This function should be used when the timeout is never expected to be reached +// This function should be used when the timeout is never expected to be reached. func (c *CosmosChain) GetTimeoutHeight(ctx context.Context) (clienttypes.Height, error) { height, err := c.Height(ctx) if err != nil { diff --git a/chain/cosmos/ics.go b/chain/cosmos/ics.go index c6743dbf9..beb0e9ead 100644 --- a/chain/cosmos/ics.go +++ b/chain/cosmos/ics.go @@ -11,11 +11,6 @@ import ( "strings" "time" - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/types" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" // nolint:staticcheck - ccvclient "github.com/cosmos/interchain-security/v5/x/ccv/provider/client" "github.com/icza/dyno" "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/strangelove-ventures/interchaintest/v8/ibc" @@ -26,6 +21,13 @@ import ( "golang.org/x/mod/semver" "golang.org/x/sync/errgroup" + sdkmath "cosmossdk.io/math" + + clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" // nolint:staticcheck + ccvclient "github.com/cosmos/interchain-security/v5/x/ccv/provider/client" + + "github.com/cosmos/cosmos-sdk/types" + govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" stakingttypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -100,7 +102,7 @@ func (c *CosmosChain) FlushPendingICSPackets(ctx context.Context, r ibc.Relayer, return r.Flush(ctx, eRep, ibcPath, ICSChannel) } -// Bootstraps the provider chain and starts it from genesis +// Bootstraps the provider chain and starts it from genesis. func (c *CosmosChain) StartProvider(testName string, ctx context.Context, additionalGenesisWallets ...ibc.WalletAmount) error { if c.cfg.InterchainSecurityConfig.ConsumerCopyProviderKey != nil { return fmt.Errorf("don't set ConsumerCopyProviderKey in the provider chain") @@ -205,7 +207,7 @@ func (c *CosmosChain) StartProvider(testName string, ctx context.Context, additi return nil } -// Bootstraps the consumer chain and starts it from genesis +// Bootstraps the consumer chain and starts it from genesis. func (c *CosmosChain) StartConsumer(testName string, ctx context.Context, additionalGenesisWallets ...ibc.WalletAmount) error { chainCfg := c.Config() @@ -358,7 +360,7 @@ func (c *CosmosChain) StartConsumer(testName string, ctx context.Context, additi zap.String("chain", exportGenesisChain), zap.String("path", exportGenesis), ) - _ = os.WriteFile(exportGenesis, genbz, 0600) + _ = os.WriteFile(exportGenesis, genbz, 0o600) } chainNodes := c.Nodes() diff --git a/chain/cosmos/module_auth.go b/chain/cosmos/module_auth.go index c847025eb..30b5d5875 100644 --- a/chain/cosmos/module_auth.go +++ b/chain/cosmos/module_auth.go @@ -4,13 +4,12 @@ import ( "context" "fmt" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" ) -// AuthQueryAccount performs a query to get the account details of the specified address +// AuthQueryAccount performs a query to get the account details of the specified address. func (c *CosmosChain) AuthQueryAccount(ctx context.Context, addr string) (*cdctypes.Any, error) { res, err := authtypes.NewQueryClient(c.GetNode().GrpcConn).Account(ctx, &authtypes.QueryAccountRequest{ Address: addr, @@ -18,13 +17,13 @@ func (c *CosmosChain) AuthQueryAccount(ctx context.Context, addr string) (*cdcty return res.Account, err } -// AuthQueryParams performs a query to get the auth module parameters +// AuthQueryParams performs a query to get the auth module parameters. func (c *CosmosChain) AuthQueryParams(ctx context.Context) (*authtypes.Params, error) { res, err := authtypes.NewQueryClient(c.GetNode().GrpcConn).Params(ctx, &authtypes.QueryParamsRequest{}) return &res.Params, err } -// AuthQueryModuleAccounts performs a query to get the account details of all the chain modules +// AuthQueryModuleAccounts performs a query to get the account details of all the chain modules. func (c *CosmosChain) AuthQueryModuleAccounts(ctx context.Context) ([]authtypes.ModuleAccount, error) { res, err := authtypes.NewQueryClient(c.GetNode().GrpcConn).ModuleAccounts(ctx, &authtypes.QueryModuleAccountsRequest{}) @@ -42,7 +41,7 @@ func (c *CosmosChain) AuthQueryModuleAccounts(ctx context.Context) ([]authtypes. return maccs, err } -// AuthGetModuleAccount performs a query to get the account details of the specified chain module +// AuthGetModuleAccount performs a query to get the account details of the specified chain module. func (c *CosmosChain) AuthQueryModuleAccount(ctx context.Context, moduleName string) (authtypes.ModuleAccount, error) { res, err := authtypes.NewQueryClient(c.GetNode().GrpcConn).ModuleAccountByName(ctx, &authtypes.QueryModuleAccountByNameRequest{ Name: moduleName, @@ -57,7 +56,7 @@ func (c *CosmosChain) AuthQueryModuleAccount(ctx context.Context, moduleName str return modAcc, err } -// GetModuleAddress performs a query to get the address of the specified chain module +// GetModuleAddress performs a query to get the address of the specified chain module. func (c *CosmosChain) AuthQueryModuleAddress(ctx context.Context, moduleName string) (string, error) { queryRes, err := c.AuthQueryModuleAccount(ctx, moduleName) if err != nil { @@ -66,13 +65,13 @@ func (c *CosmosChain) AuthQueryModuleAddress(ctx context.Context, moduleName str return queryRes.BaseAccount.Address, nil } -// Deprecated: use AuthQueryModuleAddress instead +// Deprecated: use AuthQueryModuleAddress instead. func (c *CosmosChain) GetModuleAddress(ctx context.Context, moduleName string) (string, error) { return c.AuthQueryModuleAddress(ctx, moduleName) } // GetGovernanceAddress performs a query to get the address of the chain's x/gov module -// Deprecated: use AuthQueryModuleAddress(ctx, "gov") instead +// Deprecated: use AuthQueryModuleAddress(ctx, "gov") instead. func (c *CosmosChain) GetGovernanceAddress(ctx context.Context) (string, error) { return c.GetModuleAddress(ctx, "gov") } @@ -82,7 +81,7 @@ func (c *CosmosChain) AuthQueryBech32Prefix(ctx context.Context) (string, error) return res.Bech32Prefix, err } -// AddressBytesToString converts a byte array address to a string +// AddressBytesToString converts a byte array address to a string. func (c *CosmosChain) AuthAddressBytesToString(ctx context.Context, addrBz []byte) (string, error) { res, err := authtypes.NewQueryClient(c.GetNode().GrpcConn).AddressBytesToString(ctx, &authtypes.AddressBytesToStringRequest{ AddressBytes: addrBz, @@ -90,7 +89,7 @@ func (c *CosmosChain) AuthAddressBytesToString(ctx context.Context, addrBz []byt return res.AddressString, err } -// AddressStringToBytes converts a string address to a byte array +// AddressStringToBytes converts a string address to a byte array. func (c *CosmosChain) AuthAddressStringToBytes(ctx context.Context, addr string) ([]byte, error) { res, err := authtypes.NewQueryClient(c.GetNode().GrpcConn).AddressStringToBytes(ctx, &authtypes.AddressStringToBytesRequest{ AddressString: addr, @@ -98,7 +97,7 @@ func (c *CosmosChain) AuthAddressStringToBytes(ctx context.Context, addr string) return res.AddressBytes, err } -// AccountInfo queries the account information of the given address +// AccountInfo queries the account information of the given address. func (c *CosmosChain) AuthQueryAccountInfo(ctx context.Context, addr string) (*authtypes.BaseAccount, error) { res, err := authtypes.NewQueryClient(c.GetNode().GrpcConn).AccountInfo(ctx, &authtypes.QueryAccountInfoRequest{ Address: addr, diff --git a/chain/cosmos/module_authz.go b/chain/cosmos/module_authz.go index ad5ac5e76..de7e17f43 100644 --- a/chain/cosmos/module_authz.go +++ b/chain/cosmos/module_authz.go @@ -6,14 +6,14 @@ import ( "path" "strings" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/authz" - "github.com/strangelove-ventures/interchaintest/v8/ibc" ) // AuthzGrant grants a message as a permission to an account. func (tn *ChainNode) AuthzGrant(ctx context.Context, granter ibc.Wallet, grantee, authType string, extraFlags ...string) (*sdk.TxResponse, error) { - allowed := "send|generic|delegate|unbond|redelegate" if !strings.Contains(allowed, authType) { return nil, fmt.Errorf("invalid auth type: %s allowed: %s", authType, allowed) diff --git a/chain/cosmos/module_bank.go b/chain/cosmos/module_bank.go index 5f54071ce..eb2d3fba9 100644 --- a/chain/cosmos/module_bank.go +++ b/chain/cosmos/module_bank.go @@ -4,12 +4,12 @@ import ( "context" "fmt" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - - "github.com/strangelove-ventures/interchaintest/v8/ibc" ) // BankSend sends tokens from one account to another. @@ -27,7 +27,7 @@ func (tn *ChainNode) BankSendWithNote(ctx context.Context, keyName string, amoun fmt.Sprintf("%s%s", amount.Amount.String(), amount.Denom), "--note", note) } -// Deprecated: use BankSend instead +// Deprecated: use BankSend instead. func (tn *ChainNode) SendFunds(ctx context.Context, keyName string, amount ibc.WalletAmount) error { return tn.BankSend(ctx, keyName, amount) } @@ -42,24 +42,24 @@ func (tn *ChainNode) BankMultiSend(ctx context.Context, keyName string, addresse } // GetBalance fetches the current balance for a specific account address and denom. -// Implements Chain interface +// Implements Chain interface. func (c *CosmosChain) GetBalance(ctx context.Context, address string, denom string) (sdkmath.Int, error) { return c.BankQueryBalance(ctx, address, denom) } -// BankGetBalance is an alias for GetBalance +// BankGetBalance is an alias for GetBalance. func (c *CosmosChain) BankQueryBalance(ctx context.Context, address string, denom string) (sdkmath.Int, error) { res, err := banktypes.NewQueryClient(c.GetNode().GrpcConn).Balance(ctx, &banktypes.QueryBalanceRequest{Address: address, Denom: denom}) return res.Balance.Amount, err } -// AllBalances fetches an account address's balance for all denoms it holds +// AllBalances fetches an account address's balance for all denoms it holds. func (c *CosmosChain) BankQueryAllBalances(ctx context.Context, address string) (types.Coins, error) { res, err := banktypes.NewQueryClient(c.GetNode().GrpcConn).AllBalances(ctx, &banktypes.QueryAllBalancesRequest{Address: address}) return res.GetBalances(), err } -// BankDenomMetadata fetches the metadata of a specific coin denomination +// BankDenomMetadata fetches the metadata of a specific coin denomination. func (c *CosmosChain) BankQueryDenomMetadata(ctx context.Context, denom string) (*banktypes.Metadata, error) { res, err := banktypes.NewQueryClient(c.GetNode().GrpcConn).DenomMetadata(ctx, &banktypes.QueryDenomMetadataRequest{Denom: denom}) return &res.Metadata, err diff --git a/chain/cosmos/module_cosmwasm.go b/chain/cosmos/module_cosmwasm.go index 4940471ec..43ae64a0c 100644 --- a/chain/cosmos/module_cosmwasm.go +++ b/chain/cosmos/module_cosmwasm.go @@ -10,9 +10,10 @@ import ( "path" "path/filepath" + "github.com/strangelove-ventures/interchaintest/v8/testutil" + "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/strangelove-ventures/interchaintest/v8/testutil" ) type InstantiateContractAttribute struct { @@ -161,7 +162,7 @@ func (tn *ChainNode) QueryContract(ctx context.Context, contractAddress string, return err } -// MigrateContract performs contract migration +// MigrateContract performs contract migration. func (tn *ChainNode) MigrateContract(ctx context.Context, keyName string, contractAddress string, codeID string, message string, extraExecTxArgs ...string) (res *types.TxResponse, err error) { cmd := []string{"wasm", "migrate", contractAddress, codeID, message} cmd = append(cmd, extraExecTxArgs...) diff --git a/chain/cosmos/module_distribution.go b/chain/cosmos/module_distribution.go index 29acc0de2..b2ef55099 100644 --- a/chain/cosmos/module_distribution.go +++ b/chain/cosmos/module_distribution.go @@ -53,7 +53,7 @@ func (tn *ChainNode) DistributionWithdrawValidatorRewards(ctx context.Context, k return err } -// DistributionCommission returns the validator's commission +// DistributionCommission returns the validator's commission. func (c *CosmosChain) DistributionQueryCommission(ctx context.Context, valAddr string) (*distrtypes.ValidatorAccumulatedCommission, error) { res, err := distrtypes.NewQueryClient(c.GetNode().GrpcConn). ValidatorCommission(ctx, &distrtypes.QueryValidatorCommissionRequest{ @@ -62,42 +62,42 @@ func (c *CosmosChain) DistributionQueryCommission(ctx context.Context, valAddr s return &res.Commission, err } -// DistributionCommunityPool returns the community pool +// DistributionCommunityPool returns the community pool. func (c *CosmosChain) DistributionQueryCommunityPool(ctx context.Context) (*sdk.DecCoins, error) { res, err := distrtypes.NewQueryClient(c.GetNode().GrpcConn). CommunityPool(ctx, &distrtypes.QueryCommunityPoolRequest{}) return &res.Pool, err } -// DistributionDelegationTotalRewards returns the delegator's total rewards +// DistributionDelegationTotalRewards returns the delegator's total rewards. func (c *CosmosChain) DistributionQueryDelegationTotalRewards(ctx context.Context, delegatorAddr string) (*distrtypes.QueryDelegationTotalRewardsResponse, error) { res, err := distrtypes.NewQueryClient(c.GetNode().GrpcConn). DelegationTotalRewards(ctx, &distrtypes.QueryDelegationTotalRewardsRequest{DelegatorAddress: delegatorAddr}) return res, err } -// DistributionDelegatorValidators returns the delegator's validators +// DistributionDelegatorValidators returns the delegator's validators. func (c *CosmosChain) DistributionQueryDelegatorValidators(ctx context.Context, delegatorAddr string) (*distrtypes.QueryDelegatorValidatorsResponse, error) { res, err := distrtypes.NewQueryClient(c.GetNode().GrpcConn). DelegatorValidators(ctx, &distrtypes.QueryDelegatorValidatorsRequest{DelegatorAddress: delegatorAddr}) return res, err } -// DistributionDelegatorWithdrawAddress returns the delegator's withdraw address +// DistributionDelegatorWithdrawAddress returns the delegator's withdraw address. func (c *CosmosChain) DistributionQueryDelegatorWithdrawAddress(ctx context.Context, delegatorAddr string) (string, error) { res, err := distrtypes.NewQueryClient(c.GetNode().GrpcConn). DelegatorWithdrawAddress(ctx, &distrtypes.QueryDelegatorWithdrawAddressRequest{DelegatorAddress: delegatorAddr}) return res.WithdrawAddress, err } -// DistributionParams returns the distribution params +// DistributionParams returns the distribution params. func (c *CosmosChain) DistributionQueryParams(ctx context.Context) (*distrtypes.Params, error) { res, err := distrtypes.NewQueryClient(c.GetNode().GrpcConn). Params(ctx, &distrtypes.QueryParamsRequest{}) return &res.Params, err } -// DistributionRewards returns the delegator's rewards +// DistributionRewards returns the delegator's rewards. func (c *CosmosChain) DistributionQueryRewards(ctx context.Context, delegatorAddr, valAddr string) (sdk.DecCoins, error) { res, err := distrtypes.NewQueryClient(c.GetNode().GrpcConn). DelegationRewards(ctx, &distrtypes.QueryDelegationRewardsRequest{ @@ -107,21 +107,21 @@ func (c *CosmosChain) DistributionQueryRewards(ctx context.Context, delegatorAdd return res.Rewards, err } -// DistributionValidatorSlashes returns the validator's slashes +// DistributionValidatorSlashes returns the validator's slashes. func (c *CosmosChain) DistributionQueryValidatorSlashes(ctx context.Context, valAddr string) ([]distrtypes.ValidatorSlashEvent, error) { res, err := distrtypes.NewQueryClient(c.GetNode().GrpcConn). ValidatorSlashes(ctx, &distrtypes.QueryValidatorSlashesRequest{ValidatorAddress: valAddr}) return res.Slashes, err } -// DistributionValidatorDistributionInfo returns the validator's distribution info +// DistributionValidatorDistributionInfo returns the validator's distribution info. func (c *CosmosChain) DistributionQueryValidatorDistributionInfo(ctx context.Context, valAddr string) (*distrtypes.QueryValidatorDistributionInfoResponse, error) { res, err := distrtypes.NewQueryClient(c.GetNode().GrpcConn). ValidatorDistributionInfo(ctx, &distrtypes.QueryValidatorDistributionInfoRequest{ValidatorAddress: valAddr}) return res, err } -// DistributionValidatorOutstandingRewards returns the validator's outstanding rewards +// DistributionValidatorOutstandingRewards returns the validator's outstanding rewards. func (c *CosmosChain) DistributionQueryValidatorOutstandingRewards(ctx context.Context, valAddr string) (*distrtypes.ValidatorOutstandingRewards, error) { res, err := distrtypes.NewQueryClient(c.GetNode().GrpcConn). ValidatorOutstandingRewards(ctx, &distrtypes.QueryValidatorOutstandingRewardsRequest{ValidatorAddress: valAddr}) diff --git a/chain/cosmos/module_gov.go b/chain/cosmos/module_gov.go index d9fac35c1..7c38d6e89 100644 --- a/chain/cosmos/module_gov.go +++ b/chain/cosmos/module_gov.go @@ -9,12 +9,13 @@ import ( "path/filepath" "strconv" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + upgradetypes "cosmossdk.io/x/upgrade/types" + govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" paramsutils "github.com/cosmos/cosmos-sdk/x/params/client/utils" - - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" ) // VoteOnProposal submits a vote for the specified proposal. diff --git a/chain/cosmos/module_slashing.go b/chain/cosmos/module_slashing.go index 3f5c98439..a4cb16179 100644 --- a/chain/cosmos/module_slashing.go +++ b/chain/cosmos/module_slashing.go @@ -14,7 +14,7 @@ func (tn *ChainNode) SlashingUnJail(ctx context.Context, keyName string) error { return err } -// SlashingGetParams returns slashing params +// SlashingGetParams returns slashing params. func (c *CosmosChain) SlashingQueryParams(ctx context.Context) (*slashingtypes.Params, error) { res, err := slashingtypes.NewQueryClient(c.GetNode().GrpcConn). Params(ctx, &slashingtypes.QueryParamsRequest{}) @@ -24,7 +24,7 @@ func (c *CosmosChain) SlashingQueryParams(ctx context.Context) (*slashingtypes.P return &res.Params, nil } -// SlashingSigningInfo returns signing info for a validator +// SlashingSigningInfo returns signing info for a validator. func (c *CosmosChain) SlashingQuerySigningInfo(ctx context.Context, consAddress string) (*slashingtypes.ValidatorSigningInfo, error) { res, err := slashingtypes.NewQueryClient(c.GetNode().GrpcConn). SigningInfo(ctx, &slashingtypes.QuerySigningInfoRequest{ConsAddress: consAddress}) @@ -34,7 +34,7 @@ func (c *CosmosChain) SlashingQuerySigningInfo(ctx context.Context, consAddress return &res.ValSigningInfo, nil } -// SlashingSigningInfos returns all signing infos +// SlashingSigningInfos returns all signing infos. func (c *CosmosChain) SlashingQuerySigningInfos(ctx context.Context) ([]slashingtypes.ValidatorSigningInfo, error) { res, err := slashingtypes.NewQueryClient(c.GetNode().GrpcConn). SigningInfos(ctx, &slashingtypes.QuerySigningInfosRequest{}) diff --git a/chain/cosmos/module_tokenfactory.go b/chain/cosmos/module_tokenfactory.go index 3e5bf5a41..76f16a7bd 100644 --- a/chain/cosmos/module_tokenfactory.go +++ b/chain/cosmos/module_tokenfactory.go @@ -99,7 +99,7 @@ func (c *CosmosChain) TokenFactoryQueryAdmin(ctx context.Context, fullDenom stri return res, nil } -// Deprecated: use TokenFactoryQueryAdmin instead +// Deprecated: use TokenFactoryQueryAdmin instead. func TokenFactoryGetAdmin(c *CosmosChain, ctx context.Context, fullDenom string) (*QueryDenomAuthorityMetadataResponse, error) { return c.TokenFactoryQueryAdmin(ctx, fullDenom) } diff --git a/chain/cosmos/module_upgrade.go b/chain/cosmos/module_upgrade.go index f0b0d071b..93a97e4c7 100644 --- a/chain/cosmos/module_upgrade.go +++ b/chain/cosmos/module_upgrade.go @@ -49,10 +49,9 @@ func (c *CosmosChain) UpgradeQueryAppliedPlan(ctx context.Context, name string) Name: name, }) return res, err - } -// UpgradeQueryAuthority returns the account with authority to conduct upgrades +// UpgradeQueryAuthority returns the account with authority to conduct upgrades. func (c *CosmosChain) UpgradeQueryAuthority(ctx context.Context) (string, error) { res, err := upgradetypes.NewQueryClient(c.GetNode().GrpcConn).Authority(ctx, &upgradetypes.QueryAuthorityRequest{}) return res.Address, err diff --git a/chain/cosmos/module_vesting.go b/chain/cosmos/module_vesting.go index 4e318a47f..b0b62963f 100644 --- a/chain/cosmos/module_vesting.go +++ b/chain/cosmos/module_vesting.go @@ -6,8 +6,9 @@ import ( "fmt" "path" - vestingcli "github.com/cosmos/cosmos-sdk/x/auth/vesting/client/cli" "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + + vestingcli "github.com/cosmos/cosmos-sdk/x/auth/vesting/client/cli" ) // VestingCreateAccount creates a new vesting account funded with an allocation of tokens. The account can either be a delayed or continuous vesting account, which is determined by the '--delayed' flag. diff --git a/chain/cosmos/node_test.go b/chain/cosmos/node_test.go index e3223dbaf..8eebb9f57 100644 --- a/chain/cosmos/node_test.go +++ b/chain/cosmos/node_test.go @@ -4,9 +4,10 @@ import ( "strings" "testing" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" "github.com/stretchr/testify/require" + + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) func TestCondenseMoniker_MiddleDetail(t *testing.T) { diff --git a/chain/cosmos/osmosis.go b/chain/cosmos/osmosis.go index ab81c5f99..c6ecbb77f 100644 --- a/chain/cosmos/osmosis.go +++ b/chain/cosmos/osmosis.go @@ -10,7 +10,7 @@ import ( "github.com/strangelove-ventures/interchaintest/v8/dockerutil" ) -// OsmosisPoolParams defines parameters for creating an osmosis gamm liquidity pool +// OsmosisPoolParams defines parameters for creating an osmosis gamm liquidity pool. type OsmosisPoolParams struct { Weights string `json:"weights"` InitialDeposit string `json:"initial-deposit"` diff --git a/chain/cosmos/poll.go b/chain/cosmos/poll.go index 04f642d9b..39b34d965 100644 --- a/chain/cosmos/poll.go +++ b/chain/cosmos/poll.go @@ -5,12 +5,12 @@ import ( "errors" "fmt" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testutil" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testutil" ) // PollForProposalStatus attempts to find a proposal with matching ID and status using gov v1. @@ -82,7 +82,7 @@ func PollForMessage[T any](ctx context.Context, chain *CosmosChain, registry cod return bp.DoPoll(ctx, startHeight, maxHeight) } -// PollForBalance polls until the balance matches +// PollForBalance polls until the balance matches. func PollForBalance(ctx context.Context, chain *CosmosChain, deltaBlocks int64, balance ibc.WalletAmount) error { h, err := chain.Height(ctx) if err != nil { diff --git a/chain/cosmos/query.go b/chain/cosmos/query.go index d710d453c..c33a955dc 100644 --- a/chain/cosmos/query.go +++ b/chain/cosmos/query.go @@ -4,9 +4,10 @@ import ( "context" "fmt" - tmtypes "github.com/cometbft/cometbft/rpc/core/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" + + tmtypes "github.com/cometbft/cometbft/rpc/core/types" ) type blockClient interface { diff --git a/chain/cosmos/sidecar.go b/chain/cosmos/sidecar.go index 9927e6ec0..7c6978d37 100644 --- a/chain/cosmos/sidecar.go +++ b/chain/cosmos/sidecar.go @@ -7,10 +7,9 @@ import ( dockerclient "github.com/docker/docker/client" "github.com/docker/go-connections/nat" - "go.uber.org/zap" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/strangelove-ventures/interchaintest/v8/ibc" + "go.uber.org/zap" ) type SidecarProcesses []*SidecarProcess @@ -150,7 +149,7 @@ func (s *SidecarProcess) GetHostPorts(ctx context.Context, portIDs ...string) ([ // 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 +// docker volume relative to the home directory. func (s *SidecarProcess) WriteFile(ctx context.Context, content []byte, relPath string) error { fw := dockerutil.NewFileWriter(s.logger(), s.DockerClient, s.TestName) return fw.WriteFile(ctx, s.VolumeName, relPath, content) @@ -158,7 +157,7 @@ func (s *SidecarProcess) WriteFile(ctx context.Context, content []byte, relPath // 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 +// the home directory. func (s *SidecarProcess) CopyFile(ctx context.Context, srcPath, dstPath string) error { content, err := os.ReadFile(srcPath) if err != nil { diff --git a/chain/cosmos/types.go b/chain/cosmos/types.go index 22350bcc7..af29e1a68 100644 --- a/chain/cosmos/types.go +++ b/chain/cosmos/types.go @@ -12,7 +12,7 @@ const ( ProposalVoteAbstain = "abstain" ) -// TxProposalv1 contains chain proposal transaction detail for gov module v1 (sdk v0.46.0+) +// TxProposalv1 contains chain proposal transaction detail for gov module v1 (sdk v0.46.0+). type TxProposalv1 struct { Messages []json.RawMessage `json:"messages"` Metadata string `json:"metadata"` diff --git a/chain/cosmos/wallet.go b/chain/cosmos/wallet.go index 2ee27bc08..da2efade9 100644 --- a/chain/cosmos/wallet.go +++ b/chain/cosmos/wallet.go @@ -1,12 +1,15 @@ package cosmos import ( - "github.com/cosmos/cosmos-sdk/types" "github.com/strangelove-ventures/interchaintest/v8/ibc" + + "github.com/cosmos/cosmos-sdk/types" ) -var _ ibc.Wallet = &CosmosWallet{} -var _ User = &CosmosWallet{} +var ( + _ ibc.Wallet = &CosmosWallet{} + _ User = &CosmosWallet{} +) type CosmosWallet struct { mnemonic string @@ -28,17 +31,17 @@ func (w *CosmosWallet) KeyName() string { return w.keyName } -// Get formatted address, passing in a prefix +// Get formatted address, passing in a prefix. func (w *CosmosWallet) FormattedAddress() string { return types.MustBech32ifyAddressBytes(w.chainCfg.Bech32Prefix, w.address) } -// Get mnemonic, only used for relayer wallets +// Get mnemonic, only used for relayer wallets. func (w *CosmosWallet) Mnemonic() string { return w.mnemonic } -// Get Address with chain's prefix +// Get Address with chain's prefix. func (w *CosmosWallet) Address() []byte { return w.address } diff --git a/chain/cosmos/wasm/wasm.go b/chain/cosmos/wasm/wasm.go index 46886314a..5d5e01c53 100644 --- a/chain/cosmos/wasm/wasm.go +++ b/chain/cosmos/wasm/wasm.go @@ -2,10 +2,10 @@ package wasm import ( wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" - "github.com/cosmos/cosmos-sdk/types/module/testutil" - - // simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + // simappparams "github.com/cosmos/cosmos-sdk/simapp/params". "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" + + "github.com/cosmos/cosmos-sdk/types/module/testutil" ) func WasmEncoding() *testutil.TestEncodingConfig { diff --git a/chain/ethereum/ethererum_chain.go b/chain/ethereum/ethererum_chain.go index 010bd0068..30599baf4 100644 --- a/chain/ethereum/ethererum_chain.go +++ b/chain/ethereum/ethererum_chain.go @@ -6,21 +6,20 @@ import ( "io" "time" - sdkmath "cosmossdk.io/math" - dockertypes "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/mount" "github.com/docker/docker/api/types/volume" dockerclient "github.com/docker/docker/client" "github.com/docker/go-connections/nat" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/ethclient" "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" + sdkmath "cosmossdk.io/math" ) const ( diff --git a/chain/ethereum/foundry/anvil_chain.go b/chain/ethereum/foundry/anvil_chain.go index d42b8c7ef..0f230e7ec 100644 --- a/chain/ethereum/foundry/anvil_chain.go +++ b/chain/ethereum/foundry/anvil_chain.go @@ -37,7 +37,8 @@ func (c *AnvilChain) KeystoreDir() string { } func (c *AnvilChain) Start(testName string, ctx context.Context, additionalGenesisWallets ...ibc.WalletAmount) error { - cmd := []string{c.Config().Bin, + cmd := []string{ + c.Config().Bin, "--host", "0.0.0.0", // Anyone can call "--no-cors", "--gas-price", c.Config().GasPrices, @@ -127,7 +128,7 @@ func (c *AnvilChain) RecoverKey(ctx context.Context, keyName, mnemonic string) e return nil } -// Get address of account, cast to a string to use +// Get address of account, cast to a string to use. func (c *AnvilChain) GetAddress(ctx context.Context, keyName string) ([]byte, error) { account, ok := c.keystoreMap[keyName] if !ok { diff --git a/chain/ethereum/foundry/forge.go b/chain/ethereum/foundry/forge.go index a37084e83..c9a38e7df 100644 --- a/chain/ethereum/foundry/forge.go +++ b/chain/ethereum/foundry/forge.go @@ -21,7 +21,7 @@ type ForgeScriptOpts struct { RawOptions []string // optional, appends additional options to command } -// Add private-key or keystore to cmd +// Add private-key or keystore to cmd. func (c *AnvilChain) AddKey(cmd []string, keyName string) []string { account, ok := c.keystoreMap[keyName] if !ok { @@ -34,7 +34,7 @@ func (c *AnvilChain) AddKey(cmd []string, keyName string) []string { return cmd } -// Add signature function to cmd, if present +// Add signature function to cmd, if present. func AddSignature(cmd []string, signature string) []string { if signature != "" { cmd = append(cmd, "--sig", signature) @@ -46,7 +46,7 @@ func GetConfigFilePath(configFile, localContractRootDir, solidityContractDir str return filepath.Join(localContractRootDir, solidityContractDir, configFile) } -// ReadAndAppendConfigFile, returns the cmd, configFileBz +// ReadAndAppendConfigFile, returns the cmd, configFileBz. func ReadAndAppendConfigFile(cmd []string, configFile, localContractRootDir, solidityContractDir string) ([]string, []byte, error) { // if config file is present, read the file and add it to cmd, after running, overwrite the results if configFile != "" { @@ -61,11 +61,11 @@ func ReadAndAppendConfigFile(cmd []string, configFile, localContractRootDir, sol return cmd, nil, nil } -// WriteConfigFile - if config file is present, we need to overwrite what forge changed +// WriteConfigFile - if config file is present, we need to overwrite what forge changed. func WriteConfigFile(configFile string, localContractRootDir string, solidityContractDir string, configFileBz []byte) error { if configFile != "" { configFilePath := GetConfigFilePath(configFile, localContractRootDir, solidityContractDir) - err := os.WriteFile(configFilePath, configFileBz, 0644) + err := os.WriteFile(configFilePath, configFileBz, 0o644) if err != nil { return err } diff --git a/chain/ethereum/geth/default_configs.go b/chain/ethereum/geth/default_configs.go index a38235c8f..e114d6f2f 100644 --- a/chain/ethereum/geth/default_configs.go +++ b/chain/ethereum/geth/default_configs.go @@ -31,7 +31,7 @@ func DefaultEthereumGethChainConfig( "--verbosity", "4", // Level = debug "--networkid", "15", "--rpc.txfeecap", "50.0", // 50 eth - "--rpc.gascap", "30000000", //30M + "--rpc.gascap", "30000000", // 30M "--gpo.percentile", "150", // default 60 "--gpo.ignoreprice", "1000000000", // 1gwei, default 2 "--dev.gaslimit", "30000000", // 30M, default 11.5M @@ -58,7 +58,7 @@ func DefaultBscChainConfig( { Repository: "ghcr.io/bnb-chain/bsc", Version: "1.2.13", // same version as other sim tests - //Version: "1.4.13", // this version does not work in dev mode (1.3.x+) + // Version: "1.4.13", // this version does not work in dev mode (1.3.x+) UidGid: "1000:1000", }, }, @@ -69,7 +69,7 @@ func DefaultBscChainConfig( "--verbosity", "4", // Level = debug "--networkid", "15", "--rpc.txfeecap", "50.0", // 50 eth - "--rpc.gascap", "30000000", //30M + "--rpc.gascap", "30000000", // 30M "--gpo.percentile", "150", // default 60 "--gpo.ignoreprice", "1000000000", // 1gwei, default 2 "--dev.gaslimit", "30000000", // 30M, default 11.5M diff --git a/chain/ethereum/geth/geth_chain.go b/chain/ethereum/geth/geth_chain.go index cf9538870..1307ca044 100644 --- a/chain/ethereum/geth/geth_chain.go +++ b/chain/ethereum/geth/geth_chain.go @@ -8,14 +8,14 @@ import ( "sync" "time" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/docker/docker/api/types/mount" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/strangelove-ventures/interchaintest/v8/chain/ethereum" "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" + + "github.com/cosmos/cosmos-sdk/crypto/hd" ) var _ ibc.Chain = &GethChain{} @@ -40,7 +40,8 @@ func NewGethChain(testName string, chainConfig ibc.ChainConfig, log *zap.Logger) } func (c *GethChain) Start(testName string, ctx context.Context, additionalGenesisWallets ...ibc.WalletAmount) error { - cmd := []string{c.Config().Bin, + cmd := []string{ + c.Config().Bin, "--dev", "--datadir", c.HomeDir(), "-http", "--http.addr", "0.0.0.0", "--http.port", "8545", "--allow-insecure-unlock", "--http.api", "eth,net,web3,miner,personal,txpool,debug", "--http.corsdomain", "*", "-nodiscover", "--http.vhosts=*", "--miner.gasprice", c.Config().GasPrices, @@ -52,13 +53,13 @@ func (c *GethChain) Start(testName string, ctx context.Context, additionalGenesi return c.EthereumChain.Start(ctx, cmd, []mount.Mount{}) } -// JavaScriptExec() - Execute web3 code via geth's attach command +// JavaScriptExec() - Execute web3 code via geth's attach command. func (c *GethChain) JavaScriptExec(ctx context.Context, jsCmd string) (stdout, stderr []byte, err error) { cmd := []string{c.Config().Bin, "--exec", jsCmd, "--datadir", c.HomeDir(), "attach"} return c.Exec(ctx, cmd, nil) } -// JavaScriptExecTx() - Execute a tx via web3, function ensures account is unlocked and blocks multiple txs +// JavaScriptExecTx() - Execute a tx via web3, function ensures account is unlocked and blocks multiple txs. func (c *GethChain) JavaScriptExecTx(ctx context.Context, account *NodeWallet, jsCmd string) (stdout, stderr []byte, err error) { if err := c.UnlockAccount(ctx, account); err != nil { return nil, nil, err @@ -88,7 +89,8 @@ func (c *GethChain) CreateKey(ctx context.Context, keyName string) error { EOF -`, c.HomeDir())} +`, c.HomeDir()), + } _, _, err := c.Exec(ctx, cmd, nil) if err != nil { return err @@ -128,7 +130,7 @@ func (c *GethChain) RecoverKey(ctx context.Context, keyName, mnemonic string) er return nil } -// Get address of account, cast to a string to use +// Get address of account, cast to a string to use. func (c *GethChain) GetAddress(ctx context.Context, keyName string) ([]byte, error) { account, found := c.keynameToAccountMap[keyName] if !found { @@ -200,7 +202,7 @@ func (c *GethChain) SendFundsWithNote(ctx context.Context, keyName string, amoun } // DeployContract creates a new contract on-chain, returning the contract address -// Constructor params are appended to the byteCode +// Constructor params are appended to the byteCode. func (c *GethChain) DeployContract(ctx context.Context, keyName string, abi []byte, byteCode []byte) (string, error) { account, found := c.keynameToAccountMap[keyName] if !found { diff --git a/chain/ethereum/wallet.go b/chain/ethereum/wallet.go index 86e6688a7..0993065b8 100644 --- a/chain/ethereum/wallet.go +++ b/chain/ethereum/wallet.go @@ -25,17 +25,17 @@ func (w *EthereumWallet) KeyName() string { return w.keyName } -// Get formatted address, passing in a prefix +// Get formatted address, passing in a prefix. func (w *EthereumWallet) FormattedAddress() string { return hexutil.Encode(w.address) } -// Get mnemonic, only used for relayer wallets +// Get mnemonic, only used for relayer wallets. func (w *EthereumWallet) Mnemonic() string { return w.mnemonic } -// Get Address with chain's prefix +// Get Address with chain's prefix. func (w *EthereumWallet) Address() []byte { return w.address } diff --git a/chain/internal/tendermint/events_test.go b/chain/internal/tendermint/events_test.go index 558723165..4a7643c4a 100644 --- a/chain/internal/tendermint/events_test.go +++ b/chain/internal/tendermint/events_test.go @@ -3,8 +3,9 @@ package tendermint import ( "testing" - abcitypes "github.com/cometbft/cometbft/abci/types" "github.com/stretchr/testify/require" + + abcitypes "github.com/cometbft/cometbft/abci/types" ) func TestAttributeValue(t *testing.T) { diff --git a/chain/internal/tendermint/tendermint_node.go b/chain/internal/tendermint/tendermint_node.go index ab9ff578f..6b0aeb2de 100644 --- a/chain/internal/tendermint/tendermint_node.go +++ b/chain/internal/tendermint/tendermint_node.go @@ -9,11 +9,6 @@ import ( "time" "github.com/avast/retry-go/v4" - tmjson "github.com/cometbft/cometbft/libs/json" - "github.com/cometbft/cometbft/p2p" - rpcclient "github.com/cometbft/cometbft/rpc/client" - rpchttp "github.com/cometbft/cometbft/rpc/client/http" - libclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" volumetypes "github.com/docker/docker/api/types/volume" dockerclient "github.com/docker/docker/client" "github.com/docker/go-connections/nat" @@ -22,9 +17,15 @@ import ( "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" + + tmjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/p2p" + rpcclient "github.com/cometbft/cometbft/rpc/client" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + libclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" ) -// TendermintNode represents a node in the test network that is being created +// TendermintNode represents a node in the test network that is being created. type TendermintNode struct { Log *zap.Logger @@ -50,8 +51,10 @@ func NewTendermintNode( testName string, image ibc.DockerImage, ) (*TendermintNode, error) { - tn := &TendermintNode{Log: log, Index: i, Chain: c, - DockerClient: dockerClient, NetworkID: networkID, TestName: testName, Image: image} + tn := &TendermintNode{ + Log: log, Index: i, Chain: c, + DockerClient: dockerClient, NetworkID: networkID, TestName: testName, Image: image, + } tn.containerLifecycle = dockerutil.NewContainerLifecycle(log, dockerClient, tn.Name()) @@ -81,11 +84,11 @@ func NewTendermintNode( return tn, nil } -// TendermintNodes is a collection of TendermintNode +// TendermintNodes is a collection of TendermintNode. type TendermintNodes []*TendermintNode const ( - // BlockTimeSeconds (in seconds) is approx time to create a block + // BlockTimeSeconds (in seconds) is approx time to create a block. BlockTimeSeconds = 2 p2pPort = "26656/tcp" @@ -95,17 +98,15 @@ const ( privValPort = "1234/tcp" ) -var ( - sentryPorts = nat.PortMap{ - nat.Port(p2pPort): {}, - nat.Port(rpcPort): {}, - nat.Port(grpcPort): {}, - nat.Port(apiPort): {}, - nat.Port(privValPort): {}, - } -) +var sentryPorts = nat.PortMap{ + 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 TendermintNode +// NewClient creates and assigns a new Tendermint RPC client to the TendermintNode. func (tn *TendermintNode) NewClient(addr string) error { httpClient, err := libclient.DefaultHTTPClient(addr) if err != nil { @@ -122,7 +123,7 @@ func (tn *TendermintNode) NewClient(addr string) error { return nil } -// Name is the hostname of the test node container +// Name is the hostname of the test node container. func (tn *TendermintNode) Name() string { return fmt.Sprintf("node-%d-%s-%s", tn.Index, tn.Chain.Config().ChainID, dockerutil.SanitizeContainerName(tn.TestName)) } @@ -171,7 +172,7 @@ type PrivValidatorKeyFile struct { PrivKey PrivValidatorKey `json:"priv_key"` } -// Bind returns the home folder bind point for running the node +// Bind returns the home folder bind point for running the node. func (tn *TendermintNode) Bind() []string { return []string{fmt.Sprintf("%s:%s", tn.VolumeName, tn.HomeDir())} } @@ -180,7 +181,7 @@ func (tn *TendermintNode) HomeDir() string { return path.Join("/var/tendermint", tn.Chain.Config().Name) } -// SetConfigAndPeers modifies the config for a validator node to start a chain +// SetConfigAndPeers modifies the config for a validator node to start a chain. func (tn *TendermintNode) SetConfigAndPeers(ctx context.Context, peers string) error { c := make(testutil.Toml) @@ -233,7 +234,7 @@ func (tn *TendermintNode) SetConfigAndPeers(ctx context.Context, peers string) e // Tenderment deprecate snake_case in config for hyphen-case in v0.34.1 // https://github.com/cometbft/cometbft/blob/main/CHANGELOG.md#v0341 func (tn *TendermintNode) GetConfigSeparator() (string, error) { - var sep = "_" + sep := "_" currentTnVersion, err := version.NewVersion(tn.Image.Version[1:]) if err != nil { @@ -258,9 +259,10 @@ func (tn *TendermintNode) Height(ctx context.Context) (int64, error) { return stat.SyncInfo.LatestBlockHeight, nil } -// InitHomeFolder initializes a home folder for the given node +// InitHomeFolder initializes a home folder for the given node. func (tn *TendermintNode) InitHomeFolder(ctx context.Context, mode string) error { - command := []string{tn.Chain.Config().Bin, "init", mode, + command := []string{ + tn.Chain.Config().Bin, "init", mode, "--home", tn.HomeDir(), } _, _, err := tn.Exec(ctx, command, tn.Chain.Config().Env) @@ -311,7 +313,7 @@ func (tn *TendermintNode) StartContainer(ctx context.Context) error { }, retry.Context(ctx), retry.DelayType(retry.BackOffDelay)) } -// InitValidatorFiles creates the node files and signs a genesis transaction +// InitValidatorFiles creates the node files and signs a genesis transaction. func (tn *TendermintNode) InitValidatorFiles(ctx context.Context) error { return tn.InitHomeFolder(ctx, "validator") } @@ -320,7 +322,7 @@ func (tn *TendermintNode) InitFullNodeFiles(ctx context.Context) error { return tn.InitHomeFolder(ctx, "full") } -// NodeID returns the node of a given node +// NodeID returns the node of a given node. func (tn *TendermintNode) NodeID(ctx context.Context) (string, error) { // This used to call p2p.LoadNodeKey against the file on the host, // but because we are transitioning to operating on Docker volumes, @@ -338,7 +340,7 @@ func (tn *TendermintNode) NodeID(ctx context.Context) (string, error) { return string(nk.ID()), nil } -// PeerString returns the string for connecting the nodes passed in +// PeerString returns the string for connecting the nodes passed in. func (tn TendermintNodes) PeerString(ctx context.Context, node *TendermintNode) string { addrs := make([]string, len(tn)) for i, n := range tn { @@ -360,7 +362,7 @@ func (tn TendermintNodes) PeerString(ctx context.Context, node *TendermintNode) return strings.Join(addrs, ",") } -// LogGenesisHashes logs the genesis hashes for the various nodes +// LogGenesisHashes logs the genesis hashes for the various nodes. func (tn TendermintNodes) LogGenesisHashes(ctx context.Context) error { for _, n := range tn { gen, err := n.GenesisFileContent(ctx) diff --git a/chain/penumbra/penumbra_app_node.go b/chain/penumbra/penumbra_app_node.go index 7f61ed81d..9a6e033c7 100644 --- a/chain/penumbra/penumbra_app_node.go +++ b/chain/penumbra/penumbra_app_node.go @@ -53,8 +53,10 @@ func NewPenumbraAppNode( networkID string, image ibc.DockerImage, ) (*PenumbraAppNode, error) { - pn := &PenumbraAppNode{log: log, Index: index, Chain: chain, - DockerClient: dockerClient, NetworkID: networkID, TestName: testName, Image: image} + pn := &PenumbraAppNode{ + log: log, Index: index, Chain: chain, + DockerClient: dockerClient, NetworkID: networkID, TestName: testName, Image: image, + } pn.containerLifecycle = dockerutil.NewContainerLifecycle(log, dockerClient, pn.Name()) @@ -301,7 +303,7 @@ func (p *PenumbraAppNode) GetAddress(ctx context.Context, keyName string) ([]byt } // GetBalance attempts to query the token balances for a specified key name via an instance of pcli. -// TODO we need to change the func sig to take a denom then filter out the target denom bal from stdout +// TODO we need to change the func sig to take a denom then filter out the target denom bal from stdout. func (p *PenumbraAppNode) GetBalance(ctx context.Context, keyName string) (int64, error) { keyPath := filepath.Join(p.HomeDir(), "keys", keyName) cmd := []string{"pcli", "--home", keyPath, "view", "balance"} @@ -398,7 +400,8 @@ func (p *PenumbraAppNode) SendIBCTransfer(ctx context.Context, channelID, keyNam parts := strings.Split(channelID, "-") chanNum := parts[1] - cmd := []string{"pcli", "--home", keyPath, "tx", "withdraw", + cmd := []string{ + "pcli", "--home", keyPath, "tx", "withdraw", "--to", amount.Address, "--channel", chanNum, "--timeout-height", fmt.Sprintf("0-%d", opts.Timeout.Height), diff --git a/chain/penumbra/penumbra_chain.go b/chain/penumbra/penumbra_chain.go index dc8ba12c7..3f59f46c2 100644 --- a/chain/penumbra/penumbra_chain.go +++ b/chain/penumbra/penumbra_chain.go @@ -10,13 +10,7 @@ import ( "strings" "sync" - "cosmossdk.io/math" "github.com/BurntSushi/toml" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/docker/docker/api/types" "github.com/docker/docker/client" "github.com/strangelove-ventures/interchaintest/v8/chain/internal/tendermint" @@ -25,6 +19,14 @@ import ( "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" "golang.org/x/sync/errgroup" + + "cosmossdk.io/math" + + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/crypto/keyring" ) type PenumbraChain struct { @@ -130,7 +132,7 @@ func (c *PenumbraChain) GetGRPCAddress() string { return fmt.Sprintf("%s:9090", c.getFullNode().TendermintNode.HostName()) } -// Implements Chain interface +// Implements Chain interface. func (c *PenumbraChain) GetHostPeerAddress() string { panic("NOT IMPLEMENTED") } @@ -235,7 +237,7 @@ func (c *PenumbraChain) SendFunds(ctx context.Context, keyName string, amount ib } // SendFundsWithNote will initiate a local transfer from the account associated with the specified keyName, -// amount, token denom, and recipient are specified in the amount and attach a note/memo +// amount, token denom, and recipient are specified in the amount and attach a note/memo. func (c *PenumbraChain) SendFundsWithNote(ctx context.Context, keyName string, amount ibc.WalletAmount, note string) (string, error) { panic("Penumbrachain: SendFundsWithNote unimplemented") } diff --git a/chain/penumbra/penumbra_client_node.go b/chain/penumbra/penumbra_client_node.go index 8e210166d..70e618993 100644 --- a/chain/penumbra/penumbra_client_node.go +++ b/chain/penumbra/penumbra_client_node.go @@ -10,14 +10,7 @@ import ( "strings" "time" - "cosmossdk.io/math" "github.com/BurntSushi/toml" - transfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" - transactionv1 "github.com/strangelove-ventures/interchaintest/v8/chain/penumbra/core/transaction/v1" - - //nolint:staticcheck - clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" - volumetypes "github.com/docker/docker/api/types/volume" "github.com/docker/docker/client" "github.com/docker/go-connections/nat" @@ -26,6 +19,7 @@ import ( pool "github.com/strangelove-ventures/interchaintest/v8/chain/penumbra/core/component/shielded_pool/v1" keys "github.com/strangelove-ventures/interchaintest/v8/chain/penumbra/core/keys/v1" num "github.com/strangelove-ventures/interchaintest/v8/chain/penumbra/core/num/v1" + transactionv1 "github.com/strangelove-ventures/interchaintest/v8/chain/penumbra/core/transaction/v1" custody "github.com/strangelove-ventures/interchaintest/v8/chain/penumbra/custody/v1" view "github.com/strangelove-ventures/interchaintest/v8/chain/penumbra/view/v1" "github.com/strangelove-ventures/interchaintest/v8/dockerutil" @@ -34,6 +28,12 @@ import ( "go.uber.org/zap" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" + + "cosmossdk.io/math" + + transfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" + //nolint:staticcheck + clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" ) // PenumbraClientNode represents an instance of pclientd. @@ -263,7 +263,7 @@ func (p *PenumbraClientNode) SendFunds(ctx context.Context, amount ibc.WalletAmo // SendIBCTransfer sends an IBC transfer from the current PenumbraClientNode to a specified destination address on a specified channel. // The function validates the address string on the current PenumbraClientNode instance. If the address string is empty, it returns an error. -// It translates the amount to a big integer and creates an `ibcv1.Ics20Withdrawal` with the amount, denom, destination address, return address, timeout height, timeout timestamp +// It translates the amount to a big integer and creates an `ibcv1.Ics20Withdrawal` with the amount, denom, destination address, return address, timeout height, timeout timestamp. func (p *PenumbraClientNode) SendIBCTransfer( ctx context.Context, channelID string, diff --git a/chain/penumbra/penumbra_client_node_test.go b/chain/penumbra/penumbra_client_node_test.go index c18f2f1c5..f9d899dfc 100644 --- a/chain/penumbra/penumbra_client_node_test.go +++ b/chain/penumbra/penumbra_client_node_test.go @@ -4,9 +4,10 @@ import ( "math/big" "testing" - "cosmossdk.io/math" "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/stretchr/testify/require" + + "cosmossdk.io/math" ) // TestBigIntDecoding tests the decoding of big integers. @@ -30,7 +31,7 @@ func TestBigIntDecoding(t *testing.T) { // Scenario 2: options has nil timeout value - return default timeout values // Scenario 3: both timeout values equal non-zero values - use specified timeout values // Scenario 4: only nanoseconds equals non-zero value - use specified value for timestamp and zero for height -// Scenario 5: only height equals non-zero value - use specified value for height and zero for timestamp +// Scenario 5: only height equals non-zero value - use specified value for height and zero for timestamp. func TestIbcTransferTimeout(t *testing.T) { defaultHeight, defaultTimestamp := defaultTransferTimeouts() zero := uint64(0) diff --git a/chain/penumbra/wallet.go b/chain/penumbra/wallet.go index 41cbc88af..8f4403890 100644 --- a/chain/penumbra/wallet.go +++ b/chain/penumbra/wallet.go @@ -14,7 +14,7 @@ type PenumbraWallet struct { chainCfg ibc.ChainConfig } -// NewWallet creates a new instance of PenumbraWallet with the provided parameters +// NewWallet creates a new instance of PenumbraWallet with the provided parameters. func NewWallet(keyname string, address []byte, mnemonic string, chainCfg ibc.ChainConfig) *PenumbraWallet { return &PenumbraWallet{ mnemonic: mnemonic, diff --git a/chain/polkadot/keys.go b/chain/polkadot/keys.go index 18489ff4c..57fbed896 100644 --- a/chain/polkadot/keys.go +++ b/chain/polkadot/keys.go @@ -5,10 +5,9 @@ import ( "encoding/hex" "fmt" - "github.com/decred/dcrd/dcrec/secp256k1/v2" - schnorrkel "github.com/ChainSafe/go-schnorrkel/1" "github.com/StirlingMarketingGroup/go-namecase" + "github.com/decred/dcrd/dcrec/secp256k1/v2" p2pCrypto "github.com/libp2p/go-libp2p/core/crypto" "golang.org/x/crypto/blake2b" ) @@ -18,7 +17,7 @@ const ( ss58Secp256k1Prefix = "Secp256k1HDKD" ) -var DEV_SEED, _ = hex.DecodeString("fac7959dbfe72f052e5a0c3c8d6530f202b02fd8f9f5ca3580ec8deb7797479e") +var DevSeed, _ = hex.DecodeString("fac7959dbfe72f052e5a0c3c8d6530f202b02fd8f9f5ca3580ec8deb7797479e") func DeriveEd25519FromName(name string) (*p2pCrypto.Ed25519PrivateKey, error) { chainCode := make([]byte, 32) @@ -33,7 +32,7 @@ func DeriveEd25519FromName(name string) (*p2pCrypto.Ed25519PrivateKey, error) { toHash := []byte{byte(len(ss58Ed25519Prefix) << 2)} toHash = append(toHash, []byte(ss58Ed25519Prefix)...) - toHash = append(toHash, DEV_SEED...) + toHash = append(toHash, DevSeed...) toHash = append(toHash, chainCode...) if _, err := hasher.Write(toHash); err != nil { @@ -60,7 +59,7 @@ func DeriveEd25519FromName(name string) (*p2pCrypto.Ed25519PrivateKey, error) { func DeriveSr25519FromName(path []string) (*schnorrkel.MiniSecretKey, error) { var miniSecretSeed [32]byte - _ = copy(miniSecretSeed[:], DEV_SEED[:32]) + _ = copy(miniSecretSeed[:], DevSeed[:32]) miniSecret, err := schnorrkel.NewMiniSecretKeyFromRaw(miniSecretSeed) if err != nil { return nil, fmt.Errorf("error getting mini secret from seed: %w", err) @@ -92,7 +91,7 @@ func DeriveSecp256k1FromName(name string) (*secp256k1.PrivateKey, error) { toHash := []byte{byte(len(ss58Secp256k1Prefix) << 2)} toHash = append(toHash, []byte(ss58Secp256k1Prefix)...) - toHash = append(toHash, DEV_SEED...) + toHash = append(toHash, DevSeed...) toHash = append(toHash, chainCode...) if _, err := hasher.Write(toHash); err != nil { diff --git a/chain/polkadot/parachain_node.go b/chain/polkadot/parachain_node.go index 43bdbebea..c5b809d47 100644 --- a/chain/polkadot/parachain_node.go +++ b/chain/polkadot/parachain_node.go @@ -8,9 +8,7 @@ import ( "path/filepath" "strings" - "cosmossdk.io/math" "github.com/avast/retry-go/v4" - sdktypes "github.com/cosmos/cosmos-sdk/types" "github.com/docker/docker/client" "github.com/icza/dyno" p2pcrypto "github.com/libp2p/go-libp2p/core/crypto" @@ -19,9 +17,13 @@ import ( "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/strangelove-ventures/interchaintest/v8/ibc" "go.uber.org/zap" + + "cosmossdk.io/math" + + sdktypes "github.com/cosmos/cosmos-sdk/types" ) -// Increase parachain wallet amount due to their additional precision +// Increase parachain wallet amount due to their additional precision. const parachainScaling = int64(1_000) // ParachainNode defines the properties required for running a polkadot parachain node. @@ -78,7 +80,7 @@ func (pn *ParachainNode) ParachainChainSpecFileName() string { } // ParachainChainSpecFilePathFull returns the full path to the chain spec file -// within the parachain container +// within the parachain container. func (pn *ParachainNode) ParachainChainSpecFilePathFull() string { return filepath.Join(pn.NodeHome(), pn.ParachainChainSpecFileName()) } @@ -117,7 +119,7 @@ type GetParachainIDResponse struct { ParachainID int `json:"para_id"` } -// GenerateDefaultChainSpec runs build-spec to get the default chain spec into something malleable +// GenerateDefaultChainSpec runs build-spec to get the default chain spec into something malleable. func (pn *ParachainNode) GenerateDefaultChainSpec(ctx context.Context) ([]byte, error) { cmd := []string{ pn.Bin, @@ -132,7 +134,7 @@ func (pn *ParachainNode) GenerateDefaultChainSpec(ctx context.Context) ([]byte, } // GenerateParachainGenesisFile creates the default chain spec, modifies it and returns it. -// The modified chain spec is then written to each Parachain node +// The modified chain spec is then written to each Parachain node. func (pn *ParachainNode) GenerateParachainGenesisFile(ctx context.Context, additionalGenesisWallets ...ibc.WalletAmount) ([]byte, error) { defaultChainSpec, err := pn.GenerateDefaultChainSpec(ctx) if err != nil { @@ -309,7 +311,7 @@ func (pn *ParachainNode) GetBalance(ctx context.Context, address string, denom s return GetBalance(pn.api, address) } -// GetIbcBalance returns the Coins type of ibc coins in account +// GetIbcBalance returns the Coins type of ibc coins in account. func (pn *ParachainNode) GetIbcBalance(ctx context.Context, address string, denom uint64) (sdktypes.Coin, error) { res, err := pn.api.RPC.IBC.QueryBalanceWithAddress(ctx, address, denom) if err != nil { @@ -369,7 +371,7 @@ func (pn *ParachainNode) SendIbcFunds( return nil } -// MintFunds mints an asset for a user on parachain, keyName must be the owner of the asset +// MintFunds mints an asset for a user on parachain, keyName must be the owner of the asset. func (pn *ParachainNode) MintFunds( keyName string, amount ibc.WalletAmount, diff --git a/chain/polkadot/polkadot_chain.go b/chain/polkadot/polkadot_chain.go index 6c71c3b39..ce88f0535 100644 --- a/chain/polkadot/polkadot_chain.go +++ b/chain/polkadot/polkadot_chain.go @@ -9,11 +9,8 @@ import ( "io" "strings" - "cosmossdk.io/math" "github.com/99designs/keyring" "github.com/StirlingMarketingGroup/go-namecase" - sdktypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/go-bip39" "github.com/docker/docker/api/types" volumetypes "github.com/docker/docker/api/types/volume" "github.com/docker/docker/client" @@ -27,9 +24,15 @@ import ( "github.com/strangelove-ventures/interchaintest/v8/ibc" "go.uber.org/zap" "golang.org/x/sync/errgroup" + + "cosmossdk.io/math" + + "github.com/cosmos/go-bip39" + + sdktypes "github.com/cosmos/cosmos-sdk/types" ) -// Increase polkadot wallet amount due to their additional precision +// Increase polkadot wallet amount due to their additional precision. const polkadotScaling = int64(1_000) // PolkadotChain implements the ibc.Chain interface for substrate chains. @@ -74,8 +77,10 @@ type ParachainConfig struct { } // IndexedName is a slice of the substrate dev key names used for key derivation. -var IndexedName = []string{"alice", "bob", "charlie", "dave", "ferdie"} -var IndexedUri = []string{"//Alice", "//Bob", "//Charlie", "//Dave", "//Ferdie"} +var ( + IndexedName = []string{"alice", "bob", "charlie", "dave", "ferdie"} + IndexedUri = []string{"//Alice", "//Bob", "//Charlie", "//Dave", "//Ferdie"} +) // NewPolkadotChain returns an uninitialized PolkadotChain, which implements the ibc.Chain interface. func NewPolkadotChain(log *zap.Logger, testName string, chainConfig ibc.ChainConfig, numRelayChainNodes int, parachains []ParachainConfig) *PolkadotChain { @@ -510,7 +515,7 @@ func (c *PolkadotChain) Start(testName string, ctx context.Context, additionalGe if err := fw.WriteFile(ctx, n.VolumeName, n.RawRelayChainSpecFilePathRelative(), rawChainSpecBytes); err != nil { return fmt.Errorf("error writing raw chain spec: %w", err) } - //fmt.Print(string(rawChainSpecBytes)) + // fmt.Print(string(rawChainSpecBytes)) c.logger().Info("Creating container", zap.String("name", n.Name())) if err := n.CreateNodeContainer(ctx); err != nil { return err @@ -542,7 +547,7 @@ func (c *PolkadotChain) GetRPCAddress() string { if len(c.ParachainNodes) > 0 && len(c.ParachainNodes[0]) > 0 { parachainHostName = c.ParachainNodes[0][0].HostName() - //return fmt.Sprintf("%s:%s", c.ParachainNodes[0][0].HostName(), strings.Split(rpcPort, "/")[0]) + // return fmt.Sprintf("%s:%s", c.ParachainNodes[0][0].HostName(), strings.Split(rpcPort, "/")[0]) } else { parachainHostName = c.RelayChainNodes[0].HostName() } @@ -550,7 +555,7 @@ func (c *PolkadotChain) GetRPCAddress() string { parachainUrl := fmt.Sprintf("http://%s:%s", parachainHostName, port) relaychainUrl := fmt.Sprintf("http://%s:%s", relaychainHostName, port) return fmt.Sprintf("%s,%s", parachainUrl, relaychainUrl) - //return fmt.Sprintf("%s:%s", c.RelayChainNodes[0].HostName(), strings.Split(rpcPort, "/")[0]) + // return fmt.Sprintf("%s:%s", c.RelayChainNodes[0].HostName(), strings.Split(rpcPort, "/")[0]) } // GetGRPCAddress retrieves the grpc address that can be reached by other containers in the docker network. @@ -562,7 +567,7 @@ func (c *PolkadotChain) GetGRPCAddress() string { return fmt.Sprintf("%s:%s", c.RelayChainNodes[0].HostName(), strings.Split(wsPort, "/")[0]) } -// Implements Chain interface +// Implements Chain interface. func (c *PolkadotChain) GetHostPeerAddress() string { panic("NOT IMPLEMENTED") } @@ -720,7 +725,7 @@ func (c *PolkadotChain) GetPublicKey(keyName string) ([]byte, error) { // BuildWallet will return a Polkadot wallet // If mnemonic != "", it will restore using that mnemonic -// If mnemonic == "", it will create a new key +// If mnemonic == "", it will create a new key. func (c *PolkadotChain) BuildWallet(ctx context.Context, keyName string, mnemonic string) (ibc.Wallet, error) { if mnemonic != "" { if err := c.RecoverKey(ctx, keyName, mnemonic); err != nil { @@ -799,7 +804,7 @@ func (c *PolkadotChain) GetBalance(ctx context.Context, address string, denom st return c.ParachainNodes[0][0].GetBalance(ctx, address, denom) } -// AccountInfo contains information of an account +// AccountInfo contains information of an account. type AccountInfo struct { Nonce gstypes.U32 Consumers gstypes.U32 @@ -831,7 +836,7 @@ func (c *PolkadotChain) Timeouts(ctx context.Context, height int64) ([]ibc.Packe panic("[Timeouts] not implemented yet") } -// GetKeyringPair returns the keyring pair from the keyring using keyName +// GetKeyringPair returns the keyring pair from the keyring using keyName. func (c *PolkadotChain) GetKeyringPair(keyName string) (signature.KeyringPair, error) { kp := signature.KeyringPair{} krItem, err := c.keyring.Get(keyName) @@ -847,17 +852,17 @@ func (c *PolkadotChain) GetKeyringPair(keyName string) (signature.KeyringPair, e return kp, nil } -// FindTxs implements blockdb.BlockSaver (Not implemented yet for polkadot, but we don't want to exit) +// FindTxs implements blockdb.BlockSaver (Not implemented yet for polkadot, but we don't want to exit). func (c *PolkadotChain) FindTxs(ctx context.Context, height int64) ([]blockdb.Tx, error) { return []blockdb.Tx{}, nil } -// GetIbcBalance returns the Coins type of ibc coins in account +// GetIbcBalance returns the Coins type of ibc coins in account. func (c *PolkadotChain) GetIbcBalance(ctx context.Context, address string, denom uint64) (sdktypes.Coin, error) { return c.ParachainNodes[0][0].GetIbcBalance(ctx, address, denom) } -// MintFunds mints an asset for a user on parachain, keyName must be the owner of the asset +// MintFunds mints an asset for a user on parachain, keyName must be the owner of the asset. func (c *PolkadotChain) MintFunds(keyName string, amount ibc.WalletAmount) error { return c.ParachainNodes[0][0].MintFunds(keyName, amount) } diff --git a/chain/polkadot/query.go b/chain/polkadot/query.go index 8b0ca27db..1ab1933ee 100644 --- a/chain/polkadot/query.go +++ b/chain/polkadot/query.go @@ -1,12 +1,13 @@ package polkadot import ( - "cosmossdk.io/math" gsrpc "github.com/misko9/go-substrate-rpc-client/v4" gstypes "github.com/misko9/go-substrate-rpc-client/v4/types" + + "cosmossdk.io/math" ) -// GetBalance fetches the current balance for a specific account address using the SubstrateAPI +// GetBalance fetches the current balance for a specific account address using the SubstrateAPI. func GetBalance(api *gsrpc.SubstrateAPI, address string) (math.Int, error) { meta, err := api.RPC.State.GetMetadataLatest() if err != nil { diff --git a/chain/polkadot/relay_chain_node.go b/chain/polkadot/relay_chain_node.go index 27a440938..5450347f5 100644 --- a/chain/polkadot/relay_chain_node.go +++ b/chain/polkadot/relay_chain_node.go @@ -8,19 +8,18 @@ import ( "strings" "time" - "cosmossdk.io/math" "github.com/avast/retry-go/v4" + "github.com/decred/dcrd/dcrec/secp256k1/v2" "github.com/docker/docker/client" "github.com/docker/go-connections/nat" - gsrpc "github.com/misko9/go-substrate-rpc-client/v4" - p2pCrypto "github.com/libp2p/go-libp2p/core/crypto" "github.com/libp2p/go-libp2p/core/peer" - "go.uber.org/zap" - - "github.com/decred/dcrd/dcrec/secp256k1/v2" + gsrpc "github.com/misko9/go-substrate-rpc-client/v4" "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/strangelove-ventures/interchaintest/v8/ibc" + "go.uber.org/zap" + + "cosmossdk.io/math" ) // RelayChainNode defines the properties required for running a polkadot relay chain node. @@ -51,7 +50,7 @@ type RelayChainNodes []*RelayChainNode const ( wsPort = "27451/tcp" - //rpcPort = "27452/tcp" + // rpcPort = "27452/tcp". nodePort = "27452/tcp" rpcPort = "9933/tcp" prometheusPort = "27453/tcp" diff --git a/chain/polkadot/ss58.go b/chain/polkadot/ss58.go index 0abcb3e87..83c77d808 100644 --- a/chain/polkadot/ss58.go +++ b/chain/polkadot/ss58.go @@ -61,7 +61,7 @@ func DecodeAddressSS58(address string) ([]byte, error) { } bss := ss58AddrDecoded[0 : len(ss58AddrDecoded)-checksumLength] checksum, _ := blake2b.New(64, []byte{}) - w := append(checksumPrefix[:], bss[:]...) + w := append(checksumPrefix, bss...) _, err = checksum.Write(w) if err != nil { return nil, err diff --git a/chain/polkadot/tx.go b/chain/polkadot/tx.go index b4afce48c..0df44fe9c 100644 --- a/chain/polkadot/tx.go +++ b/chain/polkadot/tx.go @@ -11,7 +11,7 @@ import ( "github.com/strangelove-ventures/interchaintest/v8/ibc" ) -// SendFundsTx sends funds to a wallet using the SubstrateAPI +// SendFundsTx sends funds to a wallet using the SubstrateAPI. func SendFundsTx(api *gsrpc.SubstrateAPI, senderKeypair signature.KeyringPair, amount ibc.WalletAmount) (gstypes.Hash, error) { hash := gstypes.Hash{} meta, err := api.RPC.State.GetMetadataLatest() @@ -37,7 +37,7 @@ func SendFundsTx(api *gsrpc.SubstrateAPI, senderKeypair signature.KeyringPair, a return CreateSignSubmitExt(api, meta, senderKeypair, call) } -// Turns on sending and receiving ibc transfers +// Turns on sending and receiving ibc transfers. func EnableIbc(api *gsrpc.SubstrateAPI, senderKeypair signature.KeyringPair) (gstypes.Hash, error) { hash := gstypes.Hash{} meta, err := api.RPC.State.GetMetadataLatest() @@ -58,7 +58,7 @@ func EnableIbc(api *gsrpc.SubstrateAPI, senderKeypair signature.KeyringPair) (gs return CreateSignSubmitExt(api, meta, senderKeypair, sc) } -// SendIbcFundsTx sends funds to a wallet using the SubstrateAPI +// SendIbcFundsTx sends funds to a wallet using the SubstrateAPI. func SendIbcFundsTx( api *gsrpc.SubstrateAPI, senderKeypair signature.KeyringPair, @@ -96,7 +96,7 @@ func SendIbcFundsTx( return CreateSignSubmitExt(api, meta, senderKeypair, call) } -// MintFunds mints an asset for a user on parachain, keyName must be the owner of the asset +// MintFunds mints an asset for a user on parachain, keyName must be the owner of the asset. func MintFundsTx( api *gsrpc.SubstrateAPI, senderKeypair signature.KeyringPair, @@ -134,7 +134,7 @@ func MintFundsTx( return CreateSignSubmitExt(api, meta, senderKeypair, call) } -// Common tx function to create an extrinsic and sign/submit it +// Common tx function to create an extrinsic and sign/submit it. func CreateSignSubmitExt( api *gsrpc.SubstrateAPI, meta *gstypes.Metadata, diff --git a/chain/polkadot/wallet.go b/chain/polkadot/wallet.go index 82ac58d12..9d58c9e28 100644 --- a/chain/polkadot/wallet.go +++ b/chain/polkadot/wallet.go @@ -30,13 +30,13 @@ func (w *PolkadotWallet) FormattedAddress() string { return string(w.address) } -// Get mnemonic, only used for relayer wallets +// Get mnemonic, only used for relayer wallets. func (w *PolkadotWallet) Mnemonic() string { return w.mnemonic } // Get Address -// TODO Change to SS58 +// TODO Change to SS58. func (w *PolkadotWallet) Address() []byte { return w.address } diff --git a/chain/thorchain/account_retriever.go b/chain/thorchain/account_retriever.go index 7805a2c7b..ac587c3ba 100644 --- a/chain/thorchain/account_retriever.go +++ b/chain/thorchain/account_retriever.go @@ -5,14 +5,13 @@ import ( "fmt" "strconv" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - grpc "google.golang.org/grpc" "google.golang.org/grpc/metadata" "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" grpctypes "github.com/cosmos/cosmos-sdk/types/grpc" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( diff --git a/chain/thorchain/address.go b/chain/thorchain/address.go index 0021ddc85..61fa9b175 100644 --- a/chain/thorchain/address.go +++ b/chain/thorchain/address.go @@ -4,9 +4,8 @@ import ( "errors" "strings" - "github.com/cosmos/cosmos-sdk/types/bech32" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/bech32" ) // AccAddressFromBech32 creates an AccAddress from a Bech32 string. diff --git a/chain/thorchain/api_query.go b/chain/thorchain/api_query.go index 559243664..d442e5528 100644 --- a/chain/thorchain/api_query.go +++ b/chain/thorchain/api_query.go @@ -12,9 +12,9 @@ import ( "strconv" "strings" - sdkmath "cosmossdk.io/math" - "github.com/strangelove-ventures/interchaintest/v8/chain/thorchain/common" + + sdkmath "cosmossdk.io/math" ) func (c *Thorchain) ApiGetBalances(addr string) (common.Coins, error) { diff --git a/chain/thorchain/broadcaster.go b/chain/thorchain/broadcaster.go index f4b37b474..6dc22a1e3 100644 --- a/chain/thorchain/broadcaster.go +++ b/chain/thorchain/broadcaster.go @@ -8,6 +8,9 @@ import ( "testing" "time" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/testutil" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" @@ -15,8 +18,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/testutil" ) type ClientContextOpt func(clientContext client.Context) client.Context @@ -216,13 +217,11 @@ func BroadcastTx(ctx context.Context, broadcaster *Broadcaster, broadcastingUser err = testutil.WaitForCondition(time.Second*30, time.Second*5, func() (bool, error) { var err error txBytes, err = broadcaster.GetTxResponseBytes(ctx, broadcastingUser) - if err != nil { return false, nil } return true, nil }) - if err != nil { return sdk.TxResponse{}, err } diff --git a/chain/thorchain/codec.go b/chain/thorchain/codec.go index 7c1194638..819956536 100644 --- a/chain/thorchain/codec.go +++ b/chain/thorchain/codec.go @@ -2,6 +2,12 @@ package thorchain import ( "cosmossdk.io/x/upgrade" + + "github.com/cosmos/ibc-go/modules/capability" + transfer "github.com/cosmos/ibc-go/v8/modules/apps/transfer" + ibccore "github.com/cosmos/ibc-go/v8/modules/core" + ibctm "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" + "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -16,11 +22,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/cosmos/ibc-go/modules/capability" - - transfer "github.com/cosmos/ibc-go/v8/modules/apps/transfer" - ibccore "github.com/cosmos/ibc-go/v8/modules/core" - ibctm "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint" ) func DefaultEncoding() testutil.TestEncodingConfig { diff --git a/chain/thorchain/common/chain.go b/chain/thorchain/common/chain.go index b721b8531..ddb4c9ae9 100644 --- a/chain/thorchain/common/chain.go +++ b/chain/thorchain/common/chain.go @@ -22,10 +22,10 @@ const ( type Chain string -// Chains represent a slice of Chain +// Chains represent a slice of Chain. type Chains []Chain -// Valid validates chain format, should consist only of uppercase letters +// Valid validates chain format, should consist only of uppercase letters. func (c Chain) Valid() error { if len(c) < 3 { return errors.New("chain id len is less than 3") @@ -41,7 +41,7 @@ func (c Chain) Valid() error { return nil } -// NewChain create a new Chain and default the siging_algo to Secp256k1 +// NewChain create a new Chain and default the siging_algo to Secp256k1. func NewChain(chainID string) (Chain, error) { chain := Chain(strings.ToUpper(chainID)) if err := chain.Valid(); err != nil { @@ -50,13 +50,13 @@ func NewChain(chainID string) (Chain, error) { return chain, nil } -// String implement fmt.Stringer +// String implement fmt.Stringer. func (c Chain) String() string { // convert it to upper case again just in case someone created a ticker via Chain("rune") return strings.ToUpper(string(c)) } -// GetGasAsset chain's base asset +// GetGasAsset chain's base asset. func (c Chain) GetGasAsset() Asset { switch c { case THORChain: diff --git a/chain/thorchain/module_bank.go b/chain/thorchain/module_bank.go index ef540809b..5d3446f12 100644 --- a/chain/thorchain/module_bank.go +++ b/chain/thorchain/module_bank.go @@ -3,26 +3,26 @@ package thorchain import ( "context" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - - "github.com/strangelove-ventures/interchaintest/v8/ibc" ) -// Deprecated: use BankSend instead +// Deprecated: use BankSend instead. func (tn *ChainNode) SendFunds(ctx context.Context, keyName string, amount ibc.WalletAmount) error { return tn.BankSend(ctx, keyName, amount) } // GetBalance fetches the current balance for a specific account address and denom. -// Implements Chain interface +// Implements Chain interface. func (c *Thorchain) GetBalance(ctx context.Context, address string, denom string) (sdkmath.Int, error) { return c.BankQueryBalance(ctx, address, denom) } -// BankGetBalance is an alias for GetBalance +// BankGetBalance is an alias for GetBalance. func (c *Thorchain) BankQueryBalance(ctx context.Context, address string, denom string) (sdkmath.Int, error) { res, err := banktypes.NewQueryClient(c.GetNode().GrpcConn).Balance(ctx, &banktypes.QueryBalanceRequest{Address: address, Denom: denom}) if err != nil { @@ -31,7 +31,7 @@ func (c *Thorchain) BankQueryBalance(ctx context.Context, address string, denom return res.Balance.Amount, nil } -// AllBalances fetches an account address's balance for all denoms it holds +// AllBalances fetches an account address's balance for all denoms it holds. func (c *Thorchain) BankQueryAllBalances(ctx context.Context, address string) (types.Coins, error) { res, err := banktypes.NewQueryClient(c.GetNode().GrpcConn).AllBalances(ctx, &banktypes.QueryAllBalancesRequest{Address: address}) if err != nil { @@ -40,7 +40,7 @@ func (c *Thorchain) BankQueryAllBalances(ctx context.Context, address string) (t return res.GetBalances(), nil } -// BankDenomMetadata fetches the metadata of a specific coin denomination +// BankDenomMetadata fetches the metadata of a specific coin denomination. func (c *Thorchain) BankQueryDenomMetadata(ctx context.Context, denom string) (*banktypes.Metadata, error) { res, err := banktypes.NewQueryClient(c.GetNode().GrpcConn).DenomMetadata(ctx, &banktypes.QueryDenomMetadataRequest{Denom: denom}) if err != nil { diff --git a/chain/thorchain/module_thorchain.go b/chain/thorchain/module_thorchain.go index ad4240c34..ad0705738 100644 --- a/chain/thorchain/module_thorchain.go +++ b/chain/thorchain/module_thorchain.go @@ -4,9 +4,9 @@ import ( "context" "fmt" - "cosmossdk.io/math" - "github.com/strangelove-ventures/interchaintest/v8/ibc" + + "cosmossdk.io/math" ) // BankSend sends tokens from one account to another. diff --git a/chain/thorchain/poll.go b/chain/thorchain/poll.go index 2b813da9b..74a5e1232 100644 --- a/chain/thorchain/poll.go +++ b/chain/thorchain/poll.go @@ -5,10 +5,10 @@ import ( "errors" "fmt" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/testutil" + + codectypes "github.com/cosmos/cosmos-sdk/codec/types" ) // PollForMessage searches every transaction for a message. Must pass a coded registry capable of decoding the cosmos transaction. @@ -44,7 +44,7 @@ func PollForMessage[T any](ctx context.Context, chain *Thorchain, registry codec return bp.DoPoll(ctx, startHeight, maxHeight) } -// PollForBalance polls until the balance matches +// PollForBalance polls until the balance matches. func PollForBalance(ctx context.Context, chain *Thorchain, deltaBlocks int64, balance ibc.WalletAmount) error { h, err := chain.Height(ctx) if err != nil { diff --git a/chain/thorchain/query.go b/chain/thorchain/query.go index dcb453114..6263de0d3 100644 --- a/chain/thorchain/query.go +++ b/chain/thorchain/query.go @@ -4,9 +4,10 @@ import ( "context" "fmt" - tmtypes "github.com/cometbft/cometbft/rpc/core/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" + + tmtypes "github.com/cometbft/cometbft/rpc/core/types" ) type blockClient interface { diff --git a/chain/thorchain/sidecar.go b/chain/thorchain/sidecar.go index d4a691248..c59bc1b22 100644 --- a/chain/thorchain/sidecar.go +++ b/chain/thorchain/sidecar.go @@ -7,10 +7,9 @@ import ( dockerclient "github.com/docker/docker/client" "github.com/docker/go-connections/nat" - "go.uber.org/zap" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/strangelove-ventures/interchaintest/v8/ibc" + "go.uber.org/zap" ) type SidecarProcesses []*SidecarProcess @@ -158,7 +157,7 @@ func (s *SidecarProcess) GetHostPorts(ctx context.Context, portIDs ...string) ([ // 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 +// docker volume relative to the home directory. func (s *SidecarProcess) WriteFile(ctx context.Context, content []byte, relPath string) error { fw := dockerutil.NewFileWriter(s.logger(), s.DockerClient, s.TestName) return fw.WriteFile(ctx, s.VolumeName, relPath, content) @@ -166,7 +165,7 @@ func (s *SidecarProcess) WriteFile(ctx context.Context, content []byte, relPath // 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 +// the home directory. func (s *SidecarProcess) CopyFile(ctx context.Context, srcPath, dstPath string) error { content, err := os.ReadFile(srcPath) if err != nil { diff --git a/chain/thorchain/thorchain.go b/chain/thorchain/thorchain.go index 078b6a4a3..b00d933e8 100644 --- a/chain/thorchain/thorchain.go +++ b/chain/thorchain/thorchain.go @@ -14,15 +14,6 @@ import ( "strings" "sync" - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/types" - clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" // nolint:staticcheck - chanTypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types" dockertypes "github.com/docker/docker/api/types" volumetypes "github.com/docker/docker/api/types/volume" "github.com/docker/docker/client" @@ -32,6 +23,18 @@ import ( "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" "golang.org/x/sync/errgroup" + + sdkmath "cosmossdk.io/math" + + clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" // nolint:staticcheck + chanTypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types" + + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/cosmos/cosmos-sdk/types" ) type Thorchain struct { @@ -190,12 +193,12 @@ func (c *Thorchain) AddFullNodes(ctx context.Context, configFileOverrides map[st return eg.Wait() } -// Implements Chain interface +// Implements Chain interface. func (c *Thorchain) Config() ibc.ChainConfig { return c.cfg } -// Implements Chain interface +// Implements Chain interface. func (c *Thorchain) Initialize(ctx context.Context, testName string, cli *client.Client, networkID string) error { if err := c.initializeSidecars(ctx, testName, cli, networkID); err != nil { return err @@ -216,7 +219,7 @@ func (c *Thorchain) Exec(ctx context.Context, cmd []string, env []string) (stdou return c.getFullNode().Exec(ctx, cmd, env) } -// Implements Chain interface +// Implements Chain interface. func (c *Thorchain) GetRPCAddress() string { if c.Config().UsesCometMock() { return fmt.Sprintf("http://%s:22331", c.getFullNode().HostnameCometMock()) @@ -225,13 +228,13 @@ func (c *Thorchain) GetRPCAddress() string { return fmt.Sprintf("http://%s:26657", c.getFullNode().HostName()) } -// Implements Chain interface +// Implements Chain interface. func (c *Thorchain) GetAPIAddress() string { return fmt.Sprintf("http://%s:1317", "127.0.0.1") - //return fmt.Sprintf("http://%s:1317", c.getFullNode().HostName()) + // return fmt.Sprintf("http://%s:1317", c.getFullNode().HostName()) } -// Implements Chain interface +// Implements Chain interface. func (c *Thorchain) GetGRPCAddress() string { return fmt.Sprintf("%s:9090", c.getFullNode().HostName()) } @@ -265,17 +268,17 @@ func (c *Thorchain) HomeDir() string { return c.getFullNode().HomeDir() } -// Implements Chain interface +// Implements Chain interface. func (c *Thorchain) CreateKey(ctx context.Context, keyName string) error { return c.getFullNode().CreateKey(ctx, keyName) } -// Implements Chain interface +// Implements Chain interface. func (c *Thorchain) RecoverKey(ctx context.Context, keyName, mnemonic string) error { return c.getFullNode().RecoverKey(ctx, keyName, mnemonic) } -// Implements Chain interface +// Implements Chain interface. func (c *Thorchain) GetAddress(ctx context.Context, keyName string) ([]byte, error) { b32Addr, err := c.getFullNode().AccountKeyBech32(ctx, keyName) if err != nil { @@ -287,7 +290,7 @@ func (c *Thorchain) GetAddress(ctx context.Context, keyName string) ([]byte, err // BuildWallet will return a Cosmos wallet // If mnemonic != "", it will restore using that mnemonic -// If mnemonic == "", it will create a new key +// If mnemonic == "", it will create a new key. func (c *Thorchain) BuildWallet(ctx context.Context, keyName string, mnemonic string) (ibc.Wallet, error) { if mnemonic != "" { c.log.Info("BuildWallet recovering key", zap.String("key_name", keyName)) @@ -339,17 +342,17 @@ func (c *Thorchain) BuildRelayerWallet(ctx context.Context, keyName string) (ibc return NewWallet(keyName, addrBytes, mnemonic, c.cfg), nil } -// Implements Chain interface +// Implements Chain interface. func (c *Thorchain) SendFunds(ctx context.Context, keyName string, amount ibc.WalletAmount) error { return c.getFullNode().BankSend(ctx, keyName, amount) } -// Implements Chain interface +// Implements Chain interface. func (c *Thorchain) SendFundsWithNote(ctx context.Context, keyName string, amount ibc.WalletAmount, note string) (string, error) { return c.getFullNode().BankSendWithNote(ctx, keyName, amount, note) } -// Implements Chain interface +// Implements Chain interface. func (c *Thorchain) SendIBCTransfer( ctx context.Context, channelID string, @@ -425,7 +428,7 @@ func (c *Thorchain) QueryBankMetadata(ctx context.Context, denom string) (*BankM } // ExportState exports the chain state at specific height. -// Implements Chain interface +// Implements Chain interface. func (c *Thorchain) ExportState(ctx context.Context, height int64) (string, error) { return c.getFullNode().ExportState(ctx, height) } @@ -576,7 +579,7 @@ func (c *Thorchain) NewSidecarProcess( return nil } -// creates the test node objects required for bootstrapping tests +// creates the test node objects required for bootstrapping tests. func (c *Thorchain) initializeChainNodes( ctx context.Context, testName string, @@ -653,7 +656,6 @@ func (c *Thorchain) initializeSidecars( } return nil }) - } if err := eg.Wait(); err != nil { return err @@ -781,7 +783,7 @@ func (c *Thorchain) prepNodes(ctx context.Context, genesisAmounts [][]types.Coin return eg.Wait() } -// Bootstraps the chain and starts it from genesis +// Bootstraps the chain and starts it from genesis. func (c *Thorchain) Start(testName string, ctx context.Context, additionalGenesisWallets ...ibc.WalletAmount) error { c.log.Info("Starting", zap.String("chain", c.Config().Name)) chainCfg := c.Config() @@ -861,7 +863,7 @@ func (c *Thorchain) Start(testName string, ctx context.Context, additionalGenesi if len(activeVals) > chainCfg.Genesis.MaxVals { c.log.Warn("Not enough validators to meet 2/3 bond threshold, increase GenesisConfig.MaxVals to reach consensus", zap.Int("required", len(activeVals)), zap.Int("max", chainCfg.Genesis.MaxVals)) - //return fmt.Errorf("too many validators required to meet bond threshold: %d, max allowed: %d: increase this limit to proceed", len(activeVals), chainCfg.Genesis.MaxVals) + // return fmt.Errorf("too many validators required to meet bond threshold: %d, max allowed: %d: increase this limit to proceed", len(activeVals), chainCfg.Genesis.MaxVals) c.NumValidators = chainCfg.Genesis.MaxVals } else { c.NumValidators = len(activeVals) @@ -979,7 +981,7 @@ func (c *Thorchain) Start(testName string, ctx context.Context, additionalGenesi zap.String("chain", exportGenesisChain), zap.String("path", exportGenesis), ) - _ = os.WriteFile(exportGenesis, genBz, 0600) + _ = os.WriteFile(exportGenesis, genBz, 0o600) } chainNodes := c.Nodes() @@ -1050,12 +1052,12 @@ func (c *Thorchain) Start(testName string, ctx context.Context, additionalGenesi return testutil.WaitForBlocks(ctx, 2, c.getFullNode()) } -// Height implements ibc.Chain +// Height implements ibc.Chain. func (c *Thorchain) Height(ctx context.Context) (int64, error) { return c.getFullNode().Height(ctx) } -// Acknowledgements implements ibc.Chain, returning all acknowledgments in block at height +// Acknowledgements implements ibc.Chain, returning all acknowledgments in block at height. func (c *Thorchain) Acknowledgements(ctx context.Context, height int64) ([]ibc.PacketAcknowledgement, error) { var acks []*chanTypes.MsgAcknowledgement err := RangeBlockMessages(ctx, c.cfg.EncodingConfig.InterfaceRegistry, c.getFullNode().Client, height, func(msg types.Msg) bool { @@ -1088,7 +1090,7 @@ func (c *Thorchain) Acknowledgements(ctx context.Context, height int64) ([]ibc.P return ibcAcks, nil } -// Timeouts implements ibc.Chain, returning all timeouts in block at height +// Timeouts implements ibc.Chain, returning all timeouts in block at height. func (c *Thorchain) Timeouts(ctx context.Context, height int64) ([]ibc.PacketTimeout, error) { var timeouts []*chanTypes.MsgTimeout err := RangeBlockMessages(ctx, c.cfg.EncodingConfig.InterfaceRegistry, c.getFullNode().Client, height, func(msg types.Msg) bool { @@ -1128,7 +1130,7 @@ func (c *Thorchain) FindTxs(ctx context.Context, height int64) ([]blockdb.Tx, er return fn.FindTxs(ctx, height) } -// StopAllNodes stops and removes all long running containers (validators and full nodes) +// StopAllNodes stops and removes all long running containers (validators and full nodes). func (c *Thorchain) StopAllNodes(ctx context.Context) error { var eg errgroup.Group for _, n := range c.Nodes() { @@ -1240,7 +1242,7 @@ func (c *Thorchain) StartAllValSidecars(ctx context.Context) error { } // GetTimeoutHeight returns a timeout height of 1000 blocks above the current block height. -// This function should be used when the timeout is never expected to be reached +// This function should be used when the timeout is never expected to be reached. func (c *Thorchain) GetTimeoutHeight(ctx context.Context) (clienttypes.Height, error) { height, err := c.Height(ctx) if err != nil { diff --git a/chain/thorchain/thornode.go b/chain/thorchain/thornode.go index 1e764e747..e3a968560 100644 --- a/chain/thorchain/thornode.go +++ b/chain/thorchain/thornode.go @@ -17,32 +17,33 @@ import ( "time" "github.com/avast/retry-go/v4" - tmjson "github.com/cometbft/cometbft/libs/json" - "github.com/cometbft/cometbft/p2p" - rpcclient "github.com/cometbft/cometbft/rpc/client" - rpchttp "github.com/cometbft/cometbft/rpc/client/http" - coretypes "github.com/cometbft/cometbft/rpc/core/types" - libclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - sdk "github.com/cosmos/cosmos-sdk/types" - authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" volumetypes "github.com/docker/docker/api/types/volume" dockerclient "github.com/docker/docker/client" "github.com/docker/go-connections/nat" "github.com/icza/dyno" + "github.com/strangelove-ventures/interchaintest/v8/blockdb" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" "golang.org/x/mod/semver" "golang.org/x/sync/errgroup" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" - "github.com/strangelove-ventures/interchaintest/v8/blockdb" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testutil" + sdkmath "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + sdk "github.com/cosmos/cosmos-sdk/types" + authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + tmjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/p2p" + rpcclient "github.com/cometbft/cometbft/rpc/client" + rpchttp "github.com/cometbft/cometbft/rpc/client/http" + coretypes "github.com/cometbft/cometbft/rpc/core/types" + libclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" ) type ChainNode struct { @@ -98,13 +99,13 @@ func NewChainNode(log *zap.Logger, validator bool, chain *Thorchain, dockerClien return tn } -// WithPreStartNode sets the preStartNode function for the ChainNode +// WithPreStartNode sets the preStartNode function for the ChainNode. func (tn *ChainNode) WithPreStartNode(preStartNode func(*ChainNode)) *ChainNode { tn.preStartNode = preStartNode return tn } -// ChainNodes is a collection of ChainNode +// ChainNodes is a collection of ChainNode. type ChainNodes []*ChainNode const ( @@ -119,17 +120,15 @@ const ( cometMockRawPort = "22331" ) -var ( - sentryPorts = nat.PortMap{ - nat.Port(p2pPort): {}, - nat.Port(rpcPort): {}, - nat.Port(grpcPort): {}, - nat.Port(apiPort): {}, - nat.Port(privValPort): {}, - } -) +var sentryPorts = nat.PortMap{ + 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 +// 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 { @@ -198,7 +197,7 @@ func (tn *ChainNode) NewSidecarProcess( return nil } -// CliContext creates a new Cosmos SDK client context +// CliContext creates a new Cosmos SDK client context. func (tn *ChainNode) CliContext() client.Context { cfg := tn.Chain.Config() return client.Context{ @@ -214,7 +213,7 @@ func (tn *ChainNode) CliContext() client.Context { } } -// Name of the test node container +// Name of the test node container. func (tn *ChainNode) Name() string { return fmt.Sprintf("%s-%s-%d-%s", tn.Chain.Config().ChainID, tn.NodeType(), tn.Index, dockerutil.SanitizeContainerName(tn.TestName)) } @@ -231,12 +230,12 @@ func (tn *ChainNode) ContainerID() string { return tn.containerLifecycle.ContainerID() } -// hostname of the test node container +// hostname of the test node container. func (tn *ChainNode) HostName() string { return dockerutil.CondenseHostName(tn.Name()) } -// hostname of the comet mock container +// hostname of the comet mock container. func (tn *ChainNode) HostnameCometMock() string { return tn.cometHostname } @@ -288,7 +287,7 @@ type PrivValidatorKeyFile struct { PrivKey PrivValidatorKey `json:"priv_key"` } -// Bind returns the home folder bind point for running the node +// 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())} } @@ -375,7 +374,7 @@ func (tn *ChainNode) SetTestConfig(ctx context.Context) error { ) } -// SetPeers modifies the config persistent_peers for a node +// 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) @@ -485,7 +484,7 @@ func (tn *ChainNode) FindTxs(ctx context.Context, height int64) ([]blockdb.Tx, e // with the chain node binary. func (tn *ChainNode) TxCommand(keyName string, command ...string) []string { command = append([]string{"tx"}, command...) - var gasPriceFound, gasAdjustmentFound, feesFound = false, false, false + gasPriceFound, gasAdjustmentFound, feesFound := false, false, false for i := 0; i < len(command); i++ { if command[i] == "--gas-prices" { gasPriceFound = true @@ -663,7 +662,7 @@ func CondenseMoniker(m string) string { return m[:keepLen] + "..." + m[len(m)-keepLen:] + suffix } -// InitHomeFolder initializes a home folder for the given node +// InitHomeFolder initializes a home folder for the given node. func (tn *ChainNode) InitHomeFolder(ctx context.Context) error { tn.lock.Lock() defer tn.lock.Unlock() @@ -677,7 +676,7 @@ func (tn *ChainNode) InitHomeFolder(ctx context.Context) error { // 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 +// 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) @@ -685,7 +684,7 @@ func (tn *ChainNode) WriteFile(ctx context.Context, content []byte, relPath stri // 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 +// the home directory. func (tn *ChainNode) CopyFile(ctx context.Context, srcPath, dstPath string) error { content, err := os.ReadFile(srcPath) if err != nil { @@ -705,7 +704,7 @@ func (tn *ChainNode) ReadFile(ctx context.Context, relPath string) ([]byte, erro return gen, nil } -// CreateKey creates a key in the keyring backend test for the given node +// 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() @@ -782,7 +781,7 @@ func (tn *ChainNode) ICSVersion(ctx context.Context) string { return "" } -// AddGenesisAccount adds a genesis account for each key +// AddGenesisAccount adds a genesis account for each key. func (tn *ChainNode) AddGenesisAccount(ctx context.Context, address string, genesisAmount []sdk.Coin) error { amount := "" for i, coin := range genesisAmount { @@ -817,7 +816,8 @@ func (tn *ChainNode) AddGenesisAccount(ctx context.Context, address string, gene } func (tn *ChainNode) Version(ctx context.Context) (string, error) { - command := []string{tn.Chain.Config().Bin, "query", "thorchain", "version", "--output", "json", + command := []string{ + tn.Chain.Config().Bin, "query", "thorchain", "version", "--output", "json", "--home", tn.HomeDir(), } @@ -835,7 +835,8 @@ func (tn *ChainNode) Version(ctx context.Context) (string, error) { } func (tn *ChainNode) GetValidatorConsPubKey(ctx context.Context) (string, error) { - command := []string{tn.Chain.Config().Bin, "tendermint", "show-validator", + command := []string{ + tn.Chain.Config().Bin, "tendermint", "show-validator", "--home", tn.HomeDir(), } @@ -1236,7 +1237,6 @@ func (tn *ChainNode) GetBuildInformation(ctx context.Context) *BinaryBuildInform Replacement: r, ReplacementVersion: rV, } - } else { // Ex: "github.com/aaa/bbb@v0.0.0-20191008050251-8e49817e8af4" parent, version := getRepoAndVersion(dep) @@ -1534,14 +1534,14 @@ func (tn *ChainNode) RemoveContainer(ctx context.Context) error { return tn.containerLifecycle.RemoveContainer(ctx) } -// InitValidatorFiles creates the node files and signs a genesis transaction +// InitValidatorFiles creates the node files and signs a genesis transaction. func (tn *ChainNode) InitValidatorGenTx( ctx context.Context, chainType *ibc.ChainConfig, genesisAmounts []sdk.Coin, genesisSelfDelegation sdk.Coin, ) error { - //if err := tn.CreateKey(ctx, valKey); err != nil { + // if err := tn.CreateKey(ctx, valKey); err != nil { // return err //} // Thorchain will only start with 1 validator @@ -1557,7 +1557,7 @@ func (tn *ChainNode) InitValidatorGenTx( return err } return nil - //return tn.Gentx(ctx, valKey, genesisSelfDelegation) + // return tn.Gentx(ctx, valKey, genesisSelfDelegation) } func (tn *ChainNode) InitFullNodeFiles(ctx context.Context) error { @@ -1610,7 +1610,7 @@ func (tn *ChainNode) AccountKeyBech32(ctx context.Context, name string) (string, return tn.KeyBech32(ctx, name, "") } -// PeerString returns the string for connecting the nodes passed in +// PeerString returns the string for connecting the nodes passed in. func (nodes ChainNodes) PeerString(ctx context.Context) string { addrs := make([]string, len(nodes)) for i, n := range nodes { @@ -1644,7 +1644,7 @@ func (nodes ChainNodes) SidecarBifrostPeers() string { return strings.Join(addrs, ",") } -// LogGenesisHashes logs the genesis hashes for the various nodes +// LogGenesisHashes logs the genesis hashes for the various nodes. func (nodes ChainNodes) LogGenesisHashes(ctx context.Context) error { for _, n := range nodes { gen, err := n.GenesisFileContent(ctx) @@ -1701,7 +1701,7 @@ func (tn *ChainNode) QueryICA(ctx context.Context, connectionID, address string) } // GetHostAddress returns the host-accessible url for a port in the container. -// This is useful for finding the url & random host port for ports exposed via ChainConfig.ExposeAdditionalPorts +// This is useful for finding the url & random host port for ports exposed via ChainConfig.ExposeAdditionalPorts. func (tn *ChainNode) GetHostAddress(ctx context.Context, portID string) (string, error) { ports, err := tn.containerLifecycle.GetHostPorts(ctx, portID) if err != nil { diff --git a/chain/thorchain/types.go b/chain/thorchain/types.go index 243f13855..33d9be164 100644 --- a/chain/thorchain/types.go +++ b/chain/thorchain/types.go @@ -85,7 +85,7 @@ type DenomAuthorityMetadata struct { // thorchain openapi types -// InboundAddress struct for InboundAddress +// InboundAddress struct for InboundAddress. type InboundAddress struct { Chain *string `json:"chain,omitempty"` PubKey *string `json:"pub_key,omitempty"` @@ -111,7 +111,7 @@ type InboundAddress struct { DustThreshold *string `json:"dust_threshold,omitempty"` } -// LiquidityProvider struct for LiquidityProvider +// LiquidityProvider struct for LiquidityProvider. type LiquidityProvider struct { Asset string `json:"asset"` RuneAddress *string `json:"rune_address,omitempty"` @@ -131,7 +131,7 @@ type LiquidityProvider struct { LuviGrowthPct *string `json:"luvi_growth_pct,omitempty"` } -// Saver struct for Saver +// Saver struct for Saver. type Saver struct { Asset string `json:"asset"` AssetAddress string `json:"asset_address"` @@ -143,7 +143,7 @@ type Saver struct { GrowthPct string `json:"growth_pct"` } -// Pool struct for Pool +// Pool struct for Pool. type Pool struct { Asset string `json:"asset"` ShortCode *string `json:"short_code,omitempty"` @@ -185,7 +185,7 @@ type Pool struct { DerivedDepthBps string `json:"derived_depth_bps"` } -// QuoteFees struct for QuoteFees +// QuoteFees struct for QuoteFees. type QuoteFees struct { // the target asset used for all fees Asset string `json:"asset"` @@ -203,7 +203,7 @@ type QuoteFees struct { TotalBps int64 `json:"total_bps"` } -// QuoteSwapResponse struct for QuoteSwapResponse +// QuoteSwapResponse struct for QuoteSwapResponse. type QuoteSwapResponse struct { // the inbound address for the transaction on the source chain InboundAddress *string `json:"inbound_address,omitempty"` @@ -246,7 +246,7 @@ type QuoteSwapResponse struct { TotalSwapSeconds *int64 `json:"total_swap_seconds,omitempty"` } -// QuoteSaverDepositResponse struct for QuoteSaverDepositResponse +// QuoteSaverDepositResponse struct for QuoteSaverDepositResponse. type QuoteSaverDepositResponse struct { // the inbound address for the transaction on the source chain InboundAddress string `json:"inbound_address"` @@ -283,7 +283,7 @@ type QuoteSaverDepositResponse struct { ExpectedAmountDeposit string `json:"expected_amount_deposit"` } -// InboundObservedStage struct for InboundObservedStage +// InboundObservedStage struct for InboundObservedStage. type InboundObservedStage struct { // returns true if any nodes have observed the transaction (to be deprecated in favour of counts) Started *bool `json:"started,omitempty"` @@ -295,7 +295,7 @@ type InboundObservedStage struct { Completed bool `json:"completed"` } -// InboundConfirmationCountedStage struct for InboundConfirmationCountedStage +// InboundConfirmationCountedStage struct for InboundConfirmationCountedStage. type InboundConfirmationCountedStage struct { // the THORChain block height when confirmation counting began CountingStartHeight *int64 `json:"counting_start_height,omitempty"` @@ -311,13 +311,13 @@ type InboundConfirmationCountedStage struct { Completed bool `json:"completed"` } -// InboundFinalisedStage struct for InboundFinalisedStage +// InboundFinalisedStage struct for InboundFinalisedStage. type InboundFinalisedStage struct { // returns true if the inbound transaction has been finalised (THORChain agreeing it exists) Completed bool `json:"completed"` } -// StreamingStatus struct for StreamingStatus +// StreamingStatus struct for StreamingStatus. type StreamingStatus struct { // how often each swap is made, in blocks Interval int64 `json:"interval"` @@ -327,20 +327,20 @@ type StreamingStatus struct { Count int64 `json:"count"` } -// SwapStatus struct for SwapStatus +// SwapStatus struct for SwapStatus. type SwapStatus struct { // true when awaiting a swap Pending bool `json:"pending"` Streaming *StreamingStatus `json:"streaming,omitempty"` } -// SwapFinalisedStage struct for SwapFinalisedStage +// SwapFinalisedStage struct for SwapFinalisedStage. type SwapFinalisedStage struct { // (to be deprecated in favor of swap_status) returns true if an inbound transaction's swap (successful or refunded) is no longer pending Completed bool `json:"completed"` } -// OutboundDelayStage struct for OutboundDelayStage +// OutboundDelayStage struct for OutboundDelayStage. type OutboundDelayStage struct { // the number of remaining THORChain blocks the outbound will be delayed RemainingDelayBlocks *int64 `json:"remaining_delay_blocks,omitempty"` @@ -350,7 +350,7 @@ type OutboundDelayStage struct { Completed bool `json:"completed"` } -// OutboundSignedStage struct for OutboundSignedStage +// OutboundSignedStage struct for OutboundSignedStage. type OutboundSignedStage struct { // THORChain height for which the external outbound is scheduled ScheduledOutboundHeight *int64 `json:"scheduled_outbound_height,omitempty"` @@ -360,7 +360,7 @@ type OutboundSignedStage struct { Completed bool `json:"completed"` } -// TxStagesResponse struct for TxStagesResponse +// TxStagesResponse struct for TxStagesResponse. type TxStagesResponse struct { InboundObserved InboundObservedStage `json:"inbound_observed"` InboundConfirmationCounted *InboundConfirmationCountedStage `json:"inbound_confirmation_counted,omitempty"` @@ -371,14 +371,14 @@ type TxStagesResponse struct { OutboundSigned *OutboundSignedStage `json:"outbound_signed,omitempty"` } -// Coin struct for Coin +// Coin struct for Coin. type Coin struct { Asset string `json:"asset"` Amount string `json:"amount"` Decimals *int64 `json:"decimals,omitempty"` } -// Tx struct for Tx +// Tx struct for Tx. type Tx struct { Id *string `json:"id,omitempty"` Chain *string `json:"chain,omitempty"` @@ -389,7 +389,7 @@ type Tx struct { Memo *string `json:"memo,omitempty"` } -// ObservedTx struct for ObservedTx +// ObservedTx struct for ObservedTx. type ObservedTx struct { Tx Tx `json:"tx"` ObservedPubKey *string `json:"observed_pub_key,omitempty"` @@ -409,7 +409,7 @@ type ObservedTx struct { Status *string `json:"status,omitempty"` } -// TxOutItem struct for TxOutItem +// TxOutItem struct for TxOutItem. type TxOutItem struct { Chain string `json:"chain"` ToAddress string `json:"to_address"` @@ -425,7 +425,7 @@ type TxOutItem struct { CloutSpent *string `json:"clout_spent,omitempty"` } -// TxDetailsResponse struct for TxDetailsResponse +// TxDetailsResponse struct for TxDetailsResponse. type TxDetailsResponse struct { TxId *string `json:"tx_id,omitempty"` Tx ObservedTx `json:"tx"` diff --git a/chain/thorchain/wallet.go b/chain/thorchain/wallet.go index e51fc254b..13b18ec8a 100644 --- a/chain/thorchain/wallet.go +++ b/chain/thorchain/wallet.go @@ -1,12 +1,15 @@ package thorchain import ( - "github.com/cosmos/cosmos-sdk/types" "github.com/strangelove-ventures/interchaintest/v8/ibc" + + "github.com/cosmos/cosmos-sdk/types" ) -var _ ibc.Wallet = &CosmosWallet{} -var _ User = &CosmosWallet{} +var ( + _ ibc.Wallet = &CosmosWallet{} + _ User = &CosmosWallet{} +) type CosmosWallet struct { mnemonic string @@ -28,17 +31,17 @@ func (w *CosmosWallet) KeyName() string { return w.keyName } -// Get formatted address, passing in a prefix +// Get formatted address, passing in a prefix. func (w *CosmosWallet) FormattedAddress() string { return types.MustBech32ifyAddressBytes(w.chainCfg.Bech32Prefix, w.address) } -// Get mnemonic, only used for relayer wallets +// Get mnemonic, only used for relayer wallets. func (w *CosmosWallet) Mnemonic() string { return w.mnemonic } -// Get Address with chain's prefix +// Get Address with chain's prefix. func (w *CosmosWallet) Address() []byte { return w.address } diff --git a/chain/utxo/cli.go b/chain/utxo/cli.go index 84138c22f..f05557756 100644 --- a/chain/utxo/cli.go +++ b/chain/utxo/cli.go @@ -9,7 +9,7 @@ import ( "strings" ) -// Depending on the wallet version, getwalletinfo may require a created wallet name +// Depending on the wallet version, getwalletinfo may require a created wallet name. func (c *UtxoChain) GetWalletVersion(ctx context.Context, keyName string) (int, error) { var walletInfo WalletInfo var stdout []byte @@ -183,7 +183,7 @@ func (c *UtxoChain) SetAccount(ctx context.Context, addr string, keyName string) } // sendToMwebAddress is used for creating the mweb transaction needed at block 431 -// no other use case is currently supported +// no other use case is currently supported. func (c *UtxoChain) sendToMwebAddress(ctx context.Context, keyName string, addr string, amount float64) error { wallet, err := c.getWalletForUse(keyName) if err != nil { diff --git a/chain/utxo/default_configs.go b/chain/utxo/default_configs.go index cd42df4d3..d1cc3b28e 100644 --- a/chain/utxo/default_configs.go +++ b/chain/utxo/default_configs.go @@ -125,8 +125,8 @@ func DefaultDogecoinChainConfig( { Repository: "registry.gitlab.com/thorchain/devops/node-launcher", Version: "dogecoin-daemon-1.14.7", - //Repository: "coinmetrics/dogecoin", - //Version: "1.14.7", + // Repository: "coinmetrics/dogecoin", + // Version: "1.14.7", UidGid: "1000:1000", }, }, diff --git a/chain/utxo/utxo_chain.go b/chain/utxo/utxo_chain.go index bc981ce73..94091ed45 100644 --- a/chain/utxo/utxo_chain.go +++ b/chain/utxo/utxo_chain.go @@ -2,16 +2,13 @@ package utxo import ( "context" - "fmt" "io" "math" - "time" - "strconv" "strings" + "time" - sdkmath "cosmossdk.io/math" dockertypes "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/mount" "github.com/docker/docker/api/types/volume" @@ -21,6 +18,8 @@ import ( "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" + + sdkmath "cosmossdk.io/math" ) var _ ibc.Chain = &UtxoChain{} @@ -170,7 +169,8 @@ func (c *UtxoChain) pullImages(ctx context.Context, cli *dockerclient.Client) { } func (c *UtxoChain) Start(testName string, ctx context.Context, additionalGenesisWallets ...ibc.WalletAmount) error { - cmd := []string{c.BinDaemon, + cmd := []string{ + c.BinDaemon, "--regtest", "-printtoconsole", "-regtest=1", @@ -386,7 +386,7 @@ func (c *UtxoChain) CreateKey(ctx context.Context, keyName string) error { return c.SetAccount(ctx, addr, keyName) } -// Get address of account, cast to a string to use +// Get address of account, cast to a string to use. func (c *UtxoChain) GetAddress(ctx context.Context, keyName string) ([]byte, error) { wallet, ok := c.KeyNameToWalletMap[keyName] if ok { diff --git a/chain/utxo/wallet.go b/chain/utxo/wallet.go index 3cacf32e0..0549cf3e2 100644 --- a/chain/utxo/wallet.go +++ b/chain/utxo/wallet.go @@ -25,17 +25,17 @@ func (w *UtxoWallet) KeyName() string { return w.keyName } -// Get formatted address, passing in a prefix +// Get formatted address, passing in a prefix. func (w *UtxoWallet) FormattedAddress() string { return w.address } -// Get mnemonic, only used for relayer wallets +// Get mnemonic, only used for relayer wallets. func (w *UtxoWallet) Mnemonic() string { return "" } -// Get Address with chain's prefix +// Get Address with chain's prefix. func (w *UtxoWallet) Address() []byte { return []byte(w.address) } diff --git a/chainfactory.go b/chainfactory.go index 124b8a19d..48e46f0f5 100644 --- a/chainfactory.go +++ b/chainfactory.go @@ -1,7 +1,6 @@ package interchaintest import ( - _ "embed" "fmt" "os" "strings" @@ -17,6 +16,8 @@ import ( "github.com/strangelove-ventures/interchaintest/v8/ibc" "go.uber.org/zap" "gopkg.in/yaml.v3" + + _ "embed" ) // ChainFactory describes how to get chains for tests. @@ -49,7 +50,7 @@ var embeddedConfiguredChains []byte var logConfiguredChainsSourceOnce sync.Once -// initBuiltinChainConfig returns an ibc.ChainConfig mapping all configured chains +// initBuiltinChainConfig returns an ibc.ChainConfig mapping all configured chains. func initBuiltinChainConfig(log *zap.Logger) (map[string]ibc.ChainConfig, error) { var dat []byte var err error @@ -144,10 +145,10 @@ func buildChain(log *zap.Logger, testName string, cfg ibc.ChainConfig, numValida switch { case strings.Contains(cfg.Name, "composable"): parachains := []polkadot.ParachainConfig{{ - //Bin: "composable", + // Bin: "composable", Bin: "parachain-node", ChainID: "dev-2000", - //ChainID: "dali-dev", + // ChainID: "dali-dev", Image: cfg.Images[1], NumNodes: nf, Flags: []string{"--execution=wasm", "--wasmtime-instantiation-strategy=recreate-instance-copy-on-write"}, diff --git a/chainset.go b/chainset.go index 5bd172693..b3c6a47bb 100644 --- a/chainset.go +++ b/chainset.go @@ -56,7 +56,6 @@ func (cs *chainSet) Initialize(ctx context.Context, testName string, cli *client c := c cs.log.Info("Initializing chain", zap.String("chain_id", c.Config().ChainID)) eg.Go(func() error { - if err := c.Initialize(ctx, testName, cli, networkID); err != nil { return fmt.Errorf("failed to initialize chain %s: %w", c.Config().Name, err) } diff --git a/cmd/interchaintest/interchaintest_test.go b/cmd/interchaintest/interchaintest_test.go index c46718578..742e52e1a 100644 --- a/cmd/interchaintest/interchaintest_test.go +++ b/cmd/interchaintest/interchaintest_test.go @@ -150,7 +150,7 @@ func configureTestReporter() error { return fmt.Errorf("failed to get user home dir: %w", err) } fpath := filepath.Join(home, ".interchaintest", "reports") - err = os.MkdirAll(fpath, 0755) + err = os.MkdirAll(fpath, 0o755) if err != nil { return fmt.Errorf("mkdirall: %w", err) } diff --git a/cmd/interchaintest/matrix_test.go b/cmd/interchaintest/matrix_test.go index 98aac8892..e2630bdf4 100644 --- a/cmd/interchaintest/matrix_test.go +++ b/cmd/interchaintest/matrix_test.go @@ -1,13 +1,14 @@ package interchaintest_test import ( - _ "embed" "encoding/json" "testing" interchaintest "github.com/strangelove-ventures/interchaintest/v8" "github.com/stretchr/testify/require" "go.uber.org/zap/zaptest" + + _ "embed" ) // Embed the matrix files as strings since they aren't intended to be changed. diff --git a/conformance/flush.go b/conformance/flush.go index e8d508ca7..602b0c084 100644 --- a/conformance/flush.go +++ b/conformance/flush.go @@ -5,14 +5,16 @@ import ( "fmt" "testing" - "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/types" "github.com/strangelove-ventures/interchaintest/v8" "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/relayer" "github.com/strangelove-ventures/interchaintest/v8/testreporter" "github.com/strangelove-ventures/interchaintest/v8/testutil" "github.com/stretchr/testify/require" + + "cosmossdk.io/math" + + "github.com/cosmos/cosmos-sdk/types" ) func TestRelayerFlushing(t *testing.T, ctx context.Context, cf interchaintest.ChainFactory, rf interchaintest.RelayerFactory, rep *testreporter.Reporter) { diff --git a/conformance/relayersetup.go b/conformance/relayersetup.go index e2feb36a3..2bf348275 100644 --- a/conformance/relayersetup.go +++ b/conformance/relayersetup.go @@ -5,14 +5,15 @@ import ( "fmt" "testing" - conntypes "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" - "github.com/cosmos/ibc-go/v8/modules/core/exported" "github.com/strangelove-ventures/interchaintest/v8" "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/testreporter" "github.com/strangelove-ventures/interchaintest/v8/testutil" "github.com/stretchr/testify/require" "golang.org/x/sync/errgroup" + + conntypes "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" + "github.com/cosmos/ibc-go/v8/modules/core/exported" ) // TestRelayerSetup contains a series of subtests that configure a relayer step-by-step. diff --git a/conformance/test.go b/conformance/test.go index 1d095551c..7842a272f 100644 --- a/conformance/test.go +++ b/conformance/test.go @@ -35,8 +35,6 @@ import ( "testing" "time" - "cosmossdk.io/math" - transfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" "github.com/docker/docker/client" "github.com/strangelove-ventures/interchaintest/v8" "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" @@ -47,6 +45,10 @@ import ( "github.com/strangelove-ventures/interchaintest/v8/testutil" "github.com/stretchr/testify/require" "golang.org/x/sync/errgroup" + + "cosmossdk.io/math" + + transfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" ) var ( @@ -465,7 +467,7 @@ func testPacketRelaySuccess( req.True(srcFinalBalance.Equal(srcInitialBalance.Add(testCoinAmount))) req.True(dstFinalBalance.Equal(dstInitialBalance.Sub(expectedDifference))) } - //[END] assert on destination to source transfer + // [END] assert on destination to source transfer } // Ensure that a queued packet that should not be relayed is not relayed. diff --git a/contract/cosmwasm/compile.go b/contract/cosmwasm/compile.go index 710ed50bb..1f3a0b385 100644 --- a/contract/cosmwasm/compile.go +++ b/contract/cosmwasm/compile.go @@ -17,7 +17,7 @@ import ( "github.com/hashicorp/go-version" ) -// compile will compile the specified repo using the specified docker image and version +// compile will compile the specified repo using the specified docker image and version. func compile(image string, optVersion string, repoPath string) (string, error) { // Set the image to pull/use arch := "" diff --git a/contract/cosmwasm/rust_optimizer.go b/contract/cosmwasm/rust_optimizer.go index 5e7c7c2d9..07a1c6fbc 100644 --- a/contract/cosmwasm/rust_optimizer.go +++ b/contract/cosmwasm/rust_optimizer.go @@ -16,7 +16,7 @@ type Contract struct { } // NewContract return a contract struct, populated with defaults and its relative path -// relativePath is the relative path to the contract on local machine +// relativePath is the relative path to the contract on local machine. func NewContract(relativePath string) *Contract { return &Contract{ DockerImage: "cosmwasm/rust-optimizer", @@ -25,13 +25,13 @@ func NewContract(relativePath string) *Contract { } } -// WithDockerImage sets a custom docker image to use +// WithDockerImage sets a custom docker image to use. func (c *Contract) WithDockerImage(image string) *Contract { c.DockerImage = image return c } -// WithVersion sets a custom version to use +// WithVersion sets a custom version to use. func (c *Contract) WithVersion(version string) *Contract { c.Version = version return c @@ -75,7 +75,7 @@ func (c *Contract) Compile() *Contract { } // WaitForCompile will wait until compilation is complete, this can be called after chain setup -// Successful compilation will return the binary location in a channel +// Successful compilation will return the binary location in a channel. func (c *Contract) WaitForCompile() (string, error) { contractBinary := "" select { diff --git a/contract/cosmwasm/workspace_optimizer.go b/contract/cosmwasm/workspace_optimizer.go index c23e573cf..afe5c51ab 100644 --- a/contract/cosmwasm/workspace_optimizer.go +++ b/contract/cosmwasm/workspace_optimizer.go @@ -17,7 +17,7 @@ type Workspace struct { } // NewWorkspace returns a workspace struct, populated with defaults and its relative path -// relativePath is the relative path to the workspace on local machine +// relativePath is the relative path to the workspace on local machine. func NewWorkspace(relativePath string) *Workspace { return &Workspace{ DockerImage: "cosmwasm/workspace-optimizer", @@ -26,13 +26,13 @@ func NewWorkspace(relativePath string) *Workspace { } } -// WithDockerImage sets a custom docker image to use +// WithDockerImage sets a custom docker image to use. func (w *Workspace) WithDockerImage(image string) *Workspace { w.DockerImage = image return w } -// WithVersion sets a custom version to use +// WithVersion sets a custom version to use. func (w *Workspace) WithVersion(version string) *Workspace { w.Version = version return w @@ -42,7 +42,7 @@ func (w *Workspace) WithVersion(version string) *Workspace { // // cosmwasm/workspace-optimizer is the expected docker image // -// The workspace object is returned, call WaitForCompile() to get results +// The workspace object is returned, call WaitForCompile() to get results. func (w *Workspace) Compile() *Workspace { w.wasmBinariesChan = make(chan map[string]string) w.errChan = make(chan error, 1) @@ -88,7 +88,7 @@ func (w *Workspace) Compile() *Workspace { } // WaitForCompile will wait until coyympilation is complete, this can be called after chain setup -// Successful compilation will return a map of crate names to binary locations in a channel +// Successful compilation will return a map of crate names to binary locations in a channel. func (w *Workspace) WaitForCompile() (map[string]string, error) { contractBinaries := make(map[string]string) select { diff --git a/dockerutil/container_lifecycle.go b/dockerutil/container_lifecycle.go index 56f8c0135..c1728affe 100644 --- a/dockerutil/container_lifecycle.go +++ b/dockerutil/container_lifecycle.go @@ -16,9 +16,8 @@ import ( dockerclient "github.com/docker/docker/client" "github.com/docker/docker/errdefs" "github.com/docker/go-connections/nat" - "go.uber.org/zap" - "github.com/strangelove-ventures/interchaintest/v8/ibc" + "go.uber.org/zap" ) // Example Go/Cosmos-SDK panic format is `panic: bad Duration: time: invalid duration "bad"\n` diff --git a/dockerutil/file.go b/dockerutil/file.go index 78cdd5353..d2e9e5b7e 100644 --- a/dockerutil/file.go +++ b/dockerutil/file.go @@ -64,7 +64,7 @@ func CopyCoverageFromContainer(ctx context.Context, t *testing.T, client *client name := hdr.Name extractedFileName := path.Base(name) - //Only extract coverage files + // Only extract coverage files if !strings.HasPrefix(extractedFileName, "cov") { continue } diff --git a/dockerutil/filewriter.go b/dockerutil/filewriter.go index 4f3466974..3db357825 100644 --- a/dockerutil/filewriter.go +++ b/dockerutil/filewriter.go @@ -90,7 +90,7 @@ func (w *FileWriter) WriteFile(ctx context.Context, volumeName, relPath string, Name: relPath, Size: int64(len(content)), - Mode: 0600, + Mode: 0o600, // Not setting uname because the container will chown it anyway. ModTime: time.Now(), diff --git a/dockerutil/image_test.go b/dockerutil/image_test.go index de0850d92..a3d266ffd 100644 --- a/dockerutil/image_test.go +++ b/dockerutil/image_test.go @@ -69,7 +69,7 @@ func TestImage_Run(t *testing.T) { echo -n hi from stderr >> /dev/stderr ` tmpDir := t.TempDir() - err := os.WriteFile(filepath.Join(tmpDir, "test.sh"), []byte(scriptBody), 0777) + err := os.WriteFile(filepath.Join(tmpDir, "test.sh"), []byte(scriptBody), 0o777) require.NoError(t, err) opts := ContainerOptions{ diff --git a/dockerutil/keyring.go b/dockerutil/keyring.go index 9d54393bf..b6f287659 100644 --- a/dockerutil/keyring.go +++ b/dockerutil/keyring.go @@ -9,11 +9,12 @@ import ( "path" "path/filepath" + "github.com/docker/docker/client" + "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/docker/docker/client" ) // NewLocalKeyringFromDockerContainer copies the contents of the given container directory into a specified local directory. diff --git a/dockerutil/setup.go b/dockerutil/setup.go index b112a838a..3143d2c44 100644 --- a/dockerutil/setup.go +++ b/dockerutil/setup.go @@ -88,7 +88,7 @@ func DockerSetup(t DockerSetupTestingT) (*client.Client, string) { return cli, network.ID } -// DockerCleanup will clean up Docker containers, networks, and the other various config files generated in testing +// DockerCleanup will clean up Docker containers, networks, and the other various config files generated in testing. func DockerCleanup(t DockerSetupTestingT, cli *client.Client) func() { return func() { showContainerLogs := os.Getenv("SHOW_CONTAINER_LOGS") @@ -198,7 +198,6 @@ func PruneVolumesWithRetry(ctx context.Context, t DockerSetupTestingT, cli *clie retry.Context(ctx), retry.DelayType(retry.FixedDelay), ) - if err != nil { t.Logf("Failed to prune volumes during docker cleanup: %v", err) return @@ -232,7 +231,6 @@ func PruneNetworksWithRetry(ctx context.Context, t DockerSetupTestingT, cli *cli retry.Context(ctx), retry.DelayType(retry.FixedDelay), ) - if err != nil { t.Logf("Failed to prune networks during docker cleanup: %v", err) return diff --git a/dockerutil/strings.go b/dockerutil/strings.go index 225055b75..8921b3434 100644 --- a/dockerutil/strings.go +++ b/dockerutil/strings.go @@ -33,7 +33,7 @@ func GetHostPort(cont types.ContainerJSON, portID string) string { var chars = []byte("abcdefghijklmnopqrstuvwxyz") -// RandLowerCaseLetterString returns a lowercase letter string of given length +// RandLowerCaseLetterString returns a lowercase letter string of given length. func RandLowerCaseLetterString(length int) string { b := make([]byte, length) for i := range b { diff --git a/docs/CODE_OF_CONDUCT.md b/docs/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..bbce80c0a --- /dev/null +++ b/docs/CODE_OF_CONDUCT.md @@ -0,0 +1,43 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socioeconomic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +- The use of sexualized language or imagery and unwelcome sexual attention or advances +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others’ private information, such as a physical or electronic address, without explicit permission +- Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies within all project spaces, and it also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project’s leadership. + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at diff --git a/docs/envOptions.md b/docs/envOptions.md index 5c31f2e61..595286ba4 100644 --- a/docs/envOptions.md +++ b/docs/envOptions.md @@ -2,7 +2,7 @@ - `CONTAINER_LOG_TAIL`: Specifies the number of lines to display from container logs. Defaults to 50 lines. -- `ICTEST_CONFIGURED_CHAINS`: override the default configuredChains.yaml embeded config. +- `ICTEST_CONFIGURED_CHAINS`: override the default configuredChains.yaml embedded config. - `ICTEST_DEBUG`: extra debugging information for test execution. diff --git a/examples/cosmos/chain_core_test.go b/examples/cosmos/chain_core_test.go index 795ba8078..5c1162db1 100644 --- a/examples/cosmos/chain_core_test.go +++ b/examples/cosmos/chain_core_test.go @@ -198,7 +198,6 @@ func testAuth(ctx context.Context, t *testing.T, chain *cosmos.CosmosChain) { accInfo, err := chain.AuthQueryAccountInfo(ctx, govAddr) require.NoError(t, err) require.EqualValues(t, govAddr, accInfo.Address) - } // testUpgrade test the queries for upgrade information. Actual upgrades take place in other test. @@ -625,7 +624,6 @@ func testStaking(ctx context.Context, t *testing.T, chain *cosmos.CosmosChain, u require.NoError(t, err) require.NotEmpty(t, delVals) require.True(t, delVals[0].OperatorAddress == val) - }) t.Run("misc", func(t *testing.T) { diff --git a/examples/cosmos/chain_genesis_stake_test.go b/examples/cosmos/chain_genesis_stake_test.go index 138cf43c4..962213845 100644 --- a/examples/cosmos/chain_genesis_stake_test.go +++ b/examples/cosmos/chain_genesis_stake_test.go @@ -95,5 +95,4 @@ func TestChainGenesisUnequalStake(t *testing.T) { require.Equal(t, val1_stake, tokens1Int) require.Equal(t, val2_stake, tokens2Int) } - } diff --git a/examples/cosmos/chain_miscellaneous_test.go b/examples/cosmos/chain_miscellaneous_test.go index 6203fb901..de0450a70 100644 --- a/examples/cosmos/chain_miscellaneous_test.go +++ b/examples/cosmos/chain_miscellaneous_test.go @@ -414,7 +414,6 @@ func testTokenFactory(ctx context.Context, t *testing.T, chain *cosmos.CosmosCha _, err = node.TokenFactoryBurnDenomFrom(ctx, user2.KeyName(), tfDenom, 1, user.FormattedAddress()) require.NoError(t, err) validateBalance(ctx, t, chain, user, tfDenom, 0) - } func testGetGovernanceAddress(ctx context.Context, t *testing.T, chain *cosmos.CosmosChain) { diff --git a/examples/cosmos/chain_param_change_test.go b/examples/cosmos/chain_param_change_test.go index 65a6c9222..74851e8dc 100644 --- a/examples/cosmos/chain_param_change_test.go +++ b/examples/cosmos/chain_param_change_test.go @@ -47,7 +47,7 @@ func CosmosChainParamChangeTest(t *testing.T, name, version string) { enableBlockDB := false ctx, _, _, _ := interchaintest.BuildInitialChain(t, chains, enableBlockDB) - var userFunds = math.NewInt(10_000_000_000) + userFunds := math.NewInt(10_000_000_000) users := interchaintest.GetAndFundTestUsers(t, ctx, t.Name(), userFunds, chain) chainUser := users[0] diff --git a/examples/cosmos/chain_upgrade_ibc_test.go b/examples/cosmos/chain_upgrade_ibc_test.go index ebcc62c7e..321759f40 100644 --- a/examples/cosmos/chain_upgrade_ibc_test.go +++ b/examples/cosmos/chain_upgrade_ibc_test.go @@ -122,7 +122,7 @@ func CosmosChainUpgradeIBCTest(t *testing.T, chainName, initialVersion, upgradeC _ = ic.Close() }) - var userFunds = math.NewInt(10_000_000_000) + userFunds := math.NewInt(10_000_000_000) users := interchaintest.GetAndFundTestUsers(t, ctx, t.Name(), userFunds, chain) chainUser := users[0] diff --git a/examples/cosmos/cometmock_test.go b/examples/cosmos/cometmock_test.go index 75dd201da..157f5918b 100644 --- a/examples/cosmos/cometmock_test.go +++ b/examples/cosmos/cometmock_test.go @@ -94,5 +94,4 @@ func TestCometMock(t *testing.T) { endBal, err := chain.GetBalance(ctx, user.FormattedAddress(), "ujuno") require.NoError(t, err) require.EqualValues(t, initBal, endBal) - } diff --git a/examples/cosmos/sdk_boundary_test.go b/examples/cosmos/sdk_boundary_test.go index f7ff3e568..280fc3782 100644 --- a/examples/cosmos/sdk_boundary_test.go +++ b/examples/cosmos/sdk_boundary_test.go @@ -28,15 +28,15 @@ func TestSDKBoundaries(t *testing.T) { t.Parallel() - var tests = []boundarySpecs{ + tests := []boundarySpecs{ { name: "sdk 45 <-> 50", chainSpecs: []*interchaintest.ChainSpec{ { - Name: "gaia", ChainName: "gaia", Version: "v7.0.3", //sdk 0.45.6 + Name: "gaia", ChainName: "gaia", Version: "v7.0.3", // sdk 0.45.6 }, { - Name: "ibc-go-simd", ChainName: "simd-50", Version: "feat-upgrade-sdk-v0.50", //sdk 0.50 alpha + Name: "ibc-go-simd", ChainName: "simd-50", Version: "feat-upgrade-sdk-v0.50", // sdk 0.50 alpha }, }, relayerVersion: "colin-event-fix", @@ -45,10 +45,10 @@ func TestSDKBoundaries(t *testing.T) { name: "sdk 47 <-> 50", chainSpecs: []*interchaintest.ChainSpec{ { - Name: "ibc-go-simd", ChainName: "simd-47", Version: "v7.2.0", //sdk 0.47.3 + Name: "ibc-go-simd", ChainName: "simd-47", Version: "v7.2.0", // sdk 0.47.3 }, { - Name: "ibc-go-simd", ChainName: "simd-50", Version: "feat-upgrade-sdk-v0.50", //sdk 0.50 alpha + Name: "ibc-go-simd", ChainName: "simd-50", Version: "feat-upgrade-sdk-v0.50", // sdk 0.50 alpha }, }, relayerVersion: "colin-event-fix", @@ -113,8 +113,6 @@ func TestSDKBoundaries(t *testing.T) { // test IBC conformance conformance.TestChainPair(t, ctx, client, network, chain, counterpartyChain, rf, rep, r, path) - }) } - } diff --git a/examples/hyperspace/hyperspace_test.go b/examples/hyperspace/hyperspace_test.go index 615f80245..3e08fc1f2 100644 --- a/examples/hyperspace/hyperspace_test.go +++ b/examples/hyperspace/hyperspace_test.go @@ -329,7 +329,7 @@ func TestHyperspace(t *testing.T) { require.NoError(t, err) exportedState, err := cosmosChain.ExportState(ctx, int64(exportStateHeight)) require.NoError(t, err) - err = os.WriteFile("exported_state.json", []byte(exportedState), 0644) + err = os.WriteFile("exported_state.json", []byte(exportedState), 0o644) require.NoError(t, err) } diff --git a/examples/ibc/client_creation_test.go b/examples/ibc/client_creation_test.go index 274788a66..64dd11868 100644 --- a/examples/ibc/client_creation_test.go +++ b/examples/ibc/client_creation_test.go @@ -29,7 +29,7 @@ func TestCreatClient(t *testing.T) { t.Parallel() - var tests = []relayerImp{ + tests := []relayerImp{ { name: "Cosmos Relayer", relayerImp: ibc.CosmosRly, @@ -135,9 +135,7 @@ func TestCreatClient(t *testing.T) { // createClients should only create a client on source, NOT destination chain require.Equal(t, len(destClientInfoBefore), len(destClientInfoAfter), "a client was created on the destination chain") - }) } - } diff --git a/examples/ibc/ics_test.go b/examples/ibc/ics_test.go index e3271925f..104f6c387 100644 --- a/examples/ibc/ics_test.go +++ b/examples/ibc/ics_test.go @@ -53,7 +53,6 @@ func TestICS(t *testing.T) { }) } } - } func icsTest(t *testing.T, version string, rly ibc.RelayerImplementation) { diff --git a/examples/ibc/learn_ibc_test.go b/examples/ibc/learn_ibc_test.go index 548666d7d..1b583e4cb 100644 --- a/examples/ibc/learn_ibc_test.go +++ b/examples/ibc/learn_ibc_test.go @@ -73,7 +73,8 @@ func TestLearn(t *testing.T) { NetworkID: network, // BlockDatabaseFile: interchaintest.DefaultBlockDatabaseFilepath(), - SkipPathCreation: false}, + SkipPathCreation: false, + }, ), ) diff --git a/examples/ibc/wasm/wasm_ibc_test.go b/examples/ibc/wasm/wasm_ibc_test.go index 1883a6607..ea6c3ddb8 100644 --- a/examples/ibc/wasm/wasm_ibc_test.go +++ b/examples/ibc/wasm/wasm_ibc_test.go @@ -229,7 +229,6 @@ func TestWasmIbc(t *testing.T) { err = juno2Chain.QueryContract(ctx, juno2ContractAddr, queryJuno2CountMsg, &juno2PreIncrementedCountResponse) require.NoError(t, err) require.Equal(t, 1, juno2PreIncrementedCountResponse.Data.Count) - } // cw_ibc_example response data diff --git a/examples/ibc/wasm/wasm_icq_test.go b/examples/ibc/wasm/wasm_icq_test.go index bbd53080f..2e8bdccbe 100644 --- a/examples/ibc/wasm/wasm_icq_test.go +++ b/examples/ibc/wasm/wasm_icq_test.go @@ -28,11 +28,11 @@ import ( // On the sender chain, CosmWasm capability is required to instantiate/execute the smart contract. On the receiver chain, // the ICQ module is required to be present in order to receive interchain queries. func TestInterchainQueriesWASM(t *testing.T) { - //TODO (1): force relayer to use specific versions of the chains configured in the file. - //os.Setenv("ICTEST_CONFIGURED_CHAINS", "./icq_wasm_configured_chains.yaml") + // TODO (1): force relayer to use specific versions of the chains configured in the file. + // os.Setenv("ICTEST_CONFIGURED_CHAINS", "./icq_wasm_configured_chains.yaml") - //TODO (2): use Juno as sender "ghcr.io/strangelove-ventures/heighliner/juno:v10.1.0" - //and Strangelove's icqd (or another chain with ICQ module present) as receiver. + // TODO (2): use Juno as sender "ghcr.io/strangelove-ventures/heighliner/juno:v10.1.0" + // and Strangelove's icqd (or another chain with ICQ module present) as receiver. logger := zaptest.NewLogger(t) @@ -46,7 +46,7 @@ func TestInterchainQueriesWASM(t *testing.T) { rep := testreporter.NewReporter(f) eRep := rep.RelayerExecReporter(t) ctx := context.Background() - contractFilePath := "sample_contracts/icq.wasm" //Contract that will be initialized on chain + contractFilePath := "sample_contracts/icq.wasm" // Contract that will be initialized on chain wasmImage := ibc.DockerImage{ Repository: "ghcr.io/strangelove-ventures/heighliner/wasmd", @@ -82,7 +82,8 @@ func TestInterchainQueriesWASM(t *testing.T) { GasAdjustment: 1.1, EncodingConfig: wasm.WasmEncoding(), ModifyGenesis: modifyGenesisAtPath(genesisAllowICQ, "app_state"), - }}, + }, + }, { ChainName: "receiver", NumValidators: &minVal, @@ -99,7 +100,8 @@ func TestInterchainQueriesWASM(t *testing.T) { GasAdjustment: 1.1, EncodingConfig: wasm.WasmEncoding(), ModifyGenesis: modifyGenesisAtPath(genesisAllowICQ, "app_state"), - }}, + }, + }, }) chains, err := cf.Chains(t.Name()) @@ -175,7 +177,7 @@ func TestInterchainQueriesWASM(t *testing.T) { err = testutil.WaitForBlocks(ctx, 5, chain1, chain2) require.NoError(t, err) - //Instantiate the smart contract on the test chain, facilitating testing of ICQ WASM functionality + // Instantiate the smart contract on the test chain, facilitating testing of ICQ WASM functionality contractAddr, err := chain1CChain.InstantiateContract(ctx, chain1User.KeyName(), wasmIcqCodeId, initMessage, true) require.NoError(t, err) logger.Info("icq contract deployed", zap.String("contractAddr", contractAddr)) @@ -227,13 +229,14 @@ func TestInterchainQueriesWASM(t *testing.T) { require.NoError(t, err) logger.Info("channel", zap.String("info", fmt.Sprintf("Channel Port: %s, Channel ID: %s, Counterparty Channel ID: %s", channel.PortID, channel.ChannelID, channel.Counterparty.ChannelID))) - //Query for the balances of an account on the counterparty chain using interchain queries. - //Get the base64 encoded chain2 user address in the format required by the AllBalances query + // Query for the balances of an account on the counterparty chain using interchain queries. + // Get the base64 encoded chain2 user address in the format required by the AllBalances query chain2UserAddrQuery := fmt.Sprintf(`{"address":"%s"}`, chain2UserAddress) chain2UserAddrQueryB64 := base64.StdEncoding.EncodeToString([]byte(chain2UserAddrQuery)) // Get current block height for chain 2 - cmd := []string{chain2.Config().Bin, "status", + cmd := []string{ + chain2.Config().Bin, "status", "--node", chain2.GetRPCAddress(), "--home", chain2.HomeDir(), } @@ -243,9 +246,10 @@ func TestInterchainQueriesWASM(t *testing.T) { err = json.Unmarshal(stdout, blockHeightC2) require.NoError(t, err) - //and chain 1 + // and chain 1 // Get current block height - cmd = []string{chain1.Config().Bin, "status", + cmd = []string{ + chain1.Config().Bin, "status", "--node", chain1.GetRPCAddress(), "--home", chain1.HomeDir(), } @@ -261,7 +265,7 @@ func TestInterchainQueriesWASM(t *testing.T) { Query: msgQuery{ Timeout: 1000, Channel: channel.ChannelID, - Requests: []RequestQuery{ //can't use abci.RequestQuery since Height/Prove JSON fields are omitted which causes contract errors + Requests: []RequestQuery{ // can't use abci.RequestQuery since Height/Prove JSON fields are omitted which causes contract errors { Height: 0, Prove: false, @@ -277,7 +281,7 @@ func TestInterchainQueriesWASM(t *testing.T) { msg := string(b) logger.Info("Executing msg ->", zap.String("msg", msg)) - //Query the contract on chain 1. The contract makes an interchain query to chain 2 to get the chain 2 user's balance. + // Query the contract on chain 1. The contract makes an interchain query to chain 2 to get the chain 2 user's balance. resp, err := chain1CChain.ExecuteContract(ctx, chain1User.KeyName(), contractAddr, msg) require.NoError(t, err) require.NotNil(t, resp) @@ -287,7 +291,8 @@ func TestInterchainQueriesWASM(t *testing.T) { require.NoError(t, err) // Check the results from the interchain query above. - cmd = []string{chain1.Config().Bin, "query", "wasm", "contract-state", "all", contractAddr, + cmd = []string{ + chain1.Config().Bin, "query", "wasm", "contract-state", "all", contractAddr, "--node", chain1.GetRPCAddress(), "--home", chain1.HomeDir(), "--chain-id", chain1.Config().ChainID, @@ -329,8 +334,8 @@ func FirstWithPort(channels []ibc.ChannelOutput, port string) *ibc.ChannelOutput type RequestQuery struct { Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"` - Height int64 `protobuf:"varint,3,opt,name=height,proto3" json:"height"` //do NOT 'omitempty' for JSON field or contract queries will error - Prove bool `protobuf:"varint,4,opt,name=prove,proto3" json:"prove"` //do NOT 'omitempty' for JSON field or contract queries will error + Height int64 `protobuf:"varint,3,opt,name=height,proto3" json:"height"` // do NOT 'omitempty' for JSON field or contract queries will error + Prove bool `protobuf:"varint,4,opt,name=prove,proto3" json:"prove"` // do NOT 'omitempty' for JSON field or contract queries will error } type msgQuery struct { @@ -365,7 +370,7 @@ func modifyGenesisAtPath(insertedBlock map[string]interface{}, key string) func( return nil, fmt.Errorf("failed to unmarshal genesis file: %w", err) } - //Get the section of the genesis file under the given key (e.g. "app_state") + // Get the section of the genesis file under the given key (e.g. "app_state") genesisBlockI, ok := g[key] if !ok { return nil, fmt.Errorf("genesis json does not have top level key: %s", key) diff --git a/examples/penumbra/penumbra_ibc_test.go b/examples/penumbra/penumbra_ibc_test.go index 681444551..366ea6e88 100644 --- a/examples/penumbra/penumbra_ibc_test.go +++ b/examples/penumbra/penumbra_ibc_test.go @@ -113,7 +113,7 @@ func TestPenumbraToPenumbraIBC(t *testing.T) { func() { err := r.StopRelayer(ctx, eRep) if err != nil { - panic(fmt.Errorf("an error occured while stopping the relayer: %s", err)) + panic(fmt.Errorf("an error occurred while stopping the relayer: %s", err)) } }, ) @@ -373,7 +373,7 @@ func TestPenumbraToCosmosIBC(t *testing.T) { func() { err := r.StopRelayer(ctx, eRep) if err != nil { - panic(fmt.Errorf("an error occured while stopping the relayer: %s", err)) + panic(fmt.Errorf("an error occurred while stopping the relayer: %s", err)) } }, ) diff --git a/examples/polkadot/polkadot_chain_test.go b/examples/polkadot/polkadot_chain_test.go index 15acf2178..689f3d7e2 100644 --- a/examples/polkadot/polkadot_chain_test.go +++ b/examples/polkadot/polkadot_chain_test.go @@ -87,7 +87,7 @@ func TestPolkadotComposableChainStart(t *testing.T) { PARACHAIN_DEFAULT_AMOUNT := math.NewInt(1_152_921_504_606_847_000) RELAYCHAIN_DEFAULT_AMOUNT := math.NewInt(1_100_000_000_000_000_000) FAUCET_AMOUNT := math.NewInt(100_000_000_000_000_000) // set in interchain.go/global - //RELAYER_AMOUNT := 1_000_000_000_000 // set in interchain.go/global + // RELAYER_AMOUNT := 1_000_000_000_000 // set in interchain.go/global // Check the faucet amounts polkadotFaucetAddress, err := polkadotChain.GetAddress(ctx, "faucet") diff --git a/examples/polkadot/push_wasm_client_code_test.go b/examples/polkadot/push_wasm_client_code_test.go index 2233b1f8b..8134ac0f8 100644 --- a/examples/polkadot/push_wasm_client_code_test.go +++ b/examples/polkadot/push_wasm_client_code_test.go @@ -57,36 +57,37 @@ func TestPushWasmClientCode(t *testing.T) { rpcOverrides["max_header_bytes"] = 2_100_000 configTomlOverrides["rpc"] = rpcOverrides - //mempoolOverrides := make(testutil.Toml) - //mempoolOverrides["max_tx_bytes"] = 6000000 - //configTomlOverrides["mempool"] = mempoolOverrides + // mempoolOverrides := make(testutil.Toml) + // mempoolOverrides["max_tx_bytes"] = 6000000 + // configTomlOverrides["mempool"] = mempoolOverrides configFileOverrides["config/app.toml"] = appTomlOverrides configFileOverrides["config/config.toml"] = configTomlOverrides cf := interchaintest.NewBuiltinChainFactory(zaptest.NewLogger(t), []*interchaintest.ChainSpec{ - {ChainConfig: ibc.ChainConfig{ - Type: "cosmos", - Name: "ibc-go-simd", - ChainID: "simd", - Images: []ibc.DockerImage{ - { - Repository: "ghcr.io/strangelove-ventures/heighliner/ibc-go-simd", - Version: "feat-wasm-clients", - UidGid: "1025:1025", + { + ChainConfig: ibc.ChainConfig{ + Type: "cosmos", + Name: "ibc-go-simd", + ChainID: "simd", + Images: []ibc.DockerImage{ + { + Repository: "ghcr.io/strangelove-ventures/heighliner/ibc-go-simd", + Version: "feat-wasm-clients", + UidGid: "1025:1025", + }, }, + Bin: "simd", + Bech32Prefix: "cosmos", + Denom: "stake", + GasPrices: "0.00stake", + GasAdjustment: 1.3, + TrustingPeriod: "504h", + // EncodingConfig: WasmClientEncoding(), + NoHostMount: true, + ConfigFileOverrides: configFileOverrides, + ModifyGenesis: modifyGenesisShortProposals(votingPeriod, maxDepositPeriod), }, - Bin: "simd", - Bech32Prefix: "cosmos", - Denom: "stake", - GasPrices: "0.00stake", - GasAdjustment: 1.3, - TrustingPeriod: "504h", - //EncodingConfig: WasmClientEncoding(), - NoHostMount: true, - ConfigFileOverrides: configFileOverrides, - ModifyGenesis: modifyGenesisShortProposals(votingPeriod, maxDepositPeriod), - }, }, }) diff --git a/examples/polkadot/substrate_cosmos_ibc_test.go b/examples/polkadot/substrate_cosmos_ibc_test.go index 90c842687..6f6c0bde9 100644 --- a/examples/polkadot/substrate_cosmos_ibc_test.go +++ b/examples/polkadot/substrate_cosmos_ibc_test.go @@ -38,8 +38,8 @@ func TestSubstrateToCosmosIBC(t *testing.T) { // Get both chains cf := interchaintest.NewBuiltinChainFactory(zaptest.NewLogger(t), []*interchaintest.ChainSpec{ { - //Name: "composable", - //Version: "seunlanlege/centauri-polkadot:v0.9.27,seunlanlege/centauri-parachain:v0.9.27", + // Name: "composable", + // Version: "seunlanlege/centauri-polkadot:v0.9.27,seunlanlege/centauri-parachain:v0.9.27", ChainConfig: ibc.ChainConfig{ Type: "polkadot", Name: "composable", @@ -84,9 +84,9 @@ func TestSubstrateToCosmosIBC(t *testing.T) { GasPrices: "0.00stake", GasAdjustment: 1.3, TrustingPeriod: "504h", - //EncodingConfig: WasmClientEncoding(), + // EncodingConfig: WasmClientEncoding(), NoHostMount: true, - //ConfigFileOverrides: configFileOverrides, + // ConfigFileOverrides: configFileOverrides, }, /* ChainName: "gaia", @@ -106,9 +106,9 @@ func TestSubstrateToCosmosIBC(t *testing.T) { zaptest.NewLogger(t), relayer.StartupFlags("-b", "100"), // These two fields are used to pass in a custom Docker image built locally - //relayer.ImagePull(false), + // relayer.ImagePull(false), relayer.CustomDockerImage("ghcr.io/composablefi/relayer", "sub-create-client", "100:1000"), - //relayer.CustomDockerImage("go-relayer", "local", "100:1000"), + // relayer.CustomDockerImage("go-relayer", "local", "100:1000"), ).Build(t, client, network) // Build the network; spin up the chains and configure the relayer @@ -135,9 +135,9 @@ func TestSubstrateToCosmosIBC(t *testing.T) { })) // If necessary you can wait for x number of blocks to pass before taking some action - //blocksToWait := 10 - //err = testutil.WaitForBlocks(ctx, blocksToWait, composable) - //require.NoError(t, err) + // blocksToWait := 10 + // err = testutil.WaitForBlocks(ctx, blocksToWait, composable) + // require.NoError(t, err) err = testutil.WaitForBlocks(ctx, 2000, simd) require.NoError(t, err) // Generate a new IBC path between the chains diff --git a/examples/thorchain/contracts/lib/forge-std/src/Vm.sol b/examples/thorchain/contracts/lib/forge-std/src/Vm.sol index 04d8db79e..16a14e2fd 100644 --- a/examples/thorchain/contracts/lib/forge-std/src/Vm.sol +++ b/examples/thorchain/contracts/lib/forge-std/src/Vm.sol @@ -531,7 +531,7 @@ interface VmSafe { /// Deploys a contract from an artifact file. Takes in the relative path to the json file or the path to the /// artifact in the form of :: where and parts are optional. - /// Additionaly accepts abi-encoded constructor arguments. + /// Additionally accepts abi-encoded constructor arguments. function deployCode(string calldata artifactPath, bytes calldata constructorArgs) external returns (address deployedAddress); diff --git a/examples/thorchain/features/arb.go b/examples/thorchain/features/arb.go index c6eafe4ee..c75d5b766 100644 --- a/examples/thorchain/features/arb.go +++ b/examples/thorchain/features/arb.go @@ -170,7 +170,7 @@ func Arb( } else { fmt.Println("No arb error") } - //require.NoError(t, err) + // require.NoError(t, err) time.Sleep(time.Second) // Deposit already wait 2 blocks, ~4 seconds } diff --git a/examples/thorchain/features/helpers.go b/examples/thorchain/features/helpers.go index f8d3206f4..971250e2f 100644 --- a/examples/thorchain/features/helpers.go +++ b/examples/thorchain/features/helpers.go @@ -100,7 +100,6 @@ func PollForSaver(ctx context.Context, thorchain *tc.Thorchain, deltaBlocks int6 if strings.EqualFold(saver.AssetAddress, exoUser.FormattedAddress()) { return saver, nil } - } time.Sleep(time.Second) // rate limit return tc.Saver{}, fmt.Errorf("saver took longer than %d blocks to show", deltaBlocks) @@ -128,7 +127,6 @@ func PollForEjectedSaver(ctx context.Context, thorchain *tc.Thorchain, deltaBloc time.Sleep(time.Second) // rate limit return saver, fmt.Errorf("saver took longer than %d blocks to eject", deltaBlocks) } - } return tc.Saver{}, nil } diff --git a/examples/thorchain/thorchain_test.go b/examples/thorchain/thorchain_test.go index 60b47caa0..26c866853 100644 --- a/examples/thorchain/thorchain_test.go +++ b/examples/thorchain/thorchain_test.go @@ -124,6 +124,6 @@ func TestThorchainSim(t *testing.T) { } require.NoError(t, eg.Wait()) - //err = testutil.WaitForBlocks(ctx, 300, thorchain) - //require.NoError(t, err, "thorchain failed to make blocks") + // err = testutil.WaitForBlocks(ctx, 300, thorchain) + // require.NoError(t, err, "thorchain failed to make blocks") } diff --git a/examples/utxo/start_test.go b/examples/utxo/start_test.go index d8f8bcc56..85788199f 100644 --- a/examples/utxo/start_test.go +++ b/examples/utxo/start_test.go @@ -18,7 +18,6 @@ import ( ) func TestUtxo(t *testing.T) { - if testing.Short() { t.Skip() } diff --git a/ibc/chain.go b/ibc/chain.go index d7d11cd74..b6f4d4b3f 100644 --- a/ibc/chain.go +++ b/ibc/chain.go @@ -3,8 +3,9 @@ package ibc import ( "context" - "cosmossdk.io/math" "github.com/docker/docker/client" + + "cosmossdk.io/math" ) type Chain interface { diff --git a/ibc/packet.go b/ibc/packet.go index 85d9ece88..1b018cd87 100644 --- a/ibc/packet.go +++ b/ibc/packet.go @@ -5,15 +5,16 @@ import ( "fmt" "reflect" - host "github.com/cosmos/ibc-go/v8/modules/core/24-host" "go.uber.org/multierr" + + host "github.com/cosmos/ibc-go/v8/modules/core/24-host" ) type Nanoseconds uint64 // Packet is a packet sent over an IBC channel as defined in ICS-4. // See: https://github.com/cosmos/ibc/blob/52a9094a5bc8c5275e25c19d0b2d9e6fd80ba31c/spec/core/ics-004-channel-and-packet-semantics/README.md -// Proto defined at: github.com/cosmos/ibc-go/v3@v3.0.0/proto/ibc/core/channel/v1/tx.proto +// Proto defined at: github.com/cosmos/ibc-go/v3@v3.0.0/proto/ibc/core/channel/v1/tx.proto. type Packet struct { Sequence uint64 // the order of sends and receives, where a packet with an earlier sequence number must be sent and received before a packet with a later sequence number SourcePort string // the port on the sending chain diff --git a/ibc/relayer.go b/ibc/relayer.go index 6589796ef..ac337ba1c 100644 --- a/ibc/relayer.go +++ b/ibc/relayer.go @@ -276,7 +276,7 @@ func (o Order) Validate() error { // CreateClientOptions contains the configuration for creating a client. -// a zero value is the same as not specifying the flag and will use the relayer defaults +// a zero value is the same as not specifying the flag and will use the relayer defaults. type CreateClientOptions struct { TrustingPeriod string TrustingPeriodPercentage int64 // only available for Go Relayer @@ -286,7 +286,7 @@ type CreateClientOptions struct { // DefaultClientOpts returns the default settings for creating clients. -// empty values will use the relayer defaults +// empty values will use the relayer defaults. func DefaultClientOpts() CreateClientOptions { return CreateClientOptions{} } diff --git a/ibc/relayer_test.go b/ibc/relayer_test.go index 5d98a6cd4..779be0836 100644 --- a/ibc/relayer_test.go +++ b/ibc/relayer_test.go @@ -3,8 +3,9 @@ package ibc import ( "testing" - chantypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types" "github.com/stretchr/testify/require" + + chantypes "github.com/cosmos/ibc-go/v8/modules/core/04-channel/types" ) func TestChannelOptsConfigured(t *testing.T) { diff --git a/ibc/types.go b/ibc/types.go index d99699774..2524c5cd6 100644 --- a/ibc/types.go +++ b/ibc/types.go @@ -9,13 +9,16 @@ import ( "strconv" "strings" - "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module/testutil" - ibcexported "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" "github.com/docker/docker/api/types" "github.com/docker/docker/client" "github.com/google/go-cmp/cmp" + + "cosmossdk.io/math" + + ibcexported "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module/testutil" ) // ChainConfig defines the chain parameters requires to run an interchaintest testnet for a chain. diff --git a/interchain.go b/interchain.go index 95d09108a..b6ef8a1b0 100644 --- a/interchain.go +++ b/interchain.go @@ -5,13 +5,14 @@ import ( "fmt" "math" - sdkmath "cosmossdk.io/math" "github.com/docker/docker/client" "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/testreporter" "go.uber.org/zap" "golang.org/x/sync/errgroup" + + sdkmath "cosmossdk.io/math" ) // Interchain represents a full IBC network, encompassing a collection of diff --git a/interchain_builder.go b/interchain_builder.go index 11a5bce3f..31c6f539b 100644 --- a/interchain_builder.go +++ b/interchain_builder.go @@ -4,8 +4,6 @@ import ( "context" "testing" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/types/module/testutil" "github.com/docker/docker/client" "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" "github.com/strangelove-ventures/interchaintest/v8/ibc" @@ -13,6 +11,9 @@ import ( "github.com/strangelove-ventures/interchaintest/v8/testreporter" "github.com/stretchr/testify/require" "go.uber.org/zap/zaptest" + + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/types/module/testutil" ) type codecRegistry func(registry codectypes.InterfaceRegistry) diff --git a/interchain_test.go b/interchain_test.go index 9d7062759..a6ceadca4 100644 --- a/interchain_test.go +++ b/interchain_test.go @@ -6,13 +6,6 @@ import ( "testing" "time" - "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/strangelove-ventures/interchaintest/v8" "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" "github.com/strangelove-ventures/interchaintest/v8/ibc" @@ -23,8 +16,17 @@ import ( "go.uber.org/zap" "go.uber.org/zap/zaptest" + "cosmossdk.io/math" + transfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" // nolint:staticcheck + + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + sdk "github.com/cosmos/cosmos-sdk/types" ) func TestInterchain_DuplicateChain_CosmosRly(t *testing.T) { diff --git a/interchaintest.go b/interchaintest.go index 6d999afbe..0da14cfbd 100644 --- a/interchaintest.go +++ b/interchaintest.go @@ -6,14 +6,14 @@ import ( "path/filepath" ) -// CreateLogFile creates a file with name in dir $HOME/.interchaintest/logs/ +// CreateLogFile creates a file with name in dir $HOME/.interchaintest/logs/. func CreateLogFile(name string) (*os.File, error) { home, err := os.UserHomeDir() if err != nil { return nil, fmt.Errorf("user home dir: %w", err) } fpath := filepath.Join(home, ".interchaintest", "logs") - err = os.MkdirAll(fpath, 0755) + err = os.MkdirAll(fpath, 0o755) if err != nil { return nil, fmt.Errorf("mkdirall: %w", err) } diff --git a/local-interchain/cmd/local-ic/interaction.go b/local-interchain/cmd/local-ic/interaction.go index b58c81de6..0d2e8a0f3 100644 --- a/local-interchain/cmd/local-ic/interaction.go +++ b/local-interchain/cmd/local-ic/interaction.go @@ -37,7 +37,6 @@ var interactCmd = &cobra.Command{ return GetFiles(), cobra.ShellCompDirectiveNoFileComp }, Run: func(cmd *cobra.Command, args []string) { - ah := &handlers.ActionHandler{ ChainId: args[0], Action: args[1], diff --git a/local-interchain/cmd/local-ic/root.go b/local-interchain/cmd/local-ic/root.go index 7c44f4f66..60c4cfc89 100644 --- a/local-interchain/cmd/local-ic/root.go +++ b/local-interchain/cmd/local-ic/root.go @@ -9,10 +9,8 @@ import ( "github.com/spf13/cobra" ) -var ( - // This must be global for the Makefile to build properly (ldflags). - MakeFileInstallDirectory string -) +// This must be global for the Makefile to build properly (ldflags). +var MakeFileInstallDirectory string var rootCmd = &cobra.Command{ Use: "local-ic", diff --git a/local-interchain/interchain/genesis.go b/local-interchain/interchain/genesis.go index 2d34f5975..a0440740f 100644 --- a/local-interchain/interchain/genesis.go +++ b/local-interchain/interchain/genesis.go @@ -26,7 +26,6 @@ func AddGenesisKeysToKeyring(ctx context.Context, config *types.Config, chains [ default: continue } - } } @@ -54,7 +53,6 @@ func PostStartupCommands(ctx context.Context, config *types.Config, chains []ibc log.Println("Startup command output", chainObj.Config().ChainID, cmd, string(output)) } } - } } @@ -83,7 +81,6 @@ func SetupGenesisWallets(config *types.Config, chains []ibc.Chain) map[ibc.Chain default: continue } - } return additionalWallets } diff --git a/local-interchain/interchain/handlers/chain_registry.go b/local-interchain/interchain/handlers/chain_registry.go index b98ac522e..652e5e85a 100644 --- a/local-interchain/interchain/handlers/chain_registry.go +++ b/local-interchain/interchain/handlers/chain_registry.go @@ -5,7 +5,7 @@ import ( "os" ) -// If the chain_registry.json file is found within the current running directory, show it as an enpoint. +// If the chain_registry.json file is found within the current running directory, show it as an endpoint. // Used in: spawn type chainRegistry struct { @@ -30,5 +30,4 @@ func (cr chainRegistry) GetChainRegistry(w http.ResponseWriter, r *http.Request) if _, err := w.Write(cr.DataJSON); err != nil { http.Error(w, "failed to write response", http.StatusInternalServerError) } - } diff --git a/local-interchain/interchain/logs.go b/local-interchain/interchain/logs.go index 00c46dee6..9ec2ba3b3 100644 --- a/local-interchain/interchain/logs.go +++ b/local-interchain/interchain/logs.go @@ -23,7 +23,7 @@ func WriteRunningChains(configsDir string, bz []byte) { } file := filepath.Join(path, "logs.json") - _ = os.WriteFile(file, bz, 0644) + _ = os.WriteFile(file, bz, 0o644) } func DumpChainsInfoToLogs(configDir string, config *types.Config, chains []ibc.Chain, connections []types.IBCChannel) { @@ -35,7 +35,6 @@ func DumpChainsInfoToLogs(configDir string, config *types.Config, chains []ibc.C // Iterate chain config & get the ibc chain's to save data to logs. for idx, chain := range config.Chains { - switch chains[idx].(type) { case *cosmos.CosmosChain: chainObj := chains[idx].(*cosmos.CosmosChain) diff --git a/local-interchain/interchain/router/router.go b/local-interchain/interchain/router/router.go index c93bc3b87..3694ed634 100644 --- a/local-interchain/interchain/router/router.go +++ b/local-interchain/interchain/router/router.go @@ -99,7 +99,6 @@ func getAllMethods(r mux.Router) []Route { }) return nil }) - if err != nil { panic(err) } diff --git a/local-interchain/interchain/types/chain_builder.go b/local-interchain/interchain/types/chain_builder.go index ba7ae4939..79e423e3b 100644 --- a/local-interchain/interchain/types/chain_builder.go +++ b/local-interchain/interchain/types/chain_builder.go @@ -178,7 +178,7 @@ func (c *Chain) SaveJSON(filePath string) error { return err } - return os.WriteFile(filePath, bz, 0777) + return os.WriteFile(filePath, bz, 0o777) } func (c *Chain) SaveYAML(filePath string) error { @@ -190,7 +190,7 @@ func (c *Chain) SaveYAML(filePath string) error { return err } - return os.WriteFile(filePath, bz, 0777) + return os.WriteFile(filePath, bz, 0o777) } func BaseHostPortOverride() map[string]string { diff --git a/local-interchain/interchain/types/chains_test.go b/local-interchain/interchain/types/chains_test.go index cde3730ce..7c820a2e3 100644 --- a/local-interchain/interchain/types/chains_test.go +++ b/local-interchain/interchain/types/chains_test.go @@ -34,5 +34,4 @@ func TestChainsGeneration(t *testing.T) { require.NoError(t, NewChainsConfig(hub, hub2, juno1, osmo1).SaveJSON("chains/gen-4-ibc.json")) }) - } diff --git a/local-interchain/interchain/types/types.go b/local-interchain/interchain/types/types.go index 6235fa426..579a42e90 100644 --- a/local-interchain/interchain/types/types.go +++ b/local-interchain/interchain/types/types.go @@ -146,7 +146,7 @@ func NewChainsConfig(chains ...*Chain) ChainsConfig { // SaveJSON saves the chains config to a file. func (cfg ChainsConfig) SaveJSON(file string) error { - if err := os.MkdirAll(filepath.Dir(file), 0777); err != nil { + if err := os.MkdirAll(filepath.Dir(file), 0o777); err != nil { return fmt.Errorf("failed to create directory: %w", err) } @@ -155,7 +155,7 @@ func (cfg ChainsConfig) SaveJSON(file string) error { return fmt.Errorf("failed to marshal chains config: %w", err) } - return os.WriteFile(file, bz, 0777) + return os.WriteFile(file, bz, 0o777) } // SaveYAML saves the chains config to a file. @@ -165,7 +165,7 @@ func (cfg ChainsConfig) SaveYAML(file string) error { return fmt.Errorf("failed to marshal chains config: %w", err) } - return os.WriteFile(file, bz, 0777) + return os.WriteFile(file, bz, 0o777) } // MainLogs is the main runtime log file of the application. diff --git a/mocktesting/t.go b/mocktesting/t.go index 85ff58bcb..ac3ef160d 100644 --- a/mocktesting/t.go +++ b/mocktesting/t.go @@ -8,7 +8,7 @@ import ( // T satisfies a subset of testing.TB useful for tests around how interchaintest interacts with instances of testing.T. // -// The methods that are unique to T are RunCleanups and Simulate +// The methods that are unique to T are RunCleanups and Simulate. type T struct { name string diff --git a/relayer/docker.go b/relayer/docker.go index 7db3a95fb..6a3aba88a 100644 --- a/relayer/docker.go +++ b/relayer/docker.go @@ -13,11 +13,10 @@ import ( volumetypes "github.com/docker/docker/api/types/volume" "github.com/docker/docker/client" "github.com/docker/docker/pkg/stdcopy" - "go.uber.org/zap" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/testutil" + "go.uber.org/zap" ) const ( @@ -148,7 +147,7 @@ func (r *DockerRelayer) ReadFileFromHomeDir(ctx context.Context, relativePath st return bytes, nil } -// Modify a toml config file in relayer home directory +// Modify a toml config file in relayer home directory. func (r *DockerRelayer) ModifyTomlConfigFile(ctx context.Context, relativePath string, modification testutil.Toml) error { return testutil.ModifyTomlConfigFile(ctx, r.log, r.client, r.testName, r.volumeName, relativePath, modification) } diff --git a/relayer/hermes/hermes_commander.go b/relayer/hermes/hermes_commander.go index add6400e1..0e8f8369e 100644 --- a/relayer/hermes/hermes_commander.go +++ b/relayer/hermes/hermes_commander.go @@ -71,7 +71,6 @@ func (c commander) ParseGetConnectionsOutput(stdout, stderr string) (ibc.Connect var outputs ibc.ConnectionOutputs for _, r := range queryResult.Result { - var versions []*ibcexported.Version for _, v := range r.ConnectionEnd.Versions { versions = append(versions, &ibcexported.Version{ diff --git a/relayer/hermes/hermes_relayer.go b/relayer/hermes/hermes_relayer.go index 47f7f4577..ab87ebbae 100644 --- a/relayer/hermes/hermes_relayer.go +++ b/relayer/hermes/hermes_relayer.go @@ -29,7 +29,7 @@ const ( var ( _ ibc.Relayer = &Relayer{} // parseRestoreKeyOutputPattern extracts the address from the hermes output. - // SUCCESS Restored key 'g2-2' (cosmos1czklnpzwaq3hfxtv6ne4vas2p9m5q3p3fgkz8e) on chain g2-2 + // SUCCESS Restored key 'g2-2' (cosmos1czklnpzwaq3hfxtv6ne4vas2p9m5q3p3fgkz8e) on chain g2-2. parseRestoreKeyOutputPattern = regexp.MustCompile(`\((.*)\)`) ) diff --git a/relayer/hermes/hermes_wallet.go b/relayer/hermes/hermes_wallet.go index 8d02c62a6..053e34b90 100644 --- a/relayer/hermes/hermes_wallet.go +++ b/relayer/hermes/hermes_wallet.go @@ -31,12 +31,12 @@ func (w *Wallet) FormattedAddress() string { return w.address } -// Get mnemonic, only used for relayer wallets +// Get mnemonic, only used for relayer wallets. func (w *Wallet) Mnemonic() string { return w.mnemonic } -// Get Address +// Get Address. func (w *Wallet) Address() []byte { return []byte(w.address) } diff --git a/relayer/hyperspace/hyperspace_commander.go b/relayer/hyperspace/hyperspace_commander.go index 6ce5b3f02..8c7e4aaca 100644 --- a/relayer/hyperspace/hyperspace_commander.go +++ b/relayer/hyperspace/hyperspace_commander.go @@ -6,13 +6,14 @@ import ( "fmt" "path" - ibcexported "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" - types23 "github.com/cosmos/ibc-go/v8/modules/core/23-commitment/types" "github.com/misko9/go-substrate-rpc-client/v4/signature" "github.com/pelletier/go-toml/v2" "github.com/strangelove-ventures/interchaintest/v8/chain/polkadot" "github.com/strangelove-ventures/interchaintest/v8/ibc" "go.uber.org/zap" + + ibcexported "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" + types23 "github.com/cosmos/ibc-go/v8/modules/core/23-commitment/types" ) // hyperspaceCommander satisfies relayer.RelayerCommander. @@ -43,14 +44,14 @@ func (hyperspaceCommander) DockerUser() string { func (c *hyperspaceCommander) AddChainConfiguration(containerFilePath, homeDir string) []string { fmt.Println("[hyperspace] AddChainConfiguration ", containerFilePath, homeDir) - //c.chainConfigPaths = append(c.chainConfigPaths, containerFilePath) + // c.chainConfigPaths = append(c.chainConfigPaths, containerFilePath) return []string{ "hyperspace", "-h", } } -// Hyperspace doesn't not have this functionality +// Hyperspace doesn't not have this functionality. func (hyperspaceCommander) AddKey(chainID, keyName, coinType, signingAlgorithm, homeDir string) []string { panic("[AddKey] Do not call me") } @@ -101,7 +102,7 @@ func (c *hyperspaceCommander) CreateClients(pathName string, opts ibc.CreateClie } } -// TODO: Implement if available in hyperspace relayer +// TODO: Implement if available in hyperspace relayer. func (hyperspaceCommander) CreateClient(srcChainID, dstChainID, pathName string, opts ibc.CreateClientOptions, homeDir string) []string { panic("[CreateClient] Not Implemented") } @@ -126,12 +127,12 @@ func (c *hyperspaceCommander) CreateConnections(pathName, homeDir string) []stri } } -// Hyperspace doesn't not have this functionality +// Hyperspace doesn't not have this functionality. func (hyperspaceCommander) FlushAcknowledgements(pathName, channelID, homeDir string) []string { panic("[FlushAcknowledgements] Do not call me") } -// Hyperspace doesn't not have this functionality +// Hyperspace doesn't not have this functionality. func (hyperspaceCommander) FlushPackets(pathName, channelID, homeDir string) []string { panic("[FlushPackets] Do not call me") } @@ -152,14 +153,13 @@ func (c *hyperspaceCommander) GeneratePath(srcChainID, dstChainID, pathName, hom return []string{"true"} } -// Hyperspace does not have paths, just two configs +// Hyperspace does not have paths, just two configs. func (hyperspaceCommander) UpdatePath(pathName, homeDir string, opts ibc.PathUpdateOptions) []string { panic("[UpdatePath] Do not call me") - } // Prints chain config which is populated by hyperspace -// Ideally, there should be a command from hyperspace to get this output +// Ideally, there should be a command from hyperspace to get this output. func (hyperspaceCommander) GetChannels(chainID, homeDir string) []string { fmt.Println("[hyperspace] Get Channels") configFilePath := path.Join(homeDir, chainID+".config") @@ -170,7 +170,7 @@ func (hyperspaceCommander) GetChannels(chainID, homeDir string) []string { } // Prints chain config which is populated by hyperspace -// Ideally, there should be a command from hyperspace to get this output +// Ideally, there should be a command from hyperspace to get this output. func (hyperspaceCommander) GetConnections(chainID, homeDir string) []string { fmt.Println("[hyperspace] Get Connections") configFilePath := path.Join(homeDir, chainID+".config") @@ -181,7 +181,7 @@ func (hyperspaceCommander) GetConnections(chainID, homeDir string) []string { } // Prints chain config which is populated by hyperspace -// Ideally, there should be a command from hyperspace to get this output +// Ideally, there should be a command from hyperspace to get this output. func (hyperspaceCommander) GetClients(chainID, homeDir string) []string { fmt.Println("[hyperspace] Get Clients") configFilePath := path.Join(homeDir, chainID+".config") @@ -191,18 +191,18 @@ func (hyperspaceCommander) GetClients(chainID, homeDir string) []string { } } -// Hyperspace does not have link cmd, call create clients, create connection, and create channel +// Hyperspace does not have link cmd, call create clients, create connection, and create channel. func (hyperspaceCommander) LinkPath(pathName, homeDir string, channelOpts ibc.CreateChannelOptions, clientOpt ibc.CreateClientOptions) []string { panic("[LinkPath] Do not use me") } // There is no hyperspace call to restore the key, so this can't return an executable. -// HyperspaceRelayer's RestoreKey will restore the key in the chain's config file +// HyperspaceRelayer's RestoreKey will restore the key in the chain's config file. func (hyperspaceCommander) RestoreKey(chainID, bech32Prefix, coinType, signingAlgorithm, mnemonic, homeDir string) []string { panic("[RestoreKey] Do not use me") } -// hyperspace can only start 1 path +// hyperspace can only start 1 path. func (c *hyperspaceCommander) StartRelayer(homeDir string, pathNames ...string) []string { fmt.Println("[hyperspace] StartRelayer", homeDir, pathNames) if len(pathNames) != 1 { @@ -225,7 +225,7 @@ func (c *hyperspaceCommander) StartRelayer(homeDir string, pathNames ...string) } } -// Hyperspace doesn't not have this functionality +// Hyperspace doesn't not have this functionality. func (hyperspaceCommander) UpdateClients(pathName, homeDir string) []string { panic("[UpdateClients] Do not use me") } @@ -249,13 +249,13 @@ func (hyperspaceCommander) DefaultContainerVersion() string { } // There is no hyperspace call to add key, so there is no stdout to parse. -// DockerRelayer's RestoreKey will restore the key in the chain's config file +// DockerRelayer's RestoreKey will restore the key in the chain's config file. func (hyperspaceCommander) ParseAddKeyOutput(stdout, stderr string) (ibc.Wallet, error) { panic("[ParseAddKeyOutput] Do not call me") } // There is no hyperspace call to restore the key, so there is no stdout to parse. -// DockerRelayer's RestoreKey will restore the key in the chain's config file +// DockerRelayer's RestoreKey will restore the key in the chain's config file. func (hyperspaceCommander) ParseRestoreKeyOutput(stdout, stderr string) string { panic("[ParseRestoreKeyOutput] Do not call me") } @@ -265,7 +265,7 @@ type ChannelsOutput struct { } // Parses output of chain config which is populated by hyperspace -// Ideally, there should be a command from hyperspace to get this output +// Ideally, there should be a command from hyperspace to get this output. func (hyperspaceCommander) ParseGetChannelsOutput(stdout, stderr string) ([]ibc.ChannelOutput, error) { var cfg ChannelsOutput err := toml.Unmarshal([]byte(stdout), &cfg) @@ -298,7 +298,7 @@ type ConnectionsOutput struct { // Parses output of chain config which is populated by hyperspace // Ideally, there should be a command from hyperspace to get this output -// Only supports 1 connection and limited info +// Only supports 1 connection and limited info. func (hyperspaceCommander) ParseGetConnectionsOutput(stdout, stderr string) (ibc.ConnectionOutputs, error) { var cfg ConnectionsOutput err := toml.Unmarshal([]byte(stdout), &cfg) @@ -336,7 +336,7 @@ type ClientOutput struct { // Parses output of chain config which is populated by hyperspace // Ideally, there should be a command from hyperspace to get this output -// Only supports 1 client +// Only supports 1 client. func (hyperspaceCommander) ParseGetClientsOutput(stdout, stderr string) (ibc.ClientOutputs, error) { var cfg ClientOutput err := toml.Unmarshal([]byte(stdout), &cfg) diff --git a/relayer/hyperspace/hyperspace_config.go b/relayer/hyperspace/hyperspace_config.go index 8004d05af..ffe214868 100644 --- a/relayer/hyperspace/hyperspace_config.go +++ b/relayer/hyperspace/hyperspace_config.go @@ -5,13 +5,14 @@ import ( "strconv" "strings" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/types" "github.com/strangelove-ventures/interchaintest/v8/chain/polkadot" "github.com/strangelove-ventures/interchaintest/v8/ibc" bip32 "github.com/tyler-smith/go-bip32" bip39 "github.com/tyler-smith/go-bip39" + + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/cosmos/cosmos-sdk/types" ) type HyperspaceRelayerCoreConfig struct { @@ -97,6 +98,7 @@ func GenKeyEntry(bech32Prefix, coinType, mnemonic string) KeyEntry { Address: address.Bytes(), // i.e. [9, 13, 32, 191, 206, 194, 159, 239, 250, 89, 193, 7, 23, 99, 96, 46, 7, 74, 172, 14] } } + func ChainConfigToHyperspaceRelayerChainConfig(chainConfig ibc.ChainConfig, keyName, rpcAddr, grpcAddr string) interface{} { chainType := chainConfig.Type if chainType == "polkadot" || chainType == "parachain" || chainType == "relaychain" { diff --git a/relayer/hyperspace/hyperspace_relayer.go b/relayer/hyperspace/hyperspace_relayer.go index c956dae23..ae43b421b 100644 --- a/relayer/hyperspace/hyperspace_relayer.go +++ b/relayer/hyperspace/hyperspace_relayer.go @@ -69,7 +69,7 @@ func HyperspaceCapabilities() map[relayer.Capability]bool { // LinkPath performs the operations that happen when a path is linked. This includes creating clients, creating connections // and establishing a channel. This happens across multiple operations rather than a single link path cli command. -// Parachains need a Polkadot epoch/session before starting, do not link in interchain.Build() +// Parachains need a Polkadot epoch/session before starting, do not link in interchain.Build(). func (r *HyperspaceRelayer) LinkPath(ctx context.Context, rep ibc.RelayerExecReporter, pathName string, channelOpts ibc.CreateChannelOptions, clientOpts ibc.CreateClientOptions) error { if err := r.CreateClients(ctx, rep, pathName, clientOpts); err != nil { return err @@ -187,6 +187,7 @@ func (r *HyperspaceRelayer) GetRelayerChainConfig( } return nil, fmt.Errorf("unsupported chain config: %s", chainType) } + func (r *HyperspaceRelayer) SetRelayerChainConfig( ctx context.Context, filePath string, diff --git a/relayer/hyperspace/wallet.go b/relayer/hyperspace/wallet.go index 58093453a..e2cfb5522 100644 --- a/relayer/hyperspace/wallet.go +++ b/relayer/hyperspace/wallet.go @@ -33,12 +33,12 @@ func (w *HyperspaceWallet) FormattedAddress() string { return w.address } -// Get mnemonic, only used for relayer wallets +// Get mnemonic, only used for relayer wallets. func (w *HyperspaceWallet) Mnemonic() string { return w.mnemonic } -// Get Address +// Get Address. func (w *HyperspaceWallet) Address() []byte { return []byte(w.address) } diff --git a/relayer/rly/cosmos_relayer.go b/relayer/rly/cosmos_relayer.go index 35a531beb..91c5b510b 100644 --- a/relayer/rly/cosmos_relayer.go +++ b/relayer/rly/cosmos_relayer.go @@ -7,11 +7,12 @@ import ( "fmt" "strings" - "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/docker/docker/client" "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/relayer" "go.uber.org/zap" + + "github.com/cosmos/cosmos-sdk/crypto/keyring" ) const ( diff --git a/relayer/rly/wallet.go b/relayer/rly/wallet.go index 84a58e80c..2b5d627e3 100644 --- a/relayer/rly/wallet.go +++ b/relayer/rly/wallet.go @@ -33,12 +33,12 @@ func (w *RlyWallet) FormattedAddress() string { return w.address } -// Get mnemonic, only used for relayer wallets +// Get mnemonic, only used for relayer wallets. func (w *RlyWallet) Mnemonic() string { return w.mnemonic } -// Get Address +// Get Address. func (w *RlyWallet) Address() []byte { return []byte(w.address) } diff --git a/test_setup.go b/test_setup.go index c9517bbfa..5a8480ba7 100644 --- a/test_setup.go +++ b/test_setup.go @@ -41,7 +41,7 @@ func DockerSetup(t dockerutil.DockerSetupTestingT) (*client.Client, string) { // creates wallets in the relayer for src and dst chain // funds relayer src and dst wallets on respective chain in genesis // creates a faucet account on the both chains (separate fullnode) -// funds faucet accounts in genesis +// funds faucet accounts in genesis. func StartChainPair( t *testing.T, ctx context.Context, diff --git a/test_user.go b/test_user.go index 3862881fa..f2480de64 100644 --- a/test_user.go +++ b/test_user.go @@ -5,12 +5,13 @@ import ( "fmt" "testing" - "cosmossdk.io/math" "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/testutil" "github.com/stretchr/testify/require" "golang.org/x/sync/errgroup" + + "cosmossdk.io/math" ) // GetAndFundTestUserWithMnemonic restores a user using the given mnemonic diff --git a/testutil/gzip.go b/testutil/gzip.go index f5ef98c05..93b0ebcad 100644 --- a/testutil/gzip.go +++ b/testutil/gzip.go @@ -5,7 +5,7 @@ import ( "compress/gzip" ) -// GzipIt compresses the input ([]byte) +// GzipIt compresses the input ([]byte). func GzipIt(input []byte) ([]byte, error) { // Create gzip writer. var b bytes.Buffer diff --git a/testutil/poll_for_state.go b/testutil/poll_for_state.go index 2386d0476..ab40a5227 100644 --- a/testutil/poll_for_state.go +++ b/testutil/poll_for_state.go @@ -50,7 +50,7 @@ func (p BlockPoller[T]) DoPoll(ctx context.Context, startHeight, maxHeight int64 return zero, pollErr } -// ChainAcker is a chain that can get its acknowledgements at a specified height +// ChainAcker is a chain that can get its acknowledgements at a specified height. type ChainAcker interface { ChainHeighter Acknowledgements(ctx context.Context, height int64) ([]ibc.PacketAcknowledgement, error) @@ -86,7 +86,7 @@ func PollForAck(ctx context.Context, chain ChainAcker, startHeight, maxHeight in return found, nil } -// ChainTimeouter is a chain that can get its timeouts at a specified height +// ChainTimeouter is a chain that can get its timeouts at a specified height. type ChainTimeouter interface { ChainHeighter Timeouts(ctx context.Context, height int64) ([]ibc.PacketTimeout, error) @@ -138,7 +138,7 @@ func (pe *packetPollError) Unwrap() error { return pe.error } -// Format is expected to be used by testify/require which prints errors via %+v +// Format is expected to be used by testify/require which prints errors via %+v. func (pe *packetPollError) Format(s fmt.State, verb rune) { if verb != 'v' && !s.Flag('+') { fmt.Fprint(s, pe.error.Error()) From 5da8d527b2a729ac394aed19b346b9738205d149 Mon Sep 17 00:00:00 2001 From: Justin Tieri <37750742+jtieri@users.noreply.github.com> Date: Sun, 6 Oct 2024 23:01:44 -0500 Subject: [PATCH 4/5] chore: fix linter warnings (#1270) --- .github/workflows/e2e-tests.yml | 12 +-- .github/workflows/lint.yml | 2 +- .github/workflows/unit-tests.yml | 4 +- .golangci.yml | 11 ++- Makefile | 18 ++++- blockdb/chain_test.go | 26 ++++--- blockdb/messages_view_test.go | 39 +++++----- blockdb/query.go | 2 +- blockdb/query_test.go | 12 ++- blockdb/sql_test.go | 4 - blockdb/test_case_test.go | 8 ++ blockdb/tui/model.go | 1 + blockdb/tui/model_test.go | 5 +- blockdb/tui/presenter/cosmos_message_test.go | 7 +- blockdb/tui/presenter/test_case_test.go | 7 +- blockdb/tui/presenter/tx_test.go | 7 +- blockdb/tui/update.go | 1 + blockdb/tui/update_test.go | 3 +- blockdb/tui/views.go | 1 + blockdb/views_test.go | 18 ++--- chain/cosmos/broadcaster.go | 8 +- chain/cosmos/chain_node.go | 51 +++++++----- chain/cosmos/codec.go | 4 +- chain/cosmos/cosmos_chain.go | 51 ++++-------- chain/cosmos/genesis.go | 1 + chain/cosmos/ics.go | 22 +++--- chain/cosmos/module_auth.go | 17 ++-- chain/cosmos/module_authz.go | 4 +- chain/cosmos/module_bank.go | 4 +- chain/cosmos/module_cosmwasm.go | 19 +++-- chain/cosmos/module_gov.go | 8 +- chain/cosmos/module_vesting.go | 6 +- chain/cosmos/node_test.go | 3 +- chain/cosmos/poll.go | 8 +- chain/cosmos/query.go | 2 +- chain/cosmos/sidecar.go | 3 +- chain/cosmos/wallet.go | 4 +- chain/cosmos/wasm/wasm.go | 5 +- chain/ethereum/ethererum_chain.go | 21 +++-- chain/ethereum/foundry/anvil_chain.go | 15 ++-- chain/ethereum/foundry/default_configs.go | 2 +- chain/ethereum/foundry/forge.go | 1 + chain/ethereum/geth/default_configs.go | 4 +- chain/ethereum/geth/geth_chain.go | 7 +- chain/ethereum/wallet.go | 1 + chain/internal/tendermint/tendermint_node.go | 14 ++-- chain/penumbra/penumbra_app_node.go | 21 ++--- chain/penumbra/penumbra_chain.go | 22 ++---- chain/penumbra/penumbra_client_node.go | 63 ++++++++------- chain/penumbra/penumbra_client_node_test.go | 3 +- chain/penumbra/penumbra_node.go | 3 +- chain/polkadot/keys.go | 6 +- chain/polkadot/keys_test.go | 7 +- chain/polkadot/parachain_node.go | 21 ++--- chain/polkadot/polkadot_chain.go | 52 ++++++------- chain/polkadot/polkadot_chain_test.go | 18 ++--- chain/polkadot/relay_chain_node.go | 27 +++---- chain/polkadot/ss58.go | 23 +++--- chain/polkadot/tx.go | 10 ++- chain/thorchain/api_query.go | 71 +++++++++-------- chain/thorchain/broadcaster.go | 8 +- chain/thorchain/common/chain.go | 2 + chain/thorchain/genesis.go | 1 + chain/thorchain/module_bank.go | 4 +- chain/thorchain/module_thorchain.go | 4 +- chain/thorchain/poll.go | 6 +- chain/thorchain/query.go | 2 +- chain/thorchain/sidecar.go | 3 +- chain/thorchain/thorchain.go | 39 ++-------- chain/thorchain/thornode.go | 55 ++++++++----- chain/thorchain/types.go | 8 +- chain/thorchain/wallet.go | 4 +- chain/utxo/cli.go | 15 ++-- chain/utxo/default_configs.go | 8 +- chain/utxo/types.go | 4 +- chain/utxo/unimplemented.go | 2 +- chain/utxo/utxo_chain.go | 62 ++++++++------- chain/utxo/wallet.go | 14 ++-- chainfactory.go | 21 ++--- chainset.go | 12 +-- chainspec.go | 6 +- chainspec_test.go | 7 +- cmd/interchaintest/flags.go | 3 +- cmd/interchaintest/interchaintest_test.go | 8 +- cmd/interchaintest/matrix_test.go | 3 +- conformance/flush.go | 11 +-- conformance/relayersetup.go | 25 +++--- conformance/test.go | 43 ++++++----- contract/cosmwasm/rust_optimizer.go | 2 +- dockerutil/container_lifecycle.go | 7 +- dockerutil/file.go | 8 +- dockerutil/fileretriever_test.go | 9 ++- dockerutil/filewriter_test.go | 9 ++- dockerutil/keyring.go | 6 +- dockerutil/setup_test.go | 4 +- dockerutil/volumeowner.go | 2 +- examples/cosmos/bad_genesis_params_test.go | 8 +- examples/cosmos/code_coverage_test.go | 2 +- examples/cosmos/ethermint_test.go | 2 +- examples/cosmos/sdk_boundary_test.go | 4 +- examples/ethereum/foundry_test.go | 2 - examples/ethereum/geth_test.go | 2 - examples/hyperspace/hyperspace_test.go | 6 +- examples/ibc/wasm/wasm_icq_test.go | 2 +- examples/penumbra/penumbra_ibc_test.go | 6 +- examples/polkadot/polkadot_chain_test.go | 4 +- .../polkadot/push_wasm_client_code_test.go | 2 +- .../polkadot/substrate_cosmos_ibc_test.go | 20 ++--- .../thorchain/chainspec_thorchain_test.go | 4 +- examples/thorchain/features/arb.go | 9 +-- examples/thorchain/features/dual_lper.go | 2 +- examples/thorchain/features/helpers.go | 12 +-- examples/thorchain/features/ragnarok.go | 2 +- examples/thorchain/features/saver_eject.go | 10 +-- examples/thorchain/features/savers.go | 6 +- examples/thorchain/features/swap.go | 10 +-- examples/thorchain/helper_test.go | 4 +- examples/thorchain/setup_test.go | 6 +- ibc/packet_test.go | 3 - ibc/relayer.go | 8 +- ibc/types.go | 20 ++++- interchain.go | 15 +--- interchain_builder.go | 16 +++- interchain_test.go | 30 +++++--- local-interchain/cmd/local-ic/new_chain.go | 2 +- local-interchain/cmd/local-ic/start_chain.go | 2 +- local-interchain/interchain/config.go | 2 +- local-interchain/interchain/start.go | 2 +- local-interchain/interchain/types/types.go | 4 +- mocktesting/t_test.go | 5 +- relayer/docker.go | 7 +- relayer/hermes/hermes_commander.go | 13 ++-- relayer/hermes/hermes_relayer.go | 40 +++++----- relayer/hermes/hermes_types.go | 4 +- relayer/hyperspace/hyperspace_commander.go | 77 +++++++++++++++---- relayer/hyperspace/hyperspace_config.go | 36 +++++---- relayer/hyperspace/hyperspace_relayer.go | 17 ++-- relayer/hyperspace/hyperspace_test.go | 3 +- relayer/options.go | 4 +- relayer/rly/cosmos_relayer.go | 9 ++- relayerfactory.go | 10 ++- tempdir_test.go | 6 +- test_setup.go | 6 +- test_user.go | 11 +-- testreporter/messages_test.go | 3 +- testreporter/reporter_test.go | 29 +++---- testutil/poll_for_state.go | 1 + testutil/poll_for_state_test.go | 3 +- testutil/toml.go | 3 +- testutil/wait.go | 4 +- testutil/wait_test.go | 14 ++++ 151 files changed, 985 insertions(+), 796 deletions(-) diff --git a/.github/workflows/e2e-tests.yml b/.github/workflows/e2e-tests.yml index ea0f7bf39..54f8a71a3 100644 --- a/.github/workflows/e2e-tests.yml +++ b/.github/workflows/e2e-tests.yml @@ -14,10 +14,10 @@ jobs: runs-on: ubuntu-latest steps: # Install and setup go - - name: Set up Go 1.21 + - name: Set up Go 1.22 uses: actions/setup-go@v5 with: - go-version: '1.21' + go-version: '1.22' - name: checkout interchaintest uses: actions/checkout@v4 @@ -35,10 +35,10 @@ jobs: runs-on: ubuntu-latest steps: # Install and setup go - - name: Set up Go 1.21 + - name: Set up Go 1.22 uses: actions/setup-go@v5 with: - go-version: '1.21' + go-version: '1.22' cache: false - name: checkout interchaintest @@ -57,10 +57,10 @@ jobs: runs-on: ubuntu-latest steps: # Install and setup go - - name: Set up Go 1.21 + - name: Set up Go 1.22 uses: actions/setup-go@v5 with: - go-version: '1.21' + go-version: '1.22' cache: false - name: checkout interchaintest diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 8f35b408e..2bb290422 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -50,5 +50,5 @@ jobs: - name: golangci-lint uses: golangci/golangci-lint-action@v6.1.0 with: - version: v1.57.2 + version: v1.61.0 args: --timeout 15m \ No newline at end of file diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 3a191012b..b9146e3dd 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -14,10 +14,10 @@ jobs: runs-on: ubuntu-latest steps: # Install and setup go - - name: Set up Go 1.21 + - name: Set up Go 1.22 uses: actions/setup-go@v5 with: - go-version: '1.21' + go-version: '1.22' - name: checkout interchaintest uses: actions/checkout@v4 diff --git a/.golangci.yml b/.golangci.yml index 2b13f2610..f9ba502f2 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -10,6 +10,7 @@ linters: - asciicheck - bidichk - bodyclose + - copyloopvar - decorder - dupl - dupword @@ -17,7 +18,6 @@ linters: - errchkjson - errname - exhaustive - - exportloopref - forbidigo - gci - goconst @@ -32,8 +32,8 @@ linters: - ineffassign - loggercheck - misspell - - nilerr - - nilnil + # - nilerr disabled because we return nil when there are errors in places that need to keep running e.g. polling/waiting for a condition + # - nilnil disabled because we return nil, nil when polling but waiting for a conditional - noctx - staticcheck - stylecheck @@ -64,6 +64,11 @@ linters-settings: gosec: excludes: - G404 # disables checks on insecure random number source + - G115 # disables checks on type conversions between signed and unsigned integers + - G306 # disables checks on WriteFile perms. Not an issue since we are writing configs/logs in a local test env + gocritic: + disabled-checks: + - appendAssign # we use append to build cmds from a config and always assign to a new slice to not overwrite cfg issues: max-issues-per-linter: 0 \ No newline at end of file diff --git a/Makefile b/Makefile index d7cf6b1e7..2622488de 100644 --- a/Makefile +++ b/Makefile @@ -3,9 +3,9 @@ protoVer=0.13.2 protoImageName=ghcr.io/cosmos/proto-builder:$(protoVer) protoImage=$(DOCKER) run --rm -v $(CURDIR):/workspace --workdir /workspace $(protoImageName) golangci_lint_cmd=golangci-lint -golangci_version=v1.57.2 +golangci_version=v1.61.0 gofumpt_cmd=gofumpt -gofumpt_version=v0.6.0 +gofumpt_version=v0.7.0 default: help @@ -19,7 +19,19 @@ interchaintest: gen ## Build interchaintest binary into ./bin .PHONY: test test: ## Run unit tests - @go test -cover -short -race -timeout=60s ./... + @go test -cover -short -race -timeout=30m -failfast -p 2 $(go list ./... | grep -v /cmd | grep -v /examples) + +.PHONY: test-conformance +test-conformance: ## Run e2e conformance tests + @go test -race -timeout 30m -failfast -v -p 2 ./cmd/interchaintest + +.PHONY: test-ibc-examples +test-ibc-examples: ## Run e2e ibc example tests + @go test -race -timeout 30m -failfast -v -p 2 ./examples/ibc + +.PHONY: test-cosmos-examples +test-cosmos-examples: ## Run e2e cosmos example tests + @go test -race -failfast -timeout 30m -v -p 2 ./examples/cosmos .PHONY: docker-reset docker-reset: ## Attempt to delete all running containers. Useful if interchaintest does not exit cleanly. diff --git a/blockdb/chain_test.go b/blockdb/chain_test.go index 7180f8dbd..566797108 100644 --- a/blockdb/chain_test.go +++ b/blockdb/chain_test.go @@ -47,6 +47,8 @@ func TestChain_SaveBlock(t *testing.T) { ) t.Run("happy path", func(t *testing.T) { + t.Parallel() + db := migratedDB() defer db.Close() @@ -98,20 +100,20 @@ ORDER BY tendermint_event_attr.id`) for i = 0; rows.Next(); i++ { var gotData, gotType, gotKey, gotValue string require.NoError(t, rows.Scan(&gotData, &gotType, &gotKey, &gotValue)) - require.Equal(t, gotData, `{"test":1}`) + require.Equal(t, `{"test":1}`, gotData) switch i { case 0: - require.Equal(t, gotType, "e1") - require.Equal(t, gotKey, "k1") - require.Equal(t, gotValue, "v1") + require.Equal(t, "e1", gotType) + require.Equal(t, "k1", gotKey) + require.Equal(t, "v1", gotValue) case 1: - require.Equal(t, gotType, "e2") - require.Equal(t, gotKey, "k2") - require.Equal(t, gotValue, "v2") + require.Equal(t, "e2", gotType) + require.Equal(t, "k2", gotKey) + require.Equal(t, "v2", gotValue) case 2: - require.Equal(t, gotType, "e2") - require.Equal(t, gotKey, "k3") - require.Equal(t, gotValue, "v3") + require.Equal(t, "e2", gotType) + require.Equal(t, "k3", gotKey) + require.Equal(t, "v3", gotValue) default: t.Fatalf("expected 3 results, got i=%d", i) } @@ -119,6 +121,8 @@ ORDER BY tendermint_event_attr.id`) }) t.Run("idempotent", func(t *testing.T) { + t.Parallel() + db := migratedDB() defer db.Close() @@ -152,6 +156,8 @@ ORDER BY tendermint_event_attr.id`) }) t.Run("zero state", func(t *testing.T) { + t.Parallel() + db := migratedDB() defer db.Close() diff --git a/blockdb/messages_view_test.go b/blockdb/messages_view_test.go index 2b23a0a8d..ae4e0c0ee 100644 --- a/blockdb/messages_view_test.go +++ b/blockdb/messages_view_test.go @@ -9,17 +9,18 @@ import ( "path/filepath" "testing" - "github.com/strangelove-ventures/interchaintest/v8" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/relayer" - "github.com/strangelove-ventures/interchaintest/v8/testreporter" - "github.com/strangelove-ventures/interchaintest/v8/testutil" "github.com/stretchr/testify/require" "go.uber.org/zap/zaptest" "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/types" + + "github.com/strangelove-ventures/interchaintest/v8" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/relayer" + "github.com/strangelove-ventures/interchaintest/v8/testreporter" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) func TestMessagesView(t *testing.T) { @@ -87,7 +88,7 @@ func TestMessagesView(t *testing.T) { var count int row := db.QueryRow(`SELECT COUNT(*) FROM v_cosmos_messages`) require.NoError(t, row.Scan(&count)) - require.Equal(t, count, 0) + require.Equal(t, 0, count) // Generate the path. // No transactions happen here. @@ -105,10 +106,10 @@ FROM v_cosmos_messages WHERE type = "/ibc.core.client.v1.MsgCreateClient" AND chain_id = ?;` var clientChainID string require.NoError(t, db.QueryRow(qCreateClient, gaia0ChainID).Scan(&clientChainID)) - require.Equal(t, clientChainID, gaia1ChainID) + require.Equal(t, gaia1ChainID, clientChainID) require.NoError(t, db.QueryRow(qCreateClient, gaia1ChainID).Scan(&clientChainID)) - require.Equal(t, clientChainID, gaia0ChainID) + require.Equal(t, gaia0ChainID, clientChainID) }) if t.Failed() { return @@ -208,8 +209,8 @@ WHERE type = "/ibc.core.channel.v1.MsgChannelOpenInit" AND chain_id = ? ` var portID, counterpartyPortID string require.NoError(t, db.QueryRow(qChannelOpenInit, gaia0ChainID).Scan(&portID, &counterpartyPortID)) - require.Equal(t, portID, gaia0Port) - require.Equal(t, counterpartyPortID, gaia1Port) + require.Equal(t, gaia0Port, portID) + require.Equal(t, gaia1Port, counterpartyPortID) // OpenTry happens on second chain. const qChannelOpenTry = `SELECT @@ -219,8 +220,8 @@ WHERE type = "/ibc.core.channel.v1.MsgChannelOpenTry" AND chain_id = ? ` var counterpartyChannelID string require.NoError(t, db.QueryRow(qChannelOpenTry, gaia1ChainID).Scan(&portID, &counterpartyPortID, &counterpartyChannelID)) - require.Equal(t, portID, gaia1Port) - require.Equal(t, counterpartyPortID, gaia0Port) + require.Equal(t, gaia1Port, portID) + require.Equal(t, gaia0Port, counterpartyPortID) require.Equal(t, counterpartyChannelID, gaia0ChannelID) // OpenAck happens on first chain again. @@ -231,7 +232,7 @@ WHERE type = "/ibc.core.channel.v1.MsgChannelOpenAck" AND chain_id = ? ` var channelID string require.NoError(t, db.QueryRow(qChannelOpenAck, gaia0ChainID).Scan(&portID, &channelID, &counterpartyChannelID)) - require.Equal(t, portID, gaia0Port) + require.Equal(t, gaia0Port, portID) require.Equal(t, channelID, gaia0ChannelID) require.Equal(t, counterpartyChannelID, gaia1ChannelID) @@ -242,7 +243,7 @@ FROM v_cosmos_messages WHERE type = "/ibc.core.channel.v1.MsgChannelOpenConfirm" AND chain_id = ? ` require.NoError(t, db.QueryRow(qChannelOpenConfirm, gaia1ChainID).Scan(&portID, &channelID)) - require.Equal(t, portID, gaia1Port) + require.Equal(t, gaia1Port, portID) require.Equal(t, channelID, gaia1ChannelID) }) if t.Failed() { @@ -274,7 +275,7 @@ WHERE type = "/ibc.applications.transfer.v1.MsgTransfer" AND chain_id = ? ` var portID, channelID string require.NoError(t, db.QueryRow(qMsgTransfer, gaia0ChainID).Scan(&portID, &channelID)) - require.Equal(t, portID, gaia0Port) + require.Equal(t, gaia0Port, portID) require.Equal(t, channelID, gaia0ChannelID) }) if t.Failed() { @@ -299,9 +300,9 @@ WHERE type = "/ibc.core.channel.v1.MsgRecvPacket" AND chain_id = ? require.NoError(t, db.QueryRow(qMsgRecvPacket, gaia1ChainID).Scan(&portID, &channelID, &counterpartyPortID, &counterpartyChannelID)) - require.Equal(t, portID, gaia0Port) + require.Equal(t, gaia0Port, portID) require.Equal(t, channelID, gaia0ChannelID) - require.Equal(t, counterpartyPortID, gaia1Port) + require.Equal(t, gaia1Port, counterpartyPortID) require.Equal(t, counterpartyChannelID, gaia1ChannelID) const qMsgAck = `SELECT @@ -311,9 +312,9 @@ WHERE type = "/ibc.core.channel.v1.MsgAcknowledgement" AND chain_id = ? ` require.NoError(t, db.QueryRow(qMsgAck, gaia0ChainID).Scan(&portID, &channelID, &counterpartyPortID, &counterpartyChannelID)) - require.Equal(t, portID, gaia0Port) + require.Equal(t, gaia0Port, portID) require.Equal(t, channelID, gaia0ChannelID) - require.Equal(t, counterpartyPortID, gaia1Port) + require.Equal(t, gaia1Port, counterpartyPortID) require.Equal(t, counterpartyChannelID, gaia1ChannelID) }) } diff --git a/blockdb/query.go b/blockdb/query.go index 30284e1a6..1461ab588 100644 --- a/blockdb/query.go +++ b/blockdb/query.go @@ -21,7 +21,7 @@ func timeToLocal(timeStr string) (time.Time, error) { if err != nil { return time.Time{}, fmt.Errorf("time.Parse RFC3339: %w", err) } - return t.In(time.Local), nil + return t.In(time.Local), nil //nolint: gosmopolitan } type SchemaVersionResult struct { diff --git a/blockdb/query_test.go b/blockdb/query_test.go index 5268ee7c5..d6ed9b8a0 100644 --- a/blockdb/query_test.go +++ b/blockdb/query_test.go @@ -37,6 +37,8 @@ func TestQuery_RecentTestCases(t *testing.T) { ctx := context.Background() t.Run("happy path", func(t *testing.T) { + t.Parallel() + db := migratedDB() defer db.Close() @@ -83,6 +85,8 @@ func TestQuery_RecentTestCases(t *testing.T) { }) t.Run("limit", func(t *testing.T) { + t.Parallel() + db := migratedDB() defer db.Close() @@ -99,6 +103,8 @@ func TestQuery_RecentTestCases(t *testing.T) { }) t.Run("no test cases", func(t *testing.T) { + t.Parallel() + db := migratedDB() defer db.Close() @@ -174,6 +180,8 @@ func TestQuery_Transactions(t *testing.T) { ctx := context.Background() t.Run("happy path", func(t *testing.T) { + t.Parallel() + db := migratedDB() defer db.Close() @@ -201,6 +209,8 @@ func TestQuery_Transactions(t *testing.T) { }) t.Run("no txs", func(t *testing.T) { + t.Parallel() + db := migratedDB() defer db.Close() @@ -212,6 +222,6 @@ func TestQuery_Transactions(t *testing.T) { results, err := NewQuery(db).Transactions(ctx, chain.id) require.NoError(t, err) - require.Len(t, results, 0) + require.Empty(t, results) }) } diff --git a/blockdb/sql_test.go b/blockdb/sql_test.go index 59cb1bab4..06bd1c593 100644 --- a/blockdb/sql_test.go +++ b/blockdb/sql_test.go @@ -63,8 +63,6 @@ func TestDB_Concurrency(t *testing.T) { // and a shared context so all fail if one fails. egWrites, egCtx := errgroup.WithContext(ctx) for i := 0; i < nWriters; i++ { - i := i - // Connecting to the database in the main goroutine // because concurrently connecting to the same database // causes a data race inside sqlite. @@ -98,8 +96,6 @@ func TestDB_Concurrency(t *testing.T) { // Separate errgroup for the queriers. var egQueries errgroup.Group for i := 0; i < nQueriers; i++ { - i := i - db, err := ConnectDB(ctx, dbPath) require.NoErrorf(t, err, "failed to connect to db for querier %d: %v", i, err) defer db.Close() diff --git a/blockdb/test_case_test.go b/blockdb/test_case_test.go index 408cbb520..51334b577 100644 --- a/blockdb/test_case_test.go +++ b/blockdb/test_case_test.go @@ -14,6 +14,8 @@ func TestCreateTestCase(t *testing.T) { ctx := context.Background() t.Run("happy path", func(t *testing.T) { + t.Parallel() + db := migratedDB() defer db.Close() @@ -39,6 +41,8 @@ func TestCreateTestCase(t *testing.T) { }) t.Run("errors", func(t *testing.T) { + t.Parallel() + db := emptyDB() _, err := CreateTestCase(ctx, db, "fail", "") require.Error(t, err) @@ -51,6 +55,8 @@ func TestTestCase_AddChain(t *testing.T) { ctx := context.Background() t.Run("happy path", func(t *testing.T) { + t.Parallel() + db := migratedDB() defer db.Close() @@ -80,6 +86,8 @@ func TestTestCase_AddChain(t *testing.T) { }) t.Run("errors", func(t *testing.T) { + t.Parallel() + db := migratedDB() defer db.Close() diff --git a/blockdb/tui/model.go b/blockdb/tui/model.go index cdee852ef..13167908a 100644 --- a/blockdb/tui/model.go +++ b/blockdb/tui/model.go @@ -6,6 +6,7 @@ import ( "github.com/atotto/clipboard" "github.com/rivo/tview" + "github.com/strangelove-ventures/interchaintest/v8/blockdb" ) diff --git a/blockdb/tui/model_test.go b/blockdb/tui/model_test.go index ec3e832ca..1e6aff283 100644 --- a/blockdb/tui/model_test.go +++ b/blockdb/tui/model_test.go @@ -4,13 +4,14 @@ import ( "testing" "time" - "github.com/strangelove-ventures/interchaintest/v8/blockdb" "github.com/stretchr/testify/require" + + "github.com/strangelove-ventures/interchaintest/v8/blockdb" ) func TestModel_RootView(t *testing.T) { m := NewModel(&mockQueryService{}, "test.db", "abc123", time.Now(), make([]blockdb.TestCaseResult, 1)) view := m.RootView() require.NotNil(t, view) - require.Greater(t, view.GetItemCount(), 0) + require.Positive(t, view.GetItemCount()) } diff --git a/blockdb/tui/presenter/cosmos_message_test.go b/blockdb/tui/presenter/cosmos_message_test.go index ea30330ad..2183b33c3 100644 --- a/blockdb/tui/presenter/cosmos_message_test.go +++ b/blockdb/tui/presenter/cosmos_message_test.go @@ -4,14 +4,17 @@ import ( "database/sql" "testing" - "github.com/strangelove-ventures/interchaintest/v8/blockdb" "github.com/stretchr/testify/require" + + "github.com/strangelove-ventures/interchaintest/v8/blockdb" ) func TestCosmosMessage(t *testing.T) { t.Parallel() t.Run("non-variable fields", func(t *testing.T) { + t.Parallel() + res := blockdb.CosmosMessageResult{ Height: 55, Index: 13, @@ -30,6 +33,8 @@ func TestCosmosMessage(t *testing.T) { }) t.Run("ibc details", func(t *testing.T) { + t.Parallel() + for _, tt := range []struct { Result blockdb.CosmosMessageResult WantClients string diff --git a/blockdb/tui/presenter/test_case_test.go b/blockdb/tui/presenter/test_case_test.go index 525a0b4b2..24fb33399 100644 --- a/blockdb/tui/presenter/test_case_test.go +++ b/blockdb/tui/presenter/test_case_test.go @@ -5,14 +5,17 @@ import ( "testing" "time" - "github.com/strangelove-ventures/interchaintest/v8/blockdb" "github.com/stretchr/testify/require" + + "github.com/strangelove-ventures/interchaintest/v8/blockdb" ) func TestTestCase(t *testing.T) { t.Parallel() t.Run("happy path", func(t *testing.T) { + t.Parallel() + result := blockdb.TestCaseResult{ ID: 321, Name: "My Test", @@ -36,6 +39,8 @@ func TestTestCase(t *testing.T) { }) t.Run("zero state", func(t *testing.T) { + t.Parallel() + var pres TestCase require.Empty(t, pres.Height()) diff --git a/blockdb/tui/presenter/tx_test.go b/blockdb/tui/presenter/tx_test.go index 50a91b5c2..18707c2bf 100644 --- a/blockdb/tui/presenter/tx_test.go +++ b/blockdb/tui/presenter/tx_test.go @@ -4,14 +4,17 @@ import ( "encoding/json" "testing" - "github.com/strangelove-ventures/interchaintest/v8/blockdb" "github.com/stretchr/testify/require" + + "github.com/strangelove-ventures/interchaintest/v8/blockdb" ) func TestTx(t *testing.T) { t.Parallel() t.Run("json", func(t *testing.T) { + t.Parallel() + tx := blockdb.TxResult{ Height: 13, Tx: []byte(`{"json":{"foo":true}}`), @@ -30,6 +33,8 @@ func TestTx(t *testing.T) { }) t.Run("non-json", func(t *testing.T) { + t.Parallel() + tx := blockdb.TxResult{ Tx: []byte(`some data`), } diff --git a/blockdb/tui/update.go b/blockdb/tui/update.go index 2287afaed..408bc3a36 100644 --- a/blockdb/tui/update.go +++ b/blockdb/tui/update.go @@ -7,6 +7,7 @@ import ( "github.com/gdamore/tcell/v2" "github.com/rivo/tview" + "github.com/strangelove-ventures/interchaintest/v8/blockdb/tui/presenter" ) diff --git a/blockdb/tui/update_test.go b/blockdb/tui/update_test.go index 623f563fc..08130ac61 100644 --- a/blockdb/tui/update_test.go +++ b/blockdb/tui/update_test.go @@ -9,8 +9,9 @@ import ( "github.com/gdamore/tcell/v2" "github.com/rivo/tview" - "github.com/strangelove-ventures/interchaintest/v8/blockdb" "github.com/stretchr/testify/require" + + "github.com/strangelove-ventures/interchaintest/v8/blockdb" ) var ( diff --git a/blockdb/tui/views.go b/blockdb/tui/views.go index 3a50633e2..3df16b53d 100644 --- a/blockdb/tui/views.go +++ b/blockdb/tui/views.go @@ -8,6 +8,7 @@ import ( "github.com/gdamore/tcell/v2" "github.com/rivo/tview" + "github.com/strangelove-ventures/interchaintest/v8/blockdb" "github.com/strangelove-ventures/interchaintest/v8/blockdb/tui/presenter" ) diff --git a/blockdb/views_test.go b/blockdb/views_test.go index 79a353546..2c84ad413 100644 --- a/blockdb/views_test.go +++ b/blockdb/views_test.go @@ -72,17 +72,17 @@ ORDER BY test_case_id, chain_kid, block_id, tx_id require.Equal(t, tcID, tc.id) require.GreaterOrEqual(t, tcCreatedAt, beforeTestCaseCreate) require.LessOrEqual(t, tcCreatedAt, beforeBlocksCreated) - require.Equal(t, tcName, "mytest") + require.Equal(t, "mytest", tcName) require.Equal(t, chainKeyID, chain.id) - require.Equal(t, chainID, "chain1") - require.Equal(t, chainType, "cosmos") + require.Equal(t, "chain1", chainID) + require.Equal(t, "cosmos", chainType) require.GreaterOrEqual(t, blockCreatedAt, beforeBlocksCreated) require.LessOrEqual(t, blockCreatedAt, afterBlocksCreated) - require.Equal(t, blockHeight, 1) + require.Equal(t, 1, blockHeight) - require.Equal(t, tx, "tx1.0") + require.Equal(t, "tx1.0", tx) // Save some state gathered from the first row. firstBlockCreatedAt := blockCreatedAt @@ -104,11 +104,11 @@ ORDER BY test_case_id, chain_kid, block_id, tx_id // New block height. require.GreaterOrEqual(t, blockCreatedAt, firstBlockCreatedAt) require.LessOrEqual(t, blockCreatedAt, afterBlocksCreated) - require.Equal(t, blockHeight, 2) + require.Equal(t, 2, blockHeight) // Next transaction. require.Greater(t, txID, firstTxID) - require.Equal(t, tx, "tx2.0") + require.Equal(t, "tx2.0", tx) secondTxID := txID @@ -126,11 +126,11 @@ ORDER BY test_case_id, chain_kid, block_id, tx_id require.Equal(t, chainKeyID, chain.id) // Same block height. - require.Equal(t, blockHeight, 2) + require.Equal(t, 2, blockHeight) // Next transaction. require.Greater(t, txID, secondTxID) - require.Equal(t, tx, "tx2.1") + require.Equal(t, "tx2.1", tx) // No more rows. require.False(t, rows.Next()) diff --git a/chain/cosmos/broadcaster.go b/chain/cosmos/broadcaster.go index 7dd7a8027..b51ba1801 100644 --- a/chain/cosmos/broadcaster.go +++ b/chain/cosmos/broadcaster.go @@ -8,9 +8,6 @@ import ( "testing" "time" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/testutil" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" @@ -18,6 +15,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" + + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) type ClientContextOpt func(clientContext client.Context) client.Context @@ -50,6 +50,8 @@ type Broadcaster struct { // NewBroadcaster returns a instance of Broadcaster which can be used with broadcast.Tx to // broadcast messages sdk messages. func NewBroadcaster(t *testing.T, chain *CosmosChain) *Broadcaster { + t.Helper() + return &Broadcaster{ t: t, chain: chain, diff --git a/chain/cosmos/chain_node.go b/chain/cosmos/chain_node.go index 4db0c25a5..488487a32 100644 --- a/chain/cosmos/chain_node.go +++ b/chain/cosmos/chain_node.go @@ -21,10 +21,6 @@ import ( volumetypes "github.com/docker/docker/api/types/volume" dockerclient "github.com/docker/docker/client" "github.com/docker/go-connections/nat" - "github.com/strangelove-ventures/interchaintest/v8/blockdb" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" "golang.org/x/mod/semver" "golang.org/x/sync/errgroup" @@ -49,6 +45,11 @@ import ( rpchttp "github.com/cometbft/cometbft/rpc/client/http" coretypes "github.com/cometbft/cometbft/rpc/core/types" libclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" + + "github.com/strangelove-ventures/interchaintest/v8/blockdb" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) // ChainNode represents a node in the test network that is being created. @@ -191,7 +192,7 @@ func (tn *ChainNode) NewSidecarProcess( VolumeName: v.Name, ImageRef: image.Ref(), TestName: tn.TestName, - UidGid: image.UidGid, + UidGid: image.UIDGID, }); err != nil { return fmt.Errorf("set volume owner: %w", err) } @@ -429,7 +430,7 @@ func (tn *ChainNode) Height(ctx context.Context) (int64, error) { // FindTxs implements blockdb.BlockSaver. func (tn *ChainNode) FindTxs(ctx context.Context, height int64) ([]blockdb.Tx, error) { - h := int64(height) + h := height var eg errgroup.Group var blockRes *coretypes.ResultBlockResults var block *coretypes.ResultBlock @@ -469,8 +470,8 @@ func (tn *ChainNode) FindTxs(ctx context.Context, height int64) ([]blockdb.Tx, e 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), + Key: attr.Key, + Value: attr.Value, } } newTx.Events[j] = blockdb.Event{ @@ -489,8 +490,8 @@ func (tn *ChainNode) FindTxs(ctx context.Context, height int64) ([]blockdb.Tx, e 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), + Key: attr.Key, + Value: attr.Value, } } finalizeBlockTx.Events[i] = blockdb.Event{ @@ -550,7 +551,7 @@ func (tn *ChainNode) ExecTx(ctx context.Context, keyName string, command ...stri return "", err } output := CosmosTx{} - err = json.Unmarshal([]byte(stdout), &output) + err = json.Unmarshal(stdout, &output) if err != nil { return "", err } @@ -566,7 +567,7 @@ func (tn *ChainNode) ExecTx(ctx context.Context, keyName string, command ...stri return "", err } output = CosmosTx{} - err = json.Unmarshal([]byte(stdout), &output) + err = json.Unmarshal(stdout, &output) if err != nil { return "", err } @@ -580,7 +581,11 @@ func (tn *ChainNode) ExecTx(ctx context.Context, keyName string, command ...stri func (tn *ChainNode) TxHashToResponse(ctx context.Context, txHash string) (*sdk.TxResponse, error) { stdout, stderr, err := tn.ExecQuery(ctx, "tx", txHash) if err != nil { - fmt.Println("TxHashToResponse err: ", err.Error()+" "+string(stderr)) + tn.log.Info("TxHashToResponse returned an error", + zap.String("tx_hash", txHash), + zap.Error(err), + zap.String("stderr", string(stderr)), + ) } i := &sdk.TxResponse{} @@ -927,12 +932,12 @@ func (tn *ChainNode) HasCommand(ctx context.Context, command ...string) bool { return true } - if strings.Contains(string(err.Error()), "Error: unknown command") { + if strings.Contains(err.Error(), "Error: unknown command") { return false } // cmd just needed more arguments, but it is a valid command (ex: appd tx bank send) - if strings.Contains(string(err.Error()), "Error: accepts") { + if strings.Contains(err.Error(), "Error: accepts") { return true } @@ -958,7 +963,7 @@ func (tn *ChainNode) GetBuildInformation(ctx context.Context) *BinaryBuildInform } var deps tempBuildDeps - if err := json.Unmarshal([]byte(stdout), &deps); err != nil { + if err := json.Unmarshal(stdout, &deps); err != nil { return nil } @@ -1020,7 +1025,7 @@ func (tn *ChainNode) QueryClientContractCode(ctx context.Context, codeHash strin if err != nil { return err } - err = json.Unmarshal([]byte(stdout), response) + err = json.Unmarshal(stdout, response) return err } @@ -1164,15 +1169,23 @@ func (tn *ChainNode) CreateNodeContainer(ctx context.Context) error { // to prevent port binding conflicts, host port overrides are only exposed on the first validator node. if tn.Validator && tn.Index == 0 && chainCfg.HostPortOverride != nil { + var fields []zap.Field + + i := 0 for intP, extP := range chainCfg.HostPortOverride { - usingPorts[nat.Port(fmt.Sprintf("%d/tcp", intP))] = []nat.PortBinding{ + port := nat.Port(fmt.Sprintf("%d/tcp", intP)) + + usingPorts[port] = []nat.PortBinding{ { HostPort: fmt.Sprintf("%d", extP), }, } + + fields = append(fields, zap.String(fmt.Sprintf("port_overrides_%d", i), fmt.Sprintf("%s:%d", port, extP))) + i++ } - fmt.Printf("Port Overrides: %v. Using: %v\n", chainCfg.HostPortOverride, usingPorts) + tn.log.Info("Port overrides", fields...) } return tn.containerLifecycle.CreateContainer(ctx, tn.TestName, tn.NetworkID, tn.Image, usingPorts, tn.Bind(), nil, tn.HostName(), cmd, chainCfg.Env, []string{}) diff --git a/chain/cosmos/codec.go b/chain/cosmos/codec.go index d7065270d..c5df26f06 100644 --- a/chain/cosmos/codec.go +++ b/chain/cosmos/codec.go @@ -1,8 +1,6 @@ package cosmos import ( - ibcwasm "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos/08-wasm-types" - "cosmossdk.io/x/upgrade" "github.com/cosmos/ibc-go/modules/capability" @@ -29,6 +27,8 @@ import ( paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/staking" + + ibcwasm "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos/08-wasm-types" ) func DefaultEncoding() testutil.TestEncodingConfig { diff --git a/chain/cosmos/cosmos_chain.go b/chain/cosmos/cosmos_chain.go index 0d88ea1b2..1096d4b54 100644 --- a/chain/cosmos/cosmos_chain.go +++ b/chain/cosmos/cosmos_chain.go @@ -16,12 +16,6 @@ import ( dockertypes "github.com/docker/docker/api/types" volumetypes "github.com/docker/docker/api/types/volume" "github.com/docker/docker/client" - "github.com/strangelove-ventures/interchaintest/v8/blockdb" - wasmtypes "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos/08-wasm-types" - "github.com/strangelove-ventures/interchaintest/v8/chain/internal/tendermint" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" "golang.org/x/sync/errgroup" @@ -37,10 +31,16 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/types" - sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" paramsutils "github.com/cosmos/cosmos-sdk/x/params/client/utils" + + "github.com/strangelove-ventures/interchaintest/v8/blockdb" + wasmtypes "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos/08-wasm-types" + "github.com/strangelove-ventures/interchaintest/v8/chain/internal/tendermint" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) // CosmosChain is a local docker testnet for a Cosmos SDK chain. @@ -89,7 +89,7 @@ func NewCosmosHeighlinerChainConfig(name string, Images: []ibc.DockerImage{ { Repository: fmt.Sprintf("ghcr.io/strangelove-ventures/heighliner/%s", name), - UidGid: dockerutil.GetHeighlinerUserString(), + UIDGID: dockerutil.GetHeighlinerUserString(), }, }, Bin: binary, @@ -161,7 +161,6 @@ func (c *CosmosChain) AddFullNodes(ctx context.Context, configFileOverrides map[ var eg errgroup.Group for i := prevCount; i < c.numFullNodes; i++ { - i := i eg.Go(func() error { fn := c.FullNodes[i] if err := fn.InitFullNodeFiles(ctx); err != nil { @@ -387,7 +386,7 @@ func (c *CosmosChain) SendIBCTransfer( dstPort, _ = tendermint.AttributeValue(events, evType, "packet_dst_port") dstChan, _ = tendermint.AttributeValue(events, evType, "packet_dst_channel") timeoutHeight, _ = tendermint.AttributeValue(events, evType, "packet_timeout_height") - timeoutTs, _ = tendermint.AttributeValue(events, evType, "packet_timeout_timestamp") + timeoutTS, _ = tendermint.AttributeValue(events, evType, "packet_timeout_timestamp") dataHex, _ = tendermint.AttributeValue(events, evType, "packet_data_hex") ) tx.Packet.SourcePort = srcPort @@ -408,9 +407,9 @@ func (c *CosmosChain) SendIBCTransfer( } tx.Packet.Sequence = seqNum - timeoutNano, err := strconv.ParseUint(timeoutTs, 10, 64) + timeoutNano, err := strconv.ParseUint(timeoutTS, 10, 64) if err != nil { - return tx, fmt.Errorf("invalid packet timestamp timeout %s: %w", timeoutTs, err) + return tx, fmt.Errorf("invalid packet timestamp timeout %s: %w", timeoutTS, err) } tx.Packet.TimeoutTimestamp = ibc.Nanoseconds(timeoutNano) @@ -429,7 +428,7 @@ func (c *CosmosChain) QueryICAAddress(ctx context.Context, connectionID, address // SendICATx sends an interchain account transaction for a specified address and sends it to the respective // interchain account on the counterparty chain. -func (c *CosmosChain) SendICATx(ctx context.Context, keyName, connectionID string, msgs []sdk.Msg, icaTxMemo string) (string, error) { +func (c *CosmosChain) SendICATx(ctx context.Context, keyName, connectionID string, msgs []types.Msg, icaTxMemo string) (string, error) { node := c.getFullNode() registry := node.Chain.Config().EncodingConfig.InterfaceRegistry encoding := "proto3" @@ -674,7 +673,7 @@ func (c *CosmosChain) NewChainNode( VolumeName: v.Name, ImageRef: image.Ref(), TestName: testName, - UidGid: image.UidGid, + UidGid: image.UIDGID, }); err != nil { return nil, fmt.Errorf("set volume owner: %w", err) } @@ -731,7 +730,7 @@ func (c *CosmosChain) NewSidecarProcess( VolumeName: v.Name, ImageRef: image.Ref(), TestName: testName, - UidGid: image.UidGid, + UidGid: image.UIDGID, }); err != nil { return fmt.Errorf("set volume owner: %w", err) } @@ -759,7 +758,6 @@ func (c *CosmosChain) initializeChainNodes( eg, egCtx := errgroup.WithContext(ctx) for i := len(c.Validators); i < c.NumValidators; i++ { - i := i eg.Go(func() error { val, err := c.NewChainNode(egCtx, testName, cli, networkID, image, true, i) if err != nil { @@ -770,7 +768,6 @@ func (c *CosmosChain) initializeChainNodes( }) } for i := len(c.FullNodes); i < c.numFullNodes; i++ { - i := i eg.Go(func() error { fn, err := c.NewChainNode(egCtx, testName, cli, networkID, image, false, i) if err != nil { @@ -799,9 +796,6 @@ func (c *CosmosChain) initializeSidecars( ) error { eg, egCtx := errgroup.WithContext(ctx) for i, cfg := range c.cfg.SidecarConfigs { - i := i - cfg := cfg - if cfg.ValidatorProcess { continue } @@ -868,8 +862,6 @@ func (c *CosmosChain) Start(testName string, ctx context.Context, additionalGene eg := new(errgroup.Group) // Initialize config and sign gentx for each validator. for i, v := range c.Validators { - v := v - i := i v.Validator = true eg.Go(func() error { if err := v.InitFullNodeFiles(ctx); err != nil { @@ -901,7 +893,6 @@ func (c *CosmosChain) Start(testName string, ctx context.Context, additionalGene // Initialize config for each full node. for _, n := range c.FullNodes { - n := n n.Validator = false eg.Go(func() error { if err := n.InitFullNodeFiles(ctx); err != nil { @@ -1018,8 +1009,6 @@ func (c *CosmosChain) Start(testName string, ctx context.Context, additionalGene // Start any sidecar processes that should be running before the chain starts eg, egCtx := errgroup.WithContext(ctx) for _, s := range c.Sidecars { - s := s - err = s.containerLifecycle.Running(ctx) if s.preStart && err != nil { eg.Go(func() error { @@ -1041,7 +1030,6 @@ func (c *CosmosChain) Start(testName string, ctx context.Context, additionalGene eg, egCtx = errgroup.WithContext(ctx) for _, n := range chainNodes { - n := n eg.Go(func() error { return n.CreateNodeContainer(egCtx) }) @@ -1054,7 +1042,6 @@ func (c *CosmosChain) Start(testName string, ctx context.Context, additionalGene eg, egCtx = errgroup.WithContext(ctx) for _, n := range chainNodes { - n := n c.log.Info("Starting container", zap.String("container", n.Name())) eg.Go(func() error { if err := n.SetPeers(egCtx, peers); err != nil { @@ -1091,7 +1078,6 @@ func (c *CosmosChain) Acknowledgements(ctx context.Context, height int64) ([]ibc } ibcAcks := make([]ibc.PacketAcknowledgement, len(acks)) for i, ack := range acks { - ack := ack ibcAcks[i] = ibc.PacketAcknowledgement{ Acknowledgement: ack.Acknowledgement, Packet: ibc.Packet{ @@ -1124,7 +1110,6 @@ func (c *CosmosChain) Timeouts(ctx context.Context, height int64) ([]ibc.PacketT } ibcTimeouts := make([]ibc.PacketTimeout, len(timeouts)) for i, ack := range timeouts { - ack := ack ibcTimeouts[i] = ibc.PacketTimeout{ Packet: ibc.Packet{ Sequence: ack.Packet.Sequence, @@ -1153,7 +1138,6 @@ func (c *CosmosChain) FindTxs(ctx context.Context, height int64) ([]blockdb.Tx, func (c *CosmosChain) StopAllNodes(ctx context.Context) error { var eg errgroup.Group for _, n := range c.Nodes() { - n := n eg.Go(func() error { if err := n.StopContainer(ctx); err != nil { return err @@ -1168,7 +1152,6 @@ func (c *CosmosChain) StopAllNodes(ctx context.Context) error { func (c *CosmosChain) StopAllSidecars(ctx context.Context) error { var eg errgroup.Group for _, s := range c.Sidecars { - s := s eg.Go(func() error { if err := s.StopContainer(ctx); err != nil { return err @@ -1187,7 +1170,6 @@ func (c *CosmosChain) StartAllNodes(ctx context.Context) error { defer c.findTxMu.Unlock() var eg errgroup.Group for _, n := range c.Nodes() { - n := n eg.Go(func() error { if err := n.CreateNodeContainer(ctx); err != nil { return err @@ -1206,8 +1188,6 @@ func (c *CosmosChain) StartAllSidecars(ctx context.Context) error { defer c.findTxMu.Unlock() var eg errgroup.Group for _, s := range c.Sidecars { - s := s - err := s.containerLifecycle.Running(ctx) if err == nil { continue @@ -1233,8 +1213,6 @@ func (c *CosmosChain) StartAllValSidecars(ctx context.Context) error { for _, v := range c.Validators { for _, s := range v.Sidecars { - s := s - err := s.containerLifecycle.Running(ctx) if err == nil { continue @@ -1256,7 +1234,6 @@ func (c *CosmosChain) VoteOnProposalAllValidators(ctx context.Context, proposalI var eg errgroup.Group for _, n := range c.Nodes() { if n.Validator { - n := n eg.Go(func() error { return n.VoteOnProposal(ctx, valKey, proposalID, vote) }) diff --git a/chain/cosmos/genesis.go b/chain/cosmos/genesis.go index 1068a15a1..4b67003e8 100644 --- a/chain/cosmos/genesis.go +++ b/chain/cosmos/genesis.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/icza/dyno" + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) diff --git a/chain/cosmos/ics.go b/chain/cosmos/ics.go index beb0e9ead..892da244c 100644 --- a/chain/cosmos/ics.go +++ b/chain/cosmos/ics.go @@ -12,10 +12,6 @@ import ( "time" "github.com/icza/dyno" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testreporter" - "github.com/strangelove-ventures/interchaintest/v8/testutil" "github.com/tidwall/gjson" "go.uber.org/zap" "golang.org/x/mod/semver" @@ -29,6 +25,11 @@ import ( "github.com/cosmos/cosmos-sdk/types" govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" stakingttypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testreporter" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) const ( @@ -216,7 +217,6 @@ func (c *CosmosChain) StartConsumer(testName string, ctx context.Context, additi eg := new(errgroup.Group) // Initialize validators and fullnodes. for _, v := range c.Nodes() { - v := v eg.Go(func() error { if err := v.InitFullNodeFiles(ctx); err != nil { return err @@ -249,8 +249,6 @@ func (c *CosmosChain) StartConsumer(testName string, ctx context.Context, additi // Copy provider priv val keys to these nodes for i, val := range c.Provider.Validators { - i := i - val := val eg.Go(func() error { copy := c.cfg.InterchainSecurityConfig.ConsumerCopyProviderKey != nil && c.cfg.InterchainSecurityConfig.ConsumerCopyProviderKey(i) if copy { @@ -330,16 +328,16 @@ func (c *CosmosChain) StartConsumer(testName string, ctx context.Context, additi return fmt.Errorf("failed to unmarshal ccv state json: %w", err) } - var genesisJson interface{} - if err := json.Unmarshal(genbz, &genesisJson); err != nil { + var genesisJSON interface{} + if err := json.Unmarshal(genbz, &genesisJSON); err != nil { return fmt.Errorf("failed to unmarshal genesis json: %w", err) } - if err := dyno.Set(genesisJson, ccvStateUnmarshaled, "app_state", "ccvconsumer"); err != nil { + if err := dyno.Set(genesisJSON, ccvStateUnmarshaled, "app_state", "ccvconsumer"); err != nil { return fmt.Errorf("failed to populate ccvconsumer genesis state: %w", err) } - if genbz, err = json.Marshal(genesisJson); err != nil { + if genbz, err = json.Marshal(genesisJSON); err != nil { return fmt.Errorf("failed to marshal genesis bytes to json: %w", err) } @@ -381,7 +379,6 @@ func (c *CosmosChain) StartConsumer(testName string, ctx context.Context, additi eg, egCtx := errgroup.WithContext(ctx) for _, n := range chainNodes { - n := n eg.Go(func() error { return n.CreateNodeContainer(egCtx) }) @@ -394,7 +391,6 @@ func (c *CosmosChain) StartConsumer(testName string, ctx context.Context, additi eg, egCtx = errgroup.WithContext(ctx) for _, n := range chainNodes { - n := n c.log.Info("Starting container", zap.String("container", n.Name())) eg.Go(func() error { if err := n.SetPeers(egCtx, peers); err != nil { diff --git a/chain/cosmos/module_auth.go b/chain/cosmos/module_auth.go index 30b5d5875..c47aacb32 100644 --- a/chain/cosmos/module_auth.go +++ b/chain/cosmos/module_auth.go @@ -2,7 +2,8 @@ package cosmos import ( "context" - "fmt" + + "go.uber.org/zap" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -112,7 +113,7 @@ func (c *CosmosChain) AuthPrintAccountInfo(chain *CosmosChain, res *cdctypes.Any if err := chain.GetCodec().Unmarshal(res.Value, &modAcc); err != nil { return err } - fmt.Printf("ModuleAccount: %+v\n", modAcc) + c.log.Info("Account info for ModuleAccount", zap.String("account", modAcc.String())) return nil case "/cosmos.vesting.v1beta1.VestingAccount": @@ -120,7 +121,7 @@ func (c *CosmosChain) AuthPrintAccountInfo(chain *CosmosChain, res *cdctypes.Any if err := chain.GetCodec().Unmarshal(res.Value, &vestingAcc); err != nil { return err } - fmt.Printf("BaseVestingAccount: %+v\n", vestingAcc) + c.log.Info("Account info for BaseVestingAccount", zap.String("account", vestingAcc.String())) return nil case "/cosmos.vesting.v1beta1.PeriodicVestingAccount": @@ -128,7 +129,7 @@ func (c *CosmosChain) AuthPrintAccountInfo(chain *CosmosChain, res *cdctypes.Any if err := chain.GetCodec().Unmarshal(res.Value, &vestingAcc); err != nil { return err } - fmt.Printf("PeriodicVestingAccount: %+v\n", vestingAcc) + c.log.Info("Account info for PeriodicVestingAccount", zap.String("account", vestingAcc.String())) return nil case "/cosmos.vesting.v1beta1.ContinuousVestingAccount": @@ -136,7 +137,7 @@ func (c *CosmosChain) AuthPrintAccountInfo(chain *CosmosChain, res *cdctypes.Any if err := chain.GetCodec().Unmarshal(res.Value, &vestingAcc); err != nil { return err } - fmt.Printf("ContinuousVestingAccount: %+v\n", vestingAcc) + c.log.Info("Account info for ContinuousVestingAccount", zap.String("account", vestingAcc.String())) return nil case "/cosmos.vesting.v1beta1.DelayedVestingAccount": @@ -144,7 +145,7 @@ func (c *CosmosChain) AuthPrintAccountInfo(chain *CosmosChain, res *cdctypes.Any if err := chain.GetCodec().Unmarshal(res.Value, &vestingAcc); err != nil { return err } - fmt.Printf("DelayedVestingAccount: %+v\n", vestingAcc) + c.log.Info("Account info for DelayedVestingAccount", zap.String("account", vestingAcc.String())) return nil case "/cosmos.vesting.v1beta1.PermanentLockedAccount": @@ -152,7 +153,7 @@ func (c *CosmosChain) AuthPrintAccountInfo(chain *CosmosChain, res *cdctypes.Any if err := chain.GetCodec().Unmarshal(res.Value, &vestingAcc); err != nil { return err } - fmt.Printf("PermanentLockedAccount: %+v\n", vestingAcc) + c.log.Info("Account info for PermanentLockedAccount", zap.String("account", vestingAcc.String())) return nil default: @@ -160,7 +161,7 @@ func (c *CosmosChain) AuthPrintAccountInfo(chain *CosmosChain, res *cdctypes.Any if err := chain.GetCodec().Unmarshal(res.Value, &baseAcc); err != nil { return err } - fmt.Printf("BaseAccount: %+v\n", baseAcc) + c.log.Info("Account info for BaseAccount", zap.String("account", baseAcc.String())) return nil } } diff --git a/chain/cosmos/module_authz.go b/chain/cosmos/module_authz.go index de7e17f43..93187121f 100644 --- a/chain/cosmos/module_authz.go +++ b/chain/cosmos/module_authz.go @@ -6,10 +6,10 @@ import ( "path" "strings" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/authz" + + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) // AuthzGrant grants a message as a permission to an account. diff --git a/chain/cosmos/module_bank.go b/chain/cosmos/module_bank.go index eb2d3fba9..0dd9f69ef 100644 --- a/chain/cosmos/module_bank.go +++ b/chain/cosmos/module_bank.go @@ -4,12 +4,12 @@ import ( "context" "fmt" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) // BankSend sends tokens from one account to another. diff --git a/chain/cosmos/module_cosmwasm.go b/chain/cosmos/module_cosmwasm.go index 43ae64a0c..1f00eee2c 100644 --- a/chain/cosmos/module_cosmwasm.go +++ b/chain/cosmos/module_cosmwasm.go @@ -10,10 +10,9 @@ import ( "path" "path/filepath" - "github.com/strangelove-ventures/interchaintest/v8/testutil" - "github.com/cosmos/cosmos-sdk/types" - sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) type InstantiateContractAttribute struct { @@ -69,7 +68,7 @@ func (tn *ChainNode) StoreContract(ctx context.Context, keyName string, fileName } res := CodeInfosResponse{} - if err := json.Unmarshal([]byte(stdout), &res); err != nil { + if err := json.Unmarshal(stdout, &res); err != nil { return "", err } @@ -102,7 +101,7 @@ func (tn *ChainNode) InstantiateContract(ctx context.Context, keyName string, co } contactsRes := QueryContractResponse{} - if err := json.Unmarshal([]byte(stdout), &contactsRes); err != nil { + if err := json.Unmarshal(stdout, &contactsRes); err != nil { return "", err } @@ -111,18 +110,18 @@ func (tn *ChainNode) InstantiateContract(ctx context.Context, keyName string, co } // 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, extraExecTxArgs ...string) (res *sdk.TxResponse, err error) { +func (tn *ChainNode) ExecuteContract(ctx context.Context, keyName string, contractAddress string, message string, extraExecTxArgs ...string) (res *types.TxResponse, err error) { cmd := []string{"wasm", "execute", contractAddress, message} cmd = append(cmd, extraExecTxArgs...) txHash, err := tn.ExecTx(ctx, keyName, cmd...) if err != nil { - return &sdk.TxResponse{}, err + return &types.TxResponse{}, err } txResp, err := tn.GetTransaction(tn.CliContext(), txHash) if err != nil { - return &sdk.TxResponse{}, fmt.Errorf("failed to get transaction %s: %w", txHash, err) + return &types.TxResponse{}, fmt.Errorf("failed to get transaction %s: %w", txHash, err) } if txResp.Code != 0 { @@ -158,7 +157,7 @@ func (tn *ChainNode) QueryContract(ctx context.Context, contractAddress string, if err != nil { return err } - err = json.Unmarshal([]byte(stdout), response) + err = json.Unmarshal(stdout, response) return err } @@ -221,7 +220,7 @@ func (tn *ChainNode) DumpContractState(ctx context.Context, contractAddress stri } res := new(DumpContractStateResponse) - if err := json.Unmarshal([]byte(stdout), res); err != nil { + if err := json.Unmarshal(stdout, res); err != nil { return nil, err } return res, nil diff --git a/chain/cosmos/module_gov.go b/chain/cosmos/module_gov.go index 7c38d6e89..b139fac1e 100644 --- a/chain/cosmos/module_gov.go +++ b/chain/cosmos/module_gov.go @@ -9,13 +9,13 @@ import ( "path/filepath" "strconv" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - upgradetypes "cosmossdk.io/x/upgrade/types" govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" paramsutils "github.com/cosmos/cosmos-sdk/x/params/client/utils" + + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" ) // VoteOnProposal submits a vote for the specified proposal. @@ -30,13 +30,13 @@ func (tn *ChainNode) VoteOnProposal(ctx context.Context, keyName string, proposa // SubmitProposal submits a gov v1 proposal to the chain. func (tn *ChainNode) SubmitProposal(ctx context.Context, keyName string, prop TxProposalv1) (string, error) { file := "proposal.json" - propJson, err := json.MarshalIndent(prop, "", " ") + 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 { + if err := fw.WriteFile(ctx, tn.VolumeName, file, propJSON); err != nil { return "", fmt.Errorf("writing contract file to docker volume: %w", err) } diff --git a/chain/cosmos/module_vesting.go b/chain/cosmos/module_vesting.go index b0b62963f..802f5f5b1 100644 --- a/chain/cosmos/module_vesting.go +++ b/chain/cosmos/module_vesting.go @@ -6,9 +6,9 @@ import ( "fmt" "path" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - vestingcli "github.com/cosmos/cosmos-sdk/x/auth/vesting/client/cli" + + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" ) // VestingCreateAccount creates a new vesting account funded with an allocation of tokens. The account can either be a delayed or continuous vesting account, which is determined by the '--delayed' flag. @@ -41,7 +41,7 @@ func (tn *ChainNode) VestingCreatePermanentLockedAccount(ctx context.Context, ke } // VestingCreatePeriodicAccount is a sequence of coins and period length in seconds. -// Periods are sequential, in that the duration of of a period only starts at the end of the previous period. +// Periods are sequential, in that the duration of a period only starts at the end of the previous period. // The duration of the first period starts upon account creation. func (tn *ChainNode) VestingCreatePeriodicAccount(ctx context.Context, keyName string, toAddr string, periods vestingcli.VestingData, flags ...string) error { file := "periods.json" diff --git a/chain/cosmos/node_test.go b/chain/cosmos/node_test.go index 8eebb9f57..787fd0d2b 100644 --- a/chain/cosmos/node_test.go +++ b/chain/cosmos/node_test.go @@ -4,10 +4,11 @@ import ( "strings" "testing" - "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" "github.com/stretchr/testify/require" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" ) func TestCondenseMoniker_MiddleDetail(t *testing.T) { diff --git a/chain/cosmos/poll.go b/chain/cosmos/poll.go index 39b34d965..72ccffeb8 100644 --- a/chain/cosmos/poll.go +++ b/chain/cosmos/poll.go @@ -5,12 +5,12 @@ import ( "errors" "fmt" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testutil" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) // PollForProposalStatus attempts to find a proposal with matching ID and status using gov v1. @@ -57,7 +57,7 @@ func PollForMessage[T any](ctx context.Context, chain *CosmosChain, registry cod fn = func(T) bool { return true } } doPoll := func(ctx context.Context, height int64) (T, error) { - h := int64(height) + h := height block, err := chain.getFullNode().Client.Block(ctx, &h) if err != nil { return zero, err diff --git a/chain/cosmos/query.go b/chain/cosmos/query.go index c33a955dc..2c0888a3c 100644 --- a/chain/cosmos/query.go +++ b/chain/cosmos/query.go @@ -17,7 +17,7 @@ type blockClient interface { // RangeBlockMessages iterates through all a block's transactions and each transaction's messages yielding to f. // Return true from f to stop iteration. func RangeBlockMessages(ctx context.Context, interfaceRegistry codectypes.InterfaceRegistry, client blockClient, height int64, done func(sdk.Msg) bool) error { - h := int64(height) + h := height block, err := client.Block(ctx, &h) if err != nil { return fmt.Errorf("tendermint rpc get block: %w", err) diff --git a/chain/cosmos/sidecar.go b/chain/cosmos/sidecar.go index 7c6978d37..e6b3b7fd5 100644 --- a/chain/cosmos/sidecar.go +++ b/chain/cosmos/sidecar.go @@ -7,9 +7,10 @@ import ( dockerclient "github.com/docker/docker/client" "github.com/docker/go-connections/nat" + "go.uber.org/zap" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/strangelove-ventures/interchaintest/v8/ibc" - "go.uber.org/zap" ) type SidecarProcesses []*SidecarProcess diff --git a/chain/cosmos/wallet.go b/chain/cosmos/wallet.go index da2efade9..5f4bb0598 100644 --- a/chain/cosmos/wallet.go +++ b/chain/cosmos/wallet.go @@ -1,9 +1,9 @@ package cosmos import ( - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/cosmos/cosmos-sdk/types" + + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) var ( diff --git a/chain/cosmos/wasm/wasm.go b/chain/cosmos/wasm/wasm.go index 5d5e01c53..4c818d485 100644 --- a/chain/cosmos/wasm/wasm.go +++ b/chain/cosmos/wasm/wasm.go @@ -2,10 +2,11 @@ package wasm import ( wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" - // simappparams "github.com/cosmos/cosmos-sdk/simapp/params". - "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" "github.com/cosmos/cosmos-sdk/types/module/testutil" + + // simappparams "github.com/cosmos/cosmos-sdk/simapp/params". + "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" ) func WasmEncoding() *testutil.TestEncodingConfig { diff --git a/chain/ethereum/ethererum_chain.go b/chain/ethereum/ethererum_chain.go index 30599baf4..9c93b5081 100644 --- a/chain/ethereum/ethererum_chain.go +++ b/chain/ethereum/ethererum_chain.go @@ -14,12 +14,13 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/ethclient" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" sdkmath "cosmossdk.io/math" + + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) const ( @@ -92,7 +93,7 @@ func (c *EthereumChain) Initialize(ctx context.Context, testName string, cli *do VolumeName: v.Name, ImageRef: image.Ref(), TestName: testName, - UidGid: image.UidGid, + UidGid: image.UIDGID, }); err != nil { return fmt.Errorf("set volume owner: %w", err) } @@ -139,15 +140,23 @@ func (c *EthereumChain) Start(ctx context.Context, cmd []string, mount []mount.M } if c.cfg.HostPortOverride != nil { + var fields []zap.Field + + i := 0 for intP, extP := range c.cfg.HostPortOverride { - usingPorts[nat.Port(fmt.Sprintf("%d/tcp", intP))] = []nat.PortBinding{ + port := nat.Port(fmt.Sprintf("%d/tcp", intP)) + + usingPorts[port] = []nat.PortBinding{ { HostPort: fmt.Sprintf("%d", extP), }, } + + fields = append(fields, zap.String(fmt.Sprintf("port_overrides_%d", i), fmt.Sprintf("%s:%d", port, extP))) + i++ } - fmt.Printf("Port Overrides: %v. Using: %v\n", c.cfg.HostPortOverride, usingPorts) + c.log.Info("Port overrides", fields...) } err := c.containerLifecycle.CreateContainer(ctx, c.testName, c.networkID, c.cfg.Images[0], usingPorts, c.Bind(), mount, c.HostName(), cmd, nil, []string{}) diff --git a/chain/ethereum/foundry/anvil_chain.go b/chain/ethereum/foundry/anvil_chain.go index 0f230e7ec..cc20b014b 100644 --- a/chain/ethereum/foundry/anvil_chain.go +++ b/chain/ethereum/foundry/anvil_chain.go @@ -12,9 +12,10 @@ import ( "github.com/docker/docker/api/types/mount" "github.com/ethereum/go-ethereum/common/hexutil" + "go.uber.org/zap" + "github.com/strangelove-ventures/interchaintest/v8/chain/ethereum" "github.com/strangelove-ventures/interchaintest/v8/ibc" - "go.uber.org/zap" ) var _ ibc.Chain = &AnvilChain{} @@ -52,16 +53,16 @@ func (c *AnvilChain) Start(testName string, ctx context.Context, additionalGenes if err != nil { return err } - localJsonFile := filepath.Join(pwd, loadState) - dockerJsonFile := path.Join(c.HomeDir(), path.Base(loadState)) + localJSONFile := filepath.Join(pwd, loadState) + dockerJSONFile := path.Join(c.HomeDir(), path.Base(loadState)) mounts = []mount.Mount{ { Type: mount.TypeBind, - Source: localJsonFile, - Target: dockerJsonFile, + Source: localJSONFile, + Target: dockerJSONFile, }, } - cmd = append(cmd, "--load-state", dockerJsonFile) + cmd = append(cmd, "--load-state", dockerJSONFile) } return c.EthereumChain.Start(ctx, cmd, mounts) @@ -201,7 +202,7 @@ func (c *AnvilChain) BuildWallet(ctx context.Context, keyName string, mnemonic s } else { // Use the genesis account if keyName == "faucet" { - mnemonic = "test test test test test test test test test test test junk" + mnemonic = "test test test test test test test test test test test junk" //nolint: dupword err := c.RecoverKey(ctx, keyName, mnemonic) if err != nil { return nil, err diff --git a/chain/ethereum/foundry/default_configs.go b/chain/ethereum/foundry/default_configs.go index 498f132ae..4c6ce2e5d 100644 --- a/chain/ethereum/foundry/default_configs.go +++ b/chain/ethereum/foundry/default_configs.go @@ -22,7 +22,7 @@ func DefaultEthereumAnvilChainConfig( { Repository: "ghcr.io/foundry-rs/foundry", Version: "latest", - UidGid: "1000:1000", + UIDGID: "1000:1000", }, }, Bin: "anvil", diff --git a/chain/ethereum/foundry/forge.go b/chain/ethereum/foundry/forge.go index c9a38e7df..0c6a8e743 100644 --- a/chain/ethereum/foundry/forge.go +++ b/chain/ethereum/foundry/forge.go @@ -8,6 +8,7 @@ import ( "path/filepath" "github.com/docker/docker/api/types/mount" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" ) diff --git a/chain/ethereum/geth/default_configs.go b/chain/ethereum/geth/default_configs.go index e114d6f2f..47434556f 100644 --- a/chain/ethereum/geth/default_configs.go +++ b/chain/ethereum/geth/default_configs.go @@ -22,7 +22,7 @@ func DefaultEthereumGethChainConfig( { Repository: "ethereum/client-go", Version: "v1.14.7", - UidGid: "1025:1025", + UIDGID: "1025:1025", }, }, Bin: "geth", @@ -59,7 +59,7 @@ func DefaultBscChainConfig( Repository: "ghcr.io/bnb-chain/bsc", Version: "1.2.13", // same version as other sim tests // Version: "1.4.13", // this version does not work in dev mode (1.3.x+) - UidGid: "1000:1000", + UIDGID: "1000:1000", }, }, Bin: "geth", diff --git a/chain/ethereum/geth/geth_chain.go b/chain/ethereum/geth/geth_chain.go index 1307ca044..f3fdc1e12 100644 --- a/chain/ethereum/geth/geth_chain.go +++ b/chain/ethereum/geth/geth_chain.go @@ -10,12 +10,13 @@ import ( "github.com/docker/docker/api/types/mount" "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/strangelove-ventures/interchaintest/v8/chain/ethereum" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" "github.com/cosmos/cosmos-sdk/crypto/hd" + + "github.com/strangelove-ventures/interchaintest/v8/chain/ethereum" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) var _ ibc.Chain = &GethChain{} diff --git a/chain/ethereum/wallet.go b/chain/ethereum/wallet.go index 0993065b8..e315a3629 100644 --- a/chain/ethereum/wallet.go +++ b/chain/ethereum/wallet.go @@ -2,6 +2,7 @@ package ethereum import ( "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) diff --git a/chain/internal/tendermint/tendermint_node.go b/chain/internal/tendermint/tendermint_node.go index 6b0aeb2de..64043ecf6 100644 --- a/chain/internal/tendermint/tendermint_node.go +++ b/chain/internal/tendermint/tendermint_node.go @@ -13,9 +13,6 @@ import ( dockerclient "github.com/docker/docker/client" "github.com/docker/go-connections/nat" "github.com/hashicorp/go-version" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" tmjson "github.com/cometbft/cometbft/libs/json" @@ -23,6 +20,10 @@ import ( rpcclient "github.com/cometbft/cometbft/rpc/client" rpchttp "github.com/cometbft/cometbft/rpc/client/http" libclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" + + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) // TendermintNode represents a node in the test network that is being created. @@ -76,7 +77,7 @@ func NewTendermintNode( VolumeName: tn.VolumeName, ImageRef: tn.Image.Ref(), TestName: tn.TestName, - UidGid: tn.Image.UidGid, + UidGid: tn.Image.UIDGID, }); err != nil { return nil, fmt.Errorf("set tendermint volume owner: %w", err) } @@ -348,15 +349,18 @@ func (tn TendermintNodes) PeerString(ctx context.Context, node *TendermintNode) // don't peer with ourself continue } + id, err := n.NodeID(ctx) if err != nil { // TODO: would this be better to panic? // When would NodeId return an error? break } + hostName := n.HostName() ps := fmt.Sprintf("%s@%s:26656", id, hostName) - fmt.Printf("{%s} peering (%s)\n", hostName, ps) + n.Log.Info("Peering", zap.String("hostname", hostName), zap.String("peer_string", ps)) + addrs[i] = ps } return strings.Join(addrs, ",") diff --git a/chain/penumbra/penumbra_app_node.go b/chain/penumbra/penumbra_app_node.go index 9a6e033c7..f7d1f65bf 100644 --- a/chain/penumbra/penumbra_app_node.go +++ b/chain/penumbra/penumbra_app_node.go @@ -11,11 +11,11 @@ import ( "github.com/BurntSushi/toml" volumetypes "github.com/docker/docker/api/types/volume" "github.com/docker/docker/client" - dockerclient "github.com/docker/docker/client" "github.com/docker/go-connections/nat" + "go.uber.org/zap" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/strangelove-ventures/interchaintest/v8/ibc" - "go.uber.org/zap" ) // PenumbraAppNode represents an instance of pcli. @@ -49,7 +49,7 @@ func NewPenumbraAppNode( chain *PenumbraChain, index int, testName string, - dockerClient *dockerclient.Client, + dockerClient *client.Client, networkID string, image ibc.DockerImage, ) (*PenumbraAppNode, error) { @@ -79,7 +79,7 @@ func NewPenumbraAppNode( VolumeName: pn.VolumeName, ImageRef: pn.Image.Ref(), TestName: pn.TestName, - UidGid: image.UidGid, + UidGid: image.UIDGID, }); err != nil { return nil, fmt.Errorf("set penumbra volume owner: %w", err) } @@ -124,8 +124,8 @@ func (p *PenumbraAppNode) HomeDir() string { // CreateKey attempts to initialize a new pcli config file with a newly generated FullViewingKey and CustodyKey. func (p *PenumbraAppNode) CreateKey(ctx context.Context, keyName string) error { keyPath := filepath.Join(p.HomeDir(), "keys", keyName) - pdUrl := fmt.Sprintf("http://%s:8080", p.HostName()) - cmd := []string{"pcli", "--home", keyPath, "init", "--grpc-url", pdUrl, "soft-kms", "generate"} + pdURL := fmt.Sprintf("http://%s:8080", p.HostName()) + cmd := []string{"pcli", "--home", keyPath, "init", "--grpc-url", pdURL, "soft-kms", "generate"} _, stderr, err := p.Exec(ctx, cmd, nil) @@ -248,13 +248,13 @@ func (p *PenumbraAppNode) GenerateGenesisFile( validators []PenumbraValidatorDefinition, allocations []PenumbraGenesisAppStateAllocation, ) error { - validatorsJson, err := json.Marshal(validators) + validatorsJSON, err := json.Marshal(validators) if err != nil { return fmt.Errorf("error marshalling validators to json: %w", err) } fw := dockerutil.NewFileWriter(p.log, p.DockerClient, p.TestName) - if err := fw.WriteFile(ctx, p.VolumeName, "validators.json", validatorsJson); err != nil { + if err := fw.WriteFile(ctx, p.VolumeName, "validators.json", validatorsJSON); err != nil { return fmt.Errorf("error writing validators to file: %w", err) } @@ -313,7 +313,8 @@ func (p *PenumbraAppNode) GetBalance(ctx context.Context, keyName string) (int64 return 0, err } - fmt.Printf("STDOUT BAL: '%s'\n", string(stdout)) + p.log.Info("Balance query result", zap.String("key_name", keyName), zap.String("output", string(stdout))) + return 0, nil } @@ -386,7 +387,7 @@ func (p *PenumbraAppNode) Exec(ctx context.Context, cmd []string, env []string) opts := dockerutil.ContainerOptions{ Binds: p.Bind(), Env: env, - User: p.Image.UidGid, + User: p.Image.UIDGID, } res := job.Run(ctx, cmd, opts) diff --git a/chain/penumbra/penumbra_chain.go b/chain/penumbra/penumbra_chain.go index 3f59f46c2..65acdcc05 100644 --- a/chain/penumbra/penumbra_chain.go +++ b/chain/penumbra/penumbra_chain.go @@ -13,10 +13,6 @@ import ( "github.com/BurntSushi/toml" "github.com/docker/docker/api/types" "github.com/docker/docker/client" - "github.com/strangelove-ventures/interchaintest/v8/chain/internal/tendermint" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" "golang.org/x/sync/errgroup" @@ -27,6 +23,11 @@ import ( cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" + + "github.com/strangelove-ventures/interchaintest/v8/chain/internal/tendermint" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) type PenumbraChain struct { @@ -369,9 +370,6 @@ func (c *PenumbraChain) Start(_ string, ctx context.Context, additionalGenesisWa eg, egCtx := errgroup.WithContext(ctx) for i, v := range validators { - v := v - i := i - keyName := fmt.Sprintf("%s-%d", valKey, i) eg.Go(func() error { if err := v.TendermintNode.InitValidatorFiles(egCtx); err != nil { @@ -461,7 +459,6 @@ func (c *PenumbraChain) Start(_ string, ctx context.Context, additionalGenesisWa } for _, n := range fullnodes { - n := n eg.Go(func() error { return n.TendermintNode.InitFullNodeFiles(egCtx) }) } @@ -477,8 +474,6 @@ func (c *PenumbraChain) Start(_ string, ctx context.Context, additionalGenesisWa // penumbra generate-testnet right now overwrites new validator keys eg, egCtx = errgroup.WithContext(ctx) for i, val := range c.PenumbraNodes[:c.numValidators] { - i := i - val := val // Use an errgroup to save some time doing many concurrent copies inside containers. eg.Go(func() error { firstValPrivKeyRelPath := fmt.Sprintf(".penumbra/testnet_data/node%d/cometbft/config/priv_validator_key.json", i) @@ -529,8 +524,6 @@ func (c *PenumbraChain) start(ctx context.Context) error { eg, egCtx := errgroup.WithContext(ctx) for _, n := range c.PenumbraNodes { - n := n - sep, err := n.TendermintNode.GetConfigSeparator() if err != nil { return err @@ -555,8 +548,6 @@ func (c *PenumbraChain) start(ctx context.Context) error { eg, egCtx = errgroup.WithContext(ctx) for _, n := range c.PenumbraNodes { - n := n - c.log.Info("Starting tendermint container", zap.String("container", n.TendermintNode.Name())) eg.Go(func() error { peers := tmNodes.PeerString(egCtx, n.TendermintNode) @@ -581,9 +572,6 @@ func (c *PenumbraChain) start(ctx context.Context) error { eg, egCtx = errgroup.WithContext(ctx) for i, val := range c.PenumbraNodes[:c.numValidators] { - val := val - i := i - keyName := fmt.Sprintf("%s-%d", valKey, i) eg.Go(func() error { diff --git a/chain/penumbra/penumbra_client_node.go b/chain/penumbra/penumbra_client_node.go index 70e618993..726b38f05 100644 --- a/chain/penumbra/penumbra_client_node.go +++ b/chain/penumbra/penumbra_client_node.go @@ -14,6 +14,16 @@ import ( volumetypes "github.com/docker/docker/api/types/volume" "github.com/docker/docker/client" "github.com/docker/go-connections/nat" + "go.uber.org/zap" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + + sdkmath "cosmossdk.io/math" + + transfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" + //nolint:staticcheck + clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" + asset "github.com/strangelove-ventures/interchaintest/v8/chain/penumbra/core/asset/v1" ibcv1 "github.com/strangelove-ventures/interchaintest/v8/chain/penumbra/core/component/ibc/v1" pool "github.com/strangelove-ventures/interchaintest/v8/chain/penumbra/core/component/shielded_pool/v1" @@ -25,15 +35,6 @@ import ( "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/testutil" - "go.uber.org/zap" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" - - "cosmossdk.io/math" - - transfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" - //nolint:staticcheck - clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" ) // PenumbraClientNode represents an instance of pclientd. @@ -109,7 +110,7 @@ func NewClientNode( VolumeName: p.VolumeName, ImageRef: image.Ref(), TestName: testName, - UidGid: image.UidGid, + UidGid: image.UIDGID, }); err != nil { return nil, fmt.Errorf("set pclientd volume owner: %w", err) } @@ -299,9 +300,15 @@ func (p *PenumbraClientNode) SendIBCTransfer( } if os.Getenv("ICTEST_DEBUG") != "" { - fmt.Printf("Timeout timestamp: %+v \n", timeoutTimestamp) - fmt.Printf("Timeout: %+v \n", timeoutHeight) - fmt.Printf("Withdrawal: %+v \n", withdrawal) + p.log.Info("Ics20 withdrawal info", + zap.String("denom", withdrawal.Denom.Denom), + zap.String("amount", amount.Amount.String()), + zap.String("destination_chain_address", withdrawal.DestinationChainAddress), + zap.String("return_address", withdrawal.ReturnAddress.String()), + zap.String("channel_id", channelID), + zap.String("timeout_height", withdrawal.TimeoutHeight.String()), + zap.Uint64("timeout_timestamp", timeoutTimestamp), + ) } // Generate a transaction plan sending ics_20 transfer @@ -399,6 +406,10 @@ func (p *PenumbraClientNode) SendIBCTransfer( } } + if confirmed == nil { + return ibc.Tx{}, fmt.Errorf("confirmed transaction is nil") + } + // TODO: fill in rest of tx details return ibc.Tx{ Height: int64(confirmed.DetectionHeight), @@ -422,11 +433,11 @@ func (p *PenumbraClientNode) SendIBCTransfer( // It creates a client for the ViewProtocolService and constructs a BalancesRequest with an AccountFilter and AssetIdFilter. // A Balances stream response is obtained from the server. // The balances are collected in a slice until the stream is done, or an error occurs. -// Otherwise, the first balance in the slice is used to construct a math.Int value and returned. +// Otherwise, the first balance in the slice is used to construct a sdkmath.Int value and returned. // Returns: -// - math.Int: The balance of the specified denom. +// - sdkmath.Int: The balance of the specified denom. // - error: An error if any occurred during the balance retrieval. -func (p *PenumbraClientNode) GetBalance(ctx context.Context, denom string) (math.Int, error) { +func (p *PenumbraClientNode) GetBalance(ctx context.Context, denom string) (sdkmath.Int, error) { viewClient := view.NewViewServiceClient(p.GRPCConn) balanceRequest := &view.BalancesRequest{ @@ -442,7 +453,7 @@ func (p *PenumbraClientNode) GetBalance(ctx context.Context, denom string) (math // zero-or-more balances, including denom and amount info per balance. balanceStream, err := viewClient.Balances(ctx, balanceRequest) if err != nil { - return math.Int{}, err + return sdkmath.Int{}, err } var balances []*view.BalancesResponse @@ -453,14 +464,14 @@ func (p *PenumbraClientNode) GetBalance(ctx context.Context, denom string) (math if err == io.EOF { break } else { - return math.Int{}, err + return sdkmath.Int{}, err } } balances = append(balances, balance) } - if len(balances) <= 0 { - return math.ZeroInt(), nil + if len(balances) == 0 { + return sdkmath.ZeroInt(), nil } balance := balances[0] @@ -474,7 +485,7 @@ func (p *PenumbraClientNode) GetBalance(ctx context.Context, denom string) (math // // Since Go does not support native uint128 we make use of the big.Int type. // see: https://github.com/penumbra-zone/penumbra/blob/4d175986f385e00638328c64d729091d45eb042a/crates/core/crypto/src/asset/amount.rs#L220-L240 -func translateHiAndLo(hi, lo uint64) math.Int { +func translateHiAndLo(hi, lo uint64) sdkmath.Int { hiBig := big.NewInt(0).SetUint64(hi) loBig := big.NewInt(0).SetUint64(lo) @@ -483,11 +494,11 @@ func translateHiAndLo(hi, lo uint64) math.Int { // Add the lower order bytes i := big.NewInt(0).Add(hiBig, loBig) - return math.NewIntFromBigInt(i) + return sdkmath.NewIntFromBigInt(i) } // translateBigInt converts a Cosmos SDK Int, which is a wrapper around Go's big.Int, into two uint64 values. -func translateBigInt(i math.Int) (uint64, uint64) { +func translateBigInt(i sdkmath.Int) (uint64, uint64) { bz := i.BigInt().Bytes() // Pad the byte slice with leading zeros to ensure it's 16 bytes long @@ -512,10 +523,10 @@ func translateBigInt(i math.Int) (uint64, uint64) { } // GetDenomMetadata invokes a gRPC request to obtain the DenomMetadata for a specified asset ID. -func (p *PenumbraClientNode) GetDenomMetadata(ctx context.Context, assetId *asset.AssetId) (*asset.Metadata, error) { +func (p *PenumbraClientNode) GetDenomMetadata(ctx context.Context, assetID *asset.AssetId) (*asset.Metadata, error) { queryClient := pool.NewQueryServiceClient(p.GRPCConn) req := &pool.AssetMetadataByIdRequest{ - AssetId: assetId, + AssetId: assetID, } resp, err := queryClient.AssetMetadataById(ctx, req) @@ -596,7 +607,7 @@ func (p *PenumbraClientNode) Exec(ctx context.Context, cmd []string, env []strin opts := dockerutil.ContainerOptions{ Binds: p.Bind(), Env: env, - User: p.Image.UidGid, + User: p.Image.UIDGID, } res := job.Run(ctx, cmd, opts) diff --git a/chain/penumbra/penumbra_client_node_test.go b/chain/penumbra/penumbra_client_node_test.go index f9d899dfc..c45bfef5e 100644 --- a/chain/penumbra/penumbra_client_node_test.go +++ b/chain/penumbra/penumbra_client_node_test.go @@ -4,10 +4,11 @@ import ( "math/big" "testing" - "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/stretchr/testify/require" "cosmossdk.io/math" + + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) // TestBigIntDecoding tests the decoding of big integers. diff --git a/chain/penumbra/penumbra_node.go b/chain/penumbra/penumbra_node.go index 1fdebf5be..50052b79c 100644 --- a/chain/penumbra/penumbra_node.go +++ b/chain/penumbra/penumbra_node.go @@ -6,9 +6,10 @@ import ( "sync" dockerclient "github.com/docker/docker/client" + "go.uber.org/zap" + "github.com/strangelove-ventures/interchaintest/v8/chain/internal/tendermint" "github.com/strangelove-ventures/interchaintest/v8/ibc" - "go.uber.org/zap" ) // PenumbraNode reporesents a node in the Penumbra network which consists of one instance of Tendermint, diff --git a/chain/polkadot/keys.go b/chain/polkadot/keys.go index 57fbed896..12146cfee 100644 --- a/chain/polkadot/keys.go +++ b/chain/polkadot/keys.go @@ -23,7 +23,7 @@ func DeriveEd25519FromName(name string) (*p2pCrypto.Ed25519PrivateKey, error) { chainCode := make([]byte, 32) derivePath := []byte{byte(len(name) << 2)} derivePath = append(derivePath, []byte(namecase.New().NameCase(name))...) - _ = copy(chainCode, []byte(derivePath)) + _ = copy(chainCode, derivePath) hasher, err := blake2b.New256(nil) if err != nil { @@ -68,7 +68,7 @@ func DeriveSr25519FromName(path []string) (*schnorrkel.MiniSecretKey, error) { var chainCode [32]byte derivePath := []byte{byte(len(pathItem) << 2)} derivePath = append(derivePath, []byte(pathItem)...) - _ = copy(chainCode[:], []byte(derivePath)) + _ = copy(chainCode[:], derivePath) miniSecret, _, err = miniSecret.HardDeriveMiniSecretKey([]byte{}, chainCode) if err != nil { return nil, fmt.Errorf("error hard deriving mini secret key") @@ -82,7 +82,7 @@ func DeriveSecp256k1FromName(name string) (*secp256k1.PrivateKey, error) { chainCode := make([]byte, 32) derivePath := []byte{byte(len(name) << 2)} derivePath = append(derivePath, []byte(namecase.New().NameCase(name))...) - _ = copy(chainCode, []byte(derivePath)) + _ = copy(chainCode, derivePath) hasher, err := blake2b.New256(nil) if err != nil { diff --git a/chain/polkadot/keys_test.go b/chain/polkadot/keys_test.go index 1bcd86f71..affefb0d4 100644 --- a/chain/polkadot/keys_test.go +++ b/chain/polkadot/keys_test.go @@ -8,8 +8,9 @@ import ( p2pCrypto "github.com/libp2p/go-libp2p/core/crypto" "github.com/libp2p/go-libp2p/core/peer" "github.com/misko9/go-substrate-rpc-client/v4/signature" - "github.com/strangelove-ventures/interchaintest/v8/chain/polkadot" "github.com/stretchr/testify/require" + + "github.com/strangelove-ventures/interchaintest/v8/chain/polkadot" ) func TestNodeKeyPeerID(t *testing.T) { @@ -22,8 +23,8 @@ func TestNodeKeyPeerID(t *testing.T) { id, err := peer.IDFromPrivateKey(privKey) require.NoError(t, err, "error getting peer id from private key") - peerId := id.String() - require.Equal(t, "12D3KooWCqDbuUHRNWPAuHpVnzZGCkkMwgEx7Xd6xgszqtVpH56c", peerId) + peerID := id.String() + require.Equal(t, "12D3KooWCqDbuUHRNWPAuHpVnzZGCkkMwgEx7Xd6xgszqtVpH56c", peerID) } func Test_DeriveEd25519FromName(t *testing.T) { diff --git a/chain/polkadot/parachain_node.go b/chain/polkadot/parachain_node.go index c5b809d47..d682b8876 100644 --- a/chain/polkadot/parachain_node.go +++ b/chain/polkadot/parachain_node.go @@ -14,13 +14,14 @@ import ( p2pcrypto "github.com/libp2p/go-libp2p/core/crypto" "github.com/libp2p/go-libp2p/core/peer" gsrpc "github.com/misko9/go-substrate-rpc-client/v4" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/ibc" "go.uber.org/zap" "cosmossdk.io/math" sdktypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) // Increase parachain wallet amount due to their additional precision. @@ -47,7 +48,7 @@ type ParachainNode struct { api *gsrpc.SubstrateAPI hostWsPort string - hostRpcPort string + hostRPCPort string } type ParachainNodes []*ParachainNode @@ -108,11 +109,11 @@ func (pn *ParachainNode) PeerID() (string, error) { // MultiAddress returns the p2p multiaddr of the node. func (pn *ParachainNode) MultiAddress() (string, error) { - peerId, err := pn.PeerID() + peerID, err := pn.PeerID() if err != nil { return "", err } - return fmt.Sprintf("/dns4/%s/tcp/%s/p2p/%s", pn.HostName(), strings.Split(nodePort, "/")[0], peerId), nil + return fmt.Sprintf("/dns4/%s/tcp/%s/p2p/%s", pn.HostName(), strings.Split(nodePort, "/")[0], peerID), nil } type GetParachainIDResponse struct { @@ -180,7 +181,7 @@ func (pn *ParachainNode) ParachainID(ctx context.Context) (int, error) { return -1, res.Err } out := GetParachainIDResponse{} - if err := json.Unmarshal([]byte(res.Stdout), &out); err != nil { + if err := json.Unmarshal(res.Stdout, &out); err != nil { return -1, err } return out.ParachainID, nil @@ -278,11 +279,11 @@ func (pn *ParachainNode) StartContainer(ctx context.Context) error { } // Set the host ports once since they will not change after the container has started. - pn.hostWsPort, pn.hostRpcPort = hostPorts[0], hostPorts[1] + pn.hostWsPort, pn.hostRPCPort = hostPorts[0], hostPorts[1] - explorerUrl := fmt.Sprintf("\033[4;34mhttps://polkadot.js.org/apps?rpc=ws://%s#/explorer\033[0m", + explorerURL := fmt.Sprintf("\033[4;34mhttps://polkadot.js.org/apps?rpc=ws://%s#/explorer\033[0m", strings.Replace(pn.hostWsPort, "localhost", "127.0.0.1", 1)) - pn.log.Info(explorerUrl, zap.String("container", pn.Name())) + pn.log.Info(explorerURL, zap.String("container", pn.Name())) var api *gsrpc.SubstrateAPI if err = retry.Do(func() error { var err error @@ -302,7 +303,7 @@ func (pn *ParachainNode) Exec(ctx context.Context, cmd []string, env []string) d opts := dockerutil.ContainerOptions{ Binds: pn.Bind(), Env: env, - User: pn.Image.UidGid, + User: pn.Image.UIDGID, } return job.Run(ctx, cmd, opts) } diff --git a/chain/polkadot/polkadot_chain.go b/chain/polkadot/polkadot_chain.go index ce88f0535..2cec86ad8 100644 --- a/chain/polkadot/polkadot_chain.go +++ b/chain/polkadot/polkadot_chain.go @@ -3,7 +3,6 @@ package polkadot import ( "context" "crypto/rand" - crand "crypto/rand" "encoding/json" "fmt" "io" @@ -14,14 +13,10 @@ import ( "github.com/docker/docker/api/types" volumetypes "github.com/docker/docker/api/types/volume" "github.com/docker/docker/client" - dockerclient "github.com/docker/docker/client" "github.com/icza/dyno" p2pcrypto "github.com/libp2p/go-libp2p/core/crypto" "github.com/misko9/go-substrate-rpc-client/v4/signature" gstypes "github.com/misko9/go-substrate-rpc-client/v4/types" - "github.com/strangelove-ventures/interchaintest/v8/blockdb" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/ibc" "go.uber.org/zap" "golang.org/x/sync/errgroup" @@ -30,6 +25,10 @@ import ( "github.com/cosmos/go-bip39" sdktypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/strangelove-ventures/interchaintest/v8/blockdb" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) // Increase polkadot wallet amount due to their additional precision. @@ -79,7 +78,7 @@ type ParachainConfig struct { // IndexedName is a slice of the substrate dev key names used for key derivation. var ( IndexedName = []string{"alice", "bob", "charlie", "dave", "ferdie"} - IndexedUri = []string{"//Alice", "//Bob", "//Charlie", "//Dave", "//Ferdie"} + IndexedURI = []string{"//Alice", "//Bob", "//Charlie", "//Dave", "//Ferdie"} ) // NewPolkadotChain returns an uninitialized PolkadotChain, which implements the ibc.Chain interface. @@ -104,7 +103,7 @@ func (c *PolkadotChain) NewRelayChainNode( ctx context.Context, i int, chain *PolkadotChain, - dockerClient *dockerclient.Client, + dockerClient *client.Client, networkID string, testName string, image ibc.DockerImage, @@ -114,7 +113,7 @@ func (c *PolkadotChain) NewRelayChainNode( return nil, err } - nodeKey, _, err := p2pcrypto.GenerateEd25519Key(crand.Reader) + nodeKey, _, err := p2pcrypto.GenerateEd25519Key(rand.Reader) if err != nil { return nil, fmt.Errorf("error generating node key: %w", err) } @@ -127,15 +126,15 @@ func (c *PolkadotChain) NewRelayChainNode( } accountKeyName := IndexedName[i] - accountKeyUri := IndexedUri[i] + accountKeyURI := IndexedURI[i] stashKeyName := accountKeyName + "stash" - stashKeyUri := accountKeyUri + "//stash" + stashKeyURI := accountKeyURI + "//stash" - if err := c.RecoverKey(ctx, accountKeyName, accountKeyUri); err != nil { + if err := c.RecoverKey(ctx, accountKeyName, accountKeyURI); err != nil { return nil, err } - if err := c.RecoverKey(ctx, stashKeyName, stashKeyUri); err != nil { + if err := c.RecoverKey(ctx, stashKeyName, stashKeyURI); err != nil { return nil, err } @@ -179,7 +178,7 @@ func (c *PolkadotChain) NewRelayChainNode( VolumeName: v.Name, ImageRef: image.Ref(), TestName: testName, - UidGid: image.UidGid, + UidGid: image.UIDGID, }); err != nil { return nil, fmt.Errorf("set volume owner: %w", err) } @@ -190,12 +189,12 @@ func (c *PolkadotChain) NewRelayChainNode( func (c *PolkadotChain) NewParachainNode( ctx context.Context, i int, - dockerClient *dockerclient.Client, + dockerClient *client.Client, networkID string, testName string, parachainConfig ParachainConfig, ) (*ParachainNode, error) { - nodeKey, _, err := p2pcrypto.GenerateEd25519Key(crand.Reader) + nodeKey, _, err := p2pcrypto.GenerateEd25519Key(rand.Reader) if err != nil { return nil, fmt.Errorf("error generating node key: %w", err) } @@ -234,7 +233,7 @@ func (c *PolkadotChain) NewParachainNode( VolumeName: v.Name, ImageRef: parachainConfig.Image.Ref(), TestName: testName, - UidGid: parachainConfig.Image.UidGid, + UidGid: parachainConfig.Image.UIDGID, }); err != nil { return nil, fmt.Errorf("set volume owner: %w", err) } @@ -431,7 +430,6 @@ func (c *PolkadotChain) Start(testName string, ctx context.Context, additionalGe return fmt.Errorf("error generating parachain genesis file: %w", err) } for _, n := range parachainNodes { - n := n eg.Go(func() error { c.logger().Info("Copying parachain chain spec", zap.String("container", n.Name())) fw := dockerutil.NewFileWriter(n.logger(), n.DockerClient, n.TestName) @@ -486,8 +484,6 @@ func (c *PolkadotChain) Start(testName string, ctx context.Context, additionalGe } for i, n := range c.RelayChainNodes { - n := n - i := i eg.Go(func() error { if i != 0 { c.logger().Info("Copying raw chain spec", zap.String("container", n.Name())) @@ -507,9 +503,7 @@ func (c *PolkadotChain) Start(testName string, ctx context.Context, additionalGe return err } for _, nodes := range c.ParachainNodes { - nodes := nodes for _, n := range nodes { - n := n eg.Go(func() error { c.logger().Info("Copying raw chain spec", zap.String("container", n.Name())) if err := fw.WriteFile(ctx, n.VolumeName, n.RawRelayChainSpecFilePathRelative(), rawChainSpecBytes); err != nil { @@ -547,15 +541,13 @@ func (c *PolkadotChain) GetRPCAddress() string { if len(c.ParachainNodes) > 0 && len(c.ParachainNodes[0]) > 0 { parachainHostName = c.ParachainNodes[0][0].HostName() - // return fmt.Sprintf("%s:%s", c.ParachainNodes[0][0].HostName(), strings.Split(rpcPort, "/")[0]) } else { parachainHostName = c.RelayChainNodes[0].HostName() } relaychainHostName := c.RelayChainNodes[0].HostName() - parachainUrl := fmt.Sprintf("http://%s:%s", parachainHostName, port) - relaychainUrl := fmt.Sprintf("http://%s:%s", relaychainHostName, port) - return fmt.Sprintf("%s,%s", parachainUrl, relaychainUrl) - // return fmt.Sprintf("%s:%s", c.RelayChainNodes[0].HostName(), strings.Split(rpcPort, "/")[0]) + parachainURL := fmt.Sprintf("http://%s:%s", parachainHostName, port) + relaychainURL := fmt.Sprintf("http://%s:%s", relaychainHostName, port) + return fmt.Sprintf("%s,%s", parachainURL, relaychainURL) } // GetGRPCAddress retrieves the grpc address that can be reached by other containers in the docker network. @@ -577,9 +569,9 @@ func (c *PolkadotChain) GetHostPeerAddress() string { // Implements Chain interface. func (c *PolkadotChain) GetHostRPCAddress() string { if len(c.ParachainNodes) > 0 && len(c.ParachainNodes[0]) > 0 { - return c.ParachainNodes[0][0].hostRpcPort + return c.ParachainNodes[0][0].hostRPCPort } - return c.RelayChainNodes[0].hostRpcPort + return c.RelayChainNodes[0].hostRPCPort } // GetHostGRPCAddress returns the grpc address that can be reached by processes on the host machine. @@ -641,7 +633,7 @@ func NewMnemonic() (string, error) { func (c *PolkadotChain) CreateKey(ctx context.Context, keyName string) error { _, err := c.keyring.Get(keyName) if err == nil { - return fmt.Errorf("Key already exists: %s", keyName) + return fmt.Errorf("key already exists: %s", keyName) } mnemonic, err := NewMnemonic() @@ -671,7 +663,7 @@ func (c *PolkadotChain) CreateKey(ctx context.Context, keyName string) error { func (c *PolkadotChain) RecoverKey(ctx context.Context, keyName, mnemonic string) error { _, err := c.keyring.Get(keyName) if err == nil { - return fmt.Errorf("Key already exists: %s", keyName) + return fmt.Errorf("key already exists: %s", keyName) } kp, err := signature.KeyringPairFromSecret(mnemonic, Ss58Format) diff --git a/chain/polkadot/polkadot_chain_test.go b/chain/polkadot/polkadot_chain_test.go index 3e3e3133c..a07c10957 100644 --- a/chain/polkadot/polkadot_chain_test.go +++ b/chain/polkadot/polkadot_chain_test.go @@ -2,13 +2,13 @@ package polkadot_test import ( "context" - "fmt" "testing" - interchaintest "github.com/strangelove-ventures/interchaintest/v8" - "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/stretchr/testify/require" "go.uber.org/zap/zaptest" + + "github.com/strangelove-ventures/interchaintest/v8" + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) func TestWalletMethods(t *testing.T) { @@ -26,12 +26,12 @@ func TestWalletMethods(t *testing.T) { { Repository: "seunlanlege/centauri-polkadot", Version: "v0.9.27", - UidGid: "1025:1025", + UIDGID: "1025:1025", }, { Repository: "seunlanlege/centauri-parachain", Version: "v0.9.27", - UidGid: "1025:1025", + UIDGID: "1025:1025", }, }, Bin: "polkadot", @@ -59,10 +59,6 @@ func TestWalletMethods(t *testing.T) { address, err := chain.GetAddress(ctx, relayKeyName) require.NoError(t, err, "Error getting relay address") - fmt.Println("Relay wallet mnemonic: ", relayWallet.Mnemonic()) - fmt.Println("Relay wallet keyname: ", relayWallet.KeyName()) - fmt.Println("Relay wallet address: ", relayWallet.FormattedAddress()) - fmt.Println("Address: ", address) require.Equal(t, relayWallet.FormattedAddress(), string(address), "Relay addresses not equal") // BuildWallet test @@ -72,10 +68,6 @@ func TestWalletMethods(t *testing.T) { address, err = chain.GetAddress(ctx, userKeyName) require.NoError(t, err, "Error getting user address") - fmt.Println("Wallet mnemonic: ", userWallet.Mnemonic()) - fmt.Println("Wallet keyname: ", userWallet.KeyName()) - fmt.Println("Wallet address: ", userWallet.FormattedAddress()) - fmt.Println("Address: ", address) require.Equal(t, userWallet.FormattedAddress(), string(address), "User addresses not equal") // RecoverKey test diff --git a/chain/polkadot/relay_chain_node.go b/chain/polkadot/relay_chain_node.go index 5450347f5..8acab22f0 100644 --- a/chain/polkadot/relay_chain_node.go +++ b/chain/polkadot/relay_chain_node.go @@ -15,11 +15,12 @@ import ( p2pCrypto "github.com/libp2p/go-libp2p/core/crypto" "github.com/libp2p/go-libp2p/core/peer" gsrpc "github.com/misko9/go-substrate-rpc-client/v4" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/ibc" "go.uber.org/zap" "cosmossdk.io/math" + + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) // RelayChainNode defines the properties required for running a polkadot relay chain node. @@ -43,7 +44,7 @@ type RelayChainNode struct { api *gsrpc.SubstrateAPI hostWsPort string - hostRpcPort string + hostRPCPort string } type RelayChainNodes []*RelayChainNode @@ -123,17 +124,17 @@ func (p *RelayChainNode) EcdsaAddress() (string, error) { // MultiAddress returns the p2p multiaddr of the node. func (p *RelayChainNode) MultiAddress() (string, error) { - peerId, err := p.PeerID() + peerID, err := p.PeerID() if err != nil { return "", err } - return fmt.Sprintf("/dns4/%s/tcp/%s/p2p/%s", p.HostName(), strings.Split(nodePort, "/")[0], peerId), nil + return fmt.Sprintf("/dns4/%s/tcp/%s/p2p/%s", p.HostName(), strings.Split(nodePort, "/")[0], peerID), nil } -func (c *RelayChainNode) logger() *zap.Logger { - return c.log.With( - zap.String("chain_id", c.Chain.Config().ChainID), - zap.String("test", c.TestName), +func (p *RelayChainNode) logger() *zap.Logger { + return p.log.With( + zap.String("chain_id", p.Chain.Config().ChainID), + zap.String("test", p.TestName), ) } @@ -243,12 +244,12 @@ func (p *RelayChainNode) StartContainer(ctx context.Context) error { } // Set the host ports once since they will not change after the container has started. - p.hostWsPort, p.hostRpcPort = hostPorts[0], hostPorts[1] + p.hostWsPort, p.hostRPCPort = hostPorts[0], hostPorts[1] p.logger().Info("Waiting for RPC endpoint to be available", zap.String("container", p.Name())) - explorerUrl := fmt.Sprintf("\033[4;34mhttps://polkadot.js.org/apps?rpc=ws://%s#/explorer\033[0m", + explorerURL := fmt.Sprintf("\033[4;34mhttps://polkadot.js.org/apps?rpc=ws://%s#/explorer\033[0m", strings.Replace(p.hostWsPort, "localhost", "127.0.0.1", 1)) - p.log.Info(explorerUrl, zap.String("container", p.Name())) + p.log.Info(explorerURL, zap.String("container", p.Name())) var api *gsrpc.SubstrateAPI if err = retry.Do(func() error { var err error @@ -270,7 +271,7 @@ func (p *RelayChainNode) Exec(ctx context.Context, cmd []string, env []string) d opts := dockerutil.ContainerOptions{ Binds: p.Bind(), Env: env, - User: p.Image.UidGid, + User: p.Image.UIDGID, } return job.Run(ctx, cmd, opts) } diff --git a/chain/polkadot/ss58.go b/chain/polkadot/ss58.go index 83c77d808..779ef09cd 100644 --- a/chain/polkadot/ss58.go +++ b/chain/polkadot/ss58.go @@ -40,24 +40,25 @@ func DecodeAddressSS58(address string) ([]byte, error) { return nil, err } var checksumLength int - if IntInSlice(len(ss58AddrDecoded), []int{3, 4, 6, 10}) { + switch { + case IntInSlice(len(ss58AddrDecoded), []int{3, 4, 6, 10}): checksumLength = 1 - } else if IntInSlice(len(ss58AddrDecoded), []int{5, 7, 11, 35}) { + case IntInSlice(len(ss58AddrDecoded), []int{5, 7, 11, 35}): checksumLength = 2 - } else if IntInSlice(len(ss58AddrDecoded), []int{8, 12}) { + case IntInSlice(len(ss58AddrDecoded), []int{8, 12}): checksumLength = 3 - } else if IntInSlice(len(ss58AddrDecoded), []int{9, 13}) { + case IntInSlice(len(ss58AddrDecoded), []int{9, 13}): checksumLength = 4 - } else if IntInSlice(len(ss58AddrDecoded), []int{14}) { + case IntInSlice(len(ss58AddrDecoded), []int{14}): checksumLength = 5 - } else if IntInSlice(len(ss58AddrDecoded), []int{15}) { + case IntInSlice(len(ss58AddrDecoded), []int{15}): checksumLength = 6 - } else if IntInSlice(len(ss58AddrDecoded), []int{16}) { + case IntInSlice(len(ss58AddrDecoded), []int{16}): checksumLength = 7 - } else if IntInSlice(len(ss58AddrDecoded), []int{17}) { + case IntInSlice(len(ss58AddrDecoded), []int{17}): checksumLength = 8 - } else { - return nil, fmt.Errorf("Cannot get checksum length") + default: + return nil, fmt.Errorf("cannot get checksum length") } bss := ss58AddrDecoded[0 : len(ss58AddrDecoded)-checksumLength] checksum, _ := blake2b.New(64, []byte{}) @@ -69,7 +70,7 @@ func DecodeAddressSS58(address string) ([]byte, error) { h := checksum.Sum(nil) if BytesToHex(h[0:checksumLength]) != BytesToHex(ss58AddrDecoded[len(ss58AddrDecoded)-checksumLength:]) { - return nil, fmt.Errorf("Checksum incorrect") + return nil, fmt.Errorf("checksum incorrect") } return ss58AddrDecoded[1 : len(ss58AddrDecoded)-checksumLength], nil } diff --git a/chain/polkadot/tx.go b/chain/polkadot/tx.go index 0df44fe9c..245e3811e 100644 --- a/chain/polkadot/tx.go +++ b/chain/polkadot/tx.go @@ -8,6 +8,7 @@ import ( gsrpc "github.com/misko9/go-substrate-rpc-client/v4" "github.com/misko9/go-substrate-rpc-client/v4/signature" gstypes "github.com/misko9/go-substrate-rpc-client/v4/types" + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) @@ -78,17 +79,18 @@ func SendIbcFundsTx( } raw := gstypes.NewU8(1) + size := gstypes.NewU8(uint8(len(amount.Address) * 4)) to := gstypes.NewStorageDataRaw([]byte(amount.Address)) channel := gstypes.NewU64(0) // Parse channel number from string timeout := gstypes.NewU8(1) timestamp := gstypes.NewOptionU64(gstypes.NewU64(0)) height := gstypes.NewOptionU64(gstypes.NewU64(3000)) // Must set timestamp or height - assetId := gstypes.NewU128(*big.NewInt(assetNum)) + assetID := gstypes.NewU128(*big.NewInt(assetNum)) amount2 := gstypes.NewU128(*amount.Amount.BigInt()) memo := gstypes.NewU8(0) - call, err := gstypes.NewCall(meta, "Ibc.transfer", raw, size, to, channel, timeout, timestamp, height, assetId, amount2, memo) + call, err := gstypes.NewCall(meta, "Ibc.transfer", raw, size, to, channel, timeout, timestamp, height, assetID, amount2, memo) if err != nil { return hash, err } @@ -123,10 +125,10 @@ func MintFundsTx( return hash, err } - assetId := gstypes.NewU128(*big.NewInt(assetNum)) + assetID := gstypes.NewU128(*big.NewInt(assetNum)) amount2 := gstypes.NewUCompact(amount.Amount.BigInt()) - call, err := gstypes.NewCall(meta, "Assets.mint", assetId, receiver, amount2) + call, err := gstypes.NewCall(meta, "Assets.mint", assetID, receiver, amount2) if err != nil { return hash, err } diff --git a/chain/thorchain/api_query.go b/chain/thorchain/api_query.go index d442e5528..0ab64eab3 100644 --- a/chain/thorchain/api_query.go +++ b/chain/thorchain/api_query.go @@ -4,7 +4,9 @@ package thorchain // Copied from thorchain's simulation test, may be replaced in the future for queries via chain binary import ( + "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -12,12 +14,12 @@ import ( "strconv" "strings" - "github.com/strangelove-ventures/interchaintest/v8/chain/thorchain/common" - sdkmath "cosmossdk.io/math" + + "github.com/strangelove-ventures/interchaintest/v8/chain/thorchain/common" ) -func (c *Thorchain) ApiGetBalances(addr string) (common.Coins, error) { +func (c *Thorchain) APIGetBalances(ctx context.Context, addr string) (common.Coins, error) { url := fmt.Sprintf("%s/cosmos/bank/v1beta1/balances/%s", c.GetAPIAddress(), addr) var balances struct { Balances []struct { @@ -25,7 +27,7 @@ func (c *Thorchain) ApiGetBalances(addr string) (common.Coins, error) { Amount string `json:"amount"` } `json:"balances"` } - err := get(url, &balances) + err := get(ctx, url, &balances) if err != nil { return nil, err } @@ -49,17 +51,17 @@ func (c *Thorchain) ApiGetBalances(addr string) (common.Coins, error) { return coins, nil } -func (c *Thorchain) ApiGetInboundAddress(chain string) (address string, router *string, err error) { +func (c *Thorchain) APIGetInboundAddress(ctx context.Context, chain string) (address string, router *string, err error) { url := fmt.Sprintf("%s/thorchain/inbound_addresses", c.GetAPIAddress()) var inboundAddresses []InboundAddress - err = get(url, &inboundAddresses) + err = get(ctx, url, &inboundAddresses) if err != nil { return "", nil, err } // find address for chain for _, inboundAddress := range inboundAddresses { - if *inboundAddress.Chain == string(chain) { + if *inboundAddress.Chain == chain { if inboundAddress.Router != nil { router = new(string) *router = *inboundAddress.Router @@ -71,10 +73,10 @@ func (c *Thorchain) ApiGetInboundAddress(chain string) (address string, router * return "", nil, fmt.Errorf("no inbound address found for chain %s", chain) } -func (c *Thorchain) ApiGetRouterAddress(chain string) (string, error) { +func (c *Thorchain) APIGetRouterAddress(ctx context.Context, chain string) (string, error) { url := fmt.Sprintf("%s/thorchain/inbound_addresses", c.GetAPIAddress()) var inboundAddresses []InboundAddress - err := get(url, &inboundAddresses) + err := get(ctx, url, &inboundAddresses) if err != nil { return "", err } @@ -89,35 +91,35 @@ func (c *Thorchain) ApiGetRouterAddress(chain string) (string, error) { return "", fmt.Errorf("no inbound address found for chain %s", chain) } -func (c *Thorchain) ApiGetLiquidityProviders(asset common.Asset) ([]LiquidityProvider, error) { +func (c *Thorchain) APIGetLiquidityProviders(ctx context.Context, asset common.Asset) ([]LiquidityProvider, error) { url := fmt.Sprintf("%s/thorchain/pool/%s/liquidity_providers", c.GetAPIAddress(), asset.String()) var liquidityProviders []LiquidityProvider - err := get(url, &liquidityProviders) + err := get(ctx, url, &liquidityProviders) return liquidityProviders, err } -func (c *Thorchain) ApiGetSavers(asset common.Asset) ([]Saver, error) { +func (c *Thorchain) APIGetSavers(ctx context.Context, asset common.Asset) ([]Saver, error) { url := fmt.Sprintf("%s/thorchain/pool/%s/savers", c.GetAPIAddress(), asset.GetLayer1Asset().String()) var savers []Saver - err := get(url, &savers) + err := get(ctx, url, &savers) return savers, err } -func (c *Thorchain) ApiGetPools() ([]Pool, error) { +func (c *Thorchain) APIGetPools(ctx context.Context) ([]Pool, error) { url := fmt.Sprintf("%s/thorchain/pools", c.GetAPIAddress()) var pools []Pool - err := get(url, &pools) + err := get(ctx, url, &pools) return pools, err } -func (c *Thorchain) ApiGetPool(asset common.Asset) (Pool, error) { +func (c *Thorchain) APIGetPool(ctx context.Context, asset common.Asset) (Pool, error) { url := fmt.Sprintf("%s/thorchain/pool/%s", c.GetAPIAddress(), asset.String()) var pool Pool - err := get(url, &pool) + err := get(ctx, url, &pool) return pool, err } -func (c *Thorchain) ApiGetSwapQuote(from, to common.Asset, amount sdkmath.Uint) (QuoteSwapResponse, error) { +func (c *Thorchain) APIGetSwapQuote(ctx context.Context, from, to common.Asset, amount sdkmath.Uint) (QuoteSwapResponse, error) { baseURL := fmt.Sprintf("%s/thorchain/quote/swap", c.GetAPIAddress()) parsedURL, err := url.Parse(baseURL) if err != nil { @@ -131,11 +133,11 @@ func (c *Thorchain) ApiGetSwapQuote(from, to common.Asset, amount sdkmath.Uint) url := parsedURL.String() var quote QuoteSwapResponse - err = get(url, "e) + err = get(ctx, url, "e) return quote, err } -func (c *Thorchain) ApiGetSaverDepositQuote(asset common.Asset, amount sdkmath.Uint) (QuoteSaverDepositResponse, error) { +func (c *Thorchain) APIGetSaverDepositQuote(ctx context.Context, asset common.Asset, amount sdkmath.Uint) (QuoteSaverDepositResponse, error) { baseURL := fmt.Sprintf("%s/thorchain/quote/saver/deposit", c.GetAPIAddress()) parsedURL, err := url.Parse(baseURL) if err != nil { @@ -148,28 +150,28 @@ func (c *Thorchain) ApiGetSaverDepositQuote(asset common.Asset, amount sdkmath.U url := parsedURL.String() var quote QuoteSaverDepositResponse - err = get(url, "e) + err = get(ctx, url, "e) return quote, err } -func (c *Thorchain) ApiGetTxStages(txid string) (TxStagesResponse, error) { +func (c *Thorchain) APIGetTxStages(ctx context.Context, txid string) (TxStagesResponse, error) { url := fmt.Sprintf("%s/thorchain/tx/stages/%s", c.GetAPIAddress(), txid) var stages TxStagesResponse - err := get(url, &stages) + err := get(ctx, url, &stages) return stages, err } -func (c *Thorchain) ApiGetTxDetails(txid string) (TxDetailsResponse, error) { +func (c *Thorchain) APIGetTxDetails(ctx context.Context, txid string) (TxDetailsResponse, error) { url := fmt.Sprintf("%s/thorchain/tx/details/%s", c.GetAPIAddress(), txid) var details TxDetailsResponse - err := get(url, &details) + err := get(ctx, url, &details) return details, err } -func (c *Thorchain) ApiGetMimirs() (map[string]int64, error) { +func (c *Thorchain) APIGetMimirs(ctx context.Context) (map[string]int64, error) { url := fmt.Sprintf("%s/thorchain/mimir", c.GetAPIAddress()) var mimirs map[string]int64 - err := get(url, &mimirs) + err := get(ctx, url, &mimirs) return mimirs, err } @@ -177,8 +179,13 @@ func (c *Thorchain) ApiGetMimirs() (map[string]int64, error) { // Internal //////////////////////////////////////////////////////////////////////////////////////// -func get(url string, target interface{}) error { - resp, err := http.Get(url) +func get(ctx context.Context, url string, target interface{}) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return err + } + + resp, err := http.DefaultClient.Do(req) if err != nil { return err } @@ -195,7 +202,7 @@ func get(url string, target interface{}) error { errResp := ErrorResponse{} err = json.Unmarshal(buf, &errResp) if err == nil && errResp.Error != "" { - return fmt.Errorf(errResp.Error) + return errors.New(errResp.Error) } // decode response @@ -203,8 +210,8 @@ func get(url string, target interface{}) error { } // ConvertAssetAmount converts the given coin to the target asset and returns the amount. -func (c *Thorchain) ConvertAssetAmount(coin Coin, asset string) (sdkmath.Uint, error) { - pools, err := c.ApiGetPools() +func (c *Thorchain) ConvertAssetAmount(ctx context.Context, coin Coin, asset string) (sdkmath.Uint, error) { + pools, err := c.APIGetPools(ctx) if err != nil { return sdkmath.ZeroUint(), err } diff --git a/chain/thorchain/broadcaster.go b/chain/thorchain/broadcaster.go index 6dc22a1e3..2a8001e8d 100644 --- a/chain/thorchain/broadcaster.go +++ b/chain/thorchain/broadcaster.go @@ -8,9 +8,6 @@ import ( "testing" "time" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/testutil" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" @@ -18,6 +15,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" + + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) type ClientContextOpt func(clientContext client.Context) client.Context @@ -50,6 +50,8 @@ type Broadcaster struct { // NewBroadcaster returns a instance of Broadcaster which can be used with broadcast.Tx to // broadcast messages sdk messages. func NewBroadcaster(t *testing.T, chain *Thorchain) *Broadcaster { + t.Helper() + return &Broadcaster{ t: t, chain: chain, diff --git a/chain/thorchain/common/chain.go b/chain/thorchain/common/chain.go index ddb4c9ae9..ed0c7917e 100644 --- a/chain/thorchain/common/chain.go +++ b/chain/thorchain/common/chain.go @@ -81,6 +81,8 @@ func (c Chain) GetGasAsset() Asset { return AVAXAsset case GAIAChain: return ATOMAsset + case EmptyChain: + return EmptyAsset default: return EmptyAsset } diff --git a/chain/thorchain/genesis.go b/chain/thorchain/genesis.go index 377e6fb82..dea907ca1 100644 --- a/chain/thorchain/genesis.go +++ b/chain/thorchain/genesis.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/icza/dyno" + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) diff --git a/chain/thorchain/module_bank.go b/chain/thorchain/module_bank.go index 5d3446f12..710e9b605 100644 --- a/chain/thorchain/module_bank.go +++ b/chain/thorchain/module_bank.go @@ -3,12 +3,12 @@ package thorchain import ( "context" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - sdkmath "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) // Deprecated: use BankSend instead. diff --git a/chain/thorchain/module_thorchain.go b/chain/thorchain/module_thorchain.go index ad0705738..ad4240c34 100644 --- a/chain/thorchain/module_thorchain.go +++ b/chain/thorchain/module_thorchain.go @@ -4,9 +4,9 @@ import ( "context" "fmt" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "cosmossdk.io/math" + + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) // BankSend sends tokens from one account to another. diff --git a/chain/thorchain/poll.go b/chain/thorchain/poll.go index 74a5e1232..fc4d31e68 100644 --- a/chain/thorchain/poll.go +++ b/chain/thorchain/poll.go @@ -5,10 +5,10 @@ import ( "errors" "fmt" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/testutil" - - codectypes "github.com/cosmos/cosmos-sdk/codec/types" ) // PollForMessage searches every transaction for a message. Must pass a coded registry capable of decoding the cosmos transaction. @@ -19,7 +19,7 @@ func PollForMessage[T any](ctx context.Context, chain *Thorchain, registry codec fn = func(T) bool { return true } } doPoll := func(ctx context.Context, height int64) (T, error) { - h := int64(height) + h := height block, err := chain.getFullNode().Client.Block(ctx, &h) if err != nil { return zero, err diff --git a/chain/thorchain/query.go b/chain/thorchain/query.go index 6263de0d3..6b8a29336 100644 --- a/chain/thorchain/query.go +++ b/chain/thorchain/query.go @@ -17,7 +17,7 @@ type blockClient interface { // RangeBlockMessages iterates through all a block's transactions and each transaction's messages yielding to f. // Return true from f to stop iteration. func RangeBlockMessages(ctx context.Context, interfaceRegistry codectypes.InterfaceRegistry, client blockClient, height int64, done func(sdk.Msg) bool) error { - h := int64(height) + h := height block, err := client.Block(ctx, &h) if err != nil { return fmt.Errorf("tendermint rpc get block: %w", err) diff --git a/chain/thorchain/sidecar.go b/chain/thorchain/sidecar.go index c59bc1b22..e59a0f1ec 100644 --- a/chain/thorchain/sidecar.go +++ b/chain/thorchain/sidecar.go @@ -7,9 +7,10 @@ import ( dockerclient "github.com/docker/docker/client" "github.com/docker/go-connections/nat" + "go.uber.org/zap" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/strangelove-ventures/interchaintest/v8/ibc" - "go.uber.org/zap" ) type SidecarProcesses []*SidecarProcess diff --git a/chain/thorchain/thorchain.go b/chain/thorchain/thorchain.go index b00d933e8..cbe044bc8 100644 --- a/chain/thorchain/thorchain.go +++ b/chain/thorchain/thorchain.go @@ -17,10 +17,6 @@ import ( dockertypes "github.com/docker/docker/api/types" volumetypes "github.com/docker/docker/api/types/volume" "github.com/docker/docker/client" - "github.com/strangelove-ventures/interchaintest/v8/blockdb" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" "golang.org/x/sync/errgroup" @@ -35,6 +31,11 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/types" + + "github.com/strangelove-ventures/interchaintest/v8/blockdb" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) type Thorchain struct { @@ -80,7 +81,7 @@ func NewThorchainHeighlinerChainConfig( Images: []ibc.DockerImage{ { Repository: "ghcr.io/strangelove-ventures/heighliner/thorchain", - UidGid: dockerutil.GetHeighlinerUserString(), + UIDGID: dockerutil.GetHeighlinerUserString(), }, }, Bin: binary, @@ -155,7 +156,6 @@ func (c *Thorchain) AddFullNodes(ctx context.Context, configFileOverrides map[st var eg errgroup.Group for i := prevCount; i < c.numFullNodes; i++ { - i := i eg.Go(func() error { fn := c.FullNodes[i] if err := fn.InitFullNodeFiles(ctx); err != nil { @@ -506,7 +506,7 @@ func (c *Thorchain) NewChainNode( VolumeName: v.Name, ImageRef: image.Ref(), TestName: testName, - UidGid: image.UidGid, + UidGid: image.UIDGID, }); err != nil { return nil, fmt.Errorf("set volume owner: %w", err) } @@ -569,7 +569,7 @@ func (c *Thorchain) NewSidecarProcess( VolumeName: v.Name, ImageRef: image.Ref(), TestName: testName, - UidGid: image.UidGid, + UidGid: image.UIDGID, }); err != nil { return fmt.Errorf("set volume owner: %w", err) } @@ -597,7 +597,6 @@ func (c *Thorchain) initializeChainNodes( eg, egCtx := errgroup.WithContext(ctx) for i := len(c.Validators); i < c.NumValidators; i++ { - i := i eg.Go(func() error { val, err := c.NewChainNode(egCtx, testName, cli, networkID, image, true, i) if err != nil { @@ -608,7 +607,6 @@ func (c *Thorchain) initializeChainNodes( }) } for i := len(c.FullNodes); i < c.numFullNodes; i++ { - i := i eg.Go(func() error { fn, err := c.NewChainNode(egCtx, testName, cli, networkID, image, false, i) if err != nil { @@ -642,9 +640,6 @@ func (c *Thorchain) initializeSidecars( ) error { eg, egCtx := errgroup.WithContext(ctx) for i, cfg := range c.cfg.SidecarConfigs { - i := i - cfg := cfg - if cfg.ValidatorProcess { continue } @@ -689,8 +684,6 @@ func (c *Thorchain) prepNodes(ctx context.Context, genesisAmounts [][]types.Coin eg, egCtx := errgroup.WithContext(ctx) // Initialize config and sign gentx for each validator. for i, v := range c.Validators { - v := v - i := i v.Validator = true eg.Go(func() error { if err := v.InitFullNodeFiles(egCtx); err != nil { @@ -752,7 +745,6 @@ func (c *Thorchain) prepNodes(ctx context.Context, genesisAmounts [][]types.Coin // Initialize config for each full node. for _, n := range c.FullNodes { - n := n n.Validator = false eg.Go(func() error { if err := n.InitFullNodeFiles(egCtx); err != nil { @@ -941,7 +933,6 @@ func (c *Thorchain) Start(testName string, ctx context.Context, additionalGenesi break } v := c.Validators[i] - validator := validator c.log.Info( "Will emulate validator", zap.String("bond_address", validator.BondAddress), @@ -999,8 +990,6 @@ func (c *Thorchain) Start(testName string, ctx context.Context, additionalGenesi // Start any sidecar processes that should be running before the chain starts eg, egCtx := errgroup.WithContext(ctx) for _, s := range c.Sidecars { - s := s - err = s.containerLifecycle.Running(ctx) if s.preStart && err != nil { eg.Go(func() error { @@ -1022,7 +1011,6 @@ func (c *Thorchain) Start(testName string, ctx context.Context, additionalGenesi eg, egCtx = errgroup.WithContext(ctx) for _, n := range chainNodes { - n := n eg.Go(func() error { return n.CreateNodeContainer(egCtx) }) @@ -1035,7 +1023,6 @@ func (c *Thorchain) Start(testName string, ctx context.Context, additionalGenesi eg, egCtx = errgroup.WithContext(ctx) for _, n := range chainNodes { - n := n c.log.Info("Starting container", zap.String("container", n.Name())) eg.Go(func() error { if err := n.SetPeers(egCtx, peers); err != nil { @@ -1072,7 +1059,6 @@ func (c *Thorchain) Acknowledgements(ctx context.Context, height int64) ([]ibc.P } ibcAcks := make([]ibc.PacketAcknowledgement, len(acks)) for i, ack := range acks { - ack := ack ibcAcks[i] = ibc.PacketAcknowledgement{ Acknowledgement: ack.Acknowledgement, Packet: ibc.Packet{ @@ -1105,7 +1091,6 @@ func (c *Thorchain) Timeouts(ctx context.Context, height int64) ([]ibc.PacketTim } ibcTimeouts := make([]ibc.PacketTimeout, len(timeouts)) for i, ack := range timeouts { - ack := ack ibcTimeouts[i] = ibc.PacketTimeout{ Packet: ibc.Packet{ Sequence: ack.Packet.Sequence, @@ -1134,7 +1119,6 @@ func (c *Thorchain) FindTxs(ctx context.Context, height int64) ([]blockdb.Tx, er func (c *Thorchain) StopAllNodes(ctx context.Context) error { var eg errgroup.Group for _, n := range c.Nodes() { - n := n eg.Go(func() error { if err := n.StopContainer(ctx); err != nil { return err @@ -1149,7 +1133,6 @@ func (c *Thorchain) StopAllNodes(ctx context.Context) error { func (c *Thorchain) StopAllSidecars(ctx context.Context) error { var eg errgroup.Group for _, s := range c.Sidecars { - s := s eg.Go(func() error { if err := s.StopContainer(ctx); err != nil { return err @@ -1168,7 +1151,6 @@ func (c *Thorchain) StartAllNodes(ctx context.Context) error { defer c.findTxMu.Unlock() var eg errgroup.Group for _, n := range c.Nodes() { - n := n eg.Go(func() error { if err := n.CreateNodeContainer(ctx); err != nil { return err @@ -1187,8 +1169,6 @@ func (c *Thorchain) StartAllSidecars(ctx context.Context) error { defer c.findTxMu.Unlock() var eg errgroup.Group for _, s := range c.Sidecars { - s := s - err := s.containerLifecycle.Running(ctx) if err == nil { continue @@ -1213,10 +1193,7 @@ func (c *Thorchain) StartAllValSidecars(ctx context.Context) error { var eg errgroup.Group for _, v := range c.Validators { - v := v for _, s := range v.Sidecars { - s := s - err := s.containerLifecycle.Running(ctx) if err == nil { continue diff --git a/chain/thorchain/thornode.go b/chain/thorchain/thornode.go index e3a968560..4560efbac 100644 --- a/chain/thorchain/thornode.go +++ b/chain/thorchain/thornode.go @@ -21,10 +21,6 @@ import ( dockerclient "github.com/docker/docker/client" "github.com/docker/go-connections/nat" "github.com/icza/dyno" - "github.com/strangelove-ventures/interchaintest/v8/blockdb" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" "golang.org/x/mod/semver" "golang.org/x/sync/errgroup" @@ -32,6 +28,7 @@ import ( "google.golang.org/grpc/credentials/insecure" sdkmath "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" @@ -44,6 +41,11 @@ import ( rpchttp "github.com/cometbft/cometbft/rpc/client/http" coretypes "github.com/cometbft/cometbft/rpc/core/types" libclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" + + "github.com/strangelove-ventures/interchaintest/v8/blockdb" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) type ChainNode struct { @@ -187,7 +189,7 @@ func (tn *ChainNode) NewSidecarProcess( VolumeName: v.Name, ImageRef: image.Ref(), TestName: tn.TestName, - UidGid: image.UidGid, + UidGid: image.UIDGID, }); err != nil { return fmt.Errorf("set volume owner: %w", err) } @@ -406,7 +408,7 @@ func (tn *ChainNode) Height(ctx context.Context) (int64, error) { // FindTxs implements blockdb.BlockSaver. func (tn *ChainNode) FindTxs(ctx context.Context, height int64) ([]blockdb.Tx, error) { - h := int64(height) + h := height var eg errgroup.Group var blockRes *coretypes.ResultBlockResults var block *coretypes.ResultBlock @@ -446,8 +448,8 @@ func (tn *ChainNode) FindTxs(ctx context.Context, height int64) ([]blockdb.Tx, e 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), + Key: attr.Key, + Value: attr.Value, } } newTx.Events[j] = blockdb.Event{ @@ -466,8 +468,8 @@ func (tn *ChainNode) FindTxs(ctx context.Context, height int64) ([]blockdb.Tx, e 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), + Key: attr.Key, + Value: attr.Value, } } finalizeBlockTx.Events[i] = blockdb.Event{ @@ -526,7 +528,7 @@ func (tn *ChainNode) ExecTx(ctx context.Context, keyName string, command ...stri return "", err } output := CosmosTx{} - err = json.Unmarshal([]byte(stdout), &output) + err = json.Unmarshal(stdout, &output) if err != nil { return "", err } @@ -542,7 +544,7 @@ func (tn *ChainNode) ExecTx(ctx context.Context, keyName string, command ...stri return "", err } output = CosmosTx{} - err = json.Unmarshal([]byte(stdout), &output) + err = json.Unmarshal(stdout, &output) if err != nil { return "", err } @@ -556,7 +558,11 @@ func (tn *ChainNode) ExecTx(ctx context.Context, keyName string, command ...stri func (tn *ChainNode) TxHashToResponse(ctx context.Context, txHash string) (*sdk.TxResponse, error) { stdout, stderr, err := tn.ExecQuery(ctx, "tx", txHash) if err != nil { - fmt.Println("TxHashToResponse err: ", err.Error()+" "+string(stderr)) + tn.log.Info("TxHashToResponse returned an error", + zap.String("tx_hash", txHash), + zap.Error(err), + zap.String("stderr", string(stderr)), + ) } i := &sdk.TxResponse{} @@ -608,6 +614,7 @@ func (tn *ChainNode) ExecBin(ctx context.Context, backendfile bool, command ...s keyringCommand := []string{ "sh", "-c", + //nolint: dupword fmt.Sprintf(`cat <= namedFixWalletVersion { + switch { + case c.WalletVersion >= namedFixWalletVersion: cmd = append(c.BaseCli, "sendrawtransaction", signedRawTxHex) - } else if c.WalletVersion > noDefaultKeyWalletVersion { + case c.WalletVersion > noDefaultKeyWalletVersion: cmd = append(c.BaseCli, "sendrawtransaction", signedRawTxHex, "0") - } else { + default: cmd = append(c.BaseCli, "sendrawtransaction", signedRawTxHex) } stdout, _, err := c.Exec(ctx, cmd, nil) diff --git a/chain/utxo/default_configs.go b/chain/utxo/default_configs.go index d1cc3b28e..7a4f8963f 100644 --- a/chain/utxo/default_configs.go +++ b/chain/utxo/default_configs.go @@ -26,7 +26,7 @@ func DefaultBitcoinChainConfig( { Repository: "bitcoin/bitcoin", Version: "26.2", - UidGid: "1025:1025", + UIDGID: "1025:1025", }, }, Bin: "bitcoind,bitcoin-cli", @@ -59,7 +59,7 @@ func DefaultBitcoinCashChainConfig( { Repository: "zquestz/bitcoin-cash-node", Version: "27.1.0", - UidGid: "1025:1025", + UIDGID: "1025:1025", }, }, Bin: "bitcoind,bitcoin-cli", @@ -92,7 +92,7 @@ func DefaultLitecoinChainConfig( { Repository: "uphold/litecoin-core", Version: "0.21", - UidGid: "1025:1025", + UIDGID: "1025:1025", }, }, Bin: "litecoind,litecoin-cli", @@ -127,7 +127,7 @@ func DefaultDogecoinChainConfig( Version: "dogecoin-daemon-1.14.7", // Repository: "coinmetrics/dogecoin", // Version: "1.14.7", - UidGid: "1000:1000", + UIDGID: "1000:1000", }, }, Bin: "dogecoind,dogecoin-cli", diff --git a/chain/utxo/types.go b/chain/utxo/types.go index 5e646ef96..a65dd81d3 100644 --- a/chain/utxo/types.go +++ b/chain/utxo/types.go @@ -14,7 +14,7 @@ type TransactionReceipt struct { type ListUtxo []Utxo type Utxo struct { - TxId string `json:"txid,omitempty"` + TxID string `json:"txid,omitempty"` Vout int `json:"vout,omitempty"` Address string `json:"address,omitempty"` Label string `json:"label,omitempty"` @@ -30,7 +30,7 @@ type Utxo struct { type SendInputs []SendInput type SendInput struct { - TxId string `json:"txid"` // hex + TxID string `json:"txid"` // hex Vout int `json:"vout"` } diff --git a/chain/utxo/unimplemented.go b/chain/utxo/unimplemented.go index 5968afc7c..06a1e12f0 100644 --- a/chain/utxo/unimplemented.go +++ b/chain/utxo/unimplemented.go @@ -59,5 +59,5 @@ func (c *UtxoChain) Timeouts(ctx context.Context, height int64) ([]ibc.PacketTim func (c *UtxoChain) BuildRelayerWallet(ctx context.Context, keyName string) (ibc.Wallet, error) { PanicFunctionName() - return nil, nil + return &UtxoWallet{}, nil } diff --git a/chain/utxo/utxo_chain.go b/chain/utxo/utxo_chain.go index 94091ed45..1fc6efb3d 100644 --- a/chain/utxo/utxo_chain.go +++ b/chain/utxo/utxo_chain.go @@ -14,12 +14,13 @@ import ( "github.com/docker/docker/api/types/volume" dockerclient "github.com/docker/docker/client" "github.com/docker/go-connections/nat" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testutil" "go.uber.org/zap" sdkmath "cosmossdk.io/math" + + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) var _ ibc.Chain = &UtxoChain{} @@ -29,6 +30,7 @@ const ( rpcPort = "18443/tcp" noDefaultKeyWalletVersion = 159_900 namedFixWalletVersion = 169_901 + faucetKeyName = "faucet" ) var natPorts = nat.PortMap{ @@ -52,8 +54,8 @@ type UtxoChain struct { // cli arguments BinDaemon string BinCli string - RpcUser string - RpcPassword string + RPCUser string + RPCPassword string BaseCli []string AddrToKeyNameMap map[string]string KeyNameToWalletMap map[string]*NodeWallet @@ -87,8 +89,8 @@ func NewUtxoChain(testName string, chainConfig ibc.ChainConfig, log *zap.Logger) log: log, BinDaemon: bins[0], BinCli: bins[1], - RpcUser: rpcUser, - RpcPassword: rpcPassword, + RPCUser: rpcUser, + RPCPassword: rpcPassword, AddrToKeyNameMap: make(map[string]string), KeyNameToWalletMap: make(map[string]*NodeWallet), unloadWalletAfterUse: false, @@ -128,7 +130,7 @@ func (c *UtxoChain) Initialize(ctx context.Context, testName string, cli *docker VolumeName: v.Name, ImageRef: image.Ref(), TestName: testName, - UidGid: image.UidGid, + UidGid: image.UIDGID, }); err != nil { return fmt.Errorf("set volume owner: %w", err) } @@ -189,26 +191,34 @@ func (c *UtxoChain) Start(testName string, ctx context.Context, additionalGenesi } if c.cfg.HostPortOverride != nil { + var fields []zap.Field + + i := 0 for intP, extP := range c.cfg.HostPortOverride { - usingPorts[nat.Port(fmt.Sprintf("%d/tcp", intP))] = []nat.PortBinding{ + port := nat.Port(fmt.Sprintf("%d/tcp", intP)) + + usingPorts[port] = []nat.PortBinding{ { HostPort: fmt.Sprintf("%d", extP), }, } + + fields = append(fields, zap.String(fmt.Sprintf("port_overrides_%d", i), fmt.Sprintf("%s:%d", port, extP))) + i++ } - fmt.Printf("Port Overrides: %v. Using: %v\n", c.cfg.HostPortOverride, usingPorts) + c.log.Info("Port overrides", fields...) } env := []string{} - if c.cfg.Images[0].UidGid != "" { - uidGid := strings.Split(c.cfg.Images[0].UidGid, ":") - if len(uidGid) != 2 { + if c.cfg.Images[0].UIDGID != "" { + uidGID := strings.Split(c.cfg.Images[0].UIDGID, ":") + if len(uidGID) != 2 { panic(fmt.Sprintf("%s chain does not have valid UidGid", c.cfg.Name)) } env = []string{ - fmt.Sprintf("UID=%s", uidGid[0]), - fmt.Sprintf("GID=%s", uidGid[1]), + fmt.Sprintf("UID=%s", uidGID[0]), + fmt.Sprintf("GID=%s", uidGID[1]), } } @@ -240,8 +250,8 @@ func (c *UtxoChain) Start(testName string, ctx context.Context, additionalGenesi c.BaseCli = []string{ c.BinCli, "-regtest", - c.RpcUser, - c.RpcPassword, + c.RPCUser, + c.RPCPassword, fmt.Sprintf("-rpcconnect=%s", c.HostName()), "-rpcport=18443", } @@ -258,7 +268,7 @@ func (c *UtxoChain) Start(testName string, ctx context.Context, additionalGenesi nextBlockHeight = 1000 } for { - faucetWallet, found := c.KeyNameToWalletMap["faucet"] + faucetWallet, found := c.KeyNameToWalletMap[faucetKeyName] if !found || !faucetWallet.ready { time.Sleep(time.Second) continue @@ -285,7 +295,7 @@ func (c *UtxoChain) Start(testName string, ctx context.Context, additionalGenesi c.logger().Error("error creating mweb wallet at block 431", zap.String("chain", c.cfg.ChainID), zap.Error(err)) return } - if err := c.sendToMwebAddress(ctx, "faucet", addr, 1); err != nil { + if err := c.sendToMwebAddress(ctx, faucetKeyName, addr, 1); err != nil { c.logger().Error("error sending to mweb wallet at block 431", zap.String("chain", c.cfg.ChainID), zap.Error(err)) return } @@ -297,24 +307,23 @@ func (c *UtxoChain) Start(testName string, ctx context.Context, additionalGenesi c.WalletVersion, _ = c.GetWalletVersion(ctx, "") - keyName := "faucet" - if err := c.CreateWallet(ctx, keyName); err != nil { + if err := c.CreateWallet(ctx, faucetKeyName); err != nil { return err } if c.WalletVersion == 0 { - c.WalletVersion, err = c.GetWalletVersion(ctx, keyName) + c.WalletVersion, err = c.GetWalletVersion(ctx, faucetKeyName) if err != nil { return err } } - addr, err := c.GetNewAddress(ctx, keyName, false) + addr, err := c.GetNewAddress(ctx, faucetKeyName, false) if err != nil { return err } - if err := c.SetAccount(ctx, addr, keyName); err != nil { + if err := c.SetAccount(ctx, addr, faucetKeyName); err != nil { return err } @@ -398,7 +407,7 @@ func (c *UtxoChain) GetAddress(ctx context.Context, keyName string) ([]byte, err return []byte(keyName), nil } - return nil, fmt.Errorf("Keyname: %s's address not found", keyName) + return nil, fmt.Errorf("keyname: %s's address not found", keyName) } func (c *UtxoChain) SendFunds(ctx context.Context, keyName string, amount ibc.WalletAmount) error { @@ -470,7 +479,6 @@ func (c *UtxoChain) GetBalance(ctx context.Context, address string, denom string return sdkmath.Int{}, fmt.Errorf("wallet not found for address: %s", address) } - balance := "" var coinsWithDecimal float64 if c.WalletVersion >= noDefaultKeyWalletVersion { if err := c.LoadWallet(ctx, keyName); err != nil { @@ -484,7 +492,7 @@ func (c *UtxoChain) GetBalance(ctx context.Context, address string, denom string if err := c.UnloadWallet(ctx, keyName); err != nil { return sdkmath.Int{}, err } - balance = strings.TrimSpace(string(stdout)) + balance := strings.TrimSpace(string(stdout)) coinsWithDecimal, err = strconv.ParseFloat(balance, 64) if err != nil { return sdkmath.Int{}, err diff --git a/chain/utxo/wallet.go b/chain/utxo/wallet.go index 0549cf3e2..420d4ad1d 100644 --- a/chain/utxo/wallet.go +++ b/chain/utxo/wallet.go @@ -53,16 +53,16 @@ func (c *UtxoChain) getWalletForNewAddress(keyName string) (*NodeWallet, error) wallet, found := c.KeyNameToWalletMap[keyName] if c.WalletVersion >= noDefaultKeyWalletVersion { if !found { - return nil, fmt.Errorf("Wallet keyname (%s) not found, has it been created?", keyName) + return nil, fmt.Errorf("wallet keyname (%s) not found, has it been created?", keyName) } if wallet.address != "" { - return nil, fmt.Errorf("Wallet keyname (%s) already has an address", keyName) + return nil, fmt.Errorf("wallet keyname (%s) already has an address", keyName) } } if c.WalletVersion < noDefaultKeyWalletVersion { if found { - return nil, fmt.Errorf("Wallet keyname (%s) already has an address", keyName) + return nil, fmt.Errorf("wallet keyname (%s) already has an address", keyName) } else { wallet = &NodeWallet{ keyName: keyName, @@ -77,10 +77,10 @@ func (c *UtxoChain) getWalletForNewAddress(keyName string) (*NodeWallet, error) func (c *UtxoChain) getWalletForSetAccount(keyName string, addr string) (*NodeWallet, error) { wallet, found := c.KeyNameToWalletMap[keyName] if !found { - return nil, fmt.Errorf("Wallet keyname (%s) not found, get new address not called", keyName) + return nil, fmt.Errorf("wallet keyname (%s) not found, get new address not called", keyName) } if wallet.address != addr { - return nil, fmt.Errorf("Wallet keyname (%s) is associated with address (%s), not (%s)", keyName, wallet.address, addr) + return nil, fmt.Errorf("wallet keyname (%s) is associated with address (%s), not (%s)", keyName, wallet.address, addr) } return wallet, nil } @@ -94,7 +94,7 @@ func (c *UtxoChain) getWalletForUse(keyName string) (*NodeWallet, error) { // For chain without wallet support, GetNewAddress() and SetAccount() must be called. // For chains with wallet support, CreateWallet() and GetNewAddress() must be called. if !wallet.ready { - return nil, fmt.Errorf("Wallet keyname (%s) is not ready for use, check creation steps", keyName) + return nil, fmt.Errorf("wallet keyname (%s) is not ready for use, check creation steps", keyName) } return wallet, nil } @@ -102,7 +102,7 @@ func (c *UtxoChain) getWalletForUse(keyName string) (*NodeWallet, error) { func (c *UtxoChain) getWallet(keyName string) (*NodeWallet, error) { wallet, found := c.KeyNameToWalletMap[keyName] if !found { - return nil, fmt.Errorf("Wallet keyname (%s) not found", keyName) + return nil, fmt.Errorf("wallet keyname (%s) not found", keyName) } return wallet, nil } diff --git a/chainfactory.go b/chainfactory.go index 48e46f0f5..1c0bc3b71 100644 --- a/chainfactory.go +++ b/chainfactory.go @@ -6,6 +6,11 @@ import ( "strings" "sync" + "go.uber.org/zap" + "gopkg.in/yaml.v3" + + _ "embed" + "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" "github.com/strangelove-ventures/interchaintest/v8/chain/ethereum/foundry" "github.com/strangelove-ventures/interchaintest/v8/chain/ethereum/geth" @@ -14,10 +19,6 @@ import ( "github.com/strangelove-ventures/interchaintest/v8/chain/thorchain" "github.com/strangelove-ventures/interchaintest/v8/chain/utxo" "github.com/strangelove-ventures/interchaintest/v8/ibc" - "go.uber.org/zap" - "gopkg.in/yaml.v3" - - _ "embed" ) // ChainFactory describes how to get chains for tests. @@ -134,11 +135,11 @@ func buildChain(log *zap.Logger, testName string, cfg ibc.ChainConfig, numValida } switch cfg.Type { - case "cosmos": + case ibc.Cosmos: return cosmos.NewCosmosChain(testName, cfg, nv, nf, log), nil - case "penumbra": + case ibc.Penumbra: return penumbra.NewPenumbraChain(log, testName, cfg, nv, nf), nil - case "polkadot": + case ibc.Polkadot: // TODO Clean this up. RelayChain config should only reference cfg.Images[0] and parachains should iterate through the remaining // Maybe just pass everything in like NewCosmosChain and NewPenumbraChain, let NewPolkadotChain figure it out // Or parachains and ICS consumer chains maybe should be their own chain @@ -158,7 +159,7 @@ func buildChain(log *zap.Logger, testName string, cfg ibc.ChainConfig, numValida default: return nil, fmt.Errorf("unexpected error, unknown polkadot parachain: %s", cfg.Name) } - case "ethereum": + case ibc.Ethereum: switch cfg.Bin { case "anvil": return foundry.NewAnvilChain(testName, cfg, log), nil @@ -167,9 +168,9 @@ func buildChain(log *zap.Logger, testName string, cfg ibc.ChainConfig, numValida default: return nil, fmt.Errorf("unknown binary: %s for ethereum chain type, must be anvil or geth", cfg.Bin) } - case "thorchain": + case ibc.Thorchain: return thorchain.NewThorchain(testName, cfg, nv, nf, log), nil - case "utxo": + case ibc.UTXO: return utxo.NewUtxoChain(testName, cfg, log), nil default: return nil, fmt.Errorf("unexpected error, unknown chain type: %s for chain: %s", cfg.Type, cfg.Name) diff --git a/chainset.go b/chainset.go index b3c6a47bb..6b4b5fd6b 100644 --- a/chainset.go +++ b/chainset.go @@ -9,12 +9,13 @@ import ( "time" "github.com/docker/docker/client" - "github.com/strangelove-ventures/interchaintest/v8/blockdb" - "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" - "github.com/strangelove-ventures/interchaintest/v8/ibc" "go.uber.org/multierr" "go.uber.org/zap" "golang.org/x/sync/errgroup" + + "github.com/strangelove-ventures/interchaintest/v8/blockdb" + "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) // chainSet is an unordered collection of ibc.Chain, @@ -53,7 +54,6 @@ func (cs *chainSet) Initialize(ctx context.Context, testName string, cli *client var eg errgroup.Group for c := range cs.chains { - c := c cs.log.Info("Initializing chain", zap.String("chain_id", c.Config().ChainID)) eg.Go(func() error { if err := c.Initialize(ctx, testName, cli, networkID); err != nil { @@ -82,7 +82,6 @@ func (cs *chainSet) CreateCommonAccount(ctx context.Context, keyName string) (fa eg, egCtx := errgroup.WithContext(ctx) for c := range cs.chains { - c := c eg.Go(func() error { wallet, err := c.BuildWallet(egCtx, keyName, "") if err != nil { @@ -109,7 +108,6 @@ func (cs *chainSet) Start(ctx context.Context, testName string, additionalGenesi eg, egCtx := errgroup.WithContext(ctx) for c := range cs.chains { - c := c if cosmosChain, ok := c.(*cosmos.CosmosChain); ok && cosmosChain.Provider != nil { // wait for provider chains to be started up first continue @@ -142,7 +140,6 @@ func (cs *chainSet) Start(ctx context.Context, testName string, additionalGenesi // Now startup any consumer chains for c := range cs.chains { - c := c if cosmosChain, ok := c.(*cosmos.CosmosChain); ok && cosmosChain.Provider != nil { eg.Go(func() error { // this is a consumer chain @@ -193,7 +190,6 @@ func (cs chainSet) TrackBlocks(ctx context.Context, testName, dbPath, gitSha str cs.collectors = make([]*blockdb.Collector, len(cs.chains)) i := 0 for c := range cs.chains { - c := c id := c.Config().ChainID finder, ok := c.(blockdb.TxFinder) if !ok { diff --git a/chainspec.go b/chainspec.go index 0d676fb14..67d6889b6 100644 --- a/chainspec.go +++ b/chainspec.go @@ -232,11 +232,9 @@ func (s *ChainSpec) applyConfigOverrides(cfg ibc.ChainConfig) (*ibc.ChainConfig, default: return nil, fmt.Errorf("unexpected parachain: %s", s.Name) } - } else { + } else if len(s.ChainConfig.Images) < 2 || s.ChainConfig.Images[1].Version == "" { // Ensure there are at least two images and check the 2nd version is populated - if len(s.ChainConfig.Images) < 2 || s.ChainConfig.Images[1].Version == "" { - return nil, fmt.Errorf("ChainCongfig.Images must be >1 and ChainConfig.Images[1].Version must not be empty") - } + return nil, fmt.Errorf("ChainCongfig.Images must be >1 and ChainConfig.Images[1].Version must not be empty") } } diff --git a/chainspec_test.go b/chainspec_test.go index 8f1af9185..b402c2d4a 100644 --- a/chainspec_test.go +++ b/chainspec_test.go @@ -5,10 +5,11 @@ import ( "testing" "github.com/google/go-cmp/cmp" - interchaintest "github.com/strangelove-ventures/interchaintest/v8" - "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/stretchr/testify/require" "go.uber.org/zap/zaptest" + + interchaintest "github.com/strangelove-ventures/interchaintest/v8" + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) func TestChainSpec_Config(t *testing.T) { @@ -57,7 +58,7 @@ func TestChainSpec_Config(t *testing.T) { // Skip Name, as that is intended to be inherited from ChainName. ChainID: "mychain-123", Images: []ibc.DockerImage{ - {Repository: "docker.example.com", Version: "latest", UidGid: "1:1"}, + {Repository: "docker.example.com", Version: "latest", UIDGID: "1:1"}, }, Bin: "/bin/true", Bech32Prefix: "foo", diff --git a/cmd/interchaintest/flags.go b/cmd/interchaintest/flags.go index e4413609b..82d781ee8 100644 --- a/cmd/interchaintest/flags.go +++ b/cmd/interchaintest/flags.go @@ -6,9 +6,10 @@ import ( "os" "time" - interchaintest "github.com/strangelove-ventures/interchaintest/v8" "go.uber.org/zap" "go.uber.org/zap/zapcore" + + interchaintest "github.com/strangelove-ventures/interchaintest/v8" ) // The value of the extra flags this test supports. diff --git a/cmd/interchaintest/interchaintest_test.go b/cmd/interchaintest/interchaintest_test.go index 742e52e1a..32320fc7a 100644 --- a/cmd/interchaintest/interchaintest_test.go +++ b/cmd/interchaintest/interchaintest_test.go @@ -12,14 +12,15 @@ import ( "time" "github.com/rivo/tview" - interchaintest "github.com/strangelove-ventures/interchaintest/v8" + "go.uber.org/zap" + + "github.com/strangelove-ventures/interchaintest/v8" "github.com/strangelove-ventures/interchaintest/v8/blockdb" blockdbtui "github.com/strangelove-ventures/interchaintest/v8/blockdb/tui" "github.com/strangelove-ventures/interchaintest/v8/conformance" "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/relayer" "github.com/strangelove-ventures/interchaintest/v8/testreporter" - "go.uber.org/zap" ) func init() { @@ -250,8 +251,7 @@ func addFlags() { func parseFlags() { flag.Parse() - switch subcommand() { - case "debug": + if subcommand() == "debug" { // Ignore errors because configured with flag.ExitOnError. _ = debugFlagSet.Parse(os.Args[2:]) } diff --git a/cmd/interchaintest/matrix_test.go b/cmd/interchaintest/matrix_test.go index e2630bdf4..0f81d0041 100644 --- a/cmd/interchaintest/matrix_test.go +++ b/cmd/interchaintest/matrix_test.go @@ -4,11 +4,12 @@ import ( "encoding/json" "testing" - interchaintest "github.com/strangelove-ventures/interchaintest/v8" "github.com/stretchr/testify/require" "go.uber.org/zap/zaptest" _ "embed" + + interchaintest "github.com/strangelove-ventures/interchaintest/v8" ) // Embed the matrix files as strings since they aren't intended to be changed. diff --git a/conformance/flush.go b/conformance/flush.go index 602b0c084..fb8637826 100644 --- a/conformance/flush.go +++ b/conformance/flush.go @@ -5,16 +5,17 @@ import ( "fmt" "testing" - "github.com/strangelove-ventures/interchaintest/v8" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/relayer" - "github.com/strangelove-ventures/interchaintest/v8/testreporter" - "github.com/strangelove-ventures/interchaintest/v8/testutil" "github.com/stretchr/testify/require" "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/types" + + "github.com/strangelove-ventures/interchaintest/v8" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/relayer" + "github.com/strangelove-ventures/interchaintest/v8/testreporter" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) func TestRelayerFlushing(t *testing.T, ctx context.Context, cf interchaintest.ChainFactory, rf interchaintest.RelayerFactory, rep *testreporter.Reporter) { diff --git a/conformance/relayersetup.go b/conformance/relayersetup.go index 2bf348275..9b94281fa 100644 --- a/conformance/relayersetup.go +++ b/conformance/relayersetup.go @@ -5,15 +5,16 @@ import ( "fmt" "testing" - "github.com/strangelove-ventures/interchaintest/v8" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testreporter" - "github.com/strangelove-ventures/interchaintest/v8/testutil" "github.com/stretchr/testify/require" "golang.org/x/sync/errgroup" conntypes "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" "github.com/cosmos/ibc-go/v8/modules/core/exported" + + "github.com/strangelove-ventures/interchaintest/v8" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testreporter" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) // TestRelayerSetup contains a series of subtests that configure a relayer step-by-step. @@ -103,7 +104,7 @@ func TestRelayerSetup(t *testing.T, ctx context.Context, cf interchaintest.Chain req.True(len(conns0) == 1 || len(conns0) == 2) if len(conns0) == 2 { // Chain might have a localhost connection. Connection IDs are sorted, so this would be at position [1]. - req.Equal(conns0[1].ID, exported.LocalhostConnectionID) + req.Equal(exported.LocalhostConnectionID, conns0[1].ID) } conn0 := conns0[0] req.NotEmpty(conn0.ID) @@ -116,7 +117,7 @@ func TestRelayerSetup(t *testing.T, ctx context.Context, cf interchaintest.Chain req.True(len(conns1) == 1 || len(conns1) == 2) if len(conns1) == 2 { // Chain might have a localhost connection. Connection IDs are sorted, so this would be at position [1]. - req.Equal(conns1[1].ID, exported.LocalhostConnectionID) + req.Equal(exported.LocalhostConnectionID, conns1[1].ID) } conn1 := conns1[0] req.NotEmpty(conn1.ID) @@ -172,14 +173,14 @@ func TestRelayerSetup(t *testing.T, ctx context.Context, cf interchaintest.Chain // Not asserting against ConnectionHops or ChannelID. req.Subset([]string{"STATE_OPEN", "Open"}, []string{ch0.State}) req.Subset([]string{"ORDER_UNORDERED", "Unordered"}, []string{ch0.Ordering}) - req.Equal(ch0.Counterparty, ibc.ChannelCounterparty{PortID: "transfer", ChannelID: ch1.ChannelID}) - req.Equal(ch0.Version, "ics20-1") - req.Equal(ch0.PortID, "transfer") + req.Equal(ibc.ChannelCounterparty{PortID: "transfer", ChannelID: ch1.ChannelID}, ch0.Counterparty) + req.Equal("ics20-1", ch0.Version) + req.Equal("transfer", ch0.PortID) req.Subset([]string{"STATE_OPEN", "Open"}, []string{ch1.State}) req.Subset([]string{"ORDER_UNORDERED", "Unordered"}, []string{ch1.Ordering}) - req.Equal(ch1.Counterparty, ibc.ChannelCounterparty{PortID: "transfer", ChannelID: ch0.ChannelID}) - req.Equal(ch1.Version, "ics20-1") - req.Equal(ch1.PortID, "transfer") + req.Equal(ibc.ChannelCounterparty{PortID: "transfer", ChannelID: ch0.ChannelID}, ch1.Counterparty) + req.Equal("ics20-1", ch1.Version) + req.Equal("transfer", ch1.PortID) }) } diff --git a/conformance/test.go b/conformance/test.go index 7842a272f..ab9a87acb 100644 --- a/conformance/test.go +++ b/conformance/test.go @@ -36,6 +36,13 @@ import ( "time" "github.com/docker/docker/client" + "github.com/stretchr/testify/require" + "golang.org/x/sync/errgroup" + + "cosmossdk.io/math" + + transfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" + "github.com/strangelove-ventures/interchaintest/v8" "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" "github.com/strangelove-ventures/interchaintest/v8/dockerutil" @@ -43,12 +50,6 @@ import ( "github.com/strangelove-ventures/interchaintest/v8/relayer" "github.com/strangelove-ventures/interchaintest/v8/testreporter" "github.com/strangelove-ventures/interchaintest/v8/testutil" - "github.com/stretchr/testify/require" - "golang.org/x/sync/errgroup" - - "cosmossdk.io/math" - - transfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" ) var ( @@ -84,24 +85,24 @@ type RelayerTestCaseConfig struct { var relayerTestCaseConfigs = [...]RelayerTestCaseConfig{ { Name: "relay packet", - PreRelayerStart: preRelayerStart_RelayPacket, + PreRelayerStart: preRelayerStartRelayPacket, Test: testPacketRelaySuccess, }, { Name: "no timeout", - PreRelayerStart: preRelayerStart_NoTimeout, + PreRelayerStart: preRelayerStartNoTimeout, Test: testPacketRelaySuccess, }, { Name: "height timeout", RequiredRelayerCapabilities: []relayer.Capability{relayer.HeightTimeout}, - PreRelayerStart: preRelayerStart_HeightTimeout, + PreRelayerStart: preRelayerStartHeightTimeout, Test: testPacketRelayFail, }, { Name: "timestamp timeout", RequiredRelayerCapabilities: []relayer.Capability{relayer.TimestampTimeout}, - PreRelayerStart: preRelayerStart_TimestampTimeout, + PreRelayerStart: preRelayerStartTimestampTimeout, Test: testPacketRelayFail, }, } @@ -137,6 +138,8 @@ func sendIBCTransfersFromBothChainsWithTimeout( channels []ibc.ChannelOutput, timeout *ibc.IBCTimeout, ) { + t.Helper() + srcChainCfg := srcChain.Config() srcUser := testCase.Users[0] @@ -225,15 +228,12 @@ func Test(t *testing.T, ctx context.Context, cfs []interchaintest.ChainFactory, if counts[2] { t.Run("chain pairs", func(t *testing.T) { for _, cf := range cfs { - cf := cf if cf.Count() != 2 { continue } t.Run(cf.Name(), func(t *testing.T) { for _, rf := range rfs { - rf := rf - t.Run(rf.Name(), func(t *testing.T) { // Record the labels for this nested test. rep.TrackTest(t) @@ -348,7 +348,6 @@ func TestChainPair( t.Run("post_relayer_start", func(t *testing.T) { for _, testCase := range testCases { - testCase := testCase t.Run(testCase.Config.Name, func(t *testing.T) { rep.TrackTest(t) requireCapabilities(t, rep, rf, testCase.Config.RequiredRelayerCapabilities...) @@ -361,25 +360,29 @@ func TestChainPair( // PreRelayerStart methods for the RelayerTestCases -func preRelayerStart_RelayPacket(ctx context.Context, t *testing.T, testCase *RelayerTestCase, srcChain ibc.Chain, dstChain ibc.Chain, channels []ibc.ChannelOutput) { +func preRelayerStartRelayPacket(ctx context.Context, t *testing.T, testCase *RelayerTestCase, srcChain ibc.Chain, dstChain ibc.Chain, channels []ibc.ChannelOutput) { + t.Helper() sendIBCTransfersFromBothChainsWithTimeout(ctx, t, testCase, srcChain, dstChain, channels, nil) } -func preRelayerStart_NoTimeout(ctx context.Context, t *testing.T, testCase *RelayerTestCase, srcChain ibc.Chain, dstChain ibc.Chain, channels []ibc.ChannelOutput) { +func preRelayerStartNoTimeout(ctx context.Context, t *testing.T, testCase *RelayerTestCase, srcChain ibc.Chain, dstChain ibc.Chain, channels []ibc.ChannelOutput) { + t.Helper() ibcTimeoutDisabled := ibc.IBCTimeout{Height: 0, NanoSeconds: 0} sendIBCTransfersFromBothChainsWithTimeout(ctx, t, testCase, srcChain, dstChain, channels, &ibcTimeoutDisabled) // TODO should we wait here to make sure it successfully relays a packet beyond the default timeout period? // would need to shorten the chain default timeouts somehow to make that a feasible test } -func preRelayerStart_HeightTimeout(ctx context.Context, t *testing.T, testCase *RelayerTestCase, srcChain ibc.Chain, dstChain ibc.Chain, channels []ibc.ChannelOutput) { +func preRelayerStartHeightTimeout(ctx context.Context, t *testing.T, testCase *RelayerTestCase, srcChain ibc.Chain, dstChain ibc.Chain, channels []ibc.ChannelOutput) { + t.Helper() ibcTimeoutHeight := ibc.IBCTimeout{Height: 10} sendIBCTransfersFromBothChainsWithTimeout(ctx, t, testCase, srcChain, dstChain, channels, &ibcTimeoutHeight) // wait for both chains to produce 15 blocks to expire timeout require.NoError(t, testutil.WaitForBlocks(ctx, 15, srcChain, dstChain), "failed to wait for blocks") } -func preRelayerStart_TimestampTimeout(ctx context.Context, t *testing.T, testCase *RelayerTestCase, srcChain ibc.Chain, dstChain ibc.Chain, channels []ibc.ChannelOutput) { +func preRelayerStartTimestampTimeout(ctx context.Context, t *testing.T, testCase *RelayerTestCase, srcChain ibc.Chain, dstChain ibc.Chain, channels []ibc.ChannelOutput) { + t.Helper() ibcTimeoutTimestamp := ibc.IBCTimeout{NanoSeconds: uint64((1 * time.Second).Nanoseconds())} sendIBCTransfersFromBothChainsWithTimeout(ctx, t, testCase, srcChain, dstChain, channels, &ibcTimeoutTimestamp) // wait for 15 seconds to expire timeout @@ -396,6 +399,8 @@ func testPacketRelaySuccess( dstChain ibc.Chain, channels []ibc.ChannelOutput, ) { + t.Helper() + req := require.New(rep.TestifyT(t)) srcChainCfg := srcChain.Config() @@ -480,6 +485,8 @@ func testPacketRelayFail( dstChain ibc.Chain, channels []ibc.ChannelOutput, ) { + t.Helper() + req := require.New(rep.TestifyT(t)) srcChainCfg := srcChain.Config() diff --git a/contract/cosmwasm/rust_optimizer.go b/contract/cosmwasm/rust_optimizer.go index 07a1c6fbc..3b4566a22 100644 --- a/contract/cosmwasm/rust_optimizer.go +++ b/contract/cosmwasm/rust_optimizer.go @@ -77,7 +77,7 @@ func (c *Contract) Compile() *Contract { // WaitForCompile will wait until compilation is complete, this can be called after chain setup // Successful compilation will return the binary location in a channel. func (c *Contract) WaitForCompile() (string, error) { - contractBinary := "" + var contractBinary string select { case err := <-c.errChan: return "", err diff --git a/dockerutil/container_lifecycle.go b/dockerutil/container_lifecycle.go index c1728affe..338447e01 100644 --- a/dockerutil/container_lifecycle.go +++ b/dockerutil/container_lifecycle.go @@ -16,11 +16,12 @@ import ( dockerclient "github.com/docker/docker/client" "github.com/docker/docker/errdefs" "github.com/docker/go-connections/nat" - "github.com/strangelove-ventures/interchaintest/v8/ibc" "go.uber.org/zap" + + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) -// Example Go/Cosmos-SDK panic format is `panic: bad Duration: time: invalid duration "bad"\n` +// Example Go/Cosmos-SDK panic format is `panic: bad Duration: time: invalid duration "bad"\n`. var panicRe = regexp.MustCompile(`panic:.*\n`) type ContainerLifecycle struct { @@ -158,7 +159,7 @@ func (c *ContainerLifecycle) CheckForFailedStart(ctx context.Context, wait time. if err := ParseSDKPanicFromText(logs.String()); err != nil { // Must use Println and not the logger as there are ascii escape codes in the logs. - fmt.Printf("\nContainer name: %s.\nerror: %s.\nlogs\n%s\n", c.containerName, err.Error(), logs.String()) + fmt.Printf("\nContainer name: %s.\nerror: %s.\nlogs\n%s\n", c.containerName, err.Error(), logs.String()) //nolint: forbidigo return fmt.Errorf("container %s failed to start: %w", c.containerName, err) } diff --git a/dockerutil/file.go b/dockerutil/file.go index d2e9e5b7e..bba0084ed 100644 --- a/dockerutil/file.go +++ b/dockerutil/file.go @@ -41,8 +41,10 @@ func CopyFile(src, dst string) (int64, error) { return nBytes, err } -func CopyCoverageFromContainer(ctx context.Context, t *testing.T, client *client.Client, containerId string, internalGoCoverDir string, extHostGoCoverDir string) { - r, _, err := client.CopyFromContainer(ctx, containerId, internalGoCoverDir) +func CopyCoverageFromContainer(ctx context.Context, t *testing.T, client *client.Client, containerID string, internalGoCoverDir string, extHostGoCoverDir string) { + t.Helper() + + r, _, err := client.CopyFromContainer(ctx, containerID, internalGoCoverDir) require.NoError(t, err) defer r.Close() @@ -58,7 +60,7 @@ func CopyCoverageFromContainer(ctx context.Context, t *testing.T, client *client require.NoError(t, err) var fileBuff bytes.Buffer - _, err = io.Copy(&fileBuff, tr) + _, err = io.Copy(&fileBuff, tr) //nolint: gosec require.NoError(t, err) name := hdr.Name diff --git a/dockerutil/fileretriever_test.go b/dockerutil/fileretriever_test.go index 0d1aa833e..594c083e3 100644 --- a/dockerutil/fileretriever_test.go +++ b/dockerutil/fileretriever_test.go @@ -5,10 +5,11 @@ import ( "testing" volumetypes "github.com/docker/docker/api/types/volume" - interchaintest "github.com/strangelove-ventures/interchaintest/v8" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/stretchr/testify/require" "go.uber.org/zap/zaptest" + + "github.com/strangelove-ventures/interchaintest/v8" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" ) func TestFileRetriever(t *testing.T) { @@ -58,12 +59,12 @@ func TestFileRetriever(t *testing.T) { t.Run("top-level file", func(t *testing.T) { b, err := fr.SingleFileContent(ctx, v.Name, "hello.txt") require.NoError(t, err) - require.Equal(t, string(b), "hello world") + require.Equal(t, "hello world", string(b)) }) t.Run("nested file", func(t *testing.T) { b, err := fr.SingleFileContent(ctx, v.Name, "foo/bar/baz.txt") require.NoError(t, err) - require.Equal(t, string(b), "test") + require.Equal(t, "test", string(b)) }) } diff --git a/dockerutil/filewriter_test.go b/dockerutil/filewriter_test.go index 43ab117ad..3f889028e 100644 --- a/dockerutil/filewriter_test.go +++ b/dockerutil/filewriter_test.go @@ -5,10 +5,11 @@ import ( "testing" volumetypes "github.com/docker/docker/api/types/volume" - interchaintest "github.com/strangelove-ventures/interchaintest/v8" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/stretchr/testify/require" "go.uber.org/zap/zaptest" + + "github.com/strangelove-ventures/interchaintest/v8" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" ) func TestFileWriter(t *testing.T) { @@ -48,7 +49,7 @@ func TestFileWriter(t *testing.T) { ) require.NoError(t, res.Err) - require.Equal(t, string(res.Stdout), "hello world") + require.Equal(t, "hello world", string(res.Stdout)) }) t.Run("create nested file", func(t *testing.T) { @@ -63,6 +64,6 @@ func TestFileWriter(t *testing.T) { ) require.NoError(t, err) - require.Equal(t, string(res.Stdout), ":D") + require.Equal(t, ":D", string(res.Stdout)) }) } diff --git a/dockerutil/keyring.go b/dockerutil/keyring.go index b6f287659..6b88f1395 100644 --- a/dockerutil/keyring.go +++ b/dockerutil/keyring.go @@ -19,8 +19,8 @@ import ( // NewLocalKeyringFromDockerContainer copies the contents of the given container directory into a specified local directory. // This allows test hosts to sign transactions on behalf of test users. -func NewLocalKeyringFromDockerContainer(ctx context.Context, dc *client.Client, localDirectory, containerKeyringDir, containerId string) (keyring.Keyring, error) { - reader, _, err := dc.CopyFromContainer(ctx, containerId, containerKeyringDir) +func NewLocalKeyringFromDockerContainer(ctx context.Context, dc *client.Client, localDirectory, containerKeyringDir, containerID string) (keyring.Keyring, error) { + reader, _, err := dc.CopyFromContainer(ctx, containerID, containerKeyringDir) if err != nil { return nil, err } @@ -39,7 +39,7 @@ func NewLocalKeyringFromDockerContainer(ctx context.Context, dc *client.Client, } var fileBuff bytes.Buffer - if _, err := io.Copy(&fileBuff, tr); err != nil { + if _, err := io.Copy(&fileBuff, tr); err != nil { //nolint: gosec return nil, err } diff --git a/dockerutil/setup_test.go b/dockerutil/setup_test.go index 84f7f8d00..95b78f32d 100644 --- a/dockerutil/setup_test.go +++ b/dockerutil/setup_test.go @@ -7,9 +7,10 @@ import ( volumetypes "github.com/docker/docker/api/types/volume" "github.com/docker/docker/errdefs" + "github.com/stretchr/testify/require" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/strangelove-ventures/interchaintest/v8/mocktesting" - "github.com/stretchr/testify/require" ) func TestDockerSetup_KeepVolumes(t *testing.T) { @@ -36,7 +37,6 @@ func TestDockerSetup_KeepVolumes(t *testing.T) { {keep: false, passed: true, volumeKept: false}, {keep: true, passed: true, volumeKept: false}, } { - tc := tc state := "failed" if tc.passed { state = "passed" diff --git a/dockerutil/volumeowner.go b/dockerutil/volumeowner.go index 6ebdabfb5..8432ab2a6 100644 --- a/dockerutil/volumeowner.go +++ b/dockerutil/volumeowner.go @@ -20,7 +20,7 @@ type VolumeOwnerOptions struct { VolumeName string ImageRef string TestName string - UidGid string + UidGid string //nolint: stylecheck } // SetVolumeOwner configures the owner of a volume to match the default user in the supplied image reference. diff --git a/examples/cosmos/bad_genesis_params_test.go b/examples/cosmos/bad_genesis_params_test.go index 274fd50d6..f39e83542 100644 --- a/examples/cosmos/bad_genesis_params_test.go +++ b/examples/cosmos/bad_genesis_params_test.go @@ -11,11 +11,9 @@ import ( "go.uber.org/zap/zaptest" ) -var ( - badGenesis = []cosmos.GenesisKV{ - cosmos.NewGenesisKV("app_state.gov.params.voting_period", "bad"), - } -) +var badGenesis = []cosmos.GenesisKV{ + cosmos.NewGenesisKV("app_state.gov.params.voting_period", "bad"), +} func TestBadInputParams(t *testing.T) { cf := interchaintest.NewBuiltinChainFactory(zaptest.NewLogger(t), []*interchaintest.ChainSpec{ diff --git a/examples/cosmos/code_coverage_test.go b/examples/cosmos/code_coverage_test.go index fd18d95a4..0a1181782 100644 --- a/examples/cosmos/code_coverage_test.go +++ b/examples/cosmos/code_coverage_test.go @@ -34,7 +34,7 @@ func TestCodeCoverage(t *testing.T) { { Repository: "ghcr.io/liftedinit/manifest-ledger", Version: "v0.0.1-alpha.10", - UidGid: "1025:1025", + UIDGID: "1025:1025", }, }, Bin: "manifestd", diff --git a/examples/cosmos/ethermint_test.go b/examples/cosmos/ethermint_test.go index 04012122d..2010c58d5 100644 --- a/examples/cosmos/ethermint_test.go +++ b/examples/cosmos/ethermint_test.go @@ -97,7 +97,7 @@ func TestEthermintChain(t *testing.T) { ChainConfig: ibc.ChainConfig{ Type: "cosmos", ChainID: "dymension_100-1", - Images: []ibc.DockerImage{{Repository: "ghcr.io/strangelove-ventures/heighliner/dymension", Version: "854ef84", UidGid: "1025:1025"}}, + Images: []ibc.DockerImage{{Repository: "ghcr.io/strangelove-ventures/heighliner/dymension", Version: "854ef84", UIDGID: "1025:1025"}}, Bin: "dymd", Bech32Prefix: wallet, Denom: denom, diff --git a/examples/cosmos/sdk_boundary_test.go b/examples/cosmos/sdk_boundary_test.go index 280fc3782..1d28bea8b 100644 --- a/examples/cosmos/sdk_boundary_test.go +++ b/examples/cosmos/sdk_boundary_test.go @@ -4,7 +4,7 @@ import ( "context" "testing" - interchaintest "github.com/strangelove-ventures/interchaintest/v8" + "github.com/strangelove-ventures/interchaintest/v8" "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" "github.com/strangelove-ventures/interchaintest/v8/conformance" "github.com/strangelove-ventures/interchaintest/v8/ibc" @@ -79,7 +79,7 @@ func TestSDKBoundaries(t *testing.T) { relayer.CustomDockerImage( rly.DefaultContainerImage, tt.relayerVersion, - rly.RlyDefaultUidGid, + rly.RlyDefaultUIDGID, ), ) diff --git a/examples/ethereum/foundry_test.go b/examples/ethereum/foundry_test.go index 12a38cca5..e6af00c44 100644 --- a/examples/ethereum/foundry_test.go +++ b/examples/ethereum/foundry_test.go @@ -18,7 +18,6 @@ import ( ) func TestFoundry(t *testing.T) { - if testing.Short() { t.Skip() } @@ -124,5 +123,4 @@ func TestFoundry(t *testing.T) { // Sleep for an additional testing time.Sleep(10 * time.Second) - } diff --git a/examples/ethereum/geth_test.go b/examples/ethereum/geth_test.go index e3232fdc0..9e3e53e84 100644 --- a/examples/ethereum/geth_test.go +++ b/examples/ethereum/geth_test.go @@ -2,7 +2,6 @@ package ethereum_test import ( "context" - "fmt" "strings" "testing" @@ -19,7 +18,6 @@ import ( ) func TestGeth(t *testing.T) { - if testing.Short() { t.Skip() } diff --git a/examples/hyperspace/hyperspace_test.go b/examples/hyperspace/hyperspace_test.go index 3e08fc1f2..78b0a5fb7 100644 --- a/examples/hyperspace/hyperspace_test.go +++ b/examples/hyperspace/hyperspace_test.go @@ -114,12 +114,12 @@ func TestHyperspace(t *testing.T) { { Repository: "polkadot-node", Version: "local", // Set your locally built version - UidGid: "1000:1000", + UIDGID: "1000:1000", }, { Repository: "parachain-node", Version: "latest", // Set your locally built version - UidGid: "1000:1000", + UIDGID: "1000:1000", }, }, Bin: "polkadot", @@ -143,7 +143,7 @@ func TestHyperspace(t *testing.T) { { Repository: "ibc-go-simd", Version: "local", // Set your locally built version - UidGid: "1025:1025", + UIDGID: "1025:1025", }, }, Bin: "simd", diff --git a/examples/ibc/wasm/wasm_icq_test.go b/examples/ibc/wasm/wasm_icq_test.go index 2e8bdccbe..9bb33ad5b 100644 --- a/examples/ibc/wasm/wasm_icq_test.go +++ b/examples/ibc/wasm/wasm_icq_test.go @@ -51,7 +51,7 @@ func TestInterchainQueriesWASM(t *testing.T) { wasmImage := ibc.DockerImage{ Repository: "ghcr.io/strangelove-ventures/heighliner/wasmd", Version: "v0.0.1", - UidGid: dockerutil.GetHeighlinerUserString(), + UIDGID: dockerutil.GetHeighlinerUserString(), } genesisAllowICQ := map[string]interface{}{ diff --git a/examples/penumbra/penumbra_ibc_test.go b/examples/penumbra/penumbra_ibc_test.go index 366ea6e88..1a7196bda 100644 --- a/examples/penumbra/penumbra_ibc_test.go +++ b/examples/penumbra/penumbra_ibc_test.go @@ -63,7 +63,7 @@ func TestPenumbraToPenumbraIBC(t *testing.T) { i := ibc.DockerImage{ Repository: "ghcr.io/cosmos/relayer", Version: "justin-pen-0.77", - UidGid: "1025:1025", + UIDGID: "1025:1025", } r := interchaintest.NewBuiltinRelayerFactory( ibc.CosmosRly, @@ -280,7 +280,7 @@ func TestPenumbraToCosmosIBC(t *testing.T) { image := ibc.DockerImage{ Repository: "ghcr.io/cosmos/ibc-go-simd", Version: "v8.3.2", - UidGid: "100:1000", + UIDGID: "100:1000", } chains, err := interchaintest.NewBuiltinChainFactory(zaptest.NewLogger(t), []*interchaintest.ChainSpec{ @@ -323,7 +323,7 @@ func TestPenumbraToCosmosIBC(t *testing.T) { i := ibc.DockerImage{ Repository: "ghcr.io/cosmos/relayer", Version: "justin-proto-update", - UidGid: "1025:1025", + UIDGID: "1025:1025", } r := interchaintest.NewBuiltinRelayerFactory( ibc.CosmosRly, diff --git a/examples/polkadot/polkadot_chain_test.go b/examples/polkadot/polkadot_chain_test.go index 689f3d7e2..2d7baa6d9 100644 --- a/examples/polkadot/polkadot_chain_test.go +++ b/examples/polkadot/polkadot_chain_test.go @@ -42,12 +42,12 @@ func TestPolkadotComposableChainStart(t *testing.T) { { Repository: "seunlanlege/centauri-polkadot", Version: "v0.9.27", - UidGid: "1000:1000", + UIDGID: "1000:1000", }, { Repository: "seunlanlege/centauri-parachain", Version: "v0.9.27", - UidGid: "1025:1025", + UIDGID: "1025:1025", }, }, Bin: "polkadot", diff --git a/examples/polkadot/push_wasm_client_code_test.go b/examples/polkadot/push_wasm_client_code_test.go index 8134ac0f8..0f2647c45 100644 --- a/examples/polkadot/push_wasm_client_code_test.go +++ b/examples/polkadot/push_wasm_client_code_test.go @@ -74,7 +74,7 @@ func TestPushWasmClientCode(t *testing.T) { { Repository: "ghcr.io/strangelove-ventures/heighliner/ibc-go-simd", Version: "feat-wasm-clients", - UidGid: "1025:1025", + UIDGID: "1025:1025", }, }, Bin: "simd", diff --git a/examples/polkadot/substrate_cosmos_ibc_test.go b/examples/polkadot/substrate_cosmos_ibc_test.go index 6f6c0bde9..4a733188a 100644 --- a/examples/polkadot/substrate_cosmos_ibc_test.go +++ b/examples/polkadot/substrate_cosmos_ibc_test.go @@ -48,12 +48,12 @@ func TestSubstrateToCosmosIBC(t *testing.T) { { Repository: "seunlanlege/centauri-polkadot", Version: "v0.9.27", - UidGid: "1025:1025", + UIDGID: "1025:1025", }, { Repository: "seunlanlege/centauri-parachain", Version: "v0.9.27", - UidGid: "1025:1025", + UIDGID: "1025:1025", }, }, Bin: "polkadot", @@ -75,7 +75,7 @@ func TestSubstrateToCosmosIBC(t *testing.T) { { Repository: "ibc-go-simd", Version: "feat-wasm-client", - UidGid: "1025:1025", + UIDGID: "1025:1025", }, }, Bin: "simd", @@ -118,13 +118,13 @@ func TestSubstrateToCosmosIBC(t *testing.T) { ic := interchaintest.NewInterchain(). AddChain(composable). AddChain(simd) //. - //AddRelayer(r, relayerName). - /*AddLink(interchaintest.InterchainLink{ - Chain1: composable, - Chain2: simd, - Relayer: r, - Path: pathName, - })*/ + //AddRelayer(r, relayerName). + /*AddLink(interchaintest.InterchainLink{ + Chain1: composable, + Chain2: simd, + Relayer: r, + Path: pathName, + })*/ require.NoError(t, ic.Build(ctx, eRep, interchaintest.InterchainBuildOptions{ TestName: t.Name(), diff --git a/examples/thorchain/chainspec_thorchain_test.go b/examples/thorchain/chainspec_thorchain_test.go index 4398e269e..8825ef79b 100644 --- a/examples/thorchain/chainspec_thorchain_test.go +++ b/examples/thorchain/chainspec_thorchain_test.go @@ -31,7 +31,7 @@ func ThorchainDefaultChainSpec(testName string, numVals int, numFn int, ethRoute chainImage := ibc.NewDockerImage("thorchain", "local", "1025:1025") genesisKVMods := []thorchain.GenesisKV{ thorchain.NewGenesisKV("app_state.bank.params.default_send_enabled", true), // disable bank module transfers - thorchain.NewGenesisKV("app_state.thorchain.reserve", "22000000000000000"), // mint to reserve for mocknet (220M) + thorchain.NewGenesisKV("app_state.thorchain.reserve", "22000000000000000"), // mint to reserve for mocknet (220M) thorchain.NewGenesisKV("app_state.thorchain.chain_contracts", []ChainContract{ { Chain: "ETH", @@ -95,7 +95,7 @@ func ThorchainDefaultChainSpec(testName string, numVals int, numFn int, ethRoute Image: chainImage, HomeDir: "/var/data/bifrost", Ports: []string{"5040", "6040", "9000"}, - //StartCmd: []string{"bifrost", "-p"}, + // StartCmd: []string{"bifrost", "-p"}, StartCmd: []string{"bifrost", "-p", "-l", "debug"}, Env: bifrostEnv, PreStart: false, diff --git a/examples/thorchain/features/arb.go b/examples/thorchain/features/arb.go index c75d5b766..f9665e3f8 100644 --- a/examples/thorchain/features/arb.go +++ b/examples/thorchain/features/arb.go @@ -21,7 +21,6 @@ func Arb( thorchain *tc.Thorchain, exoChains ...ibc.Chain, ) (users []ibc.Wallet, err error) { - fmt.Println("#### Arb") chains := append(exoChains, thorchain) users, err = GetAndFundTestUsers(t, ctx, "arb", chains...) if err != nil { @@ -33,7 +32,7 @@ func Arb( return users, err } - mimirs, err := thorchain.ApiGetMimirs() + mimirs, err := thorchain.APIGetMimirs(ctx) if err != nil { return users, err } @@ -49,8 +48,6 @@ func Arb( var eg errgroup.Group for i, exoChain := range exoChains { - i := i - exoChain := exoChain eg.Go(func() error { exoChainType, err := common.NewChain(exoChain.Config().Name) if err != nil { @@ -65,7 +62,7 @@ func Arb( } memo := fmt.Sprintf("trade+:%s", thorUser.FormattedAddress()) - exoInboundAddr, _, err := thorchain.ApiGetInboundAddress(exoChainType.String()) + exoInboundAddr, _, err := thorchain.APIGetInboundAddress(ctx, exoChainType.String()) if err != nil { return err } @@ -91,7 +88,7 @@ func Arb( maxBasisPts := uint64(10_000) for { - pools, err := thorchain.ApiGetPools() + pools, err := thorchain.APIGetPools(ctx) if err != nil { fmt.Println("Error getting arb api pools", err) time.Sleep(time.Second * 2) diff --git a/examples/thorchain/features/dual_lper.go b/examples/thorchain/features/dual_lper.go index c418c5e4b..1ff32c038 100644 --- a/examples/thorchain/features/dual_lper.go +++ b/examples/thorchain/features/dual_lper.go @@ -44,7 +44,7 @@ func DualLp( return thorUser, exoUser, fmt.Errorf("duallp, exo balance (%s), %w", exoChain.Config().Name, err) } memo = fmt.Sprintf("+:%s:%s", exoAsset, thorUser.FormattedAddress()) - exoInboundAddr, _, err := thorchain.ApiGetInboundAddress(exoChainType.String()) + exoInboundAddr, _, err := thorchain.APIGetInboundAddress(ctx, exoChainType.String()) if err != nil { return thorUser, exoUser, fmt.Errorf("duallp, inbound addr (%s), %w", exoChain.Config().Name, err) } diff --git a/examples/thorchain/features/helpers.go b/examples/thorchain/features/helpers.go index 971250e2f..e5b949e14 100644 --- a/examples/thorchain/features/helpers.go +++ b/examples/thorchain/features/helpers.go @@ -66,7 +66,7 @@ func PollForPool(ctx context.Context, thorchain *tc.Thorchain, deltaBlocks int64 return fmt.Errorf("failed to get height: %w", err) } doPoll := func(ctx context.Context, height int64) (any, error) { - pool, err := thorchain.ApiGetPool(asset) + pool, err := thorchain.APIGetPool(ctx, asset) if err != nil { time.Sleep(time.Second) // rate limit return nil, err @@ -91,7 +91,7 @@ func PollForSaver(ctx context.Context, thorchain *tc.Thorchain, deltaBlocks int6 return tc.Saver{}, fmt.Errorf("failed to get height: %w", err) } doPoll := func(ctx context.Context, height int64) (tc.Saver, error) { - savers, err := thorchain.ApiGetSavers(asset) + savers, err := thorchain.APIGetSavers(ctx, asset) if err != nil { time.Sleep(time.Second) // rate limit return tc.Saver{}, err @@ -117,7 +117,7 @@ func PollForEjectedSaver(ctx context.Context, thorchain *tc.Thorchain, deltaBloc return tc.Saver{}, fmt.Errorf("failed to get height: %w", err) } doPoll := func(ctx context.Context, height int64) (tc.Saver, error) { - savers, err := thorchain.ApiGetSavers(asset) + savers, err := thorchain.APIGetSavers(ctx, asset) if err != nil { time.Sleep(time.Second) // rate limit return tc.Saver{}, err @@ -143,7 +143,7 @@ func PollSwapCompleted(ctx context.Context, thorchain *tc.Thorchain, deltaBlocks return tc.Saver{}, fmt.Errorf("failed to get height: %w", err) } doPoll := func(ctx context.Context, height int64) (any, error) { - stages, err := thorchain.ApiGetTxStages(txHash) + stages, err := thorchain.APIGetTxStages(ctx, txHash) if err != nil { time.Sleep(time.Second) // rate limit return nil, err @@ -167,7 +167,7 @@ func PollOutboundSigned(ctx context.Context, thorchain *tc.Thorchain, deltaBlock return tc.Saver{}, fmt.Errorf("failed to get height: %w", err) } doPoll := func(ctx context.Context, height int64) (any, error) { - stages, err := thorchain.ApiGetTxStages(txHash) + stages, err := thorchain.APIGetTxStages(ctx, txHash) if err != nil { time.Sleep(time.Second) // rate limit return nil, err @@ -215,7 +215,7 @@ func PollForPoolSuspended(ctx context.Context, thorchain *tc.Thorchain, deltaBlo return fmt.Errorf("failed to get height: %w", err) } doPoll := func(ctx context.Context, height int64) (any, error) { - pool, err := thorchain.ApiGetPool(exoAsset) + pool, err := thorchain.APIGetPool(ctx, exoAsset) if err != nil { time.Sleep(time.Second) // rate limit return nil, err diff --git a/examples/thorchain/features/ragnarok.go b/examples/thorchain/features/ragnarok.go index 5268ca4dc..3a46eccae 100644 --- a/examples/thorchain/features/ragnarok.go +++ b/examples/thorchain/features/ragnarok.go @@ -29,7 +29,7 @@ func Ragnarok( } exoAsset := exoChainType.GetGasAsset() - _, err = thorchain.ApiGetPool(exoAsset) + _, err = thorchain.APIGetPool(ctx, exoAsset) if err != nil { return fmt.Errorf("pool (%s) not found to ragnarok, %w", exoChain.Config().Name, err) } diff --git a/examples/thorchain/features/saver_eject.go b/examples/thorchain/features/saver_eject.go index e6c6245c0..20ba3dfb3 100644 --- a/examples/thorchain/features/saver_eject.go +++ b/examples/thorchain/features/saver_eject.go @@ -36,7 +36,7 @@ func SaverEject( // Reset mimirs mimirLock.Lock() - mimirs, err := thorchain.ApiGetMimirs() + mimirs, err := thorchain.APIGetMimirs(ctx) if err != nil { mimirLock.Unlock() return exoUser, err @@ -65,7 +65,7 @@ func SaverEject( } exoAsset := exoChainType.GetGasAsset() - pool, err := thorchain.ApiGetPool(exoAsset) + pool, err := thorchain.APIGetPool(ctx, exoAsset) if err != nil { mimirLock.Unlock() return exoUser, err @@ -73,7 +73,7 @@ func SaverEject( saveAmount := sdkmath.NewUintFromString(pool.BalanceAsset). MulUint64(2000).QuoUint64(10_000) - saverQuote, err := thorchain.ApiGetSaverDepositQuote(exoAsset, saveAmount) + saverQuote, err := thorchain.APIGetSaverDepositQuote(ctx, exoAsset, saveAmount) if err != nil { mimirLock.Unlock() return exoUser, err @@ -95,7 +95,7 @@ func SaverEject( memo = fmt.Sprintf("+:%s", exoAsset.GetSyntheticAsset()) } - exoInboundAddr, _, err := thorchain.ApiGetInboundAddress(exoChainType.String()) + exoInboundAddr, _, err := thorchain.APIGetInboundAddress(ctx, exoChainType.String()) if err != nil { mimirLock.Unlock() return exoUser, err @@ -150,7 +150,7 @@ func SaverEject( } } - mimirs, err = thorchain.ApiGetMimirs() + mimirs, err = thorchain.APIGetMimirs(ctx) if err != nil { mimirLock.Unlock() return exoUser, err diff --git a/examples/thorchain/features/savers.go b/examples/thorchain/features/savers.go index 5e11ee759..4bfe8185e 100644 --- a/examples/thorchain/features/savers.go +++ b/examples/thorchain/features/savers.go @@ -32,14 +32,14 @@ func Saver( } exoAsset := exoChainType.GetGasAsset() - pool, err := thorchain.ApiGetPool(exoAsset) + pool, err := thorchain.APIGetPool(ctx, exoAsset) if err != nil { return exoUser, err } saveAmount := sdkmath.NewUintFromString(pool.BalanceAsset). MulUint64(500).QuoUint64(10_000) - saverQuote, err := thorchain.ApiGetSaverDepositQuote(exoAsset, saveAmount) + saverQuote, err := thorchain.APIGetSaverDepositQuote(ctx, exoAsset, saveAmount) if err != nil { return exoUser, err } @@ -60,7 +60,7 @@ func Saver( memo = fmt.Sprintf("+:%s", exoAsset.GetSyntheticAsset()) } - exoInboundAddr, _, err := thorchain.ApiGetInboundAddress(exoChainType.String()) + exoInboundAddr, _, err := thorchain.APIGetInboundAddress(ctx, exoChainType.String()) if err != nil { return exoUser, err } diff --git a/examples/thorchain/features/swap.go b/examples/thorchain/features/swap.go index a31393fc7..9e00a1770 100644 --- a/examples/thorchain/features/swap.go +++ b/examples/thorchain/features/swap.go @@ -71,13 +71,13 @@ func singleSwap( srcChainAsset := srcChainType.GetGasAsset() destChainAsset := destChainType.GetGasAsset() - pool, err := thorchain.ApiGetPool(srcChainAsset) + pool, err := thorchain.APIGetPool(ctx, srcChainAsset) if err != nil { return fmt.Errorf("getting srcChain pool, %w", err) } swapAmount := sdkmath.NewUintFromString(pool.BalanceAsset).QuoUint64(200) - swapQuote, err := thorchain.ApiGetSwapQuote(srcChainAsset, destChainAsset, swapAmount) + swapQuote, err := thorchain.APIGetSwapQuote(ctx, srcChainAsset, destChainAsset, swapAmount) if err != nil { return fmt.Errorf("get swap quote, %w", err) } @@ -104,7 +104,7 @@ func singleSwap( return err } - srcChainInboundAddr, _, err := thorchain.ApiGetInboundAddress(srcChainType.String()) + srcChainInboundAddr, _, err := thorchain.APIGetInboundAddress(ctx, srcChainType.String()) if err != nil { return fmt.Errorf("get srcChain inbound address: %w", err) } @@ -138,7 +138,7 @@ func singleSwap( } } - details, err := thorchain.ApiGetTxDetails(txHash) + details, err := thorchain.APIGetTxDetails(ctx, txHash) if err != nil { return err } @@ -160,7 +160,7 @@ func singleSwap( outAmountPlusMaxGas = outAmountPlusMaxGas.Add(sdkmath.NewUintFromString(maxGas.Amount)) } else { // shouldn't enter here for atom -> rune var maxGasAssetValue sdkmath.Uint - maxGasAssetValue, err = thorchain.ConvertAssetAmount(maxGas, destChainAsset.String()) + maxGasAssetValue, err = thorchain.ConvertAssetAmount(ctx, maxGas, destChainAsset.String()) if err != nil { return fmt.Errorf("failed to convert asset, %w", err) } diff --git a/examples/thorchain/helper_test.go b/examples/thorchain/helper_test.go index be897a7b6..208fb0487 100644 --- a/examples/thorchain/helper_test.go +++ b/examples/thorchain/helper_test.go @@ -5,7 +5,7 @@ import ( "fmt" "regexp" "time" - + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) @@ -31,7 +31,7 @@ func NiceWaitForBlocks(ctx context.Context, delta int64, chain ibc.Chain) error } currentHeight := startingHeight - for ; currentHeight < startingHeight + delta; { + for currentHeight < startingHeight+delta { time.Sleep(time.Millisecond * 200) currentHeight, err = chain.Height(ctx) if err != nil { diff --git a/examples/thorchain/setup_test.go b/examples/thorchain/setup_test.go index 2353e4963..790fcc145 100644 --- a/examples/thorchain/setup_test.go +++ b/examples/thorchain/setup_test.go @@ -34,7 +34,7 @@ import ( func StartExoChains(t *testing.T, ctx context.Context, client *client.Client, network string) ExoChains { chainSpecs := []*interchaintest.ChainSpec{ EthChainSpec("geth"), // only use this chain spec for eth or the one below - //EthChainSpec("anvil"), + // EthChainSpec("anvil"), GaiaChainSpec(), BtcChainSpec(), BchChainSpec(), @@ -164,7 +164,7 @@ func SetupContracts(ctx context.Context, ethExoChain *ExoChain, bscExoChain *Exo if ethExoChain.chain.Config().Bin == "geth" { ethContractAddr, err = SetupGethContracts(egCtx, ethExoChain) } else { - ethContractAddr, err = SetupAnvilContracts(egCtx, ethExoChain) + ethContractAddr, err = SetupAnvilContracts(egCtx, ethExoChain) } return err }) @@ -173,7 +173,7 @@ func SetupContracts(ctx context.Context, ethExoChain *ExoChain, bscExoChain *Exo bscContractAddr, err = SetupGethContracts(egCtx, bscExoChain) return err }) - + return ethContractAddr, bscContractAddr, eg.Wait() } diff --git a/ibc/packet_test.go b/ibc/packet_test.go index 57aabfce4..991321b36 100644 --- a/ibc/packet_test.go +++ b/ibc/packet_test.go @@ -109,9 +109,6 @@ func TestPacket_Equal(t *testing.T) { } { require.Equal(t, tt.WantEqual, tt.Left.Equal(tt.Right), tt) require.Equal(t, tt.WantEqual, tt.Right.Equal(tt.Left), tt) - - require.True(t, tt.Left.Equal(tt.Left)) - require.True(t, tt.Right.Equal(tt.Right)) } } diff --git a/ibc/relayer.go b/ibc/relayer.go index ac337ba1c..553077fa4 100644 --- a/ibc/relayer.go +++ b/ibc/relayer.go @@ -171,11 +171,13 @@ func GetTransferChannel(ctx context.Context, r Relayer, rep RelayerExecReporter, var srcChan *ChannelOutput for _, channel := range srcChannels { - if len(channel.ConnectionHops) == 1 && channel.ConnectionHops[0] == srcConnectionID && channel.PortID == "transfer" { + ch := channel + + if len(ch.ConnectionHops) == 1 && ch.ConnectionHops[0] == srcConnectionID && ch.PortID == "transfer" { if srcChan != nil { return nil, fmt.Errorf("found multiple transfer channels on %s for connection %s", srcChainID, srcConnectionID) } - srcChan = &channel + srcChan = &ch } } @@ -261,6 +263,8 @@ func (o Order) String() string { return "unordered" case Ordered: return "ordered" + case Invalid: + return "invalid" default: return "invalid" } diff --git a/ibc/types.go b/ibc/types.go index 2524c5cd6..d01170bf8 100644 --- a/ibc/types.go +++ b/ibc/types.go @@ -21,6 +21,18 @@ import ( "github.com/cosmos/cosmos-sdk/types/module/testutil" ) +// Chain type constant values, used to determine if a ChainConfig is of a certain type. +const ( + Polkadot = "polkadot" + Parachain = "parachain" + RelayChain = "relaychain" + Cosmos = "cosmos" + Penumbra = "penumbra" + Ethereum = "ethereum" + Thorchain = "thorchain" + UTXO = "utxo" +) + // ChainConfig defines the chain parameters requires to run an interchaintest testnet for a chain. type ChainConfig struct { // Chain type, e.g. cosmos. @@ -294,7 +306,7 @@ type SidecarConfig struct { type DockerImage struct { Repository string `json:"repository" yaml:"repository"` Version string `json:"version" yaml:"version"` - UidGid string `json:"uid-gid" yaml:"uid-gid"` + UIDGID string `json:"uid-gid" yaml:"uid-gid"` } type CometMockConfig struct { @@ -302,11 +314,11 @@ type CometMockConfig struct { BlockTimeMs int `yaml:"block-time"` } -func NewDockerImage(repository, version, uidGid string) DockerImage { +func NewDockerImage(repository, version, uidGID string) DockerImage { return DockerImage{ Repository: repository, Version: version, - UidGid: uidGid, + UIDGID: uidGID, } } @@ -325,7 +337,7 @@ func (i DockerImage) Validate() error { if i.Repository == "" { missing = append(missing, "Repository") } - if i.UidGid == "" { + if i.UIDGID == "" { missing = append(missing, "UidGid") } diff --git a/interchain.go b/interchain.go index b6ef8a1b0..8cca04eaa 100644 --- a/interchain.go +++ b/interchain.go @@ -6,13 +6,14 @@ import ( "math" "github.com/docker/docker/client" - "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testreporter" "go.uber.org/zap" "golang.org/x/sync/errgroup" sdkmath "cosmossdk.io/math" + + "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testreporter" ) // Interchain represents a full IBC network, encompassing a collection of @@ -366,8 +367,6 @@ func (ic *Interchain) Build(ctx context.Context, rep *testreporter.RelayerExecRe // For every relayer link, teach the relayer about the link and create the link. for rp, link := range ic.links { - rp := rp - link := link c0 := link.chains[0] c1 := link.chains[1] @@ -381,8 +380,6 @@ func (ic *Interchain) Build(ctx context.Context, rep *testreporter.RelayerExecRe // For every provider consumer link, teach the relayer about the link and create the link. for rp, link := range ic.providerConsumerLinks { - rp := rp - link := link p := link.provider c := link.consumer @@ -399,8 +396,6 @@ func (ic *Interchain) Build(ctx context.Context, rep *testreporter.RelayerExecRe // Now link the paths in parallel // Creates clients, connections, and channels for each link/path. for rp, link := range ic.providerConsumerLinks { - rp := rp - link := link p := link.provider c := link.consumer eg.Go(func() error { @@ -509,8 +504,6 @@ func (ic *Interchain) Build(ctx context.Context, rep *testreporter.RelayerExecRe // Now link the paths in parallel // Creates clients, connections, and channels for each link/path. for rp, link := range ic.links { - rp := rp - link := link c0 := link.chains[0] c1 := link.chains[1] eg.Go(func() error { diff --git a/interchain_builder.go b/interchain_builder.go index 31c6f539b..493f6f1fb 100644 --- a/interchain_builder.go +++ b/interchain_builder.go @@ -5,15 +5,16 @@ import ( "testing" "github.com/docker/docker/client" - "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/relayer" - "github.com/strangelove-ventures/interchaintest/v8/testreporter" "github.com/stretchr/testify/require" "go.uber.org/zap/zaptest" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types/module/testutil" + + "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/relayer" + "github.com/strangelove-ventures/interchaintest/v8/testreporter" ) type codecRegistry func(registry codectypes.InterfaceRegistry) @@ -29,6 +30,8 @@ func RegisterInterfaces(codecIR ...codecRegistry) *testutil.TestEncodingConfig { // CreateChainWithConfig builds a single chain from the given ibc config. func CreateChainWithConfig(t *testing.T, numVals, numFull int, name, version string, config ibc.ChainConfig) []ibc.Chain { + t.Helper() + if version == "" { if len(config.Images) == 0 { version = "latest" @@ -57,6 +60,8 @@ func CreateChainWithConfig(t *testing.T, numVals, numFull int, name, version str // CreateChainsWithChainSpecs builds multiple chains from the given chain specs. func CreateChainsWithChainSpecs(t *testing.T, chainSpecs []*ChainSpec) []ibc.Chain { + t.Helper() + cf := NewBuiltinChainFactory(zaptest.NewLogger(t), chainSpecs) chains, err := cf.Chains(t.Name()) @@ -74,6 +79,8 @@ func BuildInitialChainWithRelayer( links []InterchainLink, skipPathCreations bool, ) (context.Context, *Interchain, ibc.Relayer, *testreporter.Reporter, *testreporter.RelayerExecReporter, *client.Client, string) { + t.Helper() + ctx := context.Background() rep := testreporter.NewNopReporter() eRep := rep.RelayerExecReporter(t) @@ -128,6 +135,7 @@ func BuildInitialChainWithRelayer( } func BuildInitialChain(t *testing.T, chains []ibc.Chain, enableBlockDB bool) (context.Context, *Interchain, *client.Client, string) { + t.Helper() ctx, ic, _, _, _, client, network := BuildInitialChainWithRelayer(t, chains, enableBlockDB, 0, nil, nil, true) return ctx, ic, client, network } diff --git a/interchain_test.go b/interchain_test.go index a6ceadca4..923ec8b64 100644 --- a/interchain_test.go +++ b/interchain_test.go @@ -6,12 +6,6 @@ import ( "testing" "time" - "github.com/strangelove-ventures/interchaintest/v8" - "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/relayer/rly" - "github.com/strangelove-ventures/interchaintest/v8/testreporter" - "github.com/strangelove-ventures/interchaintest/v8/testutil" "github.com/stretchr/testify/require" "go.uber.org/zap" "go.uber.org/zap/zaptest" @@ -27,6 +21,13 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/strangelove-ventures/interchaintest/v8" + "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/relayer/rly" + "github.com/strangelove-ventures/interchaintest/v8/testreporter" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) func TestInterchain_DuplicateChain_CosmosRly(t *testing.T) { @@ -38,6 +39,8 @@ func TestInterchain_DuplicateChain_HermesRelayer(t *testing.T) { } func duplicateChainTest(t *testing.T, relayerImpl ibc.RelayerImplementation) { + t.Helper() + if testing.Short() { t.Skip("skipping in short mode") } @@ -85,15 +88,17 @@ func duplicateChainTest(t *testing.T, relayerImpl ibc.RelayerImplementation) { _ = ic.Close() } -func TestInterchain_GetRelayerWallets_CosmosRly(t *testing.T) { +func TestInterchain_GetRelayerWallets_CosmosRly(t *testing.T) { //nolint:tparallel getRelayerWalletsTest(t, ibc.CosmosRly) } -func TestInterchain_GetRelayerWallets_HermesRelayer(t *testing.T) { +func TestInterchain_GetRelayerWallets_HermesRelayer(t *testing.T) { //nolint:tparallel getRelayerWalletsTest(t, ibc.Hermes) } func getRelayerWalletsTest(t *testing.T, relayerImpl ibc.RelayerImplementation) { + t.Helper() + if testing.Short() { t.Skip("skipping in short mode") } @@ -250,11 +255,11 @@ func TestInterchain_CreateUser(t *testing.T) { }) } -func TestCosmosChain_BroadcastTx_CosmosRly(t *testing.T) { +func TestCosmosChain_BroadcastTx_CosmosRly(t *testing.T) { //nolint:tparallel broadcastTxCosmosChainTest(t, ibc.CosmosRly) } -func TestCosmosChain_BroadcastTx_HermesRelayer(t *testing.T) { +func TestCosmosChain_BroadcastTx_HermesRelayer(t *testing.T) { //nolint:tparallel broadcastTxCosmosChainTest(t, ibc.Hermes) } @@ -284,7 +289,6 @@ func TestInterchain_ConcurrentRelayerOps(t *testing.T) { numValidators := 1 for _, rly := range relayers { - rly := rly t.Run(rly.name, func(t *testing.T) { client, network := interchaintest.DockerSetup(t) f, err := interchaintest.CreateLogFile(fmt.Sprintf("%d.json", time.Now().Unix())) @@ -349,6 +353,8 @@ func getIBCPath(chainA, chainB ibc.Chain) string { } func broadcastTxCosmosChainTest(t *testing.T, relayerImpl ibc.RelayerImplementation) { + t.Helper() + if testing.Short() { t.Skip("skipping in short mode") } @@ -546,6 +552,8 @@ func TestInterchain_AddNil(t *testing.T) { } func assertTransactionIsValid(t *testing.T, resp sdk.TxResponse) { + t.Helper() + require.NotNil(t, resp) require.NotEqual(t, 0, resp.GasUsed) require.NotEqual(t, 0, resp.GasWanted) diff --git a/local-interchain/cmd/local-ic/new_chain.go b/local-interchain/cmd/local-ic/new_chain.go index 37f53e521..e428ea456 100644 --- a/local-interchain/cmd/local-ic/new_chain.go +++ b/local-interchain/cmd/local-ic/new_chain.go @@ -56,7 +56,7 @@ var newChainCmd = &cobra.Command{ c.SetDockerImage(ibc.DockerImage{ Repository: getOrDefault("Docker Repo", "ghcr.io/strangelove-ventures/heighliner/gaia"), Version: getOrDefault("Docker Tag / Branch Version", "v16.0.0"), - UidGid: "1025:1025", + UIDGID: "1025:1025", }) if i == 0 { c.SetHostPortOverride(types.BaseHostPortOverride()) diff --git a/local-interchain/cmd/local-ic/start_chain.go b/local-interchain/cmd/local-ic/start_chain.go index d45906702..075deb110 100644 --- a/local-interchain/cmd/local-ic/start_chain.go +++ b/local-interchain/cmd/local-ic/start_chain.go @@ -88,7 +88,7 @@ local-ic start https://pastebin.com/raw/Ummk4DTM DockerImage: ibc.DockerImage{ Repository: relayerImg, Version: relayerVer, - UidGid: relayerUidGid, + UIDGID: relayerUidGid, }, StartupFlags: relayerFlags, }, diff --git a/local-interchain/interchain/config.go b/local-interchain/interchain/config.go index 1cd683f85..4b5b685d4 100644 --- a/local-interchain/interchain/config.go +++ b/local-interchain/interchain/config.go @@ -212,7 +212,7 @@ func CreateChainConfigs(cfg types.Chain) (ibc.ChainConfig, *interchaintest.Chain { Repository: cfg.DockerImage.Repository, Version: cfg.DockerImage.Version, - UidGid: cfg.DockerImage.UidGid, + UIDGID: cfg.DockerImage.UIDGID, }, } } diff --git a/local-interchain/interchain/start.go b/local-interchain/interchain/start.go index e5c060ee3..68d321ef6 100644 --- a/local-interchain/interchain/start.go +++ b/local-interchain/interchain/start.go @@ -127,7 +127,7 @@ func StartChain(installDir, chainCfgFile string, ac *types.AppStartConfig) { interchaintestrelayer.CustomDockerImage( rlyCfg.DockerImage.Repository, rlyCfg.DockerImage.Version, - rlyCfg.DockerImage.UidGid, + rlyCfg.DockerImage.UIDGID, ), interchaintestrelayer.StartupFlags(rlyCfg.StartupFlags...), ) diff --git a/local-interchain/interchain/types/types.go b/local-interchain/interchain/types/types.go index 579a42e90..cbbc4f371 100644 --- a/local-interchain/interchain/types/types.go +++ b/local-interchain/interchain/types/types.go @@ -86,8 +86,8 @@ func (chain *Chain) SetChainDefaults() { chain.CoinType = 118 } - if chain.DockerImage.UidGid == "" { - chain.DockerImage.UidGid = "1025:1025" + if chain.DockerImage.UIDGID == "" { + chain.DockerImage.UIDGID = "1025:1025" } if chain.NumberVals == 0 { diff --git a/mocktesting/t_test.go b/mocktesting/t_test.go index 3f0bdba41..e10516a38 100644 --- a/mocktesting/t_test.go +++ b/mocktesting/t_test.go @@ -4,13 +4,14 @@ import ( "testing" "time" - "github.com/strangelove-ventures/interchaintest/v8/mocktesting" "github.com/stretchr/testify/require" + + "github.com/strangelove-ventures/interchaintest/v8/mocktesting" ) func TestT_Name(t *testing.T) { mt := mocktesting.NewT("foo") - require.Equal(t, mt.Name(), "foo") + require.Equal(t, "foo", mt.Name()) require.Panics(t, func() { _ = mocktesting.NewT("") diff --git a/relayer/docker.go b/relayer/docker.go index 6a3aba88a..4ea984994 100644 --- a/relayer/docker.go +++ b/relayer/docker.go @@ -13,10 +13,11 @@ import ( volumetypes "github.com/docker/docker/api/types/volume" "github.com/docker/docker/client" "github.com/docker/docker/pkg/stdcopy" + "go.uber.org/zap" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/testutil" - "go.uber.org/zap" ) const ( @@ -104,7 +105,7 @@ func NewDockerRelayer(ctx context.Context, log *zap.Logger, testName string, cli VolumeName: r.volumeName, ImageRef: containerImage.Ref(), TestName: testName, - UidGid: containerImage.UidGid, + UidGid: containerImage.UIDGID, }); err != nil { return nil, fmt.Errorf("set volume owner: %w", err) } @@ -471,7 +472,7 @@ func (r *DockerRelayer) ContainerImage() ibc.DockerImage { return ibc.DockerImage{ Repository: r.c.DefaultContainerImage(), Version: r.c.DefaultContainerVersion(), - UidGid: r.c.DockerUser(), + UIDGID: r.c.DockerUser(), } } diff --git a/relayer/hermes/hermes_commander.go b/relayer/hermes/hermes_commander.go index 0e8f8369e..354a90d9f 100644 --- a/relayer/hermes/hermes_commander.go +++ b/relayer/hermes/hermes_commander.go @@ -5,12 +5,13 @@ import ( "encoding/json" "fmt" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/relayer" "go.uber.org/zap" ibcexported "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" "github.com/cosmos/ibc-go/v8/modules/core/23-commitment/types" + + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/relayer" ) var _ relayer.RelayerCommander = &commander{} @@ -33,11 +34,11 @@ func (c commander) DefaultContainerVersion() string { } func (c commander) DockerUser() string { - return hermesDefaultUidGid + return hermesDefaultUIDGID } func (c commander) ParseGetChannelsOutput(stdout, stderr string) ([]ibc.ChannelOutput, error) { - jsonBz := extractJsonResult([]byte(stdout)) + jsonBz := extractJSONResult([]byte(stdout)) var result ChannelOutputResult if err := json.Unmarshal(jsonBz, &result); err != nil { return nil, err @@ -63,7 +64,7 @@ func (c commander) ParseGetChannelsOutput(stdout, stderr string) ([]ibc.ChannelO } func (c commander) ParseGetConnectionsOutput(stdout, stderr string) (ibc.ConnectionOutputs, error) { - jsonBz := extractJsonResult([]byte(stdout)) + jsonBz := extractJSONResult([]byte(stdout)) var queryResult ConnectionQueryResult if err := json.Unmarshal(jsonBz, &queryResult); err != nil { return ibc.ConnectionOutputs{}, err @@ -97,7 +98,7 @@ func (c commander) ParseGetConnectionsOutput(stdout, stderr string) (ibc.Connect } func (c commander) ParseGetClientsOutput(stdout, stderr string) (ibc.ClientOutputs, error) { - jsonBz := extractJsonResult([]byte(stdout)) + jsonBz := extractJSONResult([]byte(stdout)) var queryResult ClientQueryResult if err := json.Unmarshal(jsonBz, &queryResult); err != nil { return ibc.ClientOutputs{}, err diff --git a/relayer/hermes/hermes_relayer.go b/relayer/hermes/hermes_relayer.go index ab87ebbae..19cab3cee 100644 --- a/relayer/hermes/hermes_relayer.go +++ b/relayer/hermes/hermes_relayer.go @@ -11,9 +11,10 @@ import ( "github.com/docker/docker/client" "github.com/pelletier/go-toml" + "go.uber.org/zap" + "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/relayer" - "go.uber.org/zap" ) const ( @@ -21,7 +22,7 @@ const ( defaultContainerImage = "ghcr.io/informalsystems/hermes" DefaultContainerVersion = "1.8.2" - hermesDefaultUidGid = "1000:1000" + hermesDefaultUIDGID = "1000:1000" hermesHome = "/home/hermes" hermesConfigPath = ".hermes/config.toml" ) @@ -208,11 +209,11 @@ func (r *Relayer) CreateClients(ctx context.Context, rep ibc.RelayerExecReporter return res.Err } - chainAClientId, err := GetClientIdFromStdout(res.Stdout) + chainAClientID, err := GetClientIDFromStdout(res.Stdout) if err != nil { return err } - pathConfig.chainA.clientID = chainAClientId + pathConfig.chainA.clientID = chainAClientID chainBCreateClientCmd := []string{hermes, "--json", "create", "client", "--host-chain", pathConfig.chainB.chainID, "--reference-chain", pathConfig.chainA.chainID} if opts.TrustingPeriod != "" { @@ -226,11 +227,11 @@ func (r *Relayer) CreateClients(ctx context.Context, rep ibc.RelayerExecReporter return res.Err } - chainBClientId, err := GetClientIdFromStdout(res.Stdout) + chainBClientID, err := GetClientIDFromStdout(res.Stdout) if err != nil { return err } - pathConfig.chainB.clientID = chainBClientId + pathConfig.chainB.clientID = chainBClientID return res.Err } @@ -254,16 +255,17 @@ func (r *Relayer) CreateClient(ctx context.Context, rep ibc.RelayerExecReporter, return res.Err } - clientId, err := GetClientIdFromStdout(res.Stdout) + clientID, err := GetClientIDFromStdout(res.Stdout) if err != nil { return err } - if pathConfig.chainA.chainID == srcChainID { - pathConfig.chainA.chainID = clientId - } else if pathConfig.chainB.chainID == srcChainID { - pathConfig.chainB.chainID = clientId - } else { + switch { + case pathConfig.chainA.chainID == srcChainID: + pathConfig.chainA.chainID = clientID + case pathConfig.chainB.chainID == srcChainID: + pathConfig.chainB.chainID = clientID + default: return fmt.Errorf("%s not found in path config", srcChainID) } @@ -397,8 +399,8 @@ func (r *Relayer) validateConfig(ctx context.Context, rep ibc.RelayerExecReporte return nil } -// extractJsonResult extracts the json result for the hermes query. -func extractJsonResult(stdout []byte) []byte { +// extractJSONResult extracts the json result for the hermes query. +func extractJSONResult(stdout []byte) []byte { stdoutLines := strings.Split(string(stdout), "\n") var jsonOutput string for _, line := range stdoutLines { @@ -429,10 +431,10 @@ func (r *Relayer) getAndLockPath(pathName string) (*pathConfiguration, func(), e return path, unlock, nil } -// GetClientIdFromStdout extracts the client ID from stdout. -func GetClientIdFromStdout(stdout []byte) (string, error) { +// GetClientIDFromStdout extracts the client ID from stdout. +func GetClientIDFromStdout(stdout []byte) (string, error) { var clientCreationResult ClientCreationResponse - if err := json.Unmarshal(extractJsonResult(stdout), &clientCreationResult); err != nil { + if err := json.Unmarshal(extractJSONResult(stdout), &clientCreationResult); err != nil { return "", err } return clientCreationResult.Result.CreateClient.ClientID, nil @@ -441,7 +443,7 @@ func GetClientIdFromStdout(stdout []byte) (string, error) { // GetConnectionIDsFromStdout extracts the connectionIDs on both ends from the stdout. func GetConnectionIDsFromStdout(stdout []byte) (string, string, error) { var connectionResponse ConnectionResponse - if err := json.Unmarshal(extractJsonResult(stdout), &connectionResponse); err != nil { + if err := json.Unmarshal(extractJSONResult(stdout), &connectionResponse); err != nil { return "", "", err } return connectionResponse.Result.ASide.ConnectionID, connectionResponse.Result.BSide.ConnectionID, nil @@ -450,7 +452,7 @@ func GetConnectionIDsFromStdout(stdout []byte) (string, string, error) { // GetChannelIDsFromStdout extracts the channelIDs on both ends from stdout. func GetChannelIDsFromStdout(stdout []byte) (string, string, error) { var channelResponse ChannelCreationResponse - if err := json.Unmarshal(extractJsonResult(stdout), &channelResponse); err != nil { + if err := json.Unmarshal(extractJSONResult(stdout), &channelResponse); err != nil { return "", "", err } return channelResponse.Result.ASide.ChannelID, channelResponse.Result.BSide.ChannelID, nil diff --git a/relayer/hermes/hermes_types.go b/relayer/hermes/hermes_types.go index 2648625ea..aef7afe69 100644 --- a/relayer/hermes/hermes_types.go +++ b/relayer/hermes/hermes_types.go @@ -57,10 +57,10 @@ type ChannelEnd struct { Ordering string `json:"ordering"` State string `json:"state"` Version string `json:"version"` - Remote ChannelAndPortId `json:"remote"` + Remote ChannelAndPortID `json:"remote"` } -type ChannelAndPortId struct { +type ChannelAndPortID struct { ChannelID string `json:"channel_id"` PortID string `json:"port_id"` } diff --git a/relayer/hyperspace/hyperspace_commander.go b/relayer/hyperspace/hyperspace_commander.go index 8c7e4aaca..57cdb7fc9 100644 --- a/relayer/hyperspace/hyperspace_commander.go +++ b/relayer/hyperspace/hyperspace_commander.go @@ -5,15 +5,17 @@ import ( "context" "fmt" "path" + "strings" "github.com/misko9/go-substrate-rpc-client/v4/signature" "github.com/pelletier/go-toml/v2" - "github.com/strangelove-ventures/interchaintest/v8/chain/polkadot" - "github.com/strangelove-ventures/interchaintest/v8/ibc" "go.uber.org/zap" ibcexported "github.com/cosmos/ibc-go/v8/modules/core/03-connection/types" types23 "github.com/cosmos/ibc-go/v8/modules/core/23-commitment/types" + + "github.com/strangelove-ventures/interchaintest/v8/chain/polkadot" + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) // hyperspaceCommander satisfies relayer.RelayerCommander. @@ -43,7 +45,11 @@ func (hyperspaceCommander) DockerUser() string { } func (c *hyperspaceCommander) AddChainConfiguration(containerFilePath, homeDir string) []string { - fmt.Println("[hyperspace] AddChainConfiguration ", containerFilePath, homeDir) + c.log.Info("Hyperspace AddChainConfiguration", + zap.String("container_file_path", containerFilePath), + zap.String("home_dir", homeDir), + ) + // c.chainConfigPaths = append(c.chainConfigPaths, containerFilePath) return []string{ "hyperspace", @@ -57,7 +63,11 @@ func (hyperspaceCommander) AddKey(chainID, keyName, coinType, signingAlgorithm, } func (c *hyperspaceCommander) CreateChannel(pathName string, opts ibc.CreateChannelOptions, homeDir string) []string { - fmt.Println("[hyperspace] CreateChannel", pathName, homeDir) + c.log.Info("Hyperspace CreateChannel", + zap.String("path_name", pathName), + zap.String("home_dir", homeDir), + ) + _, ok := c.paths[pathName] if !ok { panic(fmt.Sprintf("path %s not found", pathName)) @@ -81,7 +91,15 @@ func (c *hyperspaceCommander) CreateChannel(pathName string, opts ibc.CreateChan } func (c *hyperspaceCommander) CreateClients(pathName string, opts ibc.CreateClientOptions, homeDir string) []string { - fmt.Println("[hyperspace] CreateClients", pathName, opts, homeDir) + c.log.Info("Hyperspace CreateClients", + zap.String("path_name", pathName), + zap.String("home_dir", homeDir), + zap.String("trusting_period", opts.TrustingPeriod), + zap.Int64("trusting_period_percentage", opts.TrustingPeriodPercentage), + zap.String("max_clock_drift", opts.MaxClockDrift), + zap.Bool("override", opts.Override), + ) + _, ok := c.paths[pathName] if !ok { panic(fmt.Sprintf("path %s not found", pathName)) @@ -108,7 +126,11 @@ func (hyperspaceCommander) CreateClient(srcChainID, dstChainID, pathName string, } func (c *hyperspaceCommander) CreateConnections(pathName, homeDir string) []string { - fmt.Println("[hyperspace] CreateConnections", pathName, homeDir) + c.log.Info("Hyperspace CreateConnections", + zap.String("path_name", pathName), + zap.String("home_dir", homeDir), + ) + _, ok := c.paths[pathName] if !ok { panic(fmt.Sprintf("path %s not found", pathName)) @@ -160,8 +182,12 @@ func (hyperspaceCommander) UpdatePath(pathName, homeDir string, opts ibc.PathUpd // Prints chain config which is populated by hyperspace // Ideally, there should be a command from hyperspace to get this output. -func (hyperspaceCommander) GetChannels(chainID, homeDir string) []string { - fmt.Println("[hyperspace] Get Channels") +func (c hyperspaceCommander) GetChannels(chainID, homeDir string) []string { + c.log.Info("Hyperspace GetChannels", + zap.String("chain_id", chainID), + zap.String("home_dir", homeDir), + ) + configFilePath := path.Join(homeDir, chainID+".config") return []string{ "cat", @@ -171,8 +197,12 @@ func (hyperspaceCommander) GetChannels(chainID, homeDir string) []string { // Prints chain config which is populated by hyperspace // Ideally, there should be a command from hyperspace to get this output. -func (hyperspaceCommander) GetConnections(chainID, homeDir string) []string { - fmt.Println("[hyperspace] Get Connections") +func (c hyperspaceCommander) GetConnections(chainID, homeDir string) []string { + c.log.Info("Hyperspace GetConnections", + zap.String("chain_id", chainID), + zap.String("home_dir", homeDir), + ) + configFilePath := path.Join(homeDir, chainID+".config") return []string{ "cat", @@ -182,8 +212,12 @@ func (hyperspaceCommander) GetConnections(chainID, homeDir string) []string { // Prints chain config which is populated by hyperspace // Ideally, there should be a command from hyperspace to get this output. -func (hyperspaceCommander) GetClients(chainID, homeDir string) []string { - fmt.Println("[hyperspace] Get Clients") +func (c hyperspaceCommander) GetClients(chainID, homeDir string) []string { + c.log.Info("Hyperspace GetClients", + zap.String("chain_id", chainID), + zap.String("home_dir", homeDir), + ) + configFilePath := path.Join(homeDir, chainID+".config") return []string{ "cat", @@ -204,7 +238,10 @@ func (hyperspaceCommander) RestoreKey(chainID, bech32Prefix, coinType, signingAl // hyperspace can only start 1 path. func (c *hyperspaceCommander) StartRelayer(homeDir string, pathNames ...string) []string { - fmt.Println("[hyperspace] StartRelayer", homeDir, pathNames) + fields := []zap.Field{zap.String("home_dir", homeDir), zap.String("path_names", strings.Join(pathNames, ","))} + + c.log.Info("HyperSpace StartRelayer", fields...) + if len(pathNames) != 1 { panic("Hyperspace's StartRelayer list of paths can only have 1 path") } @@ -230,8 +267,13 @@ func (hyperspaceCommander) UpdateClients(pathName, homeDir string) []string { panic("[UpdateClients] Do not use me") } -func (hyperspaceCommander) ConfigContent(ctx context.Context, cfg ibc.ChainConfig, keyName, rpcAddr, grpcAddr string) ([]byte, error) { - fmt.Println("[hyperspace] ConfigContent", cfg, keyName, rpcAddr, grpcAddr) +func (c hyperspaceCommander) ConfigContent(ctx context.Context, cfg ibc.ChainConfig, keyName, rpcAddr, grpcAddr string) ([]byte, error) { + c.log.Info("Hyperspace ConfigContent", + zap.String("rpc_addr", rpcAddr), + zap.String("grpc_addr", grpcAddr), + zap.String("key_name", keyName), + ) + HyperspaceRelayerChainConfig := ChainConfigToHyperspaceRelayerChainConfig(cfg, keyName, rpcAddr, grpcAddr) bytes, err := toml.Marshal(HyperspaceRelayerChainConfig) if err != nil { @@ -354,8 +396,9 @@ func (hyperspaceCommander) ParseGetClientsOutput(stdout, stderr string) (ibc.Cli }, nil } -func (hyperspaceCommander) Init(homeDir string) []string { - fmt.Println("[hyperspace] Init", homeDir) +func (c hyperspaceCommander) Init(homeDir string) []string { + c.log.Info("Hyperspace Init", zap.String("home_dir", homeDir)) + // Return hyperspace help to ensure hyperspace binary is accessible return []string{ "hyperspace", diff --git a/relayer/hyperspace/hyperspace_config.go b/relayer/hyperspace/hyperspace_config.go index ffe214868..733ee4f22 100644 --- a/relayer/hyperspace/hyperspace_config.go +++ b/relayer/hyperspace/hyperspace_config.go @@ -5,14 +5,15 @@ import ( "strconv" "strings" - "github.com/strangelove-ventures/interchaintest/v8/chain/polkadot" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - bip32 "github.com/tyler-smith/go-bip32" - bip39 "github.com/tyler-smith/go-bip39" + "github.com/tyler-smith/go-bip32" + "github.com/tyler-smith/go-bip39" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/types" + + "github.com/strangelove-ventures/interchaintest/v8/chain/polkadot" + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) type HyperspaceRelayerCoreConfig struct { @@ -46,7 +47,7 @@ type HyperspaceRelayerCosmosChainConfig struct { Name string `toml:"name"` RPCUrl string `toml:"rpc_url"` GRPCUrl string `toml:"grpc_url"` - WebsocketUrl string `toml:"websocket_url"` + WebsocketURL string `toml:"websocket_url"` ChainID string `toml:"chain_id"` AccountPrefix string `toml:"account_prefix"` FeeDenom string `toml:"fee_denom"` @@ -101,31 +102,32 @@ func GenKeyEntry(bech32Prefix, coinType, mnemonic string) KeyEntry { func ChainConfigToHyperspaceRelayerChainConfig(chainConfig ibc.ChainConfig, keyName, rpcAddr, grpcAddr string) interface{} { chainType := chainConfig.Type - if chainType == "polkadot" || chainType == "parachain" || chainType == "relaychain" { - chainType = "parachain" + if chainType == ibc.Polkadot || chainType == ibc.Parachain || chainType == ibc.RelayChain { + chainType = ibc.Parachain } - if chainType == "parachain" { + switch { + case chainType == ibc.Parachain: addrs := strings.Split(rpcAddr, ",") - paraRpcAddr := rpcAddr - relayRpcAddr := grpcAddr + paraRPCAddr := rpcAddr + relayRPCAddr := grpcAddr if len(addrs) > 1 { - paraRpcAddr, relayRpcAddr = addrs[0], addrs[1] + paraRPCAddr, relayRPCAddr = addrs[0], addrs[1] } return HyperspaceRelayerSubstrateChainConfig{ Type: chainType, Name: chainConfig.Name, ParaID: 2000, - ParachainRPCURL: strings.Replace(strings.Replace(paraRpcAddr, "http", "ws", 1), "9933", "27451", 1), - RelayChainRPCURL: strings.Replace(strings.Replace(relayRpcAddr, "http", "ws", 1), "9933", "27451", 1), + ParachainRPCURL: strings.Replace(strings.Replace(paraRPCAddr, "http", "ws", 1), "9933", "27451", 1), + RelayChainRPCURL: strings.Replace(strings.Replace(relayRPCAddr, "http", "ws", 1), "9933", "27451", 1), CommitmentPrefix: "0x6962632f", PrivateKey: "//Alice", SS58Version: polkadot.Ss58Format, KeyType: "sr25519", FinalityProtocol: "Grandpa", } - } else if chainType == "cosmos" { - wsUrl := strings.Replace(rpcAddr, "http", "ws", 1) + "/websocket" + case chainType == ibc.Cosmos: + wsURL := strings.Replace(rpcAddr, "http", "ws", 1) + "/websocket" return HyperspaceRelayerCosmosChainConfig{ Type: chainType, Name: chainConfig.Name, @@ -138,9 +140,9 @@ func ChainConfigToHyperspaceRelayerChainConfig(chainConfig ibc.ChainConfig, keyN RPCUrl: rpcAddr, StorePrefix: "ibc", MaxTxSize: 200000, - WebsocketUrl: wsUrl, + WebsocketURL: wsURL, } - } else { + default: panic(fmt.Sprintf("unsupported chain type %s", chainType)) } } diff --git a/relayer/hyperspace/hyperspace_relayer.go b/relayer/hyperspace/hyperspace_relayer.go index ae43b421b..ef697a0ba 100644 --- a/relayer/hyperspace/hyperspace_relayer.go +++ b/relayer/hyperspace/hyperspace_relayer.go @@ -9,9 +9,10 @@ import ( "github.com/docker/docker/client" "github.com/pelletier/go-toml/v2" + "go.uber.org/zap" + "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/relayer" - "go.uber.org/zap" ) var _ ibc.Relayer = &HyperspaceRelayer{} @@ -121,8 +122,8 @@ func (r *HyperspaceRelayer) SetClientContractHash(ctx context.Context, rep ibc.R if err != nil { return err } - switch chainType { - case "cosmos": + + if chainType == ibc.Cosmos { config.(*HyperspaceRelayerCosmosChainConfig).WasmChecksum = hash } @@ -137,11 +138,14 @@ func (r *HyperspaceRelayer) PrintCoreConfig(ctx context.Context, rep ibc.Relayer ctx, cancel := context.WithTimeout(ctx, time.Minute) defer cancel() + res := r.Exec(ctx, rep, cmd, nil) if res.Err != nil { return res.Err } - fmt.Println(string(res.Stdout)) + + fmt.Println(string(res.Stdout)) //nolint:forbidigo + return nil } @@ -153,11 +157,14 @@ func (r *HyperspaceRelayer) PrintConfigs(ctx context.Context, rep ibc.RelayerExe ctx, cancel := context.WithTimeout(ctx, time.Minute) defer cancel() + res := r.Exec(ctx, rep, cmd, nil) if res.Err != nil { return res.Err } - fmt.Println(string(res.Stdout)) + + fmt.Println(string(res.Stdout)) //nolint:forbidigo + return nil } diff --git a/relayer/hyperspace/hyperspace_test.go b/relayer/hyperspace/hyperspace_test.go index 0007558eb..7942acaff 100644 --- a/relayer/hyperspace/hyperspace_test.go +++ b/relayer/hyperspace/hyperspace_test.go @@ -3,8 +3,9 @@ package hyperspace_test import ( "testing" - "github.com/strangelove-ventures/interchaintest/v8/relayer/hyperspace" "github.com/stretchr/testify/require" + + "github.com/strangelove-ventures/interchaintest/v8/relayer/hyperspace" ) func TestKeys(t *testing.T) { diff --git a/relayer/options.go b/relayer/options.go index 1231ef837..49f732899 100644 --- a/relayer/options.go +++ b/relayer/options.go @@ -17,11 +17,11 @@ func DockerImage(image *ibc.DockerImage) RelayerOpt { // CustomDockerImage overrides the default relayer docker image. // uidGid is the uid:gid format owner that should be used within the container. // If uidGid is empty, root user will be assumed. -func CustomDockerImage(repository string, version string, uidGid string) RelayerOpt { +func CustomDockerImage(repository string, version string, uidGID string) RelayerOpt { return DockerImage(&ibc.DockerImage{ Repository: repository, Version: version, - UidGid: uidGid, + UIDGID: uidGID, }) } diff --git a/relayer/rly/cosmos_relayer.go b/relayer/rly/cosmos_relayer.go index 91c5b510b..b36d30a80 100644 --- a/relayer/rly/cosmos_relayer.go +++ b/relayer/rly/cosmos_relayer.go @@ -8,15 +8,16 @@ import ( "strings" "github.com/docker/docker/client" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/relayer" "go.uber.org/zap" "github.com/cosmos/cosmos-sdk/crypto/keyring" + + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/relayer" ) const ( - RlyDefaultUidGid = "100:1000" + RlyDefaultUIDGID = "100:1000" ) // CosmosRelayer is the ibc.Relayer implementation for github.com/cosmos/relayer. @@ -111,7 +112,7 @@ func (commander) Name() string { } func (commander) DockerUser() string { - return RlyDefaultUidGid // docker run -it --rm --entrypoint echo ghcr.io/cosmos/relayer "$(id -u):$(id -g)" + return RlyDefaultUIDGID // docker run -it --rm --entrypoint echo ghcr.io/cosmos/relayer "$(id -u):$(id -g)" } func (commander) AddChainConfiguration(containerFilePath, homeDir string) []string { diff --git a/relayerfactory.go b/relayerfactory.go index c6b52cf5f..12a28c66d 100644 --- a/relayerfactory.go +++ b/relayerfactory.go @@ -4,12 +4,13 @@ import ( "fmt" "github.com/docker/docker/client" + "go.uber.org/zap" + "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/relayer" "github.com/strangelove-ventures/interchaintest/v8/relayer/hermes" "github.com/strangelove-ventures/interchaintest/v8/relayer/hyperspace" "github.com/strangelove-ventures/interchaintest/v8/relayer/rly" - "go.uber.org/zap" ) type TestName interface { @@ -97,6 +98,11 @@ func (f *builtinRelayerFactory) Name() string { return "hermes@" + f.version } return "hermes@" + hermes.DefaultContainerVersion + case ibc.Hyperspace: + if f.version == "" { + return "hyperspace@" + f.version + } + return "hyperspace@" + hyperspace.HyperspaceDefaultContainerVersion default: panic(fmt.Errorf("RelayerImplementation %v unknown", f.impl)) } @@ -111,6 +117,8 @@ func (f builtinRelayerFactory) Capabilities() map[relayer.Capability]bool { case ibc.Hermes: // TODO: specify capability for hermes. return rly.Capabilities() + case ibc.Hyperspace: + panic("capabilities are not defined for Hyperspace relayer.") default: panic(fmt.Errorf("RelayerImplementation %v unknown", f.impl)) } diff --git a/tempdir_test.go b/tempdir_test.go index e358be411..491143ca6 100644 --- a/tempdir_test.go +++ b/tempdir_test.go @@ -6,9 +6,10 @@ import ( "strings" "testing" - interchaintest "github.com/strangelove-ventures/interchaintest/v8" - "github.com/strangelove-ventures/interchaintest/v8/mocktesting" "github.com/stretchr/testify/require" + + "github.com/strangelove-ventures/interchaintest/v8" + "github.com/strangelove-ventures/interchaintest/v8/mocktesting" ) func TestTempDir_Cleanup(t *testing.T) { @@ -59,7 +60,6 @@ func TestTempDir_Cleanup(t *testing.T) { "test passed": false, "test failed": true, } { - failed := failed t.Run(name, func(t *testing.T) { mt := mocktesting.NewT("t") diff --git a/test_setup.go b/test_setup.go index 5a8480ba7..eb4162ddd 100644 --- a/test_setup.go +++ b/test_setup.go @@ -8,6 +8,7 @@ import ( "time" "github.com/docker/docker/client" + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/testreporter" @@ -52,6 +53,8 @@ func StartChainPair( f RelayerFactory, preRelayerStartFuncs []func([]ibc.ChannelOutput), ) (ibc.Relayer, error) { + t.Helper() + relayerImpl := f.Build(t, cli, networkID) ic := NewInterchain(). @@ -97,6 +100,8 @@ func StopStartRelayerWithPreStartFuncs( preRelayerStartFuncs []func([]ibc.ChannelOutput), pathNames ...string, ) ([]ibc.ChannelOutput, error) { + t.Helper() + if err := relayerImpl.StopRelayer(ctx, eRep); err != nil { t.Logf("error stopping relayer: %v", err) } @@ -113,7 +118,6 @@ func StopStartRelayerWithPreStartFuncs( if preRelayerStart == nil { continue } - preRelayerStart := preRelayerStart wg.Add(1) go func() { preRelayerStart(channels) diff --git a/test_user.go b/test_user.go index f2480de64..b7b56186f 100644 --- a/test_user.go +++ b/test_user.go @@ -5,13 +5,14 @@ import ( "fmt" "testing" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" - "github.com/strangelove-ventures/interchaintest/v8/ibc" - "github.com/strangelove-ventures/interchaintest/v8/testutil" "github.com/stretchr/testify/require" "golang.org/x/sync/errgroup" "cosmossdk.io/math" + + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" + "github.com/strangelove-ventures/interchaintest/v8/ibc" + "github.com/strangelove-ventures/interchaintest/v8/testutil" ) // GetAndFundTestUserWithMnemonic restores a user using the given mnemonic @@ -58,11 +59,11 @@ func GetAndFundTestUsers( amount math.Int, chains ...ibc.Chain, ) []ibc.Wallet { + t.Helper() + users := make([]ibc.Wallet, len(chains)) var eg errgroup.Group for i, chain := range chains { - i := i - chain := chain eg.Go(func() error { user, err := GetAndFundTestUserWithMnemonic(ctx, keyNamePrefix, "", amount, chain) if err != nil { diff --git a/testreporter/messages_test.go b/testreporter/messages_test.go index 1e7afe70b..fd7ce8c19 100644 --- a/testreporter/messages_test.go +++ b/testreporter/messages_test.go @@ -6,8 +6,9 @@ import ( "time" "github.com/google/go-cmp/cmp" - "github.com/strangelove-ventures/interchaintest/v8/testreporter" "github.com/stretchr/testify/require" + + "github.com/strangelove-ventures/interchaintest/v8/testreporter" ) func TestWrappedMessage_RoundTrip(t *testing.T) { diff --git a/testreporter/reporter_test.go b/testreporter/reporter_test.go index 47499a1dd..7c30410f8 100644 --- a/testreporter/reporter_test.go +++ b/testreporter/reporter_test.go @@ -8,9 +8,10 @@ import ( "time" "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/require" + "github.com/strangelove-ventures/interchaintest/v8/mocktesting" "github.com/strangelove-ventures/interchaintest/v8/testreporter" - "github.com/stretchr/testify/require" ) // nopCloser wraps an io.Writer to provide a Close method that always returns nil. @@ -76,11 +77,11 @@ func TestReporter_TrackPassingSingleTest(t *testing.T) { requireTimeInRange(t, beginSuiteMsg.StartedAt, beforeStartSuite, afterStartSuite) beginTestMsg := msgs[1].(testreporter.BeginTestMessage) - require.Equal(t, beginTestMsg.Name, "my_test") + require.Equal(t, "my_test", beginTestMsg.Name) requireTimeInRange(t, beginTestMsg.StartedAt, beforeStartTest, afterStartTest) finishTestMsg := msgs[2].(testreporter.FinishTestMessage) - require.Equal(t, finishTestMsg.Name, "my_test") + require.Equal(t, "my_test", finishTestMsg.Name) require.False(t, finishTestMsg.Failed) require.False(t, finishTestMsg.Skipped) requireTimeInRange(t, finishTestMsg.FinishedAt, beforeFinishTest, afterFinishTest) @@ -116,13 +117,13 @@ func TestReporter_TrackFailingSingleTest(t *testing.T) { require.Len(t, msgs, 5) testErrorMsg := msgs[2].(testreporter.TestErrorMessage) - require.Equal(t, testErrorMsg.Name, "my_test") + require.Equal(t, "my_test", testErrorMsg.Name) // require.Fail adds some detail to the error message that complicates a plain string equality check. require.Contains(t, testErrorMsg.Message, "forced failure") requireTimeInRange(t, testErrorMsg.When, beforeFailure, afterFailure) finishTestMsg := msgs[3].(testreporter.FinishTestMessage) - require.Equal(t, finishTestMsg.Name, "my_test") + require.Equal(t, "my_test", finishTestMsg.Name) require.True(t, finishTestMsg.Failed) require.False(t, finishTestMsg.Skipped) } @@ -151,18 +152,18 @@ func TestReporter_TrackParallel(t *testing.T) { require.Len(t, msgs, 6) beginTestMsg := msgs[1].(testreporter.BeginTestMessage) - require.Equal(t, beginTestMsg.Name, "my_test") + require.Equal(t, "my_test", beginTestMsg.Name) pauseTestMsg := msgs[2].(testreporter.PauseTestMessage) - require.Equal(t, pauseTestMsg.Name, "my_test") + require.Equal(t, "my_test", pauseTestMsg.Name) requireTimeInRange(t, pauseTestMsg.When, beforeParallel, beforeParallel.Add(parallelDelay)) continueTestMsg := msgs[3].(testreporter.ContinueTestMessage) - require.Equal(t, continueTestMsg.Name, "my_test") + require.Equal(t, "my_test", continueTestMsg.Name) requireTimeInRange(t, continueTestMsg.When, afterParallel.Add(-parallelDelay), afterParallel) finishTestMsg := msgs[4].(testreporter.FinishTestMessage) - require.Equal(t, finishTestMsg.Name, "my_test") + require.Equal(t, "my_test", finishTestMsg.Name) } // Check that TrackSkip skips the underlying test. @@ -189,16 +190,16 @@ func TestReporter_TrackSkip(t *testing.T) { require.Len(t, msgs, 5) testSkipMsg := msgs[2].(testreporter.TestSkipMessage) - require.Equal(t, testSkipMsg.Name, "my_test") - require.Equal(t, testSkipMsg.Message, "skipping for reasons") + require.Equal(t, "my_test", testSkipMsg.Name) + require.Equal(t, "skipping for reasons", testSkipMsg.Message) requireTimeInRange(t, testSkipMsg.When, beforeSkip, afterSkip) finishTestMsg := msgs[3].(testreporter.FinishTestMessage) - require.Equal(t, finishTestMsg.Name, "my_test") + require.Equal(t, "my_test", finishTestMsg.Name) require.False(t, finishTestMsg.Failed) require.True(t, finishTestMsg.Skipped) - require.Equal(t, mt.Skips, []string{"skipping for reasons"}) + require.Equal(t, []string{"skipping for reasons"}, mt.Skips) require.True(t, mt.Skipped()) } @@ -214,7 +215,7 @@ func TestReporter_Errorf(t *testing.T) { mt.RunCleanups() require.NoError(t, r.Close()) - require.Equal(t, mt.Errors, []string{"failed? true"}) + require.Equal(t, []string{"failed? true"}, mt.Errors) } func TestReporter_RelayerExec(t *testing.T) { diff --git a/testutil/poll_for_state.go b/testutil/poll_for_state.go index ab40a5227..167021005 100644 --- a/testutil/poll_for_state.go +++ b/testutil/poll_for_state.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/davecgh/go-spew/spew" + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) diff --git a/testutil/poll_for_state_test.go b/testutil/poll_for_state_test.go index b7be3b848..15e3b154e 100644 --- a/testutil/poll_for_state_test.go +++ b/testutil/poll_for_state_test.go @@ -6,8 +6,9 @@ import ( "fmt" "testing" - "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/stretchr/testify/require" + + "github.com/strangelove-ventures/interchaintest/v8/ibc" ) type mockChain struct { diff --git a/testutil/toml.go b/testutil/toml.go index 9ad325dc2..85228a825 100644 --- a/testutil/toml.go +++ b/testutil/toml.go @@ -8,8 +8,9 @@ import ( "github.com/BurntSushi/toml" "github.com/docker/docker/client" - "github.com/strangelove-ventures/interchaintest/v8/dockerutil" "go.uber.org/zap" + + "github.com/strangelove-ventures/interchaintest/v8/dockerutil" ) // Toml is used for holding the decoded state of a toml config file. diff --git a/testutil/wait.go b/testutil/wait.go index 600dd8e46..44ad4c719 100644 --- a/testutil/wait.go +++ b/testutil/wait.go @@ -54,8 +54,6 @@ func NodesInSync(ctx context.Context, chain ChainHeighter, nodes []ChainHeighter return err }) for i, n := range nodes { - i := i - n := n eg.Go(func() (err error) { nodeHeights[i], err = n.Height(egCtx) return err @@ -66,7 +64,7 @@ func NodesInSync(ctx context.Context, chain ChainHeighter, nodes []ChainHeighter } for _, h := range nodeHeights { if h < chainHeight { - return fmt.Errorf("Node is not yet in sync: %d < %d", h, chainHeight) + return fmt.Errorf("node is not yet in sync: %d < %d", h, chainHeight) } } // all nodes >= chainHeight diff --git a/testutil/wait_test.go b/testutil/wait_test.go index d6e752e4c..7d7aa0db9 100644 --- a/testutil/wait_test.go +++ b/testutil/wait_test.go @@ -40,6 +40,8 @@ func TestWaitForBlocks(t *testing.T) { t.Parallel() t.Run("happy path", func(t *testing.T) { + t.Parallel() + var ( startHeight1 int64 = 10 chain1 = mockChainHeighter{CurHeight: startHeight1} @@ -57,12 +59,16 @@ func TestWaitForBlocks(t *testing.T) { }) t.Run("no chains", func(t *testing.T) { + t.Parallel() + require.Panics(t, func() { _ = WaitForBlocks(context.Background(), 100) }) }) t.Run("error", func(t *testing.T) { + t.Parallel() + errMock := mockChainHeighter{Err: errors.New("boom")} const delta = 1 err := WaitForBlocks(context.Background(), delta, &mockChainHeighter{}, &errMock) @@ -72,6 +78,8 @@ func TestWaitForBlocks(t *testing.T) { }) t.Run("0 height", func(t *testing.T) { + t.Parallel() + const delta = 1 // Set height to -1 because the mock chain auto-increments the height resulting in starting height of 0. chain := &mockChainHeighter{CurHeight: -1} @@ -121,6 +129,8 @@ func TestWaitForInSync(t *testing.T) { t.Parallel() t.Run("happy path", func(t *testing.T) { + t.Parallel() + var ( startHeightChain int64 = 10 chain = mockChainHeighterFixed{CurHeight: startHeightChain} @@ -138,6 +148,8 @@ func TestWaitForInSync(t *testing.T) { }) t.Run("no nodes", func(t *testing.T) { + t.Parallel() + var ( startHeightChain int64 = 10 chain = mockChainHeighterFixed{CurHeight: startHeightChain} @@ -148,6 +160,8 @@ func TestWaitForInSync(t *testing.T) { }) t.Run("timeout", func(t *testing.T) { + t.Parallel() + var ( startHeightChain int64 = 10 chain = mockChainHeighterFixed{CurHeight: startHeightChain} From 4490028f0243a8721c6a444407da748c0b284f96 Mon Sep 17 00:00:00 2001 From: Steve <1848680+misko9@users.noreply.github.com> Date: Mon, 7 Oct 2024 19:52:05 -0600 Subject: [PATCH 5/5] fix(thorchain/utxo): fix race conditions (#1281) --- chain/thorchain/sidecar.go | 6 +- chain/utxo/cli.go | 4 + chain/utxo/utxo_chain.go | 116 ++++++++++++++---------- chain/utxo/wallet.go | 6 ++ examples/thorchain/setup_test.go | 6 ++ examples/utxo/start_test.go | 6 ++ local-interchain/chains/state/README.md | 2 +- 7 files changed, 98 insertions(+), 48 deletions(-) diff --git a/chain/thorchain/sidecar.go b/chain/thorchain/sidecar.go index e59a0f1ec..077394a2b 100644 --- a/chain/thorchain/sidecar.go +++ b/chain/thorchain/sidecar.go @@ -71,6 +71,10 @@ func NewSidecar( homeDir = "/home/sidecar" } + // Give each sidecard their own env copy for runtime changes + envCopy := make([]string, len(env)) + copy(envCopy, env) + s := &SidecarProcess{ log: log, Index: index, @@ -85,7 +89,7 @@ func NewSidecar( homeDir: homeDir, ports: processPorts, startCmd: startCmd, - env: env, + env: envCopy, } s.containerLifecycle = dockerutil.NewContainerLifecycle(log, dockerClient, s.Name()) diff --git a/chain/utxo/cli.go b/chain/utxo/cli.go index a3bd732be..c32b8e59f 100644 --- a/chain/utxo/cli.go +++ b/chain/utxo/cli.go @@ -109,10 +109,12 @@ func (c *UtxoChain) CreateWallet(ctx context.Context, keyName string) error { return err } + c.MapAccess.Lock() c.KeyNameToWalletMap[keyName] = &NodeWallet{ keyName: keyName, loadCount: 1, } + c.MapAccess.Unlock() } return c.UnloadWallet(ctx, keyName) @@ -151,12 +153,14 @@ func (c *UtxoChain) GetNewAddress(ctx context.Context, keyName string, mweb bool addr = splitAddr[1] } + c.MapAccess.Lock() wallet.address = addr c.AddrToKeyNameMap[addr] = keyName if c.WalletVersion >= noDefaultKeyWalletVersion { wallet.ready = true } + c.MapAccess.Unlock() if err := c.UnloadWallet(ctx, keyName); err != nil { return "", err diff --git a/chain/utxo/utxo_chain.go b/chain/utxo/utxo_chain.go index 1fc6efb3d..dae15697f 100644 --- a/chain/utxo/utxo_chain.go +++ b/chain/utxo/utxo_chain.go @@ -7,6 +7,7 @@ import ( "math" "strconv" "strings" + "sync" "time" dockertypes "github.com/docker/docker/api/types" @@ -40,6 +41,7 @@ var natPorts = nat.PortMap{ type UtxoChain struct { testName string cfg ibc.ChainConfig + cancel context.CancelFunc log *zap.Logger @@ -60,6 +62,9 @@ type UtxoChain struct { AddrToKeyNameMap map[string]string KeyNameToWalletMap map[string]*NodeWallet + // Mutex for reading/writing AddrToKeyNameMap and KeyNameToWalletMap + MapAccess sync.Mutex + WalletVersion int unloadWalletAfterUse bool } @@ -259,52 +264,6 @@ func (c *UtxoChain) Start(testName string, ctx context.Context, additionalGenesi // Wait for rpc to come up time.Sleep(time.Second * 5) - go func() { - ctx := context.Background() - amount := "100" - nextBlockHeight := 100 - if c.cfg.CoinType == "3" { - amount = "1000" // Dogecoin needs more blocks for more coins - nextBlockHeight = 1000 - } - for { - faucetWallet, found := c.KeyNameToWalletMap[faucetKeyName] - if !found || !faucetWallet.ready { - time.Sleep(time.Second) - continue - } - - // If faucet exists, chain is up and running. Any future error should return from this go routine. - // If the chain stops, we will then error and return from this go routine - // Don't use ctx from Start(), it gets cancelled soon after returning. - cmd = append(c.BaseCli, "generatetoaddress", amount, faucetWallet.address) - _, _, err = c.Exec(ctx, cmd, nil) - if err != nil { - c.logger().Error("generatetoaddress error", zap.Error(err)) - return - } - amount = "1" - if nextBlockHeight == 431 && c.cfg.CoinType == "2" { - keyName := "mweb" - if err := c.CreateWallet(ctx, keyName); err != nil { - c.logger().Error("error creating mweb wallet at block 431", zap.String("chain", c.cfg.ChainID), zap.Error(err)) - return - } - addr, err := c.GetNewAddress(ctx, keyName, true) - if err != nil { - c.logger().Error("error creating mweb wallet at block 431", zap.String("chain", c.cfg.ChainID), zap.Error(err)) - return - } - if err := c.sendToMwebAddress(ctx, faucetKeyName, addr, 1); err != nil { - c.logger().Error("error sending to mweb wallet at block 431", zap.String("chain", c.cfg.ChainID), zap.Error(err)) - return - } - } - nextBlockHeight++ - time.Sleep(time.Second * 2) - } - }() - c.WalletVersion, _ = c.GetWalletVersion(ctx, "") if err := c.CreateWallet(ctx, faucetKeyName); err != nil { @@ -327,6 +286,63 @@ func (c *UtxoChain) Start(testName string, ctx context.Context, additionalGenesi return err } + go func() { + // Don't use ctx from Start(), it gets cancelled soon after returning. + goRoutineCtx := context.Background() + goRoutineCtx, c.cancel = context.WithCancel(goRoutineCtx) + amount := "100" + nextBlockHeight := 100 + if c.cfg.CoinType == "3" { + amount = "1000" // Dogecoin needs more blocks for more coins + nextBlockHeight = 1000 + } + + c.MapAccess.Lock() + faucetWallet, found := c.KeyNameToWalletMap[faucetKeyName] + if !found || !faucetWallet.ready { + c.logger().Error("faucet wallet not found or not ready") + c.MapAccess.Unlock() + return + } + c.MapAccess.Unlock() + + utxoBlockTime := time.Second * 2 + timer := time.NewTimer(utxoBlockTime) + defer timer.Stop() + for { + select { + case <-goRoutineCtx.Done(): + return + case <-timer.C: + cmd = append(c.BaseCli, "generatetoaddress", amount, faucetWallet.address) + _, _, err := c.Exec(goRoutineCtx, cmd, nil) + if err != nil { + c.logger().Error("generatetoaddress error", zap.Error(err)) + return + } + amount = "1" + if nextBlockHeight == 431 && c.cfg.CoinType == "2" { + keyName := "mweb" + if err := c.CreateWallet(goRoutineCtx, keyName); err != nil { + c.logger().Error("error creating mweb wallet at block 431", zap.String("chain", c.cfg.ChainID), zap.Error(err)) + return + } + addr, err := c.GetNewAddress(goRoutineCtx, keyName, true) + if err != nil { + c.logger().Error("error creating mweb wallet at block 431", zap.String("chain", c.cfg.ChainID), zap.Error(err)) + return + } + if err := c.sendToMwebAddress(goRoutineCtx, faucetKeyName, addr, 1); err != nil { + c.logger().Error("error sending to mweb wallet at block 431", zap.String("chain", c.cfg.ChainID), zap.Error(err)) + return + } + } + nextBlockHeight++ + timer.Reset(utxoBlockTime) + } + } + }() + // Wait for 100 blocks to be created, coins mature after 100 blocks and the faucet starts getting 50 spendable coins/block onwards // Then wait the standard 2 blocks which also gives the faucet a starting balance of 100 coins for height, err := c.Height(ctx); err == nil && height < int64(102); { @@ -397,6 +413,8 @@ func (c *UtxoChain) CreateKey(ctx context.Context, keyName string) error { // Get address of account, cast to a string to use. func (c *UtxoChain) GetAddress(ctx context.Context, keyName string) ([]byte, error) { + c.MapAccess.Lock() + defer c.MapAccess.Unlock() wallet, ok := c.KeyNameToWalletMap[keyName] if ok { return []byte(wallet.address), nil @@ -474,10 +492,12 @@ func (c *UtxoChain) Height(ctx context.Context) (int64, error) { } func (c *UtxoChain) GetBalance(ctx context.Context, address string, denom string) (sdkmath.Int, error) { + c.MapAccess.Lock() keyName, ok := c.AddrToKeyNameMap[address] if !ok { return sdkmath.Int{}, fmt.Errorf("wallet not found for address: %s", address) } + c.MapAccess.Unlock() var coinsWithDecimal float64 if c.WalletVersion >= noDefaultKeyWalletVersion { @@ -534,3 +554,7 @@ func (c *UtxoChain) BuildWallet(ctx context.Context, keyName string, mnemonic st } return NewWallet(keyName, string(address)), nil } + +func (c *UtxoChain) Stop() { + c.cancel() +} diff --git a/chain/utxo/wallet.go b/chain/utxo/wallet.go index 420d4ad1d..4bcbd1ba8 100644 --- a/chain/utxo/wallet.go +++ b/chain/utxo/wallet.go @@ -50,6 +50,8 @@ type NodeWallet struct { } func (c *UtxoChain) getWalletForNewAddress(keyName string) (*NodeWallet, error) { + c.MapAccess.Lock() + defer c.MapAccess.Unlock() wallet, found := c.KeyNameToWalletMap[keyName] if c.WalletVersion >= noDefaultKeyWalletVersion { if !found { @@ -75,6 +77,8 @@ func (c *UtxoChain) getWalletForNewAddress(keyName string) (*NodeWallet, error) } func (c *UtxoChain) getWalletForSetAccount(keyName string, addr string) (*NodeWallet, error) { + c.MapAccess.Lock() + defer c.MapAccess.Unlock() wallet, found := c.KeyNameToWalletMap[keyName] if !found { return nil, fmt.Errorf("wallet keyname (%s) not found, get new address not called", keyName) @@ -100,6 +104,8 @@ func (c *UtxoChain) getWalletForUse(keyName string) (*NodeWallet, error) { } func (c *UtxoChain) getWallet(keyName string) (*NodeWallet, error) { + c.MapAccess.Lock() + defer c.MapAccess.Unlock() wallet, found := c.KeyNameToWalletMap[keyName] if !found { return nil, fmt.Errorf("wallet keyname (%s) not found", keyName) diff --git a/examples/thorchain/setup_test.go b/examples/thorchain/setup_test.go index 790fcc145..0cce1a92e 100644 --- a/examples/thorchain/setup_test.go +++ b/examples/thorchain/setup_test.go @@ -94,6 +94,12 @@ func StartExoChains(t *testing.T, ctx context.Context, client *client.Client, ne })) t.Cleanup(func() { _ = ic.Close() + for _, chain := range chains { + utxoChain, ok := chain.(*utxo.UtxoChain) + if ok { + utxoChain.Stop() + } + } }) return exoChains diff --git a/examples/utxo/start_test.go b/examples/utxo/start_test.go index 85788199f..537b92d82 100644 --- a/examples/utxo/start_test.go +++ b/examples/utxo/start_test.go @@ -56,6 +56,12 @@ func TestUtxo(t *testing.T) { })) t.Cleanup(func() { _ = ic.Close() + for _, chain := range chains { + utxoChain, ok := chain.(*utxo.UtxoChain) + if ok { + utxoChain.Stop() + } + } }) // Create and fund a user using GetAndFundTestUsers diff --git a/local-interchain/chains/state/README.md b/local-interchain/chains/state/README.md index 4adec1875..3dd1ffa6a 100644 --- a/local-interchain/chains/state/README.md +++ b/local-interchain/chains/state/README.md @@ -1,3 +1,3 @@ ## avs-and-eigenlayer-deployed-anvil-state.json -- \ No newline at end of file +- \ No newline at end of file