From 55054282d2df794d9a5fe2599ea25473379ebc3d Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Thu, 19 May 2022 15:55:27 +0700 Subject: [PATCH] chore: gofumpt (#11839) * fumpt using main not master... * be more descriptive * fumpt * fix nits Co-authored-by: Julien Robert --- RELEASE_PROCESS.md | 1 + baseapp/abci.go | 6 -- baseapp/baseapp.go | 4 +- client/broadcast_test.go | 1 - client/config/toml.go | 2 +- client/debug/main.go | 7 +- client/grpc/tmservice/block.go | 1 + client/grpc/tmservice/service_test.go | 2 +- client/grpc_query.go | 5 +- client/grpc_query_test.go | 1 + client/input/input_test.go | 1 - client/keys/import_test.go | 2 +- client/keys/list_test.go | 2 +- client/keys/migrate_test.go | 3 +- client/query_test.go | 2 +- client/tx/legacy.go | 1 - client/v2/cli/builder.go | 1 - client/v2/cli/flag/field.go | 1 - client/v2/cli/flag/type.go | 1 - client/v2/cli/flag/value.go | 2 - codec/amino_codec_test.go | 2 +- codec/any_test.go | 4 +- codec/codec_common_test.go | 6 +- codec/proto_codec.go | 6 +- codec/proto_codec_test.go | 4 +- codec/types/any_internal_test.go | 6 +- codec/unknownproto/benchmarks_test.go | 3 + codec/unknownproto/unknown_fields.go | 12 ++- cosmovisor/errors/multi.go | 1 - cosmovisor/process.go | 3 +- cosmovisor/process_test.go | 4 +- cosmovisor/upgrade.go | 6 +- crypto/armor.go | 1 - crypto/hd/algo.go | 17 ++--- crypto/hd/hdpath_test.go | 1 - crypto/keyring/keyring_ledger_test.go | 1 - crypto/keyring/legacy_info.go | 1 - crypto/keyring/migration_test.go | 1 + crypto/keyring/signing_algorithms_test.go | 3 +- crypto/keys/ed25519/ed25519.go | 12 ++- crypto/keys/internal/benchmarking/bench.go | 1 - crypto/keys/internal/ecdsa/privkey.go | 4 - .../internal/ecdsa/privkey_internal_test.go | 4 +- crypto/keys/internal/ecdsa/pubkey.go | 1 - .../internal/ecdsa/pubkey_internal_test.go | 4 +- crypto/keys/multisig/multisig.go | 6 +- crypto/keys/multisig/multisig_test.go | 15 ++-- .../secp256k1/internal/secp256k1/curve.go | 40 +++++----- .../secp256k1/libsecp256k1/contrib/dummy.go | 1 + .../internal/secp256k1/libsecp256k1/dummy.go | 1 + .../secp256k1/libsecp256k1/include/dummy.go | 1 + .../secp256k1/libsecp256k1/src/dummy.go | 1 + .../libsecp256k1/src/modules/dummy.go | 1 + .../libsecp256k1/src/modules/ecdh/dummy.go | 1 + .../src/modules/recovery/dummy.go | 1 + .../internal/secp256k1/secp256_test.go | 2 +- crypto/keys/secp256k1/secp256k1.go | 12 ++- .../keys/secp256k1/secp256k1_internal_test.go | 1 - crypto/keys/secp256k1/secp256k1_test.go | 2 +- crypto/ledger/encode_test.go | 2 - crypto/ledger/ledger_mock.go | 3 +- crypto/ledger/ledger_real.go | 1 + crypto/ledger/ledger_secp256k1.go | 11 +-- crypto/types/compact_bit_array_test.go | 2 - crypto/xsalsa20symmetric/symmetric.go | 6 +- crypto/xsalsa20symmetric/symmetric_test.go | 2 - db/badgerdb/db.go | 12 ++- db/internal/util.go | 1 + db/memdb/db.go | 2 +- db/prefix/prefix.go | 8 +- db/rocksdb/db.go | 4 +- db/version_manager.go | 6 +- errors/errors_test.go | 30 ++++---- math/int_test.go | 3 +- math/uint_internal_test.go | 1 - math/uint_test.go | 2 +- orm/encoding/ormfield/codec.go | 1 - orm/encoding/ormfield/int32.go | 6 +- orm/encoding/ormkv/codec.go | 1 - orm/encoding/ormkv/entry.go | 4 - orm/encoding/ormkv/index_key.go | 1 - orm/encoding/ormkv/primary_key.go | 1 - orm/internal/codegen/file.go | 1 - orm/internal/codegen/index.go | 2 - orm/internal/testkv/debug.go | 1 - orm/model/ormdb/module.go | 1 - orm/model/ormdb/module_test.go | 13 ++-- orm/model/ormtable/backend.go | 2 - orm/model/ormtable/batch.go | 1 - orm/model/ormtable/bench_test.go | 2 +- orm/model/ormtable/hooks.go | 2 - orm/model/ormtable/index.go | 1 - orm/model/ormtable/index_impl.go | 6 +- orm/model/ormtable/iterator.go | 1 - orm/model/ormtable/paginate.go | 1 - orm/model/ormtable/save_test.go | 3 +- orm/model/ormtable/table_impl.go | 6 +- orm/model/ormtable/table_test.go | 5 +- orm/model/ormtable/unique.go | 6 +- pruning/manager_test.go | 6 +- server/config/config_test.go | 4 +- server/config/toml.go | 2 +- server/export_test.go | 3 +- server/grpc/server_test.go | 3 +- server/mock/app.go | 6 +- server/mock/app_test.go | 2 +- server/mock/store.go | 1 + server/mock/tx.go | 8 +- server/rosetta/converter.go | 6 +- server/rosetta/converter_test.go | 5 -- server/rosetta/lib/errors/errors_test.go | 5 +- .../lib/internal/service/construction.go | 1 - server/rosetta/lib/server/server.go | 10 +-- server/util.go | 2 +- server/util_test.go | 2 +- simapp/app.go | 3 +- simapp/params/amino.go | 1 + simapp/sim_test.go | 6 +- simapp/simd/cmd/genaccounts_test.go | 6 +- simapp/simd/cmd/root.go | 5 +- simapp/simd/cmd/testnet.go | 11 +-- simapp/state.go | 1 - simapp/test_helpers.go | 4 +- simapp/utils.go | 4 +- snapshots/chunk.go | 2 +- snapshots/manager.go | 4 +- snapshots/store.go | 4 +- snapshots/store_test.go | 27 ++++--- store/cachekv/store_test.go | 4 +- store/cachemulti/store.go | 1 - store/iavl/store_test.go | 2 +- store/internal/maps/maps_test.go | 2 + store/listenkv/store_test.go | 9 ++- store/rootmulti/store.go | 3 +- store/rootmulti/store_test.go | 1 - store/streaming/file/service.go | 8 +- store/streaming/file/service_test.go | 2 +- store/tools/ics23/smt/create_test.go | 32 ++++---- store/tracekv/store_test.go | 1 - store/transient/store.go | 6 +- store/types/errors.go | 4 +- store/types/iterator.go | 1 - store/types/store.go | 1 - store/v2alpha1/multi/snapshot.go | 2 +- store/v2alpha1/multi/store.go | 2 + store/v2alpha1/multi/store_test.go | 9 ++- store/v2alpha1/multi/test_util.go | 39 ++++++---- store/v2alpha1/smt/proof_test.go | 2 +- testutil/network/network.go | 10 ++- testutil/network/network_test.go | 1 + testutil/network/util.go | 5 +- testutil/testdata/table.go | 4 +- testutil/testdata/tx.go | 2 + types/address.go | 14 ++-- types/address/hash_test.go | 4 +- types/address_test.go | 1 - types/bench_test.go | 4 +- types/coin_test.go | 14 ++-- types/context.go | 2 +- types/dec_coin_test.go | 38 ++++++---- types/decimal_test.go | 37 ++++++---- types/module/module.go | 3 +- types/module/module_test.go | 6 +- types/module/simulation.go | 1 - types/query/filtered_pagination.go | 1 - types/query/filtered_pagination_test.go | 2 - types/query/pagination.go | 1 - types/simulation/rand_util.go | 4 +- types/simulation/types.go | 1 - types/store_internal_test.go | 2 +- types/store_test.go | 4 +- types/tx/signing/signature.go | 1 - types/tx/types.go | 2 + types/utils_test.go | 30 +++++--- x/auth/client/cli/tx_multisign.go | 4 +- x/auth/client/cli/tx_sign.go | 4 +- x/auth/client/testutil/cli_test.go | 1 + x/auth/client/testutil/suite.go | 7 +- x/auth/client/tx.go | 4 +- x/auth/client/tx_test.go | 2 +- x/auth/keeper/grpc_query.go | 2 - x/auth/keeper/grpc_query_test.go | 18 ++--- x/auth/keeper/keeper.go | 1 - x/auth/middleware/basic_test.go | 1 - x/auth/middleware/block_gas.go | 1 - x/auth/middleware/branch_store_test.go | 2 +- x/auth/middleware/feegrant_test.go | 3 +- x/auth/middleware/gas_test.go | 2 + x/auth/middleware/middleware_test.go | 3 +- x/auth/middleware/sigverify.go | 1 - x/auth/middleware/tips_test.go | 9 ++- x/auth/migrations/legacytx/stdtx_builder.go | 2 +- x/auth/migrations/legacytx/stdtx_test.go | 2 +- x/auth/migrations/v043/store.go | 4 - x/auth/migrations/v043/store_test.go | 11 --- x/auth/testutil/suite.go | 6 +- x/auth/tx/direct_aux.go | 1 - x/auth/tx/encode_decode_test.go | 29 +++++--- x/auth/tx/encoder.go | 1 - x/auth/tx/query.go | 2 +- x/auth/tx/service.go | 4 +- x/auth/types/genesis_test.go | 4 +- x/auth/types/permissions_test.go | 1 - x/auth/vesting/client/testutil/cli_test.go | 1 + x/auth/vesting/msg_server.go | 1 - x/auth/vesting/types/msgs.go | 1 + x/auth/vesting/types/vesting_account.go | 24 ++++-- x/auth/vesting/types/vesting_account_test.go | 4 +- x/authz/authorization_grant.go | 4 +- x/authz/authorization_grant_test.go | 3 +- x/authz/client/cli/query.go | 5 +- x/authz/client/cli/tx.go | 1 - x/authz/client/testutil/grpc.go | 3 - x/authz/client/testutil/tx.go | 10 +-- x/authz/codec.go | 1 + x/authz/errors.go | 2 +- x/authz/generic_authorization.go | 4 +- x/authz/keeper/grpc_query.go | 6 +- x/authz/keeper/keeper.go | 11 +-- x/authz/keeper/keeper_test.go | 2 - x/authz/keeper/keys_test.go | 8 +- x/authz/migrations/v046/keys.go | 4 +- x/authz/migrations/v046/keys_test.go | 8 +- x/authz/module/abci.go | 1 - x/authz/module/abci_test.go | 4 +- x/authz/msgs.go | 3 +- x/authz/msgs_test.go | 46 ++++++++---- x/authz/simulation/operations.go | 4 +- x/authz/simulation/operations_test.go | 6 +- x/bank/keeper/grpc_query.go | 4 - x/bank/keeper/invariants.go | 1 - x/bank/keeper/keeper.go | 6 -- x/bank/keeper/send.go | 1 - x/bank/migrations/v046/keys.go | 4 +- x/bank/migrations/v046/store.go | 2 +- x/bank/simulation/operations.go | 7 -- x/bank/types/balance.go | 1 + x/bank/types/balance_test.go | 1 - x/bank/types/genesis_test.go | 2 - x/bank/types/metadata_test.go | 25 ++++--- x/bank/types/msgs_test.go | 13 ++-- x/bank/types/send_authorization.go | 4 +- x/capability/keeper/keeper.go | 2 - x/capability/types/genesis_test.go | 6 -- x/crisis/client/testsuite/cli_test.go | 1 + x/crisis/keeper/keeper.go | 1 - x/crisis/types/params.go | 6 +- x/distribution/client/cli/tx.go | 1 - x/distribution/client/common/common_test.go | 3 +- x/distribution/client/testutil/suite.go | 22 ++++-- x/distribution/keeper/allocation.go | 1 - x/distribution/keeper/delegation.go | 3 +- x/distribution/keeper/grpc_query.go | 2 - x/distribution/keeper/hooks.go | 2 + x/distribution/keeper/invariants.go | 3 - x/distribution/keeper/keeper.go | 1 - x/distribution/keeper/store.go | 3 +- x/distribution/migrations/v043/helpers.go | 2 +- x/distribution/simulation/operations.go | 3 - x/distribution/simulation/operations_test.go | 2 - x/distribution/types/fee_pool_test.go | 1 - x/distribution/types/genesis.go | 1 - x/distribution/types/query.go | 6 +- x/evidence/client/cli/query.go | 1 - x/evidence/client/testutil/cli_test.go | 1 + x/evidence/keeper/grpc_query.go | 1 - x/evidence/keeper/grpc_query_test.go | 4 +- x/evidence/keeper/keeper.go | 1 - x/evidence/types/genesis_test.go | 7 +- x/evidence/types/msgs.go | 1 + x/feegrant/client/cli/query.go | 3 - x/feegrant/client/cli/tx.go | 1 - x/feegrant/filtered_fee.go | 6 +- x/feegrant/grant.go | 4 +- x/feegrant/keeper/grpc_query.go | 2 - x/feegrant/keeper/grpc_query_test.go | 1 - x/feegrant/keeper/keeper.go | 1 - x/feegrant/keeper/keeper_test.go | 1 - x/feegrant/keeper/msg_server_test.go | 1 - x/feegrant/key.go | 3 +- x/feegrant/simulation/operations.go | 4 - x/feegrant/simulation/operations_test.go | 1 - x/genutil/client/cli/gentx.go | 4 +- x/genutil/client/cli/init_test.go | 3 +- x/genutil/client/testutil/cli_test.go | 1 + x/genutil/client/testutil/validate_genesis.go | 1 - x/genutil/collect.go | 1 - x/genutil/collect_test.go | 2 +- x/genutil/gentx.go | 3 - x/genutil/gentx_test.go | 1 - x/genutil/module.go | 1 - x/genutil/types/genesis_state.go | 1 - x/genutil/types/genesis_state_test.go | 1 - x/genutil/utils.go | 5 +- x/genutil/utils_test.go | 2 +- x/gov/client/cli/query.go | 4 - x/gov/client/utils/query.go | 2 - x/gov/client/utils/query_test.go | 5 +- x/gov/common_test.go | 12 ++- x/gov/keeper/grpc_query.go | 3 - x/gov/keeper/grpc_query_test.go | 4 +- x/gov/keeper/hooks_test.go | 2 + x/gov/keeper/keeper.go | 1 - x/gov/keeper/msg_server.go | 1 - x/gov/keeper/querier_test.go | 4 +- x/gov/keeper/tally.go | 1 - x/gov/migrations/v046/convert_test.go | 1 - x/gov/simulation/operations.go | 10 ++- x/gov/simulation/operations_test.go | 2 - x/gov/types/hooks.go | 2 + x/gov/types/keys_test.go | 2 - x/gov/types/v1/genesis_test.go | 1 - x/gov/types/v1/proposal.go | 1 - x/gov/types/v1/tally.go | 4 +- x/gov/types/v1beta1/msgs.go | 1 + x/gov/types/v1beta1/tally.go | 4 +- x/group/client/testutil/query.go | 3 +- x/group/client/testutil/tx.go | 17 ++++- x/group/genesis_test.go | 2 - x/group/internal/orm/indexer_test.go | 3 +- x/group/internal/orm/iterator.go | 2 +- x/group/internal/orm/iterator_test.go | 1 - x/group/internal/orm/primary_key_test.go | 1 - x/group/internal/orm/table.go | 2 +- x/group/internal/orm/table_test.go | 6 +- x/group/internal/orm/types_test.go | 2 +- x/group/keeper/genesis.go | 1 - x/group/keeper/genesis_test.go | 2 - x/group/keeper/invariants.go | 1 - x/group/keeper/invariants_test.go | 1 - x/group/keeper/keeper.go | 2 - x/group/keeper/keeper_test.go | 9 ++- x/group/keeper/msg_server.go | 11 ++- x/group/module/abci_test.go | 8 +- x/group/msgs.go | 20 +++-- x/group/proposal.go | 1 - x/group/simulation/genesis.go | 1 - x/group/simulation/genesis_test.go | 1 - x/group/simulation/operations.go | 74 ++++++++++++------- x/group/types.go | 5 +- x/mint/client/cli/query.go | 3 - x/mint/client/testutil/cli_test.go | 1 + x/mint/simulation/params_test.go | 1 - x/mint/types/codec.go | 4 +- x/mint/types/minter_test.go | 14 ++-- x/mint/types/params.go | 2 - x/nft/keeper/genesis.go | 1 - x/nft/keeper/grpc_query.go | 2 - x/nft/keeper/grpc_query_test.go | 9 +-- x/nft/keeper/keeper_test.go | 2 +- x/nft/keeper/keys.go | 6 +- x/nft/keeper/nft.go | 3 +- x/nft/msgs.go | 4 +- x/nft/simulation/operations.go | 15 ++-- x/nft/simulation/operations_test.go | 1 - x/params/client/testutil/cli_test.go | 1 + x/params/keeper/grpc_query.go | 1 - x/params/module.go | 1 - x/simulation/event_stats.go | 2 +- x/simulation/log.go | 1 - x/simulation/mock_tendermint.go | 5 +- x/simulation/params_test.go | 3 +- x/simulation/simulate.go | 13 ++-- x/simulation/util.go | 2 - x/slashing/client/cli/query.go | 1 - x/slashing/client/testutil/cli_test.go | 1 + x/slashing/init_test.go | 6 +- x/slashing/keeper/common_test.go | 6 +- x/slashing/keeper/grpc_query_test.go | 2 +- x/slashing/keeper/keeper_test.go | 1 - x/slashing/keeper/signing_info.go | 8 +- x/slashing/simulation/genesis_test.go | 1 - x/slashing/simulation/operations.go | 2 - x/slashing/types/genesis.go | 1 - x/slashing/types/params.go | 1 - x/slashing/types/signing_info.go | 1 - x/staking/app_test.go | 1 - x/staking/client/cli/tx.go | 2 - x/staking/client/cli/tx_test.go | 12 ++- x/staking/client/testutil/test_helpers.go | 8 +- x/staking/keeper/alias_functions.go | 3 +- x/staking/keeper/common_test.go | 4 +- x/staking/keeper/delegation.go | 41 ++++------ x/staking/keeper/delegation_test.go | 16 ++-- x/staking/keeper/grpc_query.go | 10 +-- x/staking/keeper/grpc_query_test.go | 48 ++++++++---- x/staking/keeper/keeper_test.go | 5 +- x/staking/keeper/querier.go | 1 - x/staking/keeper/slash.go | 6 +- x/staking/keeper/validator.go | 12 ++- x/staking/keeper/validator_bench_test.go | 4 +- x/staking/keeper/validator_test.go | 8 +- x/staking/simulation/genesis_test.go | 3 +- x/staking/simulation/operations_test.go | 4 +- x/staking/types/authz.go | 16 ++-- x/staking/types/authz_test.go | 21 ++++-- x/staking/types/delegation.go | 4 +- x/staking/types/historical_info_test.go | 5 +- x/staking/types/hooks.go | 9 +++ x/staking/types/keys_test.go | 36 ++++++--- x/staking/types/params.go | 6 +- x/staking/types/validator.go | 2 - x/staking/types/validator_test.go | 1 - x/upgrade/client/proposal_handler.go | 6 +- x/upgrade/client/testutil/suite.go | 1 - x/upgrade/keeper/keeper_test.go | 1 - x/upgrade/plan/downloader.go | 2 +- x/upgrade/plan/downloader_test.go | 8 +- x/upgrade/types/plan_test.go | 2 - x/upgrade/types/proposal.go | 1 + x/upgrade/types/proposal_test.go | 1 - x/upgrade/types/storeloader_test.go | 2 +- 412 files changed, 1014 insertions(+), 1053 deletions(-) diff --git a/RELEASE_PROCESS.md b/RELEASE_PROCESS.md index 07e1edf7e204..76b9156d47da 100644 --- a/RELEASE_PROCESS.md +++ b/RELEASE_PROCESS.md @@ -31,6 +31,7 @@ v1.0.0-beta1 → v1.0.0-beta2 → ... → v1.0.0-rc1 → v1.0.0-rc2 → ... → * create new release candidate tags after bugs are fixed. * After the team feels the release branch is stable and everything works, create a full release: * update `CHANGELOG.md`. + * run `gofumpt -w -l .` to format the code. * create a new annotated git tag (eg `git -a v1.1.0`) in the release branch. * Create a GitHub release. diff --git a/baseapp/abci.go b/baseapp/abci.go index e03d4b587fb4..87529d2560e4 100644 --- a/baseapp/abci.go +++ b/baseapp/abci.go @@ -143,7 +143,6 @@ func (app *BaseApp) FilterPeerByID(info string) abci.ResponseQuery { // BeginBlock implements the ABCI application interface. func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeginBlock) { - if app.cms.TracingEnabled() { app.cms.SetTracingContext(sdk.TraceContext( map[string]interface{}{"blockHeight": req.Header.Height}, @@ -209,7 +208,6 @@ func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeg // EndBlock implements the ABCI interface. func (app *BaseApp) EndBlock(req abci.RequestEndBlock) (res abci.ResponseEndBlock) { - if app.deliverState.ms.TracingEnabled() { app.deliverState.ms = app.deliverState.ms.SetTracingContext(nil).(sdk.CacheMultiStore) } @@ -240,7 +238,6 @@ func (app *BaseApp) EndBlock(req abci.RequestEndBlock) (res abci.ResponseEndBloc // will contain releveant error information. Regardless of tx execution outcome, // the ResponseCheckTx will contain relevant gas execution context. func (app *BaseApp) CheckTx(req abci.RequestCheckTx) abci.ResponseCheckTx { - var mode runTxMode switch { @@ -274,7 +271,6 @@ func (app *BaseApp) CheckTx(req abci.RequestCheckTx) abci.ResponseCheckTx { // Regardless of tx execution outcome, the ResponseDeliverTx will contain relevant // gas execution context. func (app *BaseApp) DeliverTx(req abci.RequestDeliverTx) abci.ResponseDeliverTx { - var abciRes abci.ResponseDeliverTx defer func() { for _, streamingListener := range app.abciListeners { @@ -297,7 +293,6 @@ func (app *BaseApp) DeliverTx(req abci.RequestDeliverTx) abci.ResponseDeliverTx } return abciRes - } // Commit implements the ABCI interface. It will commit all state that exists in @@ -308,7 +303,6 @@ func (app *BaseApp) DeliverTx(req abci.RequestDeliverTx) abci.ResponseDeliverTx // against that height and gracefully halt if it matches the latest committed // height. func (app *BaseApp) Commit() (res abci.ResponseCommit) { - header := app.deliverState.ctx.BlockHeader() retainHeight := app.GetBlockRetentionHeight(header.Height) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 2dfa029b7c2f..7634416e656d 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -25,9 +25,7 @@ const ( runTxModeDeliver // Deliver a transaction ) -var ( - _ abci.Application = (*BaseApp)(nil) -) +var _ abci.Application = (*BaseApp)(nil) type ( // Enum mode for app.runTx diff --git a/client/broadcast_test.go b/client/broadcast_test.go index 424c7d364753..32b9b42c1fca 100644 --- a/client/broadcast_test.go +++ b/client/broadcast_test.go @@ -66,5 +66,4 @@ func TestBroadcastError(t *testing.T) { require.Equal(t, txHash, resp.TxHash) } } - } diff --git a/client/config/toml.go b/client/config/toml.go index a26cf78e6f17..97c8b00b42c5 100644 --- a/client/config/toml.go +++ b/client/config/toml.go @@ -42,7 +42,7 @@ func writeConfigToFile(configFilePath string, config *ClientConfig) error { return err } - return os.WriteFile(configFilePath, buffer.Bytes(), 0600) + return os.WriteFile(configFilePath, buffer.Bytes(), 0o600) } // ensureConfigPath creates a directory configPath if it does not exist diff --git a/client/debug/main.go b/client/debug/main.go index 05a1b311337c..5eb795ffb9ed 100644 --- a/client/debug/main.go +++ b/client/debug/main.go @@ -20,9 +20,7 @@ import ( legacybech32 "github.com/cosmos/cosmos-sdk/types/bech32/legacybech32" ) -var ( - flagPubkeyType = "type" -) +var flagPubkeyType = "type" // Cmd creates a main CLI command func Cmd() *cobra.Command { @@ -178,7 +176,6 @@ $ %s debug pubkey-raw cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg cmd.Println("Bech32 Acc:", accPub) cmd.Println("Bech32 Validator Operator:", valPub) if pubkeyType == "ed25519" { - cmd.Println("Bech32 Validator Consensus:", consensusPub) } @@ -200,7 +197,6 @@ $ %s debug addr cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg `, version.AppName), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - addrString := args[0] var addr []byte @@ -216,7 +212,6 @@ $ %s debug addr cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg if err3 != nil { return fmt.Errorf("expected hex or bech32. Got errors: hex: %v, bech32 acc: %v, bech32 val: %v", err, err2, err3) - } } } diff --git a/client/grpc/tmservice/block.go b/client/grpc/tmservice/block.go index 3bed4268f303..6f3b1e556993 100644 --- a/client/grpc/tmservice/block.go +++ b/client/grpc/tmservice/block.go @@ -2,6 +2,7 @@ package tmservice import ( "context" + "github.com/cosmos/cosmos-sdk/client" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/tendermint/tendermint/rpc/coretypes" diff --git a/client/grpc/tmservice/service_test.go b/client/grpc/tmservice/service_test.go index 54607bef29f7..35934f934629 100644 --- a/client/grpc/tmservice/service_test.go +++ b/client/grpc/tmservice/service_test.go @@ -113,7 +113,7 @@ func (s IntegrationTestSuite) TestQueryLatestValidatorSet() { s.Require().Equal(true, ok) s.Require().Equal(content, val.PubKey) - //with pagination + // with pagination _, err = s.queryClient.GetLatestValidatorSet(context.Background(), &tmservice.GetLatestValidatorSetRequest{Pagination: &qtypes.PageRequest{ Offset: 0, Limit: 10, diff --git a/client/grpc_query.go b/client/grpc_query.go index 15c0725f2e57..dd0f5ab11335 100644 --- a/client/grpc_query.go +++ b/client/grpc_query.go @@ -4,11 +4,12 @@ import ( gocontext "context" "errors" "fmt" + "reflect" + "strconv" + "github.com/cosmos/cosmos-sdk/codec" proto "github.com/gogo/protobuf/proto" "google.golang.org/grpc/encoding" - "reflect" - "strconv" gogogrpc "github.com/gogo/protobuf/grpc" abci "github.com/tendermint/tendermint/abci/types" diff --git a/client/grpc_query_test.go b/client/grpc_query_test.go index b63937ac2337..faff1ad5dc64 100644 --- a/client/grpc_query_test.go +++ b/client/grpc_query_test.go @@ -1,3 +1,4 @@ +//go:build norace // +build norace package client_test diff --git a/client/input/input_test.go b/client/input/input_test.go index 9e85eb256a20..3132afcdfaa4 100644 --- a/client/input/input_test.go +++ b/client/input/input_test.go @@ -53,5 +53,4 @@ func TestReadLineFromBuf(t *testing.T) { _, err := readLineFromBuf(buf) require.ErrorIs(t, err, expectedErr) }) - } diff --git a/client/keys/import_test.go b/client/keys/import_test.go index 720fe1939fe0..416992c2c55a 100644 --- a/client/keys/import_test.go +++ b/client/keys/import_test.go @@ -94,7 +94,7 @@ HbP+c6JmeJy9JXe2rbbF1QtCX1gLqGcDQPBXiCtFvP7/8wTZtVOPj8vREzhZ9ElO t.Cleanup(cleanupKeys(t, kb, "keyname1")) keyfile := filepath.Join(kbHome, "key.asc") - require.NoError(t, os.WriteFile(keyfile, []byte(armoredKey), 0644)) + require.NoError(t, os.WriteFile(keyfile, []byte(armoredKey), 0o644)) defer func() { _ = os.RemoveAll(kbHome) diff --git a/client/keys/list_test.go b/client/keys/list_test.go index 771c06ede8fd..548413efad06 100644 --- a/client/keys/list_test.go +++ b/client/keys/list_test.go @@ -42,7 +42,7 @@ func Test_runListCmd(t *testing.T) { clientCtx := client.Context{}.WithKeyring(kb) ctx := context.WithValue(context.Background(), client.ClientContextKey, &clientCtx) - path := "" //sdk.GetConfig().GetFullBIP44Path() + path := "" // sdk.GetConfig().GetFullBIP44Path() _, err = kb.NewAccount("something", testdata.TestMnemonic, "", path, hd.Secp256k1) require.NoError(t, err) diff --git a/client/keys/migrate_test.go b/client/keys/migrate_test.go index 3e5e54942a91..b105db7cb747 100644 --- a/client/keys/migrate_test.go +++ b/client/keys/migrate_test.go @@ -43,7 +43,6 @@ func (s *MigrateTestSuite) SetupSuite() { } func (s *MigrateTestSuite) Test_runListAndShowCmd() { - // adding LegacyInfo item into keyring multi := multisig.NewLegacyAminoPubKey( 1, []cryptotypes.PubKey{ @@ -60,7 +59,7 @@ func (s *MigrateTestSuite) Test_runListAndShowCmd() { Description: "SDK keyring version", } - //run test simd keys list - to see that the migrated key is there + // run test simd keys list - to see that the migrated key is there cmd := ListKeysCmd() cmd.Flags().AddFlagSet(Commands("home").PersistentFlags()) diff --git a/client/query_test.go b/client/query_test.go index 14cc25ba9d97..04532f566ba3 100644 --- a/client/query_test.go +++ b/client/query_test.go @@ -1,3 +1,4 @@ +//go:build norace // +build norace package client_test @@ -11,7 +12,6 @@ import ( ) func (s *IntegrationTestSuite) TestQueryABCIHeight() { - testCases := []struct { name string reqHeight int64 diff --git a/client/tx/legacy.go b/client/tx/legacy.go index 7a46e194aaa5..c07982a3fe4d 100644 --- a/client/tx/legacy.go +++ b/client/tx/legacy.go @@ -20,7 +20,6 @@ func ConvertTxToStdTx(codec *codec.LegacyAmino, tx signing.Tx) (legacytx.StdTx, err := CopyTx(tx, builder, true) if err != nil { - return legacytx.StdTx{}, err } diff --git a/client/v2/cli/builder.go b/client/v2/cli/builder.go index ecc4b0c9c094..992fc9df4e74 100644 --- a/client/v2/cli/builder.go +++ b/client/v2/cli/builder.go @@ -10,7 +10,6 @@ import ( // Builder manages options for building CLI commands. type Builder struct { - // flag.Builder embeds the flag builder and its options. flag.Builder diff --git a/client/v2/cli/flag/field.go b/client/v2/cli/flag/field.go index fa96802e9948..c894e0610e48 100644 --- a/client/v2/cli/flag/field.go +++ b/client/v2/cli/flag/field.go @@ -20,7 +20,6 @@ type FieldValueBinder interface { // Options specifies options for specific flags. type Options struct { - // Prefix is a prefix to prepend to all flags. Prefix string } diff --git a/client/v2/cli/flag/type.go b/client/v2/cli/flag/type.go index c47e31f7e850..62fce2a6bcd2 100644 --- a/client/v2/cli/flag/type.go +++ b/client/v2/cli/flag/type.go @@ -8,7 +8,6 @@ import ( // Type specifies a custom flag type. type Type interface { - // NewValue returns a new pflag.Value which must also implement either // SimpleValue or ListValue. NewValue(context.Context, *Builder) pflag.Value diff --git a/client/v2/cli/flag/value.go b/client/v2/cli/flag/value.go index 94d75bf05dd8..304139e642a2 100644 --- a/client/v2/cli/flag/value.go +++ b/client/v2/cli/flag/value.go @@ -6,14 +6,12 @@ import ( // SimpleValue wraps a simple (non-list and non-map) protobuf value. type SimpleValue interface { - // Get returns the value. Get() protoreflect.Value } // ListValue wraps a protobuf list/repeating value. type ListValue interface { - // AppendTo appends the values to the provided list. AppendTo(protoreflect.List) } diff --git a/codec/amino_codec_test.go b/codec/amino_codec_test.go index c2f09710ae2b..460ef8ca4184 100644 --- a/codec/amino_codec_test.go +++ b/codec/amino_codec_test.go @@ -121,7 +121,7 @@ func TestAminoCodecUnpackAnyFails(t *testing.T) { func TestAminoCodecFullDecodeAndEncode(t *testing.T) { // This tx comes from https://github.com/cosmos/cosmos-sdk/issues/8117. txSigned := `{"type":"cosmos-sdk/StdTx","value":{"msg":[{"type":"cosmos-sdk/MsgCreateValidator","value":{"description":{"moniker":"fulltest","identity":"satoshi","website":"example.com","details":"example inc"},"commission":{"rate":"0.500000000000000000","max_rate":"1.000000000000000000","max_change_rate":"0.200000000000000000"},"min_self_delegation":"1000000","delegator_address":"cosmos14pt0q5cwf38zt08uu0n6yrstf3rndzr5057jys","validator_address":"cosmosvaloper14pt0q5cwf38zt08uu0n6yrstf3rndzr52q28gr","pubkey":{"type":"tendermint/PubKeyEd25519","value":"CYrOiM3HtS7uv1B1OAkknZnFYSRpQYSYII8AtMMtev0="},"value":{"denom":"umuon","amount":"700000000"}}}],"fee":{"amount":[{"denom":"umuon","amount":"6000"}],"gas":"160000"},"signatures":[{"pub_key":{"type":"tendermint/PubKeySecp256k1","value":"AwAOXeWgNf1FjMaayrSnrOOKz+Fivr6DiI/i0x0sZCHw"},"signature":"RcnfS/u2yl7uIShTrSUlDWvsXo2p2dYu6WJC8VDVHMBLEQZWc8bsINSCjOnlsIVkUNNe1q/WCA9n3Gy1+0zhYA=="}],"memo":"","timeout_height":"0"}}` - var legacyCdc = simapp.MakeTestEncodingConfig().Amino + legacyCdc := simapp.MakeTestEncodingConfig().Amino var tx legacytx.StdTx err := legacyCdc.UnmarshalJSON([]byte(txSigned), &tx) require.NoError(t, err) diff --git a/codec/any_test.go b/codec/any_test.go index 92bb9d0d5004..8b4b96a7fb5b 100644 --- a/codec/any_test.go +++ b/codec/any_test.go @@ -79,7 +79,7 @@ func TestMarshalProtoPubKey(t *testing.T) { var pkI cryptotypes.PubKey err = ccfg.InterfaceRegistry.UnpackAny(&pkAny2, &pkI) require.NoError(err) - var pk2 = pkAny2.GetCachedValue().(cryptotypes.PubKey) + pk2 := pkAny2.GetCachedValue().(cryptotypes.PubKey) require.True(pk2.Equals(pk)) // **** test binary serialization **** @@ -92,7 +92,7 @@ func TestMarshalProtoPubKey(t *testing.T) { require.NoError(err) err = ccfg.InterfaceRegistry.UnpackAny(&pkAny3, &pkI) require.NoError(err) - var pk3 = pkAny3.GetCachedValue().(cryptotypes.PubKey) + pk3 := pkAny3.GetCachedValue().(cryptotypes.PubKey) require.True(pk3.Equals(pk)) } diff --git a/codec/codec_common_test.go b/codec/codec_common_test.go index c2435b08206b..d9a8c756ec3f 100644 --- a/codec/codec_common_test.go +++ b/codec/codec_common_test.go @@ -104,7 +104,8 @@ func testMarshaling(t *testing.T, cdc codec.Codec) { &testdata.Cat{}, false, true, - }} + }, + } if _, ok := cdc.(*codec.AminoCodec); ok { testCases = append(testCases, testCase{ "any marshaling", @@ -123,7 +124,8 @@ func testMarshaling(t *testing.T, cdc codec.Codec) { func(i codec.ProtoMarshaler) ([]byte, error) { return cdc.MarshalJSON(i) }, func(i codec.ProtoMarshaler) []byte { return cdc.MustMarshalJSON(i) }, func(bz []byte, ptr codec.ProtoMarshaler) error { return cdc.UnmarshalJSON(bz, ptr) }, - func(bz []byte, ptr codec.ProtoMarshaler) { cdc.MustUnmarshalJSON(bz, ptr) }} + func(bz []byte, ptr codec.ProtoMarshaler) { cdc.MustUnmarshalJSON(bz, ptr) }, + } t.Run(tc.name+"_BinaryBare", func(t *testing.T) { testMarshalingTestCase(require.New(t), tc, m1) }) diff --git a/codec/proto_codec.go b/codec/proto_codec.go index faccd9528181..05bdf1b05210 100644 --- a/codec/proto_codec.go +++ b/codec/proto_codec.go @@ -29,8 +29,10 @@ type ProtoCodec struct { interfaceRegistry types.InterfaceRegistry } -var _ Codec = &ProtoCodec{} -var _ ProtoCodecMarshaler = &ProtoCodec{} +var ( + _ Codec = &ProtoCodec{} + _ ProtoCodecMarshaler = &ProtoCodec{} +) // NewProtoCodec returns a reference to a new ProtoCodec func NewProtoCodec(interfaceRegistry types.InterfaceRegistry) *ProtoCodec { diff --git a/codec/proto_codec_test.go b/codec/proto_codec_test.go index 40d810deefc1..6e83501cf501 100644 --- a/codec/proto_codec_test.go +++ b/codec/proto_codec_test.go @@ -99,8 +99,8 @@ func mustAny(msg proto.Message) *types.Any { } func BenchmarkProtoCodecMarshalLengthPrefixed(b *testing.B) { - var pCdc = codec.NewProtoCodec(types.NewInterfaceRegistry()) - var msg = &testdata.HasAnimal{ + pCdc := codec.NewProtoCodec(types.NewInterfaceRegistry()) + msg := &testdata.HasAnimal{ X: 1000, Animal: mustAny(&testdata.HasAnimal{ X: 2000, diff --git a/codec/types/any_internal_test.go b/codec/types/any_internal_test.go index b3e847965d59..f03e8247f67a 100644 --- a/codec/types/any_internal_test.go +++ b/codec/types/any_internal_test.go @@ -23,8 +23,10 @@ type Animal interface { Greet() string } -var _ Animal = (*Dog)(nil) -var _ proto.Message = (*Dog)(nil) +var ( + _ Animal = (*Dog)(nil) + _ proto.Message = (*Dog)(nil) +) func TestAnyPackUnpack(t *testing.T) { registry := NewInterfaceRegistry() diff --git a/codec/unknownproto/benchmarks_test.go b/codec/unknownproto/benchmarks_test.go index 373dda7acfd5..c38f5c47a2b8 100644 --- a/codec/unknownproto/benchmarks_test.go +++ b/codec/unknownproto/benchmarks_test.go @@ -45,6 +45,7 @@ func init() { func BenchmarkRejectUnknownFields_serial(b *testing.B) { benchmarkRejectUnknownFields(b, false) } + func BenchmarkRejectUnknownFields_parallel(b *testing.B) { benchmarkRejectUnknownFields(b, true) } @@ -82,9 +83,11 @@ func benchmarkRejectUnknownFields(b *testing.B, parallel bool) { func BenchmarkProtoUnmarshal_serial(b *testing.B) { benchmarkProtoUnmarshal(b, false) } + func BenchmarkProtoUnmarshal_parallel(b *testing.B) { benchmarkProtoUnmarshal(b, true) } + func benchmarkProtoUnmarshal(b *testing.B, parallel bool) { b.ReportAllocs() diff --git a/codec/unknownproto/unknown_fields.go b/codec/unknownproto/unknown_fields.go index 36b745e1e04b..3af40ffed15b 100644 --- a/codec/unknownproto/unknown_fields.go +++ b/codec/unknownproto/unknown_fields.go @@ -162,8 +162,10 @@ func RejectUnknownFields(bz []byte, msg proto.Message, allowUnknownNonCriticals return hasUnknownNonCriticals, nil } -var protoMessageForTypeNameMu sync.RWMutex -var protoMessageForTypeNameCache = make(map[string]proto.Message) +var ( + protoMessageForTypeNameMu sync.RWMutex + protoMessageForTypeNameCache = make(map[string]proto.Message) +) // protoMessageForTypeName takes in a fully qualified name e.g. testdata.TestVersionFD1 // and returns a corresponding empty protobuf message that serves the prototype for typechecking. @@ -382,8 +384,10 @@ type descriptorMatch struct { desc *descriptor.DescriptorProto } -var descprotoCacheMu sync.RWMutex -var descprotoCache = make(map[reflect.Type]*descriptorMatch) +var ( + descprotoCacheMu sync.RWMutex + descprotoCache = make(map[reflect.Type]*descriptorMatch) +) // getDescriptorInfo retrieves the mapping of field numbers to their respective field descriptors. func getDescriptorInfo(desc descriptorIface, msg proto.Message) (map[int32]*descriptor.FieldDescriptorProto, *descriptor.DescriptorProto, error) { diff --git a/cosmovisor/errors/multi.go b/cosmovisor/errors/multi.go index d37212da2d96..a78a61a4e8f4 100644 --- a/cosmovisor/errors/multi.go +++ b/cosmovisor/errors/multi.go @@ -82,5 +82,4 @@ func LogErrors(logger *zerolog.Logger, msg string, err error) { default: logger.Error().Err(err).Msg(msg) } - } diff --git a/cosmovisor/process.go b/cosmovisor/process.go index 4087352de75a..17b9b67eaf04 100644 --- a/cosmovisor/process.go +++ b/cosmovisor/process.go @@ -95,7 +95,7 @@ func (l Launcher) WaitForUpgradeOrExit(cmd *exec.Cmd) (bool, error) { l.logger.Error().Err(err) } - var cmdDone = make(chan error) + cmdDone := make(chan error) go func() { cmdDone <- cmd.Wait() }() @@ -212,7 +212,6 @@ func IsSkipUpgradeHeight(args []string, upgradeInfo upgradetypes.Plan) bool { if h == int(upgradeInfo.Height) { return true } - } return false } diff --git a/cosmovisor/process_test.go b/cosmovisor/process_test.go index 31e948472b77..623634277bb6 100644 --- a/cosmovisor/process_test.go +++ b/cosmovisor/process_test.go @@ -32,7 +32,7 @@ func (s *processTestSuite) TestLaunchProcess() { logger := cosmovisor.NewLogger() // should run the genesis binary and produce expected output - var stdout, stderr = NewBuffer(), NewBuffer() + stdout, stderr := NewBuffer(), NewBuffer() currentBin, err := cfg.CurrentBin() require.NoError(err) require.Equal(cfg.GenesisBin(), currentBin) @@ -91,7 +91,7 @@ func (s *processTestSuite) TestLaunchProcessWithDownloads() { launcher, err := cosmovisor.NewLauncher(logger, cfg) require.NoError(err) - var stdout, stderr = NewBuffer(), NewBuffer() + stdout, stderr := NewBuffer(), NewBuffer() args := []string{"some", "args", upgradeFilename} doUpgrade, err := launcher.Run(args, stdout, stderr) diff --git a/cosmovisor/upgrade.go b/cosmovisor/upgrade.go index a3e5960ffe89..9667ffb5ede4 100644 --- a/cosmovisor/upgrade.go +++ b/cosmovisor/upgrade.go @@ -91,11 +91,11 @@ func MarkExecutable(path string) error { return fmt.Errorf("stating binary: %w", err) } // end early if world exec already set - if info.Mode()&0001 == 1 { + if info.Mode()&0o001 == 1 { return nil } // now try to set all exec bits - newMode := info.Mode().Perm() | 0111 + newMode := info.Mode().Perm() | 0o111 return os.Chmod(path, newMode) } @@ -162,7 +162,7 @@ func EnsureBinary(path string) error { } // this checks if the world-executable bit is set (we cannot check owner easily) - exec := info.Mode().Perm() & 0001 + exec := info.Mode().Perm() & 0o001 if exec == 0 { return fmt.Errorf("%s is not world executable", info.Name()) } diff --git a/crypto/armor.go b/crypto/armor.go index 2a45e67ce586..1da3e9703326 100644 --- a/crypto/armor.go +++ b/crypto/armor.go @@ -148,7 +148,6 @@ func EncryptArmorPrivKey(privKey cryptotypes.PrivKey, passphrase string, algo st func encryptPrivKey(privKey cryptotypes.PrivKey, passphrase string) (saltBytes []byte, encBytes []byte) { saltBytes = crypto.CRandBytes(16) key, err := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), BcryptSecurityParameter) - if err != nil { panic(sdkerrors.Wrap(err, "error generating bcrypt key from passphrase")) } diff --git a/crypto/hd/algo.go b/crypto/hd/algo.go index 5f9965a24531..0feb4ff49b47 100644 --- a/crypto/hd/algo.go +++ b/crypto/hd/algo.go @@ -22,21 +22,20 @@ const ( Sr25519Type = PubKeyType("sr25519") ) -var ( - // Secp256k1 uses the Bitcoin secp256k1 ECDSA parameters. - Secp256k1 = secp256k1Algo{} -) +// Secp256k1 uses the Bitcoin secp256k1 ECDSA parameters. +var Secp256k1 = secp256k1Algo{} -type DeriveFn func(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error) -type GenerateFn func(bz []byte) types.PrivKey +type ( + DeriveFn func(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error) + GenerateFn func(bz []byte) types.PrivKey +) type WalletGenerator interface { Derive(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error) Generate(bz []byte) types.PrivKey } -type secp256k1Algo struct { -} +type secp256k1Algo struct{} func (s secp256k1Algo) Name() PubKeyType { return Secp256k1Type @@ -63,7 +62,7 @@ func (s secp256k1Algo) Derive() DeriveFn { // Generate generates a secp256k1 private key from the given bytes. func (s secp256k1Algo) Generate() GenerateFn { return func(bz []byte) types.PrivKey { - var bzArr = make([]byte, secp256k1.PrivKeySize) + bzArr := make([]byte, secp256k1.PrivKeySize) copy(bzArr, bz) return &secp256k1.PrivKey{Key: bzArr} diff --git a/crypto/hd/hdpath_test.go b/crypto/hd/hdpath_test.go index ec4ec3936fd6..6ea418b92db3 100644 --- a/crypto/hd/hdpath_test.go +++ b/crypto/hd/hdpath_test.go @@ -89,7 +89,6 @@ func TestParamsFromPath(t *testing.T) { require.Nil(t, params, errStr) require.Error(t, err, errStr) } - } func TestCreateHDPath(t *testing.T) { diff --git a/crypto/keyring/keyring_ledger_test.go b/crypto/keyring/keyring_ledger_test.go index b57351ba947a..6845b6088212 100644 --- a/crypto/keyring/keyring_ledger_test.go +++ b/crypto/keyring/keyring_ledger_test.go @@ -19,7 +19,6 @@ func TestInMemoryCreateLedger(t *testing.T) { kb := NewInMemory(cdc) k, err := kb.SaveLedgerKey("some_account", hd.Secp256k1, "cosmos", 118, 3, 1) - if err != nil { require.Error(t, err) require.Equal(t, "ledger nano S: support for ledger devices is not available in this executable", err.Error()) diff --git a/crypto/keyring/legacy_info.go b/crypto/keyring/legacy_info.go index 8b05b6a0312c..8de45feb1be2 100644 --- a/crypto/keyring/legacy_info.go +++ b/crypto/keyring/legacy_info.go @@ -255,7 +255,6 @@ func unMarshalLegacyInfo(bz []byte) (info LegacyInfo, err error) { // privKeyFromLegacyInfo exports a private key from LegacyInfo func privKeyFromLegacyInfo(info LegacyInfo) (cryptotypes.PrivKey, error) { - switch linfo := info.(type) { case legacyLocalInfo: if linfo.PrivKeyArmor == "" { diff --git a/crypto/keyring/migration_test.go b/crypto/keyring/migration_test.go index 939bc4a83ef0..2435671e4e47 100644 --- a/crypto/keyring/migration_test.go +++ b/crypto/keyring/migration_test.go @@ -229,6 +229,7 @@ func (s *MigrationTestSuite) TestMigrateErrEmptyItemData() { _, err := s.ks.migrate(n1) s.Require().EqualError(err, sdkerrors.Wrap(sdkerrors.ErrKeyNotFound, n1).Error()) } + func TestMigrationTestSuite(t *testing.T) { suite.Run(t, new(MigrationTestSuite)) } diff --git a/crypto/keyring/signing_algorithms_test.go b/crypto/keyring/signing_algorithms_test.go index e99492f12a17..131ade58b4e2 100644 --- a/crypto/keyring/signing_algorithms_test.go +++ b/crypto/keyring/signing_algorithms_test.go @@ -59,8 +59,7 @@ func TestAltSigningAlgoList_String(t *testing.T) { require.Equal(t, fmt.Sprintf("%s,notSupported", hd.Secp256k1Type), list.String()) } -type notSupportedAlgo struct { -} +type notSupportedAlgo struct{} func (n notSupportedAlgo) Name() hd.PubKeyType { return "notSupported" diff --git a/crypto/keys/ed25519/ed25519.go b/crypto/keys/ed25519/ed25519.go index 4ade041c4137..05d5d7466e13 100644 --- a/crypto/keys/ed25519/ed25519.go +++ b/crypto/keys/ed25519/ed25519.go @@ -34,8 +34,10 @@ const ( keyType = "ed25519" ) -var _ cryptotypes.PrivKey = &PrivKey{} -var _ codec.AminoMarshaler = &PrivKey{} +var ( + _ cryptotypes.PrivKey = &PrivKey{} + _ codec.AminoMarshaler = &PrivKey{} +) // Bytes returns the privkey byte format. func (privKey *PrivKey) Bytes() []byte { @@ -150,8 +152,10 @@ func GenPrivKeyFromSecret(secret []byte) *PrivKey { //------------------------------------- -var _ cryptotypes.PubKey = &PubKey{} -var _ codec.AminoMarshaler = &PubKey{} +var ( + _ cryptotypes.PubKey = &PubKey{} + _ codec.AminoMarshaler = &PubKey{} +) // Address is the SHA256-20 of the raw pubkey bytes. // It doesn't implement ADR-28 addresses and it must not be used diff --git a/crypto/keys/internal/benchmarking/bench.go b/crypto/keys/internal/benchmarking/bench.go index aab5d5f30382..dc99a082fdfa 100644 --- a/crypto/keys/internal/benchmarking/bench.go +++ b/crypto/keys/internal/benchmarking/bench.go @@ -30,7 +30,6 @@ func BenchmarkSigning(b *testing.B, priv types.PrivKey) { b.ResetTimer() for i := 0; i < b.N; i++ { _, err := priv.Sign(message) - if err != nil { b.FailNow() } diff --git a/crypto/keys/internal/ecdsa/privkey.go b/crypto/keys/internal/ecdsa/privkey.go index 690c07670d64..2aeedb1c4ddc 100644 --- a/crypto/keys/internal/ecdsa/privkey.go +++ b/crypto/keys/internal/ecdsa/privkey.go @@ -29,7 +29,6 @@ func IsSNormalized(sigS *big.Int) bool { // NormalizeS will invert the s value if not already in the lower half // of curve order value func NormalizeS(sigS *big.Int) *big.Int { - if IsSNormalized(sigS) { return sigS } @@ -41,7 +40,6 @@ func NormalizeS(sigS *big.Int) *big.Int { // R, S are padded to 32 bytes respectively. // code roughly copied from secp256k1_nocgo.go func signatureRaw(r *big.Int, s *big.Int) []byte { - rBytes := r.Bytes() sBytes := s.Bytes() sigBytes := make([]byte, 64) @@ -90,10 +88,8 @@ func (sk *PrivKey) Bytes() []byte { // It then raw encodes the signature as two fixed width 32-byte values // concatenated, reusing the code copied from secp256k1_nocgo.go func (sk *PrivKey) Sign(msg []byte) ([]byte, error) { - digest := sha256.Sum256(msg) r, s, err := ecdsa.Sign(rand.Reader, &sk.PrivateKey, digest[:]) - if err != nil { return nil, err } diff --git a/crypto/keys/internal/ecdsa/privkey_internal_test.go b/crypto/keys/internal/ecdsa/privkey_internal_test.go index 1f412ee7dcfe..660a62aa2ba8 100644 --- a/crypto/keys/internal/ecdsa/privkey_internal_test.go +++ b/crypto/keys/internal/ecdsa/privkey_internal_test.go @@ -38,11 +38,11 @@ func (suite *SKSuite) TestMarshal() { require := suite.Require() const size = 32 - var buffer = make([]byte, size) + buffer := make([]byte, size) _, err := suite.sk.MarshalTo(buffer) require.NoError(err) - var sk = new(PrivKey) + sk := new(PrivKey) err = sk.Unmarshal(buffer, secp256r1, size) require.NoError(err) require.True(sk.Equal(&suite.sk.PrivateKey)) diff --git a/crypto/keys/internal/ecdsa/pubkey.go b/crypto/keys/internal/ecdsa/pubkey.go index 75fbd8b8826d..69b4a7f58504 100644 --- a/crypto/keys/internal/ecdsa/pubkey.go +++ b/crypto/keys/internal/ecdsa/pubkey.go @@ -60,7 +60,6 @@ func (pk *PubKey) Bytes() []byte { // lower half of the curve order // 7/21/21 - expects raw encoded signature (fixed-width 64-bytes, R || S) func (pk *PubKey) VerifySignature(msg []byte, sig []byte) bool { - // check length for raw signature // which is two 32-byte padded big.Ints // concatenated diff --git a/crypto/keys/internal/ecdsa/pubkey_internal_test.go b/crypto/keys/internal/ecdsa/pubkey_internal_test.go index 88dc95a3bbd5..5434c8504c83 100644 --- a/crypto/keys/internal/ecdsa/pubkey_internal_test.go +++ b/crypto/keys/internal/ecdsa/pubkey_internal_test.go @@ -59,12 +59,12 @@ func (suite *PKSuite) TestMarshal() { require := suite.Require() const size = 33 // secp256r1 size - var buffer = make([]byte, size) + buffer := make([]byte, size) n, err := suite.pk.MarshalTo(buffer) require.NoError(err) require.Equal(size, n) - var pk = new(PubKey) + pk := new(PubKey) err = pk.Unmarshal(buffer, secp256r1, size) require.NoError(err) require.True(pk.PublicKey.Equal(&suite.pk.PublicKey)) diff --git a/crypto/keys/multisig/multisig.go b/crypto/keys/multisig/multisig.go index e39c508be6f8..eb381bf5987a 100644 --- a/crypto/keys/multisig/multisig.go +++ b/crypto/keys/multisig/multisig.go @@ -11,8 +11,10 @@ import ( "github.com/cosmos/cosmos-sdk/types/tx/signing" ) -var _ multisigtypes.PubKey = &LegacyAminoPubKey{} -var _ types.UnpackInterfacesMessage = &LegacyAminoPubKey{} +var ( + _ multisigtypes.PubKey = &LegacyAminoPubKey{} + _ types.UnpackInterfacesMessage = &LegacyAminoPubKey{} +) // NewLegacyAminoPubKey returns a new LegacyAminoPubKey. // Multisig can be constructed with multiple same keys - it will increase the power of diff --git a/crypto/keys/multisig/multisig_test.go b/crypto/keys/multisig/multisig_test.go index c19be78f8575..ae3023da828b 100644 --- a/crypto/keys/multisig/multisig_test.go +++ b/crypto/keys/multisig/multisig_test.go @@ -110,7 +110,8 @@ func TestVerifyMultisignature(t *testing.T) { pk = genPk }, true, - }, { + }, + { "wrong size for sig bit array", func(require *require.Assertions) { pubKeys := generatePubKeys(3) @@ -165,7 +166,8 @@ func TestVerifyMultisignature(t *testing.T) { ) }, true, - }, { + }, + { "duplicate signatures", func(require *require.Assertions) { pubKeys, sigs := generatePubKeysAndSignatures(5, msg) @@ -178,7 +180,8 @@ func TestVerifyMultisignature(t *testing.T) { sig.Signatures = append(sig.Signatures, sigs[0]) }, false, - }, { + }, + { "duplicated key", func(require *require.Assertions) { // here we test an edge case where we create a multi sig with two same @@ -191,7 +194,8 @@ func TestVerifyMultisignature(t *testing.T) { multisig.AddSignature(sig, sigs[0], 1) }, true, - }, { + }, + { "same key used twice", func(require *require.Assertions) { pubkeys, sigs := generatePubKeysAndSignatures(3, msg) @@ -201,7 +205,8 @@ func TestVerifyMultisignature(t *testing.T) { multisig.AddSignature(sig, sigs[0], 1) }, false, - }, { + }, + { "unable to verify signature", func(require *require.Assertions) { pubKeys := generatePubKeys(2) diff --git a/crypto/keys/secp256k1/internal/secp256k1/curve.go b/crypto/keys/secp256k1/internal/secp256k1/curve.go index fa1b199a3484..b5c80b23ad62 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/curve.go +++ b/crypto/keys/secp256k1/internal/secp256k1/curve.go @@ -93,19 +93,19 @@ func (BitCurve *BitCurve) Params() *elliptic.CurveParams { // IsOnCurve returns true if the given (x,y) lies on the BitCurve. func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { // y² = x³ + b - y2 := new(big.Int).Mul(y, y) //y² - y2.Mod(y2, BitCurve.P) //y²%P + y2 := new(big.Int).Mul(y, y) // y² + y2.Mod(y2, BitCurve.P) // y²%P - x3 := new(big.Int).Mul(x, x) //x² - x3.Mul(x3, x) //x³ + x3 := new(big.Int).Mul(x, x) // x² + x3.Mul(x3, x) // x³ - x3.Add(x3, BitCurve.B) //x³+B + x3.Add(x3, BitCurve.B) // x³+B x3.Mod(x3, BitCurve.P) //(x³+B)%P return x3.Cmp(y2) == 0 } -//TODO: double check if the function is okay +// TODO: double check if the function is okay // affineFromJacobian reverses the Jacobian transform. See the comment at the // top of the file. func (BitCurve *BitCurve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) { @@ -217,30 +217,30 @@ func (BitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) { // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l - a := new(big.Int).Mul(x, x) //X1² - b := new(big.Int).Mul(y, y) //Y1² - c := new(big.Int).Mul(b, b) //B² + a := new(big.Int).Mul(x, x) // X1² + b := new(big.Int).Mul(y, y) // Y1² + c := new(big.Int).Mul(b, b) // B² - d := new(big.Int).Add(x, b) //X1+B + d := new(big.Int).Add(x, b) // X1+B d.Mul(d, d) //(X1+B)² d.Sub(d, a) //(X1+B)²-A d.Sub(d, c) //(X1+B)²-A-C - d.Mul(d, big.NewInt(2)) //2*((X1+B)²-A-C) + d.Mul(d, big.NewInt(2)) // 2*((X1+B)²-A-C) - e := new(big.Int).Mul(big.NewInt(3), a) //3*A - f := new(big.Int).Mul(e, e) //E² + e := new(big.Int).Mul(big.NewInt(3), a) // 3*A + f := new(big.Int).Mul(e, e) // E² - x3 := new(big.Int).Mul(big.NewInt(2), d) //2*D - x3.Sub(f, x3) //F-2*D + x3 := new(big.Int).Mul(big.NewInt(2), d) // 2*D + x3.Sub(f, x3) // F-2*D x3.Mod(x3, BitCurve.P) - y3 := new(big.Int).Sub(d, x3) //D-X3 - y3.Mul(e, y3) //E*(D-X3) - y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) //E*(D-X3)-8*C + y3 := new(big.Int).Sub(d, x3) // D-X3 + y3.Mul(e, y3) // E*(D-X3) + y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) // E*(D-X3)-8*C y3.Mod(y3, BitCurve.P) - z3 := new(big.Int).Mul(y, z) //Y1*Z1 - z3.Mul(big.NewInt(2), z3) //3*Y1*Z1 + z3 := new(big.Int).Mul(y, z) // Y1*Z1 + z3.Mul(big.NewInt(2), z3) // 3*Y1*Z1 z3.Mod(z3, BitCurve.P) return x3, y3, z3 diff --git a/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/contrib/dummy.go b/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/contrib/dummy.go index fda594be9914..2c946210c54d 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/contrib/dummy.go +++ b/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/contrib/dummy.go @@ -1,3 +1,4 @@ +//go:build dummy // +build dummy // Package c contains only a C file. diff --git a/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/dummy.go b/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/dummy.go index 379b16992f47..04bbe3d76ecc 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/dummy.go +++ b/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/dummy.go @@ -1,3 +1,4 @@ +//go:build dummy // +build dummy // Package c contains only a C file. diff --git a/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/include/dummy.go b/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/include/dummy.go index 5af540c73c4a..64c71b8451d8 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/include/dummy.go +++ b/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/include/dummy.go @@ -1,3 +1,4 @@ +//go:build dummy // +build dummy // Package c contains only a C file. diff --git a/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/src/dummy.go b/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/src/dummy.go index 65868f38a8ea..2df270adc35e 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/src/dummy.go +++ b/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/src/dummy.go @@ -1,3 +1,4 @@ +//go:build dummy // +build dummy // Package c contains only a C file. diff --git a/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/src/modules/dummy.go b/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/src/modules/dummy.go index 3c7a696439f0..99c538db51b0 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/src/modules/dummy.go +++ b/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/src/modules/dummy.go @@ -1,3 +1,4 @@ +//go:build dummy // +build dummy // Package c contains only a C file. diff --git a/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/src/modules/ecdh/dummy.go b/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/src/modules/ecdh/dummy.go index b6fc38327ec8..48c2e0aa5453 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/src/modules/ecdh/dummy.go +++ b/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/src/modules/ecdh/dummy.go @@ -1,3 +1,4 @@ +//go:build dummy // +build dummy // Package c contains only a C file. diff --git a/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/src/modules/recovery/dummy.go b/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/src/modules/recovery/dummy.go index b9491f0cb9f4..8efbd7abe71b 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/src/modules/recovery/dummy.go +++ b/crypto/keys/secp256k1/internal/secp256k1/libsecp256k1/src/modules/recovery/dummy.go @@ -1,3 +1,4 @@ +//go:build dummy // +build dummy // Package c contains only a C file. diff --git a/crypto/keys/secp256k1/internal/secp256k1/secp256_test.go b/crypto/keys/secp256k1/internal/secp256k1/secp256_test.go index ef2a3a3790b4..dbf61b37879f 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/secp256_test.go +++ b/crypto/keys/secp256k1/internal/secp256k1/secp256_test.go @@ -48,7 +48,7 @@ func randSig() []byte { // tests for malleability // highest bit of signature ECDSA s value must be 0, in the 33th byte func compactSigCheck(t *testing.T, sig []byte) { - var b = int(sig[32]) + b := int(sig[32]) if b < 0 { t.Errorf("highest bit is negative: %d", b) } diff --git a/crypto/keys/secp256k1/secp256k1.go b/crypto/keys/secp256k1/secp256k1.go index 231a895a6103..51034275cd94 100644 --- a/crypto/keys/secp256k1/secp256k1.go +++ b/crypto/keys/secp256k1/secp256k1.go @@ -17,8 +17,10 @@ import ( "github.com/cosmos/cosmos-sdk/types/errors" ) -var _ cryptotypes.PrivKey = &PrivKey{} -var _ codec.AminoMarshaler = &PrivKey{} +var ( + _ cryptotypes.PrivKey = &PrivKey{} + _ codec.AminoMarshaler = &PrivKey{} +) const ( PrivKeySize = 32 @@ -138,8 +140,10 @@ func GenPrivKeyFromSecret(secret []byte) *PrivKey { //------------------------------------- -var _ cryptotypes.PubKey = &PubKey{} -var _ codec.AminoMarshaler = &PubKey{} +var ( + _ cryptotypes.PubKey = &PubKey{} + _ codec.AminoMarshaler = &PubKey{} +) // PubKeySize is comprised of 32 bytes for one field element // (the x-coordinate), plus one byte for the parity of the y-coordinate. diff --git a/crypto/keys/secp256k1/secp256k1_internal_test.go b/crypto/keys/secp256k1/secp256k1_internal_test.go index a2c8e73bcbe7..7cbe5949f70c 100644 --- a/crypto/keys/secp256k1/secp256k1_internal_test.go +++ b/crypto/keys/secp256k1/secp256k1_internal_test.go @@ -10,7 +10,6 @@ import ( ) func Test_genPrivKey(t *testing.T) { - empty := make([]byte, 32) oneB := big.NewInt(1).Bytes() onePadded := make([]byte, 32) diff --git a/crypto/keys/secp256k1/secp256k1_test.go b/crypto/keys/secp256k1/secp256k1_test.go index 79d2faf5158e..63f5579459f1 100644 --- a/crypto/keys/secp256k1/secp256k1_test.go +++ b/crypto/keys/secp256k1/secp256k1_test.go @@ -41,7 +41,7 @@ func TestPubKeySecp256k1Address(t *testing.T) { addrBbz, _, _ := base58.CheckDecode(d.addr) addrB := crypto.Address(addrBbz) - var priv = secp256k1.PrivKey{Key: privB} + priv := secp256k1.PrivKey{Key: privB} pubKey := priv.PubKey() pubT, _ := pubKey.(*secp256k1.PubKey) diff --git a/crypto/ledger/encode_test.go b/crypto/ledger/encode_test.go index 38f3cceaa5d2..7a60c3d147f5 100644 --- a/crypto/ledger/encode_test.go +++ b/crypto/ledger/encode_test.go @@ -44,7 +44,6 @@ func ExamplePrintRegisteredTypes() { } func TestNilEncodings(t *testing.T) { - // Check nil Signature. var a, b []byte checkAminoJSON(t, &a, &b, true) @@ -59,5 +58,4 @@ func TestNilEncodings(t *testing.T) { var e, f cryptotypes.PrivKey checkAminoJSON(t, &e, &f, true) require.EqualValues(t, e, f) - } diff --git a/crypto/ledger/ledger_mock.go b/crypto/ledger/ledger_mock.go index 868815982e1f..740a773d12ce 100644 --- a/crypto/ledger/ledger_mock.go +++ b/crypto/ledger/ledger_mock.go @@ -28,8 +28,7 @@ func init() { } } -type LedgerSECP256K1Mock struct { -} +type LedgerSECP256K1Mock struct{} func (mock LedgerSECP256K1Mock) Close() error { return nil diff --git a/crypto/ledger/ledger_real.go b/crypto/ledger/ledger_real.go index 07f8a8e3ed6a..48c87aff7683 100644 --- a/crypto/ledger/ledger_real.go +++ b/crypto/ledger/ledger_real.go @@ -1,3 +1,4 @@ +//go:build cgo && ledger && !test_ledger_mock // +build cgo,ledger,!test_ledger_mock package ledger diff --git a/crypto/ledger/ledger_secp256k1.go b/crypto/ledger/ledger_secp256k1.go index db09ba2e8d3a..dffded571ab5 100644 --- a/crypto/ledger/ledger_secp256k1.go +++ b/crypto/ledger/ledger_secp256k1.go @@ -14,11 +14,9 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/types" ) -var ( - // discoverLedger defines a function to be invoked at runtime for discovering - // a connected Ledger device. - discoverLedger discoverLedgerFn -) +// discoverLedger defines a function to be invoked at runtime for discovering +// a connected Ledger device. +var discoverLedger discoverLedgerFn type ( // discoverLedgerFn defines a Ledger discovery function that returns a @@ -102,8 +100,7 @@ func (pkl PrivKeyLedgerSecp256k1) Sign(message []byte) ([]byte, error) { } // ShowAddress triggers a ledger device to show the corresponding address. -func ShowAddress(path hd.BIP44Params, expectedPubKey types.PubKey, - accountAddressPrefix string) error { +func ShowAddress(path hd.BIP44Params, expectedPubKey types.PubKey, accountAddressPrefix string) error { device, err := getDevice() if err != nil { return err diff --git a/crypto/types/compact_bit_array_test.go b/crypto/types/compact_bit_array_test.go index 1a76d4531352..143f3a07891c 100644 --- a/crypto/types/compact_bit_array_test.go +++ b/crypto/types/compact_bit_array_test.go @@ -67,7 +67,6 @@ func TestBitArrayEqual(t *testing.T) { } func TestJSONMarshalUnmarshal(t *testing.T) { - bA1 := NewCompactBitArray(0) bA2 := NewCompactBitArray(1) @@ -218,7 +217,6 @@ func TestCompactBitArrayNumOfTrueBitsBefore(t *testing.T) { require.NoError(t, err) for i := 0; i < len(tc.bAIndex); i++ { - require.Equal(t, tc.trueValueIndex[i], bA.NumTrueBitsBefore(tc.bAIndex[i]), "tc %d, i %d", tcIndex, i) } }) diff --git a/crypto/xsalsa20symmetric/symmetric.go b/crypto/xsalsa20symmetric/symmetric.go index cf24daea35ce..e205985e33fa 100644 --- a/crypto/xsalsa20symmetric/symmetric.go +++ b/crypto/xsalsa20symmetric/symmetric.go @@ -10,8 +10,10 @@ import ( // TODO, make this into a struct that implements crypto.Symmetric. -const nonceLen = 24 -const secretLen = 32 +const ( + nonceLen = 24 + secretLen = 32 +) // secret must be 32 bytes long. Use something like Sha256(Bcrypt(passphrase)) // The ciphertext is (secretbox.Overhead + 24) bytes longer than the plaintext. diff --git a/crypto/xsalsa20symmetric/symmetric_test.go b/crypto/xsalsa20symmetric/symmetric_test.go index b35633b96cb3..0a7431671877 100644 --- a/crypto/xsalsa20symmetric/symmetric_test.go +++ b/crypto/xsalsa20symmetric/symmetric_test.go @@ -11,7 +11,6 @@ import ( ) func TestSimple(t *testing.T) { - plaintext := []byte("sometext") secret := []byte("somesecretoflengththirtytwo===32") ciphertext := EncryptSymmetric(plaintext, secret) @@ -22,7 +21,6 @@ func TestSimple(t *testing.T) { } func TestSimpleWithKDF(t *testing.T) { - plaintext := []byte("sometext") secretPass := []byte("somesecret") secret, err := bcrypt.GenerateFromPassword(secretPass, 12) diff --git a/db/badgerdb/db.go b/db/badgerdb/db.go index 6f0fb1fb3c41..532216b88f63 100644 --- a/db/badgerdb/db.go +++ b/db/badgerdb/db.go @@ -19,9 +19,7 @@ import ( "github.com/dgraph-io/ristretto/z" ) -var ( - versionsFilename = "versions.csv" -) +var versionsFilename = "versions.csv" var ( _ db.DBConnection = (*BadgerDB)(nil) @@ -74,7 +72,7 @@ type versionManager struct { func NewDB(dir string) (*BadgerDB, error) { // Since Badger doesn't support database names, we join both to obtain // the final directory to use for the database. - if err := os.MkdirAll(dir, 0755); err != nil { + if err := os.MkdirAll(dir, 0o755); err != nil { return nil, err } opts := badger.DefaultOptions(dir) @@ -102,7 +100,7 @@ func NewDBWithOptions(opts badger.Options) (*BadgerDB, error) { // Load metadata CSV file containing valid versions func readVersionsFile(path string) (*versionManager, error) { - file, err := os.OpenFile(path, os.O_RDONLY|os.O_CREATE, 0644) + file, err := os.OpenFile(path, os.O_RDONLY|os.O_CREATE, 0o644) if err != nil { return nil, err } @@ -143,14 +141,14 @@ func readVersionsFile(path string) (*versionManager, error) { // Write version metadata to CSV file func writeVersionsFile(vm *versionManager, path string) error { - file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0644) + file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o644) if err != nil { return err } defer file.Close() w := csv.NewWriter(file) rows := [][]string{ - []string{"0", strconv.FormatUint(vm.lastTs, 10)}, + {"0", strconv.FormatUint(vm.lastTs, 10)}, } for it := vm.Iterator(); it.Next(); { version := it.Value() diff --git a/db/internal/util.go b/db/internal/util.go index b33f8ac67733..ea7425319ce3 100644 --- a/db/internal/util.go +++ b/db/internal/util.go @@ -2,6 +2,7 @@ package util import ( "fmt" + dbm "github.com/cosmos/cosmos-sdk/db" ) diff --git a/db/memdb/db.go b/db/memdb/db.go index f3f50377c7c2..c3c83d525037 100644 --- a/db/memdb/db.go +++ b/db/memdb/db.go @@ -178,7 +178,7 @@ func (dbm *MemDB) Revert() error { if !has { return fmt.Errorf("bad version history: version %v not saved", last) } - for ver, _ := range dbm.saved { + for ver := range dbm.saved { if ver > last { delete(dbm.saved, ver) } diff --git a/db/prefix/prefix.go b/db/prefix/prefix.go index c6ed87cba84f..3ddf1b41b4d0 100644 --- a/db/prefix/prefix.go +++ b/db/prefix/prefix.go @@ -24,9 +24,11 @@ type prefixW struct { prefix []byte } -var _ db.DBReader = (*prefixR)(nil) -var _ db.DBReadWriter = (*prefixRW)(nil) -var _ db.DBWriter = (*prefixW)(nil) +var ( + _ db.DBReader = (*prefixR)(nil) + _ db.DBReadWriter = (*prefixRW)(nil) + _ db.DBWriter = (*prefixW)(nil) +) // NewPrefixReader returns a DBReader that only has access to the subset of DB keys // that contain the given prefix. diff --git a/db/rocksdb/db.go b/db/rocksdb/db.go index cb312b625f03..32a82f817647 100644 --- a/db/rocksdb/db.go +++ b/db/rocksdb/db.go @@ -71,7 +71,7 @@ type dbOptions struct { // NewDB creates a new RocksDB key-value database with inside the given directory. // If dir does not exist, it will be created. func NewDB(dir string) (*dbManager, error) { - if err := os.MkdirAll(dir, 0755); err != nil { + if err := os.MkdirAll(dir, 0o755); err != nil { return nil, err } @@ -100,7 +100,7 @@ func NewDB(dir string) (*dbManager, error) { cpCache: checkpointCache{cache: map[uint64]*cpCacheEntry{}}, } - err := os.MkdirAll(mgr.checkpointsDir(), 0755) + err := os.MkdirAll(mgr.checkpointsDir(), 0o755) if err != nil { return nil, err } diff --git a/db/version_manager.go b/db/version_manager.go index b884e7160114..b8a2a6b055b5 100644 --- a/db/version_manager.go +++ b/db/version_manager.go @@ -65,7 +65,7 @@ func (vm *VersionManager) Save(target uint64) (uint64, error) { } func findLimit(m map[uint64]struct{}, cmp func(uint64, uint64) bool, init uint64) uint64 { - for x, _ := range m { + for x := range m { if cmp(x, init) { init = x } @@ -99,7 +99,7 @@ func (vi *vmIterator) Value() uint64 { return vi.buf } func (vm *VersionManager) Iterator() VersionIterator { ch := make(chan uint64) go func() { - for ver, _ := range vm.versions { + for ver := range vm.versions { ch <- ver } close(ch) @@ -125,7 +125,7 @@ func (vm *VersionManager) Equal(that VersionSet) bool { func (vm *VersionManager) Copy() *VersionManager { vmap := make(map[uint64]struct{}) - for ver, _ := range vm.versions { + for ver := range vm.versions { vmap[ver] = struct{}{} } return &VersionManager{versions: vmap, initial: vm.initial, last: vm.last} diff --git a/errors/errors_test.go b/errors/errors_test.go index 028ec5141d16..1dda2344e664 100644 --- a/errors/errors_test.go +++ b/errors/errors_test.go @@ -3,11 +3,12 @@ package errors import ( stdlib "errors" "fmt" + "testing" + "github.com/pkg/errors" "github.com/stretchr/testify/suite" "google.golang.org/grpc/codes" grpcstatus "google.golang.org/grpc/status" - "testing" ) type errorsTestSuite struct { @@ -114,8 +115,8 @@ func (s *errorsTestSuite) TestIsOf() { require := s.Require() var errNil *Error - var err = ErrInvalidAddress - var errW = Wrap(ErrLogic, "more info") + err := ErrInvalidAddress + errW := Wrap(ErrLogic, "more info") require.False(IsOf(errNil), "nil error should always have no causer") require.False(IsOf(errNil, err), "nil error should always have no causer") @@ -127,12 +128,11 @@ func (s *errorsTestSuite) TestIsOf() { require.True(IsOf(errW, ErrLogic)) require.True(IsOf(errW, err, ErrLogic)) require.True(IsOf(errW, nil, errW), "error should much itself") - var err2 = errors.New("other error") + err2 := errors.New("other error") require.True(IsOf(err2, nil, err2), "error should much itself") } -type customError struct { -} +type customError struct{} func (customError) Error() string { return "custom error" @@ -169,35 +169,35 @@ func (s *errorsTestSuite) TestWrappedIs() { } func (s *errorsTestSuite) TestWrappedIsMultiple() { - var errTest = errors.New("test error") - var errTest2 = errors.New("test error 2") + errTest := errors.New("test error") + errTest2 := errors.New("test error 2") err := Wrap(errTest2, Wrap(errTest, "some random description").Error()) s.Require().True(stdlib.Is(err, errTest2)) } func (s *errorsTestSuite) TestWrappedIsFail() { - var errTest = errors.New("test error") - var errTest2 = errors.New("test error 2") + errTest := errors.New("test error") + errTest2 := errors.New("test error 2") err := Wrap(errTest2, Wrap(errTest, "some random description").Error()) s.Require().False(stdlib.Is(err, errTest)) } func (s *errorsTestSuite) TestWrappedUnwrap() { - var errTest = errors.New("test error") + errTest := errors.New("test error") err := Wrap(errTest, "some random description") s.Require().Equal(errTest, stdlib.Unwrap(err)) } func (s *errorsTestSuite) TestWrappedUnwrapMultiple() { - var errTest = errors.New("test error") - var errTest2 = errors.New("test error 2") + errTest := errors.New("test error") + errTest2 := errors.New("test error 2") err := Wrap(errTest2, Wrap(errTest, "some random description").Error()) s.Require().Equal(errTest2, stdlib.Unwrap(err)) } func (s *errorsTestSuite) TestWrappedUnwrapFail() { - var errTest = errors.New("test error") - var errTest2 = errors.New("test error 2") + errTest := errors.New("test error") + errTest2 := errors.New("test error 2") err := Wrap(errTest2, Wrap(errTest, "some random description").Error()) s.Require().NotEqual(errTest, stdlib.Unwrap(err)) } diff --git a/math/int_test.go b/math/int_test.go index 3bb401081da4..c39fce0ee51c 100644 --- a/math/int_test.go +++ b/math/int_test.go @@ -170,7 +170,6 @@ func (s *intTestSuite) TestArithInt() { s.Require().Equal(tc.nres, tc.ires.Int64(), "Int arithmetic operation does not match with int64 operation. tc #%d", tcnum) } } - } func (s *intTestSuite) TestCompInt() { @@ -394,7 +393,7 @@ func (s *intTestSuite) TestIntEq() { } func TestRoundTripMarshalToInt(t *testing.T) { - var values = []int64{ + values := []int64{ 0, 1, 1 << 10, diff --git a/math/uint_internal_test.go b/math/uint_internal_test.go index 3f86c93604af..a3f1fb4f5e1b 100644 --- a/math/uint_internal_test.go +++ b/math/uint_internal_test.go @@ -51,5 +51,4 @@ func (s *uintInternalTestSuite) TestUintSize() { s.Require().Equal(2, x.Size()) x = NewUint(100) s.Require().Equal(3, x.Size()) - } diff --git a/math/uint_test.go b/math/uint_test.go index ddc84067d13d..bb177eb6eaa0 100644 --- a/math/uint_test.go +++ b/math/uint_test.go @@ -292,7 +292,7 @@ func maxuint(i1, i2 uint64) uint64 { } func TestRoundTripMarshalToUint(t *testing.T) { - var values = []uint64{ + values := []uint64{ 0, 1, 1 << 10, diff --git a/orm/encoding/ormfield/codec.go b/orm/encoding/ormfield/codec.go index dee0529e222f..14a1d4804c71 100644 --- a/orm/encoding/ormfield/codec.go +++ b/orm/encoding/ormfield/codec.go @@ -13,7 +13,6 @@ import ( // Codec defines an interface for decoding and encoding values in ORM index keys. type Codec interface { - // Decode decodes a value in a key. Decode(r Reader) (protoreflect.Value, error) diff --git a/orm/encoding/ormfield/int32.go b/orm/encoding/ormfield/int32.go index 97eb93070da8..a3482ba862a6 100644 --- a/orm/encoding/ormfield/int32.go +++ b/orm/encoding/ormfield/int32.go @@ -14,8 +14,10 @@ type Int32Codec struct{} var int32Codec = Int32Codec{} -const int32Max = 2147483647 -const int32Offset = int32Max + 1 +const ( + int32Max = 2147483647 + int32Offset = int32Max + 1 +) func (i Int32Codec) Decode(r Reader) (protoreflect.Value, error) { var x uint32 diff --git a/orm/encoding/ormkv/codec.go b/orm/encoding/ormkv/codec.go index afaa4b044020..1f93b9e54220 100644 --- a/orm/encoding/ormkv/codec.go +++ b/orm/encoding/ormkv/codec.go @@ -6,7 +6,6 @@ import "google.golang.org/protobuf/reflect/protoreflect" // kv-store backing an ORM instance. EntryCodec's enable full logical decoding // of ORM data. type EntryCodec interface { - // DecodeEntry decodes a kv-pair into an Entry. DecodeEntry(k, v []byte) (Entry, error) diff --git a/orm/encoding/ormkv/entry.go b/orm/encoding/ormkv/entry.go index 869eb9fbef38..2098afbac6a9 100644 --- a/orm/encoding/ormkv/entry.go +++ b/orm/encoding/ormkv/entry.go @@ -26,7 +26,6 @@ type Entry interface { // PrimaryKeyEntry represents a logically decoded primary-key entry. type PrimaryKeyEntry struct { - // TableName is the table this entry represents. TableName protoreflect.FullName @@ -71,7 +70,6 @@ func (p *PrimaryKeyEntry) doNotImplement() {} // IndexKeyEntry represents a logically decoded index entry. type IndexKeyEntry struct { - // TableName is the table this entry represents. TableName protoreflect.FullName @@ -111,14 +109,12 @@ func (i *IndexKeyEntry) String() string { if i.IsUnique { return fmt.Sprintf("UNIQ %s", i.string()) } else { - return fmt.Sprintf("IDX %s", i.string()) } } // SeqEntry represents a sequence for tables with auto-incrementing primary keys. type SeqEntry struct { - // TableName is the table this entry represents. TableName protoreflect.FullName diff --git a/orm/encoding/ormkv/index_key.go b/orm/encoding/ormkv/index_key.go index 335a5f820a92..55284f220636 100644 --- a/orm/encoding/ormkv/index_key.go +++ b/orm/encoding/ormkv/index_key.go @@ -62,7 +62,6 @@ func NewIndexKeyCodec(prefix []byte, messageType protoreflect.MessageType, index } func (cdc IndexKeyCodec) DecodeIndexKey(k, _ []byte) (indexFields, primaryKey []protoreflect.Value, err error) { - values, err := cdc.DecodeKey(bytes.NewReader(k)) // got prefix key if err == io.EOF { diff --git a/orm/encoding/ormkv/primary_key.go b/orm/encoding/ormkv/primary_key.go index 268cb1dc7f28..ff4509cb562e 100644 --- a/orm/encoding/ormkv/primary_key.go +++ b/orm/encoding/ormkv/primary_key.go @@ -51,7 +51,6 @@ func (p PrimaryKeyCodec) DecodeIndexKey(k, _ []byte) (indexFields, primaryKey [] primaryKey = indexFields } return indexFields, primaryKey, nil - } func (p PrimaryKeyCodec) DecodeEntry(k, v []byte) (Entry, error) { diff --git a/orm/internal/codegen/file.go b/orm/internal/codegen/file.go index 6adf8df61d5d..c19b81ac9edb 100644 --- a/orm/internal/codegen/file.go +++ b/orm/internal/codegen/file.go @@ -153,7 +153,6 @@ func (f fileGen) genStoreConstructor(stores []*protogen.Message) { } f.P("}, nil") f.P("}") - } func (f fileGen) fieldsToCamelCase(fields string) string { diff --git a/orm/internal/codegen/index.go b/orm/internal/codegen/index.go index 61c1281e35ae..9b889d431e46 100644 --- a/orm/internal/codegen/index.go +++ b/orm/internal/codegen/index.go @@ -9,7 +9,6 @@ import ( ) func (t tableGen) genIndexKeys() { - // interface that all keys must adhere to t.P("type ", t.indexKeyInterfaceName(), " interface {") t.P("id() uint32") @@ -112,7 +111,6 @@ func (t tableGen) genIndex(fields string, id uint32, isPrimaryKey bool) { for i := 1; i < len(fieldsSlc)+1; i++ { t.genWithMethods(idxKeyName, fieldsSlc[:i]) } - } func (t tableGen) genIndexInterfaceMethods(id uint32, indexStructName string) { diff --git a/orm/internal/testkv/debug.go b/orm/internal/testkv/debug.go index 8cdc032f5a67..5e2382246d46 100644 --- a/orm/internal/testkv/debug.go +++ b/orm/internal/testkv/debug.go @@ -14,7 +14,6 @@ import ( // Debugger is an interface that handles debug info from the debug store wrapper. type Debugger interface { - // Log logs a single log message. Log(string) diff --git a/orm/model/ormdb/module.go b/orm/model/ormdb/module.go index dfdc63f72047..4c6e1a0a34c5 100644 --- a/orm/model/ormdb/module.go +++ b/orm/model/ormdb/module.go @@ -51,7 +51,6 @@ type moduleDB struct { // ModuleDBOptions are options for constructing a ModuleDB. type ModuleDBOptions struct { - // TypeResolver is an optional type resolver to be used when unmarshaling // protobuf messages. If it is nil, protoregistry.GlobalTypes will be used. TypeResolver ormtable.TypeResolver diff --git a/orm/model/ormdb/module_test.go b/orm/model/ormdb/module_test.go index d7150455111d..5bb7a68420e5 100644 --- a/orm/model/ormdb/module_test.go +++ b/orm/model/ormdb/module_test.go @@ -355,13 +355,14 @@ func TestGetBackendResolver(t *testing.T) { }) assert.ErrorContains(t, err, "unsupported") - _, err = ormdb.NewModuleDB(&ormv1alpha1.ModuleSchemaDescriptor{SchemaFile: []*ormv1alpha1.ModuleSchemaDescriptor_FileEntry{ - { - Id: 1, - ProtoFileName: testpb.File_testpb_bank_proto.Path(), - StorageType: ormv1alpha1.StorageType_STORAGE_TYPE_MEMORY, + _, err = ormdb.NewModuleDB(&ormv1alpha1.ModuleSchemaDescriptor{ + SchemaFile: []*ormv1alpha1.ModuleSchemaDescriptor_FileEntry{ + { + Id: 1, + ProtoFileName: testpb.File_testpb_bank_proto.Path(), + StorageType: ormv1alpha1.StorageType_STORAGE_TYPE_MEMORY, + }, }, - }, }, ormdb.ModuleDBOptions{ GetBackendResolver: getResolver, }) diff --git a/orm/model/ormtable/backend.go b/orm/model/ormtable/backend.go index 8013309d0fab..66ff949ad5c0 100644 --- a/orm/model/ormtable/backend.go +++ b/orm/model/ormtable/backend.go @@ -50,7 +50,6 @@ type Backend interface { // If the index store is not defined, the commitment store will be // used for all operations. type ReadBackendOptions struct { - // CommitmentStoreReader is a reader for the commitment store. CommitmentStoreReader kv.ReadonlyStore @@ -135,7 +134,6 @@ func (c backend) IndexStore() kv.Store { // If the index store is not defined, the commitment store will be // used for all operations. type BackendOptions struct { - // CommitmentStore is the commitment store. CommitmentStore kv.Store diff --git a/orm/model/ormtable/batch.go b/orm/model/ormtable/batch.go index c34dbf44464a..7983bee77269 100644 --- a/orm/model/ormtable/batch.go +++ b/orm/model/ormtable/batch.go @@ -75,7 +75,6 @@ func flushBuf(store kv.Store, writes []*batchWriterEntry) error { return err } } - } return nil } diff --git a/orm/model/ormtable/bench_test.go b/orm/model/ormtable/bench_test.go index d160da700fcc..6194b3cfed46 100644 --- a/orm/model/ormtable/bench_test.go +++ b/orm/model/ormtable/bench_test.go @@ -219,7 +219,7 @@ func getBalance(store kv.Store, address, denom string) (*testpb.Balance, error) return nil, fmt.Errorf("not found") } - var balance = testpb.Balance{} + balance := testpb.Balance{} err = proto.Unmarshal(bz, &balance) if err != nil { return nil, err diff --git a/orm/model/ormtable/hooks.go b/orm/model/ormtable/hooks.go index 288bfd2b43db..c5a76a6af8fa 100644 --- a/orm/model/ormtable/hooks.go +++ b/orm/model/ormtable/hooks.go @@ -9,7 +9,6 @@ import ( // ValidateHooks defines an interface for a table hooks which can intercept // insert, update and delete operations and possibly return an error. type ValidateHooks interface { - // ValidateInsert is called before the message is inserted. // If error is not nil the insertion will fail. ValidateInsert(context.Context, proto.Message) error @@ -30,7 +29,6 @@ type ValidateHooks interface { // may be called but the enclosing transaction may still fail. The context // is provided in each method to help coordinate this. type WriteHooks interface { - // OnInsert is called after an message is inserted into the store. OnInsert(context.Context, proto.Message) diff --git a/orm/model/ormtable/index.go b/orm/model/ormtable/index.go index eb4974d6c13e..903c19348505 100644 --- a/orm/model/ormtable/index.go +++ b/orm/model/ormtable/index.go @@ -16,7 +16,6 @@ import ( // are stateless, with all state existing only in the store passed // to index methods. type Index interface { - // List does iteration over the index with the provided prefix key and options. // Prefix key values must correspond in type to the index's fields and the // number of values provided cannot exceed the number of fields in the index, diff --git a/orm/model/ormtable/index_impl.go b/orm/model/ormtable/index_impl.go index a566b93964a7..7289efc40af4 100644 --- a/orm/model/ormtable/index_impl.go +++ b/orm/model/ormtable/index_impl.go @@ -61,8 +61,10 @@ func (i indexKeyIndex) ListRange(ctx context.Context, from, to []interface{}, op return rangeIterator(backend.IndexStoreReader(), backend, i, i.KeyCodec, from, to, options) } -var _ indexer = &indexKeyIndex{} -var _ Index = &indexKeyIndex{} +var ( + _ indexer = &indexKeyIndex{} + _ Index = &indexKeyIndex{} +) func (i indexKeyIndex) doNotImplement() {} diff --git a/orm/model/ormtable/iterator.go b/orm/model/ormtable/iterator.go index 3aa62d314acf..baf662febd65 100644 --- a/orm/model/ormtable/iterator.go +++ b/orm/model/ormtable/iterator.go @@ -18,7 +18,6 @@ import ( // Instead you should do reads and writes separately, or use a helper // function like DeleteBy which does this efficiently. type Iterator interface { - // Next advances the iterator and returns true if a valid entry is found. // Next must be called before starting iteration. Next() bool diff --git a/orm/model/ormtable/paginate.go b/orm/model/ormtable/paginate.go index 56f30cf8fb04..7c38405c1443 100644 --- a/orm/model/ormtable/paginate.go +++ b/orm/model/ormtable/paginate.go @@ -76,7 +76,6 @@ func (it *paginationIterator) Next() bool { // so the index == total entries. it.pageRes.Total = uint64(it.i) } - } return false } diff --git a/orm/model/ormtable/save_test.go b/orm/model/ormtable/save_test.go index dc3a24edd0ca..564a8edb2f1d 100644 --- a/orm/model/ormtable/save_test.go +++ b/orm/model/ormtable/save_test.go @@ -3,11 +3,12 @@ package ormtable_test import ( "context" "fmt" + "testing" + "github.com/cosmos/cosmos-sdk/orm/model/ormtable" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/encoding/protojson" - "testing" "github.com/regen-network/gocuke" "gotest.tools/v3/assert" diff --git a/orm/model/ormtable/table_impl.go b/orm/model/ormtable/table_impl.go index b598161b6cf6..b0d77ccf7c69 100644 --- a/orm/model/ormtable/table_impl.go +++ b/orm/model/ormtable/table_impl.go @@ -414,8 +414,10 @@ func (t tableImpl) Get(ctx context.Context, message proto.Message) (found bool, return t.primaryKeyIndex.get(backend, message, keyValues) } -var _ Table = &tableImpl{} -var _ Schema = &tableImpl{} +var ( + _ Table = &tableImpl{} + _ Schema = &tableImpl{} +) type saveMode int diff --git a/orm/model/ormtable/table_test.go b/orm/model/ormtable/table_test.go index b8f1365272a3..d3f0f5925b4b 100644 --- a/orm/model/ormtable/table_test.go +++ b/orm/model/ormtable/table_test.go @@ -98,7 +98,6 @@ func TestPaginationLimitCountTotal(t *testing.T) { pr := it.PageResponse() assert.Check(t, pr != nil) assert.Equal(t, uint64(3), pr.Total) - } func TestImportedMessageIterator(t *testing.T) { @@ -187,7 +186,7 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen assert.Assert(t, it.Next()) msg, err := it.GetMessage() assert.NilError(t, err) - //t.Logf("data[%d] %v == %v", i, data[i], msg) + // t.Logf("data[%d] %v == %v", i, data[i], msg) assert.DeepEqual(t, data[i], msg, protocmp.Transform()) } // make sure the iterator is done @@ -498,7 +497,6 @@ func runTestScenario(t *testing.T, table ormtable.Table, backend ormtable.Backen it, err = store.List(ctx, testpb.ExampleTablePrimaryKey{}) assert.NilError(t, err) assertIteratorItems(it, 2, 6, 10) - } func TestRandomTableData(t *testing.T) { @@ -604,7 +602,6 @@ func testIndex(t *testing.T, model *IndexModel) { assert.DeepEqual(t, model.data[i], data2[i], protocmp.Transform()) } } - } func reverseData(data []proto.Message) []proto.Message { diff --git a/orm/model/ormtable/unique.go b/orm/model/ormtable/unique.go index 63386942ae09..912b9db16fd8 100644 --- a/orm/model/ormtable/unique.go +++ b/orm/model/ormtable/unique.go @@ -190,8 +190,10 @@ func (u uniqueKeyIndex) Fields() string { return u.fields.String() } -var _ indexer = &uniqueKeyIndex{} -var _ UniqueIndex = &uniqueKeyIndex{} +var ( + _ indexer = &uniqueKeyIndex{} + _ UniqueIndex = &uniqueKeyIndex{} +) // isNonTrivialUniqueKey checks if unique key fields are non-trivial, meaning that they // don't contain the full primary key. If they contain the full primary key, then diff --git a/pruning/manager_test.go b/pruning/manager_test.go index 1bb712a8a369..85d38e8c8af7 100644 --- a/pruning/manager_test.go +++ b/pruning/manager_test.go @@ -4,7 +4,6 @@ import ( "container/list" "errors" "fmt" - "testing" "github.com/golang/mock/gomock" @@ -312,7 +311,6 @@ func TestHandleHeight_FlushLoadFromDisk(t *testing.T) { } func TestHandleHeight_DbErr_Panic(t *testing.T) { - ctrl := gomock.NewController(t) // Setup @@ -367,7 +365,6 @@ func TestHandleHeightSnapshot_FlushLoadFromDisk(t *testing.T) { } func TestHandleHeightSnapshot_DbErr_Panic(t *testing.T) { - ctrl := gomock.NewController(t) // Setup @@ -509,7 +506,7 @@ func TestLoadPruningHeights(t *testing.T) { } func TestLoadPruningHeights_PruneNothing(t *testing.T) { - var manager = pruning.NewManager(db.NewMemDB(), log.NewNopLogger()) + manager := pruning.NewManager(db.NewMemDB(), log.NewNopLogger()) require.NotNil(t, manager) manager.SetOptions(types.NewPruningOptions(types.PruningNothing)) @@ -518,7 +515,6 @@ func TestLoadPruningHeights_PruneNothing(t *testing.T) { } func TestGetFlushAndResetPruningHeights_DbErr_Panic(t *testing.T) { - ctrl := gomock.NewController(t) // Setup diff --git a/server/config/config_test.go b/server/config/config_test.go index 4c396cf45586..442e56026ec4 100644 --- a/server/config/config_test.go +++ b/server/config/config_test.go @@ -2,11 +2,11 @@ package config import ( "bytes" - "github.com/spf13/viper" - "github.com/stretchr/testify/assert" "path/filepath" "testing" + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/server/config/toml.go b/server/config/toml.go index d8c05f7d30c1..a93fffd1ecd6 100644 --- a/server/config/toml.go +++ b/server/config/toml.go @@ -276,7 +276,7 @@ func WriteConfigFile(configFilePath string, config interface{}) { panic(err) } - mustWriteFile(configFilePath, buffer.Bytes(), 0644) + mustWriteFile(configFilePath, buffer.Bytes(), 0o644) } func mustWriteFile(filePath string, contents []byte, mode os.FileMode) { diff --git a/server/export_test.go b/server/export_test.go index d48b99ebec76..b8cd1804849a 100644 --- a/server/export_test.go +++ b/server/export_test.go @@ -116,7 +116,6 @@ func TestExportCmd_Height(t *testing.T) { require.Equal(t, tc.expHeight, exportedGenDoc.InitialHeight) }) } - } func setupApp(t *testing.T, tempDir string) (*simapp.SimApp, context.Context, *tmtypes.GenesisDoc, *cobra.Command) { @@ -180,7 +179,7 @@ func setupApp(t *testing.T, tempDir string) (*simapp.SimApp, context.Context, *t } func createConfigFolder(dir string) error { - return os.Mkdir(path.Join(dir, "config"), 0700) + return os.Mkdir(path.Join(dir, "config"), 0o700) } func saveGenesisFile(genDoc *tmtypes.GenesisDoc, dir string) error { diff --git a/server/grpc/server_test.go b/server/grpc/server_test.go index 082399425306..5655d700c684 100644 --- a/server/grpc/server_test.go +++ b/server/grpc/server_test.go @@ -6,10 +6,11 @@ package grpc_test import ( "context" "fmt" - "github.com/cosmos/cosmos-sdk/codec" "testing" "time" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/jhump/protoreflect/grpcreflect" "github.com/stretchr/testify/require" diff --git a/server/mock/app.go b/server/mock/app.go index 9fd4d72f480e..83e562223558 100644 --- a/server/mock/app.go +++ b/server/mock/app.go @@ -136,8 +136,7 @@ func InitChainer(key storetypes.StoreKey) func(sdk.Context, abci.RequestInitChai // AppGenState can be passed into InitCmd, returns a static string of a few // key-values that can be parsed by InitChainer -func AppGenState(_ *codec.LegacyAmino, _ types.GenesisDoc, _ []json.RawMessage) (appState json. - RawMessage, err error) { +func AppGenState(_ *codec.LegacyAmino, _ types.GenesisDoc, _ []json.RawMessage) (appState json.RawMessage, err error) { appState = json.RawMessage(`{ "values": [ { @@ -154,8 +153,7 @@ func AppGenState(_ *codec.LegacyAmino, _ types.GenesisDoc, _ []json.RawMessage) } // AppGenStateEmpty returns an empty transaction state for mocking. -func AppGenStateEmpty(_ *codec.LegacyAmino, _ types.GenesisDoc, _ []json.RawMessage) ( - appState json.RawMessage, err error) { +func AppGenStateEmpty(_ *codec.LegacyAmino, _ types.GenesisDoc, _ []json.RawMessage) (appState json.RawMessage, err error) { appState = json.RawMessage(``) return } diff --git a/server/mock/app_test.go b/server/mock/app_test.go index 2741925df026..94362c887068 100644 --- a/server/mock/app_test.go +++ b/server/mock/app_test.go @@ -24,7 +24,7 @@ func TestInitApp(t *testing.T) { appState, err := AppGenState(nil, types.GenesisDoc{}, nil) require.NoError(t, err) - //TODO test validators in the init chain? + // TODO test validators in the init chain? req := abci.RequestInitChain{ AppStateBytes: appState, } diff --git a/server/mock/store.go b/server/mock/store.go index 745ea44e49dc..ebc4caaa421f 100644 --- a/server/mock/store.go +++ b/server/mock/store.go @@ -125,6 +125,7 @@ func (ms multiStore) SetSnapshotInterval(snapshotInterval uint64) { func (ms multiStore) SetInterBlockCache(_ sdk.MultiStorePersistentCache) { panic("not implemented") } + func (ms multiStore) SetIAVLCacheSize(size int) { panic("not implemented") } diff --git a/server/mock/tx.go b/server/mock/tx.go index bfa6e6ad6b4b..e6f5d2d764ea 100644 --- a/server/mock/tx.go +++ b/server/mock/tx.go @@ -25,9 +25,11 @@ func (msg *kvstoreTx) Reset() {} func (msg *kvstoreTx) String() string { return "TODO" } func (msg *kvstoreTx) ProtoMessage() {} -var _ sdk.Tx = &kvstoreTx{} -var _ sdk.Msg = &kvstoreTx{} -var _ middleware.GasTx = &kvstoreTx{} +var ( + _ sdk.Tx = &kvstoreTx{} + _ sdk.Msg = &kvstoreTx{} + _ middleware.GasTx = &kvstoreTx{} +) func NewTx(key, value string) kvstoreTx { bytes := fmt.Sprintf("%s=%s", key, value) diff --git a/server/rosetta/converter.go b/server/rosetta/converter.go index 9c0e6a7152f6..54c154579861 100644 --- a/server/rosetta/converter.go +++ b/server/rosetta/converter.go @@ -206,7 +206,6 @@ func (c converter) UnsignedTx(ops []*rosettatypes.Operation) (tx authsigning.Tx, } return builder.GetTx(), nil - } // Msg unmarshals the rosetta metadata to the given sdk.Msg @@ -328,7 +327,6 @@ func (c converter) BalanceOps(status string, events []abci.Event) []*rosettatype // has changed and rosetta needs to reflect those changes too. // The balance operations are multiple, one for each denom. func sdkEventToBalanceOperations(status string, event abci.Event) (operations []*rosettatypes.Operation, isBalanceEvent bool) { - var ( accountIdentifier string coinChange sdk.Coins @@ -510,7 +508,7 @@ func (c converter) HashToTxType(hashBytes []byte) (txType TransactionType, realH // StatusToSyncStatus converts a tendermint status to rosetta sync status func (c converter) SyncStatus(status *tmcoretypes.ResultStatus) *rosettatypes.SyncStatus { // determine sync status - var stage = StatusPeerSynced + stage := StatusPeerSynced if status.SyncInfo.CatchingUp { stage = StatusPeerSyncing } @@ -578,7 +576,6 @@ func (c converter) Peers(peers []tmcoretypes.Peer) []*rosettatypes.Peer { // OpsAndSigners takes transactions bytes and returns the operation, is signed is true it will return // the account identifiers which have signed the transaction func (c converter) OpsAndSigners(txBytes []byte) (ops []*rosettatypes.Operation, signers []*rosettatypes.AccountIdentifier, err error) { - rosTx, err := c.ToRosetta().Tx(txBytes, nil) if err != nil { return nil, nil, err @@ -672,7 +669,6 @@ func (c converter) PubKey(pubKey *rosettatypes.PublicKey) (cryptotypes.PubKey, e // SigningComponents takes a sdk tx and construction metadata and returns signable components func (c converter) SigningComponents(tx authsigning.Tx, metadata *ConstructionMetadata, rosPubKeys []*rosettatypes.PublicKey) (txBytes []byte, payloadsToSign []*rosettatypes.SigningPayload, err error) { - // verify metadata correctness feeAmount, err := sdk.ParseCoinsNormalized(metadata.GasPrice) if err != nil { diff --git a/server/rosetta/converter_test.go b/server/rosetta/converter_test.go index 1177d33405df..4fecf99dc51b 100644 --- a/server/rosetta/converter_test.go +++ b/server/rosetta/converter_test.go @@ -92,7 +92,6 @@ func (s *ConverterTestSuite) TestFromRosettaOpsToTxSuccess() { s.Require().Equal(getMsgs[0], msg1) s.Require().Equal(getMsgs[1], msg2) - } func (s *ConverterTestSuite) TestFromRosettaOpsToTxErrors() { @@ -114,9 +113,7 @@ func (s *ConverterTestSuite) TestFromRosettaOpsToTxErrors() { _, err := s.c.ToSDK().UnsignedTx([]*rosettatypes.Operation{op}) s.Require().ErrorIs(err, crgerrs.ErrBadArgument) - }) - } func (s *ConverterTestSuite) TestMsgToMetaMetaToMsg() { @@ -137,7 +134,6 @@ func (s *ConverterTestSuite) TestMsgToMetaMetaToMsg() { } func (s *ConverterTestSuite) TestSignedTx() { - s.Run("success", func() { const payloadsJSON = `[{"hex_bytes":"82ccce81a3e4a7272249f0e25c3037a316ee2acce76eb0c25db00ef6634a4d57303b2420edfdb4c9a635ad8851fe5c7a9379b7bc2baadc7d74f7e76ac97459b5","signing_payload":{"address":"cosmos147klh7th5jkjy3aajsj2rqvhtvh9mfde37wq5g","hex_bytes":"ed574d84b095250280de38bf8c254e4a1f8755e5bd300b1f6ca2671688136ecc","account_identifier":{"address":"cosmos147klh7th5jkjy3aajsj2rqvhtvh9mfde37wq5g"},"signature_type":"ecdsa"},"public_key":{"hex_bytes":"034c92046950c876f4a5cb6c7797d6eeb9ef80d67ced4d45fb62b1e859240ba9ad","curve_type":"secp256k1"},"signature_type":"ecdsa"}]` const expectedSignedTxHex = "0a8e010a8b010a1c2f636f736d6f732e62616e6b2e763162657461312e4d736753656e64126b0a2d636f736d6f733134376b6c68377468356a6b6a793361616a736a3272717668747668396d666465333777713567122d636f736d6f73316d6e7670386c786b616679346c787777617175356561653764787630647a36687767797436331a0b0a057374616b651202313612620a4e0a460a1f2f636f736d6f732e63727970746f2e736563703235366b312e5075624b657912230a21034c92046950c876f4a5cb6c7797d6eeb9ef80d67ced4d45fb62b1e859240ba9ad12040a02087f12100a0a0a057374616b651201311090a10f1a4082ccce81a3e4a7272249f0e25c3037a316ee2acce76eb0c25db00ef6634a4d57303b2420edfdb4c9a635ad8851fe5c7a9379b7bc2baadc7d74f7e76ac97459b5" @@ -291,7 +287,6 @@ func (s *ConverterTestSuite) TestSigningComponents() { }) s.Require().NoError(err) }) - } func (s *ConverterTestSuite) TestBalanceOps() { diff --git a/server/rosetta/lib/errors/errors_test.go b/server/rosetta/lib/errors/errors_test.go index 6efe446f5b2c..84be297e0ba1 100644 --- a/server/rosetta/lib/errors/errors_test.go +++ b/server/rosetta/lib/errors/errors_test.go @@ -30,7 +30,6 @@ func TestRegisterError(t *testing.T) { // add a new error on a sealed registry error = RegisterError(1024, "bytes", false, "bytes") assert.NotNil(t, error) - } func TestError_Error(t *testing.T) { @@ -58,12 +57,12 @@ func TestToRosetta(t *testing.T) { assert.NotNil(t, ToRosetta(&MyError{})) } -type MyError struct { -} +type MyError struct{} func (e *MyError) Error() string { return "" } + func (e *MyError) Is(err error) bool { return true } diff --git a/server/rosetta/lib/internal/service/construction.go b/server/rosetta/lib/internal/service/construction.go index 45c51df2a2c5..6f2d0f85da6e 100644 --- a/server/rosetta/lib/internal/service/construction.go +++ b/server/rosetta/lib/internal/service/construction.go @@ -129,7 +129,6 @@ func (on OnlineNetwork) ConstructionParse(ctx context.Context, request *types.Co AccountIdentifierSigners: signers, Metadata: nil, }, nil - } // ConstructionPayloads Payloads is called with an array of operations and the response from diff --git a/server/rosetta/lib/server/server.go b/server/rosetta/lib/server/server.go index 1d82ce8a6ff5..238583103ae6 100644 --- a/server/rosetta/lib/server/server.go +++ b/server/rosetta/lib/server/server.go @@ -13,8 +13,10 @@ import ( crgtypes "github.com/cosmos/cosmos-sdk/server/rosetta/lib/types" ) -const DefaultRetries = 5 -const DefaultRetryWait = 5 * time.Second +const ( + DefaultRetries = 5 + DefaultRetryWait = 5 * time.Second +) // Settings define the rosetta server settings type Settings struct { @@ -55,9 +57,7 @@ func NewServer(settings Settings) (Server, error) { return Server{}, fmt.Errorf("cannot build asserter: %w", err) } - var ( - adapter crgtypes.API - ) + var adapter crgtypes.API switch settings.Offline { case true: adapter, err = newOfflineAdapter(settings) diff --git a/server/util.go b/server/util.go index 27654c2d93df..ca7d4c63cfd8 100644 --- a/server/util.go +++ b/server/util.go @@ -412,6 +412,6 @@ func openTraceWriter(traceWriterFile string) (w io.Writer, err error) { return os.OpenFile( traceWriterFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, - 0666, + 0o666, ) } diff --git a/server/util_test.go b/server/util_test.go index 70f96e42c7a9..37e23e8d5f94 100644 --- a/server/util_test.go +++ b/server/util_test.go @@ -395,7 +395,7 @@ func TestInterceptConfigsPreRunHandlerPrecedenceConfigDefault(t *testing.T) { func TestInterceptConfigsWithBadPermissions(t *testing.T) { tempDir := t.TempDir() subDir := filepath.Join(tempDir, "nonPerms") - if err := os.Mkdir(subDir, 0600); err != nil { + if err := os.Mkdir(subDir, 0o600); err != nil { t.Fatalf("Failed to create sub directory: %v", err) } cmd := server.StartCmd(nil, "/foobar") diff --git a/simapp/app.go b/simapp/app.go index 799a95b60513..6baad02cec61 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -208,7 +208,6 @@ func NewSimApp( homePath string, invCheckPeriod uint, encodingConfig simappparams.EncodingConfig, appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp), ) *SimApp { - appCodec := encodingConfig.Codec legacyAmino := encodingConfig.Amino interfaceRegistry := encodingConfig.InterfaceRegistry @@ -341,7 +340,7 @@ func NewSimApp( // NOTE: we may consider parsing `appOpts` inside module constructors. For the moment // we prefer to be more strict in what arguments the modules expect. - var skipGenesisInvariants = cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants)) + skipGenesisInvariants := cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants)) // NOTE: Any module instantiated in the module manager that is later modified // must be passed by reference here. diff --git a/simapp/params/amino.go b/simapp/params/amino.go index cdf86d0ea2e0..d603987dd5f5 100644 --- a/simapp/params/amino.go +++ b/simapp/params/amino.go @@ -1,3 +1,4 @@ +//go:build test_amino // +build test_amino package params diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 70b2d9644a52..bde9aa5859e4 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -175,11 +175,13 @@ func TestAppImportExport(t *testing.T) { storeKeysPrefixes := []StoreKeysPrefixes{ {app.keys[authtypes.StoreKey], newApp.keys[authtypes.StoreKey], [][]byte{}}, - {app.keys[stakingtypes.StoreKey], newApp.keys[stakingtypes.StoreKey], + { + app.keys[stakingtypes.StoreKey], newApp.keys[stakingtypes.StoreKey], [][]byte{ stakingtypes.UnbondingQueueKey, stakingtypes.RedelegationQueueKey, stakingtypes.ValidatorQueueKey, stakingtypes.HistoricalInfoKey, - }}, // ordering may change but it doesn't matter + }, + }, // ordering may change but it doesn't matter {app.keys[slashingtypes.StoreKey], newApp.keys[slashingtypes.StoreKey], [][]byte{}}, {app.keys[minttypes.StoreKey], newApp.keys[minttypes.StoreKey], [][]byte{}}, {app.keys[distrtypes.StoreKey], newApp.keys[distrtypes.StoreKey], [][]byte{}}, diff --git a/simapp/simd/cmd/genaccounts_test.go b/simapp/simd/cmd/genaccounts_test.go index ed6d93508567..ca751fc34f62 100644 --- a/simapp/simd/cmd/genaccounts_test.go +++ b/simapp/simd/cmd/genaccounts_test.go @@ -3,10 +3,11 @@ package cmd_test import ( "context" "fmt" + "testing" + "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" - "testing" "github.com/spf13/viper" "github.com/stretchr/testify/require" @@ -96,7 +97,8 @@ func TestAddGenesisAccountCmd(t *testing.T) { cmd.SetArgs([]string{ tc.addr, tc.denom, - fmt.Sprintf("--%s=home", flags.FlagHome)}) + fmt.Sprintf("--%s=home", flags.FlagHome), + }) if tc.expectErr { require.Error(t, cmd.ExecuteContext(ctx)) diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 373b7d40e24a..cb0d3f6e0c34 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -297,9 +297,8 @@ func (a appCreator) newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, a // appExport creates a new simapp (optionally at a given height) // and exports state. func (a appCreator) appExport( - logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string, - appOpts servertypes.AppOptions) (servertypes.ExportedApp, error) { - + logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string, appOpts servertypes.AppOptions, +) (servertypes.ExportedApp, error) { var simApp *simapp.SimApp homePath, ok := appOpts.Get(flags.FlagHome).(string) if !ok || homePath == "" { diff --git a/simapp/simd/cmd/testnet.go b/simapp/simd/cmd/testnet.go index 885fc186d5a5..2b03f8a53235 100644 --- a/simapp/simd/cmd/testnet.go +++ b/simapp/simd/cmd/testnet.go @@ -137,7 +137,6 @@ Example: args.algo, _ = cmd.Flags().GetString(flags.FlagKeyAlgorithm) return initTestnetFiles(clientCtx, cmd, config, mbm, genBalIterator, args) - }, } @@ -163,7 +162,6 @@ Example: simd testnet --v 4 --output-dir ./.testnets `, RunE: func(cmd *cobra.Command, _ []string) error { - args := startArgs{} args.outputDir, _ = cmd.Flags().GetString(flagOutputDir) args.chainID, _ = cmd.Flags().GetString(flags.FlagChainID) @@ -177,7 +175,6 @@ Example: args.printMnemonic, _ = cmd.Flags().GetBool(flagPrintMnemonic) return startTestnet(cmd, args) - }, } @@ -190,7 +187,7 @@ Example: return cmd } -const nodeDirPerm = 0755 +const nodeDirPerm = 0o755 // initTestnetFiles initializes testnet files for a testnet to be run in a separate process func initTestnetFiles( @@ -356,7 +353,6 @@ func initGenFiles( genAccounts []authtypes.GenesisAccount, genBalances []banktypes.Balance, genFiles []string, numValidators int, ) error { - appGenState := mbm.DefaultGenesis(clientCtx.Codec) // set the accounts in the genesis state @@ -406,7 +402,6 @@ func collectGenFiles( nodeIDs []string, valPubKeys []cryptotypes.PubKey, numValidators int, outputDir, nodeDirPrefix, nodeDaemonHome string, genBalIterator banktypes.GenesisBalancesIterator, ) error { - var appState json.RawMessage genTime := tmtime.Now() @@ -475,12 +470,12 @@ func writeFile(name string, dir string, contents []byte) error { writePath := filepath.Join(dir) file := filepath.Join(writePath, name) - err := tmos.EnsureDir(writePath, 0755) + err := tmos.EnsureDir(writePath, 0o755) if err != nil { return err } - err = ioutil.WriteFile(file, contents, 0644) // nolint: gosec + err = ioutil.WriteFile(file, contents, 0o644) // nolint: gosec if err != nil { return err } diff --git a/simapp/state.go b/simapp/state.go index add654b55f3e..135863c5bd7c 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -29,7 +29,6 @@ import ( func AppStateFn(cdc codec.JSONCodec, simManager *module.SimulationManager) simtypes.AppStateFn { return func(r *rand.Rand, accs []simtypes.Account, config simtypes.Config, ) (appState json.RawMessage, simAccs []simtypes.Account, chainID string, genesisTimestamp time.Time) { - if FlagGenesisTimeValue == 0 { genesisTimestamp = simtypes.RandTimestamp(r) } else { diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 5f7df59a73ba..fcdef96e3dfe 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -146,7 +146,8 @@ func Setup(t *testing.T, isCheckTx bool) *SimApp { func genesisStateWithValSet(t *testing.T, app *SimApp, genesisState GenesisState, valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, - balances ...banktypes.Balance) GenesisState { + balances ...banktypes.Balance, +) GenesisState { // set genesis accounts authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) @@ -411,7 +412,6 @@ func SignCheckDeliver( t *testing.T, txCfg client.TxConfig, app *bam.BaseApp, header tmproto.Header, msgs []sdk.Msg, chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey, ) (sdk.GasInfo, *sdk.Result, error) { - tx, err := helpers.GenSignedMockTx( txCfg, msgs, diff --git a/simapp/utils.go b/simapp/utils.go index 1478104a5d8c..8c4a5abd1b78 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -84,7 +84,7 @@ func CheckExportSimulation( return err } - if err := os.WriteFile(config.ExportStatePath, []byte(exported.AppState), 0600); err != nil { + if err := os.WriteFile(config.ExportStatePath, []byte(exported.AppState), 0o600); err != nil { return err } } @@ -96,7 +96,7 @@ func CheckExportSimulation( return err } - if err := os.WriteFile(config.ExportParamsPath, paramsBz, 0600); err != nil { + if err := os.WriteFile(config.ExportParamsPath, paramsBz, 0o600); err != nil { return err } } diff --git a/snapshots/chunk.go b/snapshots/chunk.go index 1f654546e142..74503f058027 100644 --- a/snapshots/chunk.go +++ b/snapshots/chunk.go @@ -1,10 +1,10 @@ package snapshots import ( - snapshottypes "github.com/cosmos/cosmos-sdk/snapshots/types" "io" "math" + snapshottypes "github.com/cosmos/cosmos-sdk/snapshots/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) diff --git a/snapshots/manager.go b/snapshots/manager.go index 58986aab2716..8d10dcc9c713 100644 --- a/snapshots/manager.go +++ b/snapshots/manager.go @@ -66,9 +66,7 @@ const ( snapshotMaxItemSize = int(64e6) // SDK has no key/value size limit, so we set an arbitrary limit ) -var ( - ErrOptsZeroSnapshotInterval = errors.New("snaphot-interval must not be 0") -) +var ErrOptsZeroSnapshotInterval = errors.New("snaphot-interval must not be 0") // NewManager creates a new manager. func NewManager(store *Store, opts types.SnapshotOptions, multistore types.Snapshotter, extensions map[string]types.ExtensionSnapshotter, logger log.Logger) *Manager { diff --git a/snapshots/store.go b/snapshots/store.go index 0a3e4388e8b4..8105938b80f1 100644 --- a/snapshots/store.go +++ b/snapshots/store.go @@ -36,7 +36,7 @@ func NewStore(db db.DB, dir string) (*Store, error) { if dir == "" { return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "snapshot directory not given") } - err := os.MkdirAll(dir, 0755) + err := os.MkdirAll(dir, 0o755) if err != nil { return nil, sdkerrors.Wrapf(err, "failed to create snapshot directory %q", dir) } @@ -261,7 +261,7 @@ func (s *Store) Save( for chunkBody := range chunks { defer chunkBody.Close() // nolint: staticcheck dir := s.pathSnapshot(height, format) - err = os.MkdirAll(dir, 0755) + err = os.MkdirAll(dir, 0o755) if err != nil { return nil, sdkerrors.Wrapf(err, "failed to create snapshot directory %q", dir) } diff --git a/snapshots/store_test.go b/snapshots/store_test.go index 1cb27f577211..b2a8354bb2b9 100644 --- a/snapshots/store_test.go +++ b/snapshots/store_test.go @@ -114,7 +114,8 @@ func TestStore_Get(t *testing.T) { Hash: hash([][]byte{{2, 1, 0}, {2, 1, 1}}), Metadata: types.Metadata{ ChunkHashes: checksums([][]byte{ - {2, 1, 0}, {2, 1, 1}}), + {2, 1, 0}, {2, 1, 1}, + }), }, }, snapshot) } @@ -149,16 +150,20 @@ func TestStore_List(t *testing.T) { require.NoError(t, err) require.Equal(t, []*types.Snapshot{ - {Height: 3, Format: 2, Chunks: 3, Hash: hash([][]byte{{3, 2, 0}, {3, 2, 1}, {3, 2, 2}}), + { + Height: 3, Format: 2, Chunks: 3, Hash: hash([][]byte{{3, 2, 0}, {3, 2, 1}, {3, 2, 2}}), Metadata: types.Metadata{ChunkHashes: checksums([][]byte{{3, 2, 0}, {3, 2, 1}, {3, 2, 2}})}, }, - {Height: 2, Format: 2, Chunks: 3, Hash: hash([][]byte{{2, 2, 0}, {2, 2, 1}, {2, 2, 2}}), + { + Height: 2, Format: 2, Chunks: 3, Hash: hash([][]byte{{2, 2, 0}, {2, 2, 1}, {2, 2, 2}}), Metadata: types.Metadata{ChunkHashes: checksums([][]byte{{2, 2, 0}, {2, 2, 1}, {2, 2, 2}})}, }, - {Height: 2, Format: 1, Chunks: 2, Hash: hash([][]byte{{2, 1, 0}, {2, 1, 1}}), + { + Height: 2, Format: 1, Chunks: 2, Hash: hash([][]byte{{2, 1, 0}, {2, 1, 1}}), Metadata: types.Metadata{ChunkHashes: checksums([][]byte{{2, 1, 0}, {2, 1, 1}})}, }, - {Height: 1, Format: 1, Chunks: 2, Hash: hash([][]byte{{1, 1, 0}, {1, 1, 1}}), + { + Height: 1, Format: 1, Chunks: 2, Hash: hash([][]byte{{1, 1, 0}, {1, 1, 1}}), Metadata: types.Metadata{ChunkHashes: checksums([][]byte{{1, 1, 0}, {1, 1, 1}})}, }, }, snapshots) @@ -182,7 +187,8 @@ func TestStore_Load(t *testing.T) { Hash: hash([][]byte{{2, 1, 0}, {2, 1, 1}}), Metadata: types.Metadata{ ChunkHashes: checksums([][]byte{ - {2, 1, 0}, {2, 1, 1}}), + {2, 1, 0}, {2, 1, 1}, + }), }, }, snapshot) @@ -240,13 +246,16 @@ func TestStore_Prune(t *testing.T) { snapshots, err = store.List() require.NoError(t, err) require.Equal(t, []*types.Snapshot{ - {Height: 3, Format: 2, Chunks: 3, Hash: hash([][]byte{{3, 2, 0}, {3, 2, 1}, {3, 2, 2}}), + { + Height: 3, Format: 2, Chunks: 3, Hash: hash([][]byte{{3, 2, 0}, {3, 2, 1}, {3, 2, 2}}), Metadata: types.Metadata{ChunkHashes: checksums([][]byte{{3, 2, 0}, {3, 2, 1}, {3, 2, 2}})}, }, - {Height: 2, Format: 2, Chunks: 3, Hash: hash([][]byte{{2, 2, 0}, {2, 2, 1}, {2, 2, 2}}), + { + Height: 2, Format: 2, Chunks: 3, Hash: hash([][]byte{{2, 2, 0}, {2, 2, 1}, {2, 2, 2}}), Metadata: types.Metadata{ChunkHashes: checksums([][]byte{{2, 2, 0}, {2, 2, 1}, {2, 2, 2}})}, }, - {Height: 2, Format: 1, Chunks: 2, Hash: hash([][]byte{{2, 1, 0}, {2, 1, 1}}), + { + Height: 2, Format: 1, Chunks: 2, Hash: hash([][]byte{{2, 1, 0}, {2, 1, 1}}), Metadata: types.Metadata{ChunkHashes: checksums([][]byte{{2, 1, 0}, {2, 1, 1}})}, }, }, snapshots) diff --git a/store/cachekv/store_test.go b/store/cachekv/store_test.go index 0404f33f2a28..d589932d30fc 100644 --- a/store/cachekv/store_test.go +++ b/store/cachekv/store_test.go @@ -112,7 +112,7 @@ func TestCacheKVIteratorBounds(t *testing.T) { // iterate over all of them itr := st.Iterator(nil, nil) - var i = 0 + i := 0 for ; itr.Valid(); itr.Next() { k, v := itr.Key(), itr.Value() require.Equal(t, keyFmt(i), k) @@ -380,7 +380,7 @@ func doRandomOp(t *testing.T, st types.CacheKVStore, truth dbm.DB, maxKey int) { // iterate over whole domain func assertIterateDomain(t *testing.T, st types.KVStore, expectedN int) { itr := st.Iterator(nil, nil) - var i = 0 + i := 0 for ; itr.Valid(); itr.Next() { k, v := itr.Key(), itr.Value() require.Equal(t, keyFmt(i), k) diff --git a/store/cachemulti/store.go b/store/cachemulti/store.go index 8e11ccee0dca..2e39554e17ce 100644 --- a/store/cachemulti/store.go +++ b/store/cachemulti/store.go @@ -77,7 +77,6 @@ func NewStore( db dbm.DB, stores map[types.StoreKey]types.CacheWrapper, keys map[string]types.StoreKey, traceWriter io.Writer, traceContext types.TraceContext, listeners map[types.StoreKey][]types.WriteListener, ) Store { - return NewFromKVStore(dbadapter.Store{DB: db}, stores, keys, traceWriter, traceContext, listeners) } diff --git a/store/iavl/store_test.go b/store/iavl/store_test.go index b9c9e25ad43d..e39a6ebee15b 100644 --- a/store/iavl/store_test.go +++ b/store/iavl/store_test.go @@ -284,7 +284,7 @@ func TestIAVLReverseIterator(t *testing.T) { iavlStore.Set([]byte{0x00, 0x02}, []byte("0 2")) iavlStore.Set([]byte{0x01}, []byte("1")) - var testReverseIterator = func(t *testing.T, start []byte, end []byte, expected []string) { + testReverseIterator := func(t *testing.T, start []byte, end []byte, expected []string) { iter := iavlStore.ReverseIterator(start, end) var i int for i = 0; iter.Valid(); iter.Next() { diff --git a/store/internal/maps/maps_test.go b/store/internal/maps/maps_test.go index 8f6b1163eaec..ce7ad72e649d 100644 --- a/store/internal/maps/maps_test.go +++ b/store/internal/maps/maps_test.go @@ -12,6 +12,7 @@ func TestEmptyKeyMerkleMap(t *testing.T) { db := newMerkleMap() require.Panics(t, func() { db.set("", []byte("value")) }, "setting an empty key should panic") } + func TestMerkleMap(t *testing.T) { tests := []struct { keys []string @@ -59,6 +60,7 @@ func TestEmptyKeySimpleMap(t *testing.T) { db := newSimpleMap() require.Panics(t, func() { db.Set("", []byte("value")) }, "setting an empty key should panic") } + func TestSimpleMap(t *testing.T) { tests := []struct { keys []string diff --git a/store/listenkv/store_test.go b/store/listenkv/store_test.go index 5d4fd0cca9c4..8d0510ba49ce 100644 --- a/store/listenkv/store_test.go +++ b/store/listenkv/store_test.go @@ -29,9 +29,11 @@ var kvPairs = []types.KVPair{ {Key: keyFmt(3), Value: valFmt(3)}, } -var testStoreKey = types.NewKVStoreKey("listen_test") -var interfaceRegistry = codecTypes.NewInterfaceRegistry() -var testMarshaller = codec.NewProtoCodec(interfaceRegistry) +var ( + testStoreKey = types.NewKVStoreKey("listen_test") + interfaceRegistry = codecTypes.NewInterfaceRegistry() + testMarshaller = codec.NewProtoCodec(interfaceRegistry) +) func newListenKVStore(w io.Writer) *listenkv.Store { store := newEmptyListenKVStore(w) @@ -130,7 +132,6 @@ func TestListenKVStoreSet(t *testing.T) { store := newEmptyListenKVStore(&buf) require.Panics(t, func() { store.Set([]byte(""), []byte("value")) }, "setting an empty key should panic") require.Panics(t, func() { store.Set(nil, []byte("value")) }, "setting a nil key should panic") - } func TestListenKVStoreDelete(t *testing.T) { diff --git a/store/rootmulti/store.go b/store/rootmulti/store.go index 28804dfd1aaf..d31cb2e42b03 100644 --- a/store/rootmulti/store.go +++ b/store/rootmulti/store.go @@ -202,7 +202,7 @@ func (rs *Store) loadVersion(ver int64, upgrades *types.StoreUpgrades) error { } // load each Store (note this doesn't panic on unmounted keys now) - var newStores = make(map[types.StoreKey]types.CommitKVStore) + newStores := make(map[types.StoreKey]types.CommitKVStore) storesKeys := make([]types.StoreKey, 0, len(rs.storesParams)) @@ -405,7 +405,6 @@ func (rs *Store) Commit() types.CommitID { // This case means that no commit has been made in the store, we // start from initialVersion. version = rs.initialVersion - } else { // This case can means two things: // - either there was already a previous commit in the store, in which diff --git a/store/rootmulti/store_test.go b/store/rootmulti/store_test.go index d1d65770b09f..ccd58b153feb 100644 --- a/store/rootmulti/store_test.go +++ b/store/rootmulti/store_test.go @@ -316,7 +316,6 @@ func TestParsePath(t *testing.T) { require.NoError(t, err) require.Equal(t, substore, "bang") require.Equal(t, subsubpath, "/baz") - } func TestMultiStoreRestart(t *testing.T) { diff --git a/store/streaming/file/service.go b/store/streaming/file/service.go index 16c1b5c82b35..28e77a52fa39 100644 --- a/store/streaming/file/service.go +++ b/store/streaming/file/service.go @@ -133,7 +133,7 @@ func (fss *StreamingService) openBeginBlockFile(req abci.RequestBeginBlock) (*os if fss.filePrefix != "" { fileName = fmt.Sprintf("%s-%s", fss.filePrefix, fileName) } - return os.OpenFile(filepath.Join(fss.writeDir, fileName), os.O_CREATE|os.O_WRONLY, 0600) + return os.OpenFile(filepath.Join(fss.writeDir, fileName), os.O_CREATE|os.O_WRONLY, 0o600) } // ListenDeliverTx satisfies the baseapp.ABCIListener interface @@ -183,7 +183,7 @@ func (fss *StreamingService) openDeliverTxFile() (*os.File, error) { fileName = fmt.Sprintf("%s-%s", fss.filePrefix, fileName) } fss.currentTxIndex++ - return os.OpenFile(filepath.Join(fss.writeDir, fileName), os.O_CREATE|os.O_WRONLY, 0600) + return os.OpenFile(filepath.Join(fss.writeDir, fileName), os.O_CREATE|os.O_WRONLY, 0o600) } // ListenEndBlock satisfies the baseapp.ABCIListener interface @@ -232,7 +232,7 @@ func (fss *StreamingService) openEndBlockFile() (*os.File, error) { if fss.filePrefix != "" { fileName = fmt.Sprintf("%s-%s", fss.filePrefix, fileName) } - return os.OpenFile(filepath.Join(fss.writeDir, fileName), os.O_CREATE|os.O_WRONLY, 0600) + return os.OpenFile(filepath.Join(fss.writeDir, fileName), os.O_CREATE|os.O_WRONLY, 0o600) } // Stream satisfies the baseapp.StreamingService interface @@ -272,7 +272,7 @@ func (fss *StreamingService) Close() error { // to dir. It returns nil if dir is writable. func isDirWriteable(dir string) error { f := path.Join(dir, ".touch") - if err := ioutil.WriteFile(f, []byte(""), 0600); err != nil { + if err := ioutil.WriteFile(f, []byte(""), 0o600); err != nil { return err } return os.Remove(f) diff --git a/store/streaming/file/service_test.go b/store/streaming/file/service_test.go index db5b2137f99b..cc9fdca88136 100644 --- a/store/streaming/file/service_test.go +++ b/store/streaming/file/service_test.go @@ -128,7 +128,7 @@ func TestFileStreamingService(t *testing.T) { if os.Getenv("CI") != "" { t.Skip("Skipping TestFileStreamingService in CI environment") } - err := os.Mkdir(testDir, 0700) + err := os.Mkdir(testDir, 0o700) require.Nil(t, err) defer os.RemoveAll(testDir) diff --git a/store/tools/ics23/smt/create_test.go b/store/tools/ics23/smt/create_test.go index 1a3e74e70869..71ec7722661e 100644 --- a/store/tools/ics23/smt/create_test.go +++ b/store/tools/ics23/smt/create_test.go @@ -10,21 +10,23 @@ import ( "github.com/cosmos/cosmos-sdk/store/tools/ics23/smt/helpers" ) -var numKeys = 50 -var cases = map[string]struct { - size int - loc tmproofs.Where -}{ - "tiny left": {size: 10, loc: tmproofs.Left}, - "tiny middle": {size: 10, loc: tmproofs.Middle}, - "tiny right": {size: 10, loc: tmproofs.Right}, - "small left": {size: 100, loc: tmproofs.Left}, - "small middle": {size: 100, loc: tmproofs.Middle}, - "small right": {size: 100, loc: tmproofs.Right}, - "big left": {size: 5431, loc: tmproofs.Left}, - "big middle": {size: 5431, loc: tmproofs.Middle}, - "big right": {size: 5431, loc: tmproofs.Right}, -} +var ( + numKeys = 50 + cases = map[string]struct { + size int + loc tmproofs.Where + }{ + "tiny left": {size: 10, loc: tmproofs.Left}, + "tiny middle": {size: 10, loc: tmproofs.Middle}, + "tiny right": {size: 10, loc: tmproofs.Right}, + "small left": {size: 100, loc: tmproofs.Left}, + "small middle": {size: 100, loc: tmproofs.Middle}, + "small right": {size: 100, loc: tmproofs.Right}, + "big left": {size: 5431, loc: tmproofs.Left}, + "big middle": {size: 5431, loc: tmproofs.Middle}, + "big right": {size: 5431, loc: tmproofs.Right}, + } +) func TestCreateMembership(t *testing.T) { for name, tc := range cases { diff --git a/store/tracekv/store_test.go b/store/tracekv/store_test.go index db9a981237f4..1b81e89bafd2 100644 --- a/store/tracekv/store_test.go +++ b/store/tracekv/store_test.go @@ -111,7 +111,6 @@ func TestTraceKVStoreSet(t *testing.T) { store := newEmptyTraceKVStore(&buf) require.Panics(t, func() { store.Set([]byte(""), []byte("value")) }, "setting an empty key should panic") require.Panics(t, func() { store.Set(nil, []byte("value")) }, "setting a nil key should panic") - } func TestTraceKVStoreDelete(t *testing.T) { diff --git a/store/transient/store.go b/store/transient/store.go index b9723b56efd5..4d4fc5b81d6e 100644 --- a/store/transient/store.go +++ b/store/transient/store.go @@ -8,8 +8,10 @@ import ( "github.com/cosmos/cosmos-sdk/store/types" ) -var _ types.Committer = (*Store)(nil) -var _ types.KVStore = (*Store)(nil) +var ( + _ types.Committer = (*Store)(nil) + _ types.KVStore = (*Store)(nil) +) // Store is a wrapper for a MemDB with Commiter implementation type Store struct { diff --git a/store/types/errors.go b/store/types/errors.go index 780fcdef37ab..f2f395aea806 100644 --- a/store/types/errors.go +++ b/store/types/errors.go @@ -6,6 +6,4 @@ import ( const StoreCodespace = "store" -var ( - ErrInvalidProof = sdkerrors.Register(StoreCodespace, 2, "invalid proof") -) +var ErrInvalidProof = sdkerrors.Register(StoreCodespace, 2, "invalid proof") diff --git a/store/types/iterator.go b/store/types/iterator.go index cfce4124e397..a328e87a68a6 100644 --- a/store/types/iterator.go +++ b/store/types/iterator.go @@ -34,7 +34,6 @@ type PaginatedIterator struct { page, limit uint // provided during initialization iterated uint // incremented in a call to Next - } func (pi *PaginatedIterator) skip() { diff --git a/store/types/store.go b/store/types/store.go index 988bbf55a4f1..bb628dd26922 100644 --- a/store/types/store.go +++ b/store/types/store.go @@ -92,7 +92,6 @@ func (s *StoreUpgrades) RenamedFrom(key string) string { } } return "" - } type MultiStore interface { diff --git a/store/v2alpha1/multi/snapshot.go b/store/v2alpha1/multi/snapshot.go index 37f687873954..434c5e1c6fc5 100644 --- a/store/v2alpha1/multi/snapshot.go +++ b/store/v2alpha1/multi/snapshot.go @@ -107,7 +107,7 @@ func (rs *Store) Restore( } var subStore *substore - var storeSchemaReceived = false + storeSchemaReceived := false var snapshotItem snapshottypes.SnapshotItem diff --git a/store/v2alpha1/multi/store.go b/store/v2alpha1/multi/store.go index 3bf6c73096ab..e4eb13c7d9a1 100644 --- a/store/v2alpha1/multi/store.go +++ b/store/v2alpha1/multi/store.go @@ -892,9 +892,11 @@ func (tlm *traceListenMixin) ListeningEnabled(key types.StoreKey) bool { func (tlm *traceListenMixin) TracingEnabled() bool { return tlm.TraceWriter != nil } + func (tlm *traceListenMixin) SetTracer(w io.Writer) { tlm.TraceWriter = w } + func (tlm *traceListenMixin) SetTraceContext(tc types.TraceContext) { tlm.TraceContext = tc } diff --git a/store/v2alpha1/multi/store_test.go b/store/v2alpha1/multi/store_test.go index cdcbbd2fb98b..de09003518d0 100644 --- a/store/v2alpha1/multi/store_test.go +++ b/store/v2alpha1/multi/store_test.go @@ -163,7 +163,7 @@ func TestIterators(t *testing.T) { string([]byte{0x01}): "1", }) - var testCase = func(t *testing.T, iter types.Iterator, expected []string) { + testCase := func(t *testing.T, iter types.Iterator, expected []string) { var i int for i = 0; iter.Valid(); iter.Next() { expectedValue := expected[i] @@ -260,7 +260,8 @@ func TestCommit(t *testing.T) { testFailedCommit := func(t *testing.T, store *Store, db dbm.DBConnection, - opts StoreConfig) { + opts StoreConfig, + ) { if db == nil { db = store.stateDB } @@ -936,8 +937,8 @@ func TestListeners(t *testing.T) { }, } - var interfaceRegistry = codecTypes.NewInterfaceRegistry() - var marshaller = codec.NewProtoCodec(interfaceRegistry) + interfaceRegistry := codecTypes.NewInterfaceRegistry() + marshaller := codec.NewProtoCodec(interfaceRegistry) db := memdb.NewDB() opts := simpleStoreConfig(t) diff --git a/store/v2alpha1/multi/test_util.go b/store/v2alpha1/multi/test_util.go index cc03639906d9..a03d60f54f03 100644 --- a/store/v2alpha1/multi/test_util.go +++ b/store/v2alpha1/multi/test_util.go @@ -7,25 +7,30 @@ import ( dbm "github.com/cosmos/cosmos-sdk/db" ) -type dbDeleteVersionFails struct{ dbm.DBConnection } -type dbRWCommitFails struct{ dbm.DBConnection } -type dbRWCrudFails struct{ dbm.DBConnection } -type dbSaveVersionFails struct{ dbm.DBConnection } -type dbRevertFails struct { - dbm.DBConnection - // order of calls to fail on (eg. [1, 0] => first call fails; second succeeds) - failOn []bool -} +type ( + dbDeleteVersionFails struct{ dbm.DBConnection } + dbRWCommitFails struct{ dbm.DBConnection } + dbRWCrudFails struct{ dbm.DBConnection } + dbSaveVersionFails struct{ dbm.DBConnection } + dbRevertFails struct { + dbm.DBConnection + // order of calls to fail on (eg. [1, 0] => first call fails; second succeeds) + failOn []bool + } +) + type dbVersionsIs struct { dbm.DBConnection vset dbm.VersionSet } -type dbVersionsFails struct{ dbm.DBConnection } -type rwCommitFails struct{ dbm.DBReadWriter } -type rwCrudFails struct { - dbm.DBReadWriter - onKey []byte -} +type ( + dbVersionsFails struct{ dbm.DBConnection } + rwCommitFails struct{ dbm.DBReadWriter } + rwCrudFails struct { + dbm.DBReadWriter + onKey []byte + } +) func (dbVersionsFails) Versions() (dbm.VersionSet, error) { return nil, errors.New("dbVersionsFails") } func (db dbVersionsIs) Versions() (dbm.VersionSet, error) { return db.vset, nil } @@ -48,6 +53,7 @@ func (tx rwCommitFails) Commit() error { tx.Discard() return errors.New("rwCommitFails") } + func (db dbRWCommitFails) ReadWriter() dbm.DBReadWriter { return rwCommitFails{db.DBConnection.ReadWriter()} } @@ -58,18 +64,21 @@ func (rw rwCrudFails) Get(k []byte) ([]byte, error) { } return rw.DBReadWriter.Get(k) } + func (rw rwCrudFails) Has(k []byte) (bool, error) { if rw.onKey == nil || bytes.Equal(rw.onKey, k) { return false, errors.New("rwCrudFails.Has") } return rw.DBReadWriter.Has(k) } + func (rw rwCrudFails) Set(k []byte, v []byte) error { if rw.onKey == nil || bytes.Equal(rw.onKey, k) { return errors.New("rwCrudFails.Set") } return rw.DBReadWriter.Set(k, v) } + func (rw rwCrudFails) Delete(k []byte) error { if rw.onKey == nil || bytes.Equal(rw.onKey, k) { return errors.New("rwCrudFails.Delete") diff --git a/store/v2alpha1/smt/proof_test.go b/store/v2alpha1/smt/proof_test.go index 3ef6573dab32..b2d3b191929e 100644 --- a/store/v2alpha1/smt/proof_test.go +++ b/store/v2alpha1/smt/proof_test.go @@ -55,7 +55,7 @@ func TestProofOpInterface(t *testing.T) { assert.Equal(t, key, tmProofOp.Key, key) assert.NotEmpty(t, tmProofOp.Data) - //decode + // decode decoded, err := smtstore.ProofDecoder(tmProofOp) assert.NoError(t, err) assert.NotNil(t, decoded) diff --git a/testutil/network/network.go b/testutil/network/network.go index 2d89c4e69e9c..b4675a769f7c 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -178,8 +178,10 @@ type Logger interface { Logf(format string, args ...interface{}) } -var _ Logger = (*testing.T)(nil) -var _ Logger = (*CLILogger)(nil) +var ( + _ Logger = (*testing.T)(nil) + _ Logger = (*CLILogger)(nil) +) // CLILogger wraps a cobra.Command and provides command logging methods. type CLILogger struct { @@ -309,12 +311,12 @@ func New(l Logger, baseDir string, cfg Config) (*Network, error) { clientDir := filepath.Join(network.BaseDir, nodeDirName, "simcli") gentxsDir := filepath.Join(network.BaseDir, "gentxs") - err := os.MkdirAll(filepath.Join(nodeDir, "config"), 0755) + err := os.MkdirAll(filepath.Join(nodeDir, "config"), 0o755) if err != nil { return nil, err } - err = os.MkdirAll(clientDir, 0755) + err = os.MkdirAll(clientDir, 0o755) if err != nil { return nil, err } diff --git a/testutil/network/network_test.go b/testutil/network/network_test.go index 43859ff5a8a4..c7b5e4291ccc 100644 --- a/testutil/network/network_test.go +++ b/testutil/network/network_test.go @@ -1,3 +1,4 @@ +//go:build norace // +build norace package network_test diff --git a/testutil/network/util.go b/testutil/network/util.go index 79777ed09881..7aa84703ac93 100644 --- a/testutil/network/util.go +++ b/testutil/network/util.go @@ -152,7 +152,6 @@ func collectGenFiles(cfg Config, vals []*Validator, outputDir string) error { } func initGenFiles(cfg Config, genAccounts []authtypes.GenesisAccount, genBalances []banktypes.Balance, genFiles []string) error { - // set the accounts in the genesis state var authGenState authtypes.GenesisState cfg.Codec.MustUnmarshalJSON(cfg.GenesisState[authtypes.ModuleName], &authGenState) @@ -197,12 +196,12 @@ func writeFile(name string, dir string, contents []byte) error { writePath := filepath.Join(dir) file := filepath.Join(writePath, name) - err := tmos.EnsureDir(writePath, 0755) + err := tmos.EnsureDir(writePath, 0o755) if err != nil { return err } - err = ioutil.WriteFile(file, contents, 0644) // nolint: gosec + err = ioutil.WriteFile(file, contents, 0o644) // nolint: gosec if err != nil { return err } diff --git a/testutil/testdata/table.go b/testutil/testdata/table.go index 8faae88a451d..691d6c8cc34a 100644 --- a/testutil/testdata/table.go +++ b/testutil/testdata/table.go @@ -2,9 +2,7 @@ package testdata import "github.com/cosmos/cosmos-sdk/types/errors" -var ( - ErrTest = errors.Register("table_testdata", 2, "test") -) +var ErrTest = errors.Register("table_testdata", 2, "test") func (g TableModel) PrimaryKeyFields() []interface{} { return []interface{}{g.Id} diff --git a/testutil/testdata/tx.go b/testutil/testdata/tx.go index 5d0051f41a6a..d16dd06d0ebd 100644 --- a/testutil/testdata/tx.go +++ b/testutil/testdata/tx.go @@ -63,6 +63,7 @@ func (msg *TestMsg) GetSignBytes() []byte { } return sdk.MustSortJSON(bz) } + func (msg *TestMsg) GetSigners() []sdk.AccAddress { signers := make([]sdk.AccAddress, 0, len(msg.Signers)) for _, addr := range msg.Signers { @@ -71,6 +72,7 @@ func (msg *TestMsg) GetSigners() []sdk.AccAddress { } return signers } + func (msg *TestMsg) ValidateBasic() error { for _, addr := range msg.Signers { if _, err := sdk.AccAddressFromBech32(addr); err != nil { diff --git a/types/address.go b/types/address.go index 3c7fa6055b88..5fd3fa051b32 100644 --- a/types/address.go +++ b/types/address.go @@ -118,8 +118,11 @@ type Address interface { // Ensure that different address types implement the interface var _ Address = AccAddress{} -var _ Address = ValAddress{} -var _ Address = ConsAddress{} + +var ( + _ Address = ValAddress{} + _ Address = ConsAddress{} +) // ---------------------------------------------------------------------------- // account @@ -223,7 +226,6 @@ func (aa AccAddress) MarshalYAML() (interface{}, error) { func (aa *AccAddress) UnmarshalJSON(data []byte) error { var s string err := json.Unmarshal(data, &s) - if err != nil { return err } @@ -273,7 +275,7 @@ func (aa AccAddress) String() string { return "" } - var key = conv.UnsafeBytesToStr(aa) + key := conv.UnsafeBytesToStr(aa) accAddrMu.Lock() defer accAddrMu.Unlock() addr, ok := accAddrCache.Get(key) @@ -423,7 +425,7 @@ func (va ValAddress) String() string { return "" } - var key = conv.UnsafeBytesToStr(va) + key := conv.UnsafeBytesToStr(va) valAddrMu.Lock() defer valAddrMu.Unlock() addr, ok := valAddrCache.Get(key) @@ -578,7 +580,7 @@ func (ca ConsAddress) String() string { return "" } - var key = conv.UnsafeBytesToStr(ca) + key := conv.UnsafeBytesToStr(ca) consAddrMu.Lock() defer consAddrMu.Unlock() addr, ok := consAddrCache.Get(key) diff --git a/types/address/hash_test.go b/types/address/hash_test.go index ae712c18dd4a..06fede65948c 100644 --- a/types/address/hash_test.go +++ b/types/address/hash_test.go @@ -63,7 +63,7 @@ func (suite *AddressSuite) TestComposed() { func (suite *AddressSuite) TestModule() { assert := suite.Assert() - var modName, key = "myModule", []byte{1, 2} + modName, key := "myModule", []byte{1, 2} addr := Module(modName, key) assert.Len(addr, Len, "must have address length") @@ -77,7 +77,7 @@ func (suite *AddressSuite) TestModule() { func (suite *AddressSuite) TestDerive() { assert := suite.Assert() - var addr, key1, key2 = []byte{1, 2}, []byte{3, 4}, []byte{1, 2} + addr, key1, key2 := []byte{1, 2}, []byte{3, 4}, []byte{1, 2} d1 := Derive(addr, key1) d2 := Derive(addr, key2) d3 := Derive(key1, key2) diff --git a/types/address_test.go b/types/address_test.go index 8898d2edec2d..18bb929c61fa 100644 --- a/types/address_test.go +++ b/types/address_test.go @@ -298,7 +298,6 @@ func (s *addressTestSuite) TestAddressInterface() { s.T().Fail() } } - } func (s *addressTestSuite) TestVerifyAddressFormat() { diff --git a/types/bench_test.go b/types/bench_test.go index 89fd9f19ea02..639ba471d214 100644 --- a/types/bench_test.go +++ b/types/bench_test.go @@ -30,7 +30,7 @@ func BenchmarkParseCoin(b *testing.B) { } func BenchmarkUintMarshal(b *testing.B) { - var values = []uint64{ + values := []uint64{ 0, 1, 1 << 10, @@ -55,7 +55,7 @@ func BenchmarkUintMarshal(b *testing.B) { } func BenchmarkIntMarshal(b *testing.B) { - var values = []int64{ + values := []int64{ 0, 1, 1 << 10, diff --git a/types/coin_test.go b/types/coin_test.go index 7ee9c91c661e..361ddf9ea2d4 100644 --- a/types/coin_test.go +++ b/types/coin_test.go @@ -108,7 +108,6 @@ func (s *coinTestSuite) TestCoinIsValid() { } func (s *coinTestSuite) TestCustomValidation() { - newDnmRegex := `[\x{1F600}-\x{1F6FF}]` sdk.SetCoinDenomRegex(func() string { return newDnmRegex @@ -739,7 +738,8 @@ func (s *coinTestSuite) TestCoins_Validate() { {"mineral", sdk.OneInt()}, }, false, - }, { + }, + { "duplicate denomination", sdk.Coins{ {"gas", sdk.OneInt()}, @@ -775,8 +775,13 @@ func (s *coinTestSuite) TestMinMax() { {"zero-one", sdk.Coins{}, sdk.Coins{{testDenom1, one}}, sdk.Coins{}, sdk.Coins{{testDenom1, one}}}, {"two-zero", sdk.Coins{{testDenom2, two}}, sdk.Coins{}, sdk.Coins{}, sdk.Coins{{testDenom2, two}}}, {"disjoint", sdk.Coins{{testDenom1, one}}, sdk.Coins{{testDenom2, two}}, sdk.Coins{}, sdk.Coins{{testDenom1, one}, {testDenom2, two}}}, - {"overlap", sdk.Coins{{testDenom1, one}, {testDenom2, two}}, sdk.Coins{{testDenom1, two}, {testDenom2, one}}, - sdk.Coins{{testDenom1, one}, {testDenom2, one}}, sdk.Coins{{testDenom1, two}, {testDenom2, two}}}, + { + "overlap", + sdk.Coins{{testDenom1, one}, {testDenom2, two}}, + sdk.Coins{{testDenom1, two}, {testDenom2, one}}, + sdk.Coins{{testDenom1, one}, {testDenom2, one}}, + sdk.Coins{{testDenom1, two}, {testDenom2, two}}, + }, } for _, tc := range cases { @@ -1126,7 +1131,6 @@ func (s *coinTestSuite) TestCoinsIsAnyNil() { s.Require().True(sdk.Coins{twoAtom, nilAtom, fiveAtom, threeEth}.IsAnyNil()) s.Require().True(sdk.Coins{nilAtom, twoAtom, fiveAtom, threeEth}.IsAnyNil()) s.Require().False(sdk.Coins{twoAtom, fiveAtom, threeEth}.IsAnyNil()) - } func (s *coinTestSuite) TestMarshalJSONCoins() { diff --git a/types/context.go b/types/context.go index ccd860efa057..30bec2154f5d 100644 --- a/types/context.go +++ b/types/context.go @@ -61,7 +61,7 @@ func (c Context) EventManager() *EventManager { return c.eventManager } // clone the header before returning func (c Context) BlockHeader() tmproto.Header { - var msg = proto.Clone(&c.header).(*tmproto.Header) + msg := proto.Clone(&c.header).(*tmproto.Header) return *msg } diff --git a/types/dec_coin_test.go b/types/dec_coin_test.go index 52f50d24fc22..170ec0e53519 100644 --- a/types/dec_coin_test.go +++ b/types/dec_coin_test.go @@ -399,7 +399,8 @@ func (s *decCoinTestSuite) TestParseDecCoins() { }, false, }, - {"0.0stake,0.004stake,5.04atom", // remove zero coins + { + "0.0stake,0.004stake,5.04atom", // remove zero coins sdk.DecCoins{ sdk.NewDecCoinFromDec("atom", sdk.NewDecWithPrec(5040000000000000000, sdk.Precision)), sdk.NewDecCoinFromDec("stake", sdk.NewDecWithPrec(4000000000000000, sdk.Precision)), @@ -644,7 +645,8 @@ func (s *decCoinTestSuite) TestDecCoins_GetDenomByIndex() { sdk.DecCoins{ sdk.DecCoin{testDenom1, sdk.NewDec(5)}, sdk.DecCoin{testDenom2, sdk.NewDec(57)}, - }, 1, testDenom2, false, + }, + 1, testDenom2, false, }, } @@ -710,7 +712,6 @@ func (s *decCoinTestSuite) TestDecCoin_IsLT() { expectedResult bool expectedPanic bool }{ - {"Same Denom - Less than other coin", sdk.DecCoin{testDenom1, sdk.NewDec(3)}, sdk.DecCoin{testDenom1, sdk.NewDec(19)}, true, false}, {"Same Denom - Greater than other coin", sdk.DecCoin{testDenom1, sdk.NewDec(343340)}, sdk.DecCoin{testDenom1, sdk.NewDec(14)}, false, false}, @@ -748,7 +749,6 @@ func (s *decCoinTestSuite) TestDecCoin_IsGTE() { expectedResult bool expectedPanic bool }{ - {"Same Denom - Less than other coin", sdk.DecCoin{testDenom1, sdk.NewDec(3)}, sdk.DecCoin{testDenom1, sdk.NewDec(19)}, false, false}, {"Same Denom - Greater than other coin", sdk.DecCoin{testDenom1, sdk.NewDec(343340)}, sdk.DecCoin{testDenom1, sdk.NewDec(14)}, true, false}, @@ -924,7 +924,6 @@ func (s *decCoinTestSuite) TestDecCoins_MulDecTruncate() { } func (s *decCoinTestSuite) TestDecCoins_QuoDec() { - testCases := []struct { name string coins sdk.DecCoins @@ -985,22 +984,33 @@ func (s *decCoinTestSuite) TestDecCoin_IsEqual() { expectedResult bool expectedPanic bool }{ - - {"Different Denom Same Amount", sdk.DecCoin{testDenom1, sdk.NewDec(20)}, + { + "Different Denom Same Amount", + sdk.DecCoin{testDenom1, sdk.NewDec(20)}, sdk.DecCoin{testDenom2, sdk.NewDec(20)}, - false, true}, + false, true, + }, - {"Different Denom Different Amount", sdk.DecCoin{testDenom1, sdk.NewDec(20)}, + { + "Different Denom Different Amount", + sdk.DecCoin{testDenom1, sdk.NewDec(20)}, sdk.DecCoin{testDenom2, sdk.NewDec(10)}, - false, true}, + false, true, + }, - {"Same Denom Different Amount", sdk.DecCoin{testDenom1, sdk.NewDec(20)}, + { + "Same Denom Different Amount", + sdk.DecCoin{testDenom1, sdk.NewDec(20)}, sdk.DecCoin{testDenom1, sdk.NewDec(10)}, - false, false}, + false, false, + }, - {"Same Denom Same Amount", sdk.DecCoin{testDenom1, sdk.NewDec(20)}, + { + "Same Denom Same Amount", sdk.DecCoin{testDenom1, sdk.NewDec(20)}, - true, false}, + sdk.DecCoin{testDenom1, sdk.NewDec(20)}, + true, false, + }, } for i, tc := range testCases { diff --git a/types/decimal_test.go b/types/decimal_test.go index 684888b49363..a6939c5f7a05 100644 --- a/types/decimal_test.go +++ b/types/decimal_test.go @@ -78,10 +78,14 @@ func (s *decimalTestSuite) TestNewDecFromStr() { {"0.8", false, sdk.NewDecWithPrec(8, 1)}, {"0.11111", false, sdk.NewDecWithPrec(11111, 5)}, {"314460551102969.3144278234343371835", true, sdk.NewDec(3141203149163817869)}, - {"314460551102969314427823434337.1835718092488231350", - true, sdk.NewDecFromBigIntWithPrec(largeBigInt, 4)}, - {"314460551102969314427823434337.1835", - false, sdk.NewDecFromBigIntWithPrec(largeBigInt, 4)}, + { + "314460551102969314427823434337.1835718092488231350", + true, sdk.NewDecFromBigIntWithPrec(largeBigInt, 4), + }, + { + "314460551102969314427823434337.1835", + false, sdk.NewDecFromBigIntWithPrec(largeBigInt, 4), + }, {".", true, sdk.Dec{}}, {".0", true, sdk.NewDec(0)}, {"1.", true, sdk.NewDec(1)}, @@ -189,7 +193,6 @@ func (s *decimalTestSuite) TestEqualities() { s.Require().Equal(tc.lt, tc.d1.LT(tc.d2), "LT result is incorrect, tc %d", tcIndex) s.Require().Equal(tc.eq, tc.d1.Equal(tc.d2), "equality result is incorrect, tc %d", tcIndex) } - } func (s *decimalTestSuite) TestDecsEqual() { @@ -233,19 +236,27 @@ func (s *decimalTestSuite) TestArithmetic() { {sdk.NewDec(1), sdk.NewDec(-1), sdk.NewDec(-1), sdk.NewDec(-1), sdk.NewDec(-1), sdk.NewDec(-1), sdk.NewDec(-1), sdk.NewDec(0), sdk.NewDec(2)}, {sdk.NewDec(-1), sdk.NewDec(1), sdk.NewDec(-1), sdk.NewDec(-1), sdk.NewDec(-1), sdk.NewDec(-1), sdk.NewDec(-1), sdk.NewDec(0), sdk.NewDec(-2)}, - {sdk.NewDec(3), sdk.NewDec(7), sdk.NewDec(21), sdk.NewDec(21), + { + sdk.NewDec(3), sdk.NewDec(7), sdk.NewDec(21), sdk.NewDec(21), sdk.NewDecWithPrec(428571428571428571, 18), sdk.NewDecWithPrec(428571428571428572, 18), sdk.NewDecWithPrec(428571428571428571, 18), - sdk.NewDec(10), sdk.NewDec(-4)}, - {sdk.NewDec(2), sdk.NewDec(4), sdk.NewDec(8), sdk.NewDec(8), sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), - sdk.NewDec(6), sdk.NewDec(-2)}, + sdk.NewDec(10), sdk.NewDec(-4), + }, + { + sdk.NewDec(2), sdk.NewDec(4), sdk.NewDec(8), sdk.NewDec(8), sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(5, 1), + sdk.NewDec(6), sdk.NewDec(-2), + }, {sdk.NewDec(100), sdk.NewDec(100), sdk.NewDec(10000), sdk.NewDec(10000), sdk.NewDec(1), sdk.NewDec(1), sdk.NewDec(1), sdk.NewDec(200), sdk.NewDec(0)}, - {sdk.NewDecWithPrec(15, 1), sdk.NewDecWithPrec(15, 1), sdk.NewDecWithPrec(225, 2), sdk.NewDecWithPrec(225, 2), - sdk.NewDec(1), sdk.NewDec(1), sdk.NewDec(1), sdk.NewDec(3), sdk.NewDec(0)}, - {sdk.NewDecWithPrec(3333, 4), sdk.NewDecWithPrec(333, 4), sdk.NewDecWithPrec(1109889, 8), sdk.NewDecWithPrec(1109889, 8), + { + sdk.NewDecWithPrec(15, 1), sdk.NewDecWithPrec(15, 1), sdk.NewDecWithPrec(225, 2), sdk.NewDecWithPrec(225, 2), + sdk.NewDec(1), sdk.NewDec(1), sdk.NewDec(1), sdk.NewDec(3), sdk.NewDec(0), + }, + { + sdk.NewDecWithPrec(3333, 4), sdk.NewDecWithPrec(333, 4), sdk.NewDecWithPrec(1109889, 8), sdk.NewDecWithPrec(1109889, 8), sdk.MustNewDecFromStr("10.009009009009009009"), sdk.MustNewDecFromStr("10.009009009009009010"), sdk.MustNewDecFromStr("10.009009009009009009"), - sdk.NewDecWithPrec(3666, 4), sdk.NewDecWithPrec(3, 1)}, + sdk.NewDecWithPrec(3666, 4), sdk.NewDecWithPrec(3, 1), + }, } for tcIndex, tc := range tests { diff --git a/types/module/module.go b/types/module/module.go index 60c524a39f09..81bd7b246913 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -226,7 +226,6 @@ type Manager struct { // NewManager creates a new Manager object func NewManager(modules ...AppModule) *Manager { - moduleMap := make(map[string]AppModule) modulesStr := make([]string, 0, len(modules)) for _, module := range modules { @@ -422,7 +421,7 @@ func (m Manager) RunMigrations(ctx sdk.Context, cfg Configurator, fromVM Version if !ok { return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "expected %T, got %T", configurator{}, cfg) } - var modules = m.OrderMigrations + modules := m.OrderMigrations if modules == nil { modules = DefaultMigrationsOrder(m.ModuleNames()) } diff --git a/types/module/module_test.go b/types/module/module_test.go index 4bbae7f4bc26..37bbf088cc70 100644 --- a/types/module/module_test.go +++ b/types/module/module_test.go @@ -209,7 +209,8 @@ func TestManager_InitGenesis(t *testing.T) { // test panic genesisData = map[string]json.RawMessage{ "module1": json.RawMessage(`{"key": "value"}`), - "module2": json.RawMessage(`{"key": "value"}`)} + "module2": json.RawMessage(`{"key": "value"}`), + } mockAppModule1.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(cdc), gomock.Eq(genesisData["module1"])).Times(1).Return([]abci.ValidatorUpdate{{}}) mockAppModule2.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(cdc), gomock.Eq(genesisData["module2"])).Times(1).Return([]abci.ValidatorUpdate{{}}) require.Panics(t, func() { mm.InitGenesis(ctx, cdc, genesisData) }) @@ -235,7 +236,8 @@ func TestManager_ExportGenesis(t *testing.T) { want := map[string]json.RawMessage{ "module1": json.RawMessage(`{"key1": "value1"}`), - "module2": json.RawMessage(`{"key2": "value2"}`)} + "module2": json.RawMessage(`{"key2": "value2"}`), + } require.Equal(t, want, mm.ExportGenesis(ctx, cdc)) } diff --git a/types/module/simulation.go b/types/module/simulation.go index 21e6d99d7fbc..591e11e0846a 100644 --- a/types/module/simulation.go +++ b/types/module/simulation.go @@ -2,7 +2,6 @@ package module import ( "encoding/json" - "math/rand" "time" diff --git a/types/query/filtered_pagination.go b/types/query/filtered_pagination.go index 47dd31aaba71..0f755c55e788 100644 --- a/types/query/filtered_pagination.go +++ b/types/query/filtered_pagination.go @@ -19,7 +19,6 @@ func FilteredPaginate( pageRequest *PageRequest, onResult func(key []byte, value []byte, accumulate bool) (bool, error), ) (*PageResponse, error) { - // if the PageRequest is nil, use default PageRequest if pageRequest == nil { pageRequest = &PageRequest{} diff --git a/types/query/filtered_pagination_test.go b/types/query/filtered_pagination_test.go index 694d0c3cbbcd..08ba8513a9d1 100644 --- a/types/query/filtered_pagination_test.go +++ b/types/query/filtered_pagination_test.go @@ -168,7 +168,6 @@ func (s *paginationTestSuite) TestReverseFilteredPaginations() { s.T().Log("verify Reverse pagination returns valid result") s.Require().Equal(balances[235:241].String(), balns.Sort().String()) - } func ExampleFilteredPaginate(t *testing.T) { @@ -218,7 +217,6 @@ func ExampleFilteredPaginate(t *testing.T) { return false, nil }) - if err != nil { // should return no error fmt.Println(err) } diff --git a/types/query/pagination.go b/types/query/pagination.go index e5cd71b71c83..a01587387d12 100644 --- a/types/query/pagination.go +++ b/types/query/pagination.go @@ -54,7 +54,6 @@ func Paginate( pageRequest *PageRequest, onResult func(key []byte, value []byte) error, ) (*PageResponse, error) { - // if the PageRequest is nil, use default PageRequest if pageRequest == nil { pageRequest = &PageRequest{} diff --git a/types/simulation/rand_util.go b/types/simulation/rand_util.go index f136da396990..ce64bd7e8645 100644 --- a/types/simulation/rand_util.go +++ b/types/simulation/rand_util.go @@ -53,7 +53,7 @@ func RandPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) { // RandomAmount generates a random amount // Note: The range of RandomAmount includes max, and is, in fact, biased to return max as well as 0. func RandomAmount(r *rand.Rand, max sdk.Int) sdk.Int { - var randInt = big.NewInt(0) + randInt := big.NewInt(0) switch r.Intn(10) { case 0: @@ -70,7 +70,7 @@ func RandomAmount(r *rand.Rand, max sdk.Int) sdk.Int { // RandomDecAmount generates a random decimal amount // Note: The range of RandomDecAmount includes max, and is, in fact, biased to return max as well as 0. func RandomDecAmount(r *rand.Rand, max sdk.Dec) sdk.Dec { - var randInt = big.NewInt(0) + randInt := big.NewInt(0) switch r.Intn(10) { case 0: diff --git a/types/simulation/types.go b/types/simulation/types.go index 7efb64ba3149..199f47fa38e2 100644 --- a/types/simulation/types.go +++ b/types/simulation/types.go @@ -84,7 +84,6 @@ func NewOperationMsg(msg sdk.Msg, ok bool, comment string, cdc *codec.ProtoCodec bz := cdc.MustMarshalJSON(msg) return NewOperationMsgBasic(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), comment, ok, bz) - } // NoOpMsg - create a no-operation message diff --git a/types/store_internal_test.go b/types/store_internal_test.go index e55ae175dbdc..2ec4c6944cf0 100644 --- a/types/store_internal_test.go +++ b/types/store_internal_test.go @@ -16,7 +16,7 @@ func TestStoreIntSuite(t *testing.T) { } func (s *storeIntSuite) TestAssertNoPrefix() { - var testCases = []struct { + testCases := []struct { keys []string expectPanic bool }{ diff --git a/types/store_test.go b/types/store_test.go index 7d4dfecb644b..0588e40b6e4d 100644 --- a/types/store_test.go +++ b/types/store_test.go @@ -25,7 +25,7 @@ func (s *storeTestSuite) SetupSuite() { } func (s *storeTestSuite) TestPrefixEndBytes() { - var testCases = []struct { + testCases := []struct { prefix []byte expected []byte }{ @@ -48,7 +48,7 @@ func (s *storeTestSuite) TestCommitID() { var empty types.CommitID s.Require().True(empty.IsZero()) - var nonempty = types.CommitID{ + nonempty := types.CommitID{ Version: 1, Hash: []byte("testhash"), } diff --git a/types/tx/signing/signature.go b/types/tx/signing/signature.go index 1323543f023a..c5faf4b8d1d4 100644 --- a/types/tx/signing/signature.go +++ b/types/tx/signing/signature.go @@ -92,7 +92,6 @@ var _, _ codectypes.UnpackInterfacesMessage = &SignatureDescriptors{}, &Signatur func (sds *SignatureDescriptors) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { for _, sig := range sds.Signatures { err := sig.UnpackInterfaces(unpacker) - if err != nil { return err } diff --git a/types/tx/types.go b/types/tx/types.go index cbdb50a43ca4..a4816b1283a6 100644 --- a/types/tx/types.go +++ b/types/tx/types.go @@ -128,9 +128,11 @@ func (t *Tx) GetSigners() []sdk.AccAddress { func (t *Tx) GetGas() uint64 { return t.AuthInfo.Fee.GasLimit } + func (t *Tx) GetFee() sdk.Coins { return t.AuthInfo.Fee.Amount } + func (t *Tx) FeePayer() sdk.AccAddress { feePayer := t.AuthInfo.Fee.Payer if feePayer != "" { diff --git a/types/utils_test.go b/types/utils_test.go index 06576d407749..7a196acafe2c 100644 --- a/types/utils_test.go +++ b/types/utils_test.go @@ -30,20 +30,28 @@ func (s *utilsTestSuite) TestSortJSON() { wantErr bool }{ // simple case - {unsortedJSON: `{"cosmos":"foo", "atom":"bar", "tendermint":"foobar"}`, - want: `{"atom":"bar","cosmos":"foo","tendermint":"foobar"}`, wantErr: false}, + { + unsortedJSON: `{"cosmos":"foo", "atom":"bar", "tendermint":"foobar"}`, + want: `{"atom":"bar","cosmos":"foo","tendermint":"foobar"}`, wantErr: false, + }, // failing case (invalid JSON): - {unsortedJSON: `"cosmos":"foo",,,, "atom":"bar", "tendermint":"foobar"}`, - want: "", - wantErr: true}, + { + unsortedJSON: `"cosmos":"foo",,,, "atom":"bar", "tendermint":"foobar"}`, + want: "", + wantErr: true, + }, // genesis.json - {unsortedJSON: `{"consensus_params":{"block_size_params":{"max_bytes":22020096,"max_txs":100000,"max_gas":-1},"tx_size_params":{"max_bytes":10240,"max_gas":-1},"block_gossip_params":{"block_part_size_bytes":65536},"evidence_params":{"max_age":100000}},"validators":[{"pub_key":{"type":"AC26791624DE60","value":"c7UMMAbjFuc5GhGPy0E5q5tefy12p9Tq0imXqdrKXwo="},"power":100,"name":""}],"app_hash":"","genesis_time":"2018-05-11T15:52:25.424795506Z","chain_id":"test-chain-Q6VeoW","app_state":{"accounts":[{"address":"718C9C23F98C9642569742ADDD9F9AB9743FBD5D","coins":[{"denom":"Token","amount":1000},{"denom":"stake","amount":50}]}],"stake":{"pool":{"total_supply":50,"bonded_shares":"0","unbonded_shares":"0","bonded_pool":0,"unbonded_pool":0,"inflation_last_time":0,"inflation":"7/100"},"params":{"inflation_rate_change":"13/100","inflation_max":"1/5","inflation_min":"7/100","goal_bonded":"67/100","max_validators":100,"bond_denom":"stake"},"candidates":null,"bonds":null}}}`, - want: `{"app_hash":"","app_state":{"accounts":[{"address":"718C9C23F98C9642569742ADDD9F9AB9743FBD5D","coins":[{"amount":1000,"denom":"Token"},{"amount":50,"denom":"stake"}]}],"stake":{"bonds":null,"candidates":null,"params":{"bond_denom":"stake","goal_bonded":"67/100","inflation_max":"1/5","inflation_min":"7/100","inflation_rate_change":"13/100","max_validators":100},"pool":{"bonded_pool":0,"bonded_shares":"0","inflation":"7/100","inflation_last_time":0,"total_supply":50,"unbonded_pool":0,"unbonded_shares":"0"}}},"chain_id":"test-chain-Q6VeoW","consensus_params":{"block_gossip_params":{"block_part_size_bytes":65536},"block_size_params":{"max_bytes":22020096,"max_gas":-1,"max_txs":100000},"evidence_params":{"max_age":100000},"tx_size_params":{"max_bytes":10240,"max_gas":-1}},"genesis_time":"2018-05-11T15:52:25.424795506Z","validators":[{"name":"","power":100,"pub_key":{"type":"AC26791624DE60","value":"c7UMMAbjFuc5GhGPy0E5q5tefy12p9Tq0imXqdrKXwo="}}]}`, - wantErr: false}, + { + unsortedJSON: `{"consensus_params":{"block_size_params":{"max_bytes":22020096,"max_txs":100000,"max_gas":-1},"tx_size_params":{"max_bytes":10240,"max_gas":-1},"block_gossip_params":{"block_part_size_bytes":65536},"evidence_params":{"max_age":100000}},"validators":[{"pub_key":{"type":"AC26791624DE60","value":"c7UMMAbjFuc5GhGPy0E5q5tefy12p9Tq0imXqdrKXwo="},"power":100,"name":""}],"app_hash":"","genesis_time":"2018-05-11T15:52:25.424795506Z","chain_id":"test-chain-Q6VeoW","app_state":{"accounts":[{"address":"718C9C23F98C9642569742ADDD9F9AB9743FBD5D","coins":[{"denom":"Token","amount":1000},{"denom":"stake","amount":50}]}],"stake":{"pool":{"total_supply":50,"bonded_shares":"0","unbonded_shares":"0","bonded_pool":0,"unbonded_pool":0,"inflation_last_time":0,"inflation":"7/100"},"params":{"inflation_rate_change":"13/100","inflation_max":"1/5","inflation_min":"7/100","goal_bonded":"67/100","max_validators":100,"bond_denom":"stake"},"candidates":null,"bonds":null}}}`, + want: `{"app_hash":"","app_state":{"accounts":[{"address":"718C9C23F98C9642569742ADDD9F9AB9743FBD5D","coins":[{"amount":1000,"denom":"Token"},{"amount":50,"denom":"stake"}]}],"stake":{"bonds":null,"candidates":null,"params":{"bond_denom":"stake","goal_bonded":"67/100","inflation_max":"1/5","inflation_min":"7/100","inflation_rate_change":"13/100","max_validators":100},"pool":{"bonded_pool":0,"bonded_shares":"0","inflation":"7/100","inflation_last_time":0,"total_supply":50,"unbonded_pool":0,"unbonded_shares":"0"}}},"chain_id":"test-chain-Q6VeoW","consensus_params":{"block_gossip_params":{"block_part_size_bytes":65536},"block_size_params":{"max_bytes":22020096,"max_gas":-1,"max_txs":100000},"evidence_params":{"max_age":100000},"tx_size_params":{"max_bytes":10240,"max_gas":-1}},"genesis_time":"2018-05-11T15:52:25.424795506Z","validators":[{"name":"","power":100,"pub_key":{"type":"AC26791624DE60","value":"c7UMMAbjFuc5GhGPy0E5q5tefy12p9Tq0imXqdrKXwo="}}]}`, + wantErr: false, + }, // from the TXSpec: - {unsortedJSON: `{"chain_id":"test-chain-1","sequence":1,"fee_bytes":{"amount":[{"amount":5,"denom":"photon"}],"gas":10000},"msg_bytes":{"inputs":[{"address":"696E707574","coins":[{"amount":10,"denom":"atom"}]}],"outputs":[{"address":"6F7574707574","coins":[{"amount":10,"denom":"atom"}]}]},"alt_bytes":null}`, - want: `{"alt_bytes":null,"chain_id":"test-chain-1","fee_bytes":{"amount":[{"amount":5,"denom":"photon"}],"gas":10000},"msg_bytes":{"inputs":[{"address":"696E707574","coins":[{"amount":10,"denom":"atom"}]}],"outputs":[{"address":"6F7574707574","coins":[{"amount":10,"denom":"atom"}]}]},"sequence":1}`, - wantErr: false}, + { + unsortedJSON: `{"chain_id":"test-chain-1","sequence":1,"fee_bytes":{"amount":[{"amount":5,"denom":"photon"}],"gas":10000},"msg_bytes":{"inputs":[{"address":"696E707574","coins":[{"amount":10,"denom":"atom"}]}],"outputs":[{"address":"6F7574707574","coins":[{"amount":10,"denom":"atom"}]}]},"alt_bytes":null}`, + want: `{"alt_bytes":null,"chain_id":"test-chain-1","fee_bytes":{"amount":[{"amount":5,"denom":"photon"}],"gas":10000},"msg_bytes":{"inputs":[{"address":"696E707574","coins":[{"amount":10,"denom":"atom"}]}],"outputs":[{"address":"6F7574707574","coins":[{"amount":10,"denom":"atom"}]}]},"sequence":1}`, + wantErr: false, + }, } for tcIndex, tc := range cases { diff --git a/x/auth/client/cli/tx_multisign.go b/x/auth/client/cli/tx_multisign.go index 722f76a6f58a..48c819cb8eab 100644 --- a/x/auth/client/cli/tx_multisign.go +++ b/x/auth/client/cli/tx_multisign.go @@ -192,7 +192,7 @@ func makeMultiSignCmd() func(cmd *cobra.Command, args []string) (err error) { return } - fp, err := os.OpenFile(outputDoc, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) + fp, err := os.OpenFile(outputDoc, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644) if err != nil { return err } @@ -259,7 +259,7 @@ func makeBatchMultisignCmd() func(cmd *cobra.Command, args []string) error { txFactory = txFactory.WithSignMode(signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON) } - var infile = os.Stdin + infile := os.Stdin if args[0] != "-" { infile, err = os.Open(args[0]) defer func() { diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index 2831fea729d7..39626e5ed1ac 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -153,7 +153,7 @@ func setOutputFile(cmd *cobra.Command) (func(), error) { return func() {}, nil } - fp, err := os.OpenFile(outputDoc, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) + fp, err := os.OpenFile(outputDoc, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644) if err != nil { return func() {}, err } @@ -302,7 +302,7 @@ func makeSignCmd() func(cmd *cobra.Command, args []string) error { return nil } - fp, err := os.OpenFile(outputDoc, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) + fp, err := os.OpenFile(outputDoc, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o644) if err != nil { return err } diff --git a/x/auth/client/testutil/cli_test.go b/x/auth/client/testutil/cli_test.go index 0a7a5cc25871..f23e88847c30 100644 --- a/x/auth/client/testutil/cli_test.go +++ b/x/auth/client/testutil/cli_test.go @@ -1,3 +1,4 @@ +//go:build norace // +build norace package testutil diff --git a/x/auth/client/testutil/suite.go b/x/auth/client/testutil/suite.go index 40aa258dd5e6..cf9aeb465515 100644 --- a/x/auth/client/testutil/suite.go +++ b/x/auth/client/testutil/suite.go @@ -231,7 +231,7 @@ func (s *IntegrationTestSuite) TestCLISignGenOnly() { func (s *IntegrationTestSuite) TestCLISignBatch() { val := s.network.Validators[0] - var sendTokens = sdk.NewCoins( + sendTokens := sdk.NewCoins( sdk.NewCoin(fmt.Sprintf("%stoken", val.Moniker), sdk.NewInt(10)), sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), ) @@ -284,7 +284,7 @@ func (s *IntegrationTestSuite) TestCLISignAminoJSON() { require := s.Require() val1 := s.network.Validators[0] txCfg := val1.ClientCtx.TxConfig - var sendTokens = sdk.NewCoins( + sendTokens := sdk.NewCoins( sdk.NewCoin(fmt.Sprintf("%stoken", val1.Moniker), sdk.NewInt(10)), sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)), ) @@ -1813,7 +1813,8 @@ func (s *IntegrationTestSuite) TestAuxToFee() { } func (s *IntegrationTestSuite) createBankMsg(val *network.Validator, toAddr sdk.AccAddress, amount sdk.Coins, extraFlags ...string) (testutil.BufferWriter, error) { - flags := []string{fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), + flags := []string{ + fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), diff --git a/x/auth/client/tx.go b/x/auth/client/tx.go index a57f28d3d956..38203299de87 100644 --- a/x/auth/client/tx.go +++ b/x/auth/client/tx.go @@ -68,7 +68,8 @@ func SignTx(txFactory tx.Factory, clientCtx client.Context, name string, txBuild // This function should only be used when signing with a multisig. For // normal keys, please use SignTx directly. func SignTxWithSignerAddress(txFactory tx.Factory, clientCtx client.Context, addr sdk.AccAddress, - name string, txBuilder client.TxBuilder, offline, overwrite bool) (err error) { + name string, txBuilder client.TxBuilder, offline, overwrite bool, +) (err error) { // Multisigs only support LEGACY_AMINO_JSON signing. if txFactory.SignMode() == signing.SignMode_SIGN_MODE_UNSPECIFIED { txFactory = txFactory.WithSignMode(signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON) @@ -145,7 +146,6 @@ func (bs *BatchScanner) Scan() bool { func populateAccountFromState( txBldr tx.Factory, clientCtx client.Context, addr sdk.AccAddress, ) (tx.Factory, error) { - num, seq, err := clientCtx.AccountRetriever.GetAccountNumberSequence(clientCtx, addr) if err != nil { return txBldr, err diff --git a/x/auth/client/tx_test.go b/x/auth/client/tx_test.go index fc52206d6e07..4934e0febc91 100644 --- a/x/auth/client/tx_test.go +++ b/x/auth/client/tx_test.go @@ -149,7 +149,7 @@ func compareEncoders(t *testing.T, expected sdk.TxEncoder, actual sdk.TxEncoder) } func makeCodec() *codec.LegacyAmino { - var cdc = codec.NewLegacyAmino() + cdc := codec.NewLegacyAmino() sdk.RegisterLegacyAminoCodec(cdc) cryptocodec.RegisterCrypto(cdc) authtypes.RegisterLegacyAminoCodec(cdc) diff --git a/x/auth/keeper/grpc_query.go b/x/auth/keeper/grpc_query.go index 83fbb07c6be8..8bd3a40e0aec 100644 --- a/x/auth/keeper/grpc_query.go +++ b/x/auth/keeper/grpc_query.go @@ -39,7 +39,6 @@ func (ak AccountKeeper) Accounts(c context.Context, req *types.QueryAccountsRequ accounts = append(accounts, any) return nil }) - if err != nil { return nil, status.Errorf(codes.Internal, "paginate: %v", err) } @@ -59,7 +58,6 @@ func (ak AccountKeeper) Account(c context.Context, req *types.QueryAccountReques ctx := sdk.UnwrapSDKContext(c) addr, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { return nil, err } diff --git a/x/auth/keeper/grpc_query_test.go b/x/auth/keeper/grpc_query_test.go index ba0f4b273a41..307fda03356f 100644 --- a/x/auth/keeper/grpc_query_test.go +++ b/x/auth/keeper/grpc_query_test.go @@ -16,9 +16,7 @@ const addrStr = "cosmos13c3d4wq2t22dl0dstraf8jc3f902e3fsy9n3wv" var addrBytes = []byte{0x8e, 0x22, 0xda, 0xb8, 0xa, 0x5a, 0x94, 0xdf, 0xbd, 0xb0, 0x58, 0xfa, 0x93, 0xcb, 0x11, 0x49, 0x5e, 0xac, 0xc5, 0x30} func (suite *KeeperTestSuite) TestGRPCQueryAccounts() { - var ( - req *types.QueryAccountsRequest - ) + var req *types.QueryAccountsRequest _, _, first := testdata.KeyTestPubAddr() _, _, second := testdata.KeyTestPubAddr() @@ -74,9 +72,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryAccounts() { } func (suite *KeeperTestSuite) TestGRPCQueryAccount() { - var ( - req *types.QueryAccountRequest - ) + var req *types.QueryAccountRequest _, _, addr := testdata.KeyTestPubAddr() testCases := []struct { @@ -200,9 +196,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryParameters() { } func (suite *KeeperTestSuite) TestGRPCQueryModuleAccounts() { - var ( - req *types.QueryModuleAccountsRequest - ) + var req *types.QueryModuleAccountsRequest testCases := []struct { msg string @@ -217,7 +211,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryModuleAccounts() { }, true, func(res *types.QueryModuleAccountsResponse) { - var mintModuleExists = false + mintModuleExists := false for _, acc := range res.Accounts { var account types.AccountI err := suite.app.InterfaceRegistry().UnpackAny(acc, &account) @@ -240,7 +234,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryModuleAccounts() { }, true, func(res *types.QueryModuleAccountsResponse) { - var mintModuleExists = false + mintModuleExists := false for _, acc := range res.Accounts { var account types.AccountI err := suite.app.InterfaceRegistry().UnpackAny(acc, &account) @@ -337,7 +331,6 @@ func (suite *KeeperTestSuite) TestAddressBytesToString() { suite.Require().Error(err) suite.Require().Nil(res) } - }) } } @@ -384,7 +377,6 @@ func (suite *KeeperTestSuite) TestAddressStringToBytes() { suite.Require().Error(err) suite.Require().Nil(res) } - }) } } diff --git a/x/auth/keeper/keeper.go b/x/auth/keeper/keeper.go index cccc4ffb2575..207f65b0f838 100644 --- a/x/auth/keeper/keeper.go +++ b/x/auth/keeper/keeper.go @@ -74,7 +74,6 @@ func NewAccountKeeper( cdc codec.BinaryCodec, key storetypes.StoreKey, paramstore paramtypes.Subspace, proto func() types.AccountI, maccPerms map[string][]string, bech32Prefix string, ) AccountKeeper { - // set KeyTable if it has not already been set if !paramstore.HasKeyTable() { paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) diff --git a/x/auth/middleware/basic_test.go b/x/auth/middleware/basic_test.go index 7bc583ed8d75..5c28ecae8ffa 100644 --- a/x/auth/middleware/basic_test.go +++ b/x/auth/middleware/basic_test.go @@ -246,7 +246,6 @@ func (s *MWTestSuite) TestTxHeightTimeoutMiddleware() { // SimulateTx _, err = txHandler.SimulateTx(sdk.WrapSDKContext(ctx), tx.Request{Tx: testTx}) s.Require().Equal(tc.expectErr, err != nil, err) - }) } } diff --git a/x/auth/middleware/block_gas.go b/x/auth/middleware/block_gas.go index bfd67f92ecbe..00632f6139b3 100644 --- a/x/auth/middleware/block_gas.go +++ b/x/auth/middleware/block_gas.go @@ -41,7 +41,6 @@ func (cbgh consumeBlockGasHandler) DeliverTx(ctx context.Context, req tx.Request sdkCtx.BlockGasMeter().ConsumeGas( sdkCtx.GasMeter().GasConsumedToLimit(), "block gas meter", ) - }() return cbgh.next.DeliverTx(ctx, req) diff --git a/x/auth/middleware/branch_store_test.go b/x/auth/middleware/branch_store_test.go index 80e116fb2a82..12181052539c 100644 --- a/x/auth/middleware/branch_store_test.go +++ b/x/auth/middleware/branch_store_test.go @@ -52,7 +52,7 @@ func (s *MWTestSuite) TestBranchStore() { // testMsgTxHandler is a test txHandler that handles one single TestMsg, // consumes the given `tc.gasToConsume`, and sets the bank store "ok" key to "ok". - var testMsgTxHandler = customTxHandler{func(ctx context.Context, req tx.Request) (tx.Response, error) { + testMsgTxHandler := customTxHandler{func(ctx context.Context, req tx.Request) (tx.Response, error) { msg, ok := req.Tx.GetMsgs()[0].(*testdata.TestMsg) if !ok { return tx.Response{}, fmt.Errorf("Wrong Msg type, expected %T, got %T", (*testdata.TestMsg)(nil), msg) diff --git a/x/auth/middleware/feegrant_test.go b/x/auth/middleware/feegrant_test.go index 547f57a589d1..e3ca6e62fbda 100644 --- a/x/auth/middleware/feegrant_test.go +++ b/x/auth/middleware/feegrant_test.go @@ -174,7 +174,8 @@ func SigGasNoConsumer(meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, para } func genTxWithFeeGranter(gen client.TxConfig, msgs []sdk.Msg, feeAmt sdk.Coins, gas uint64, chainID string, accNums, - accSeqs []uint64, feeGranter sdk.AccAddress, priv ...cryptotypes.PrivKey) (sdk.Tx, error) { + accSeqs []uint64, feeGranter sdk.AccAddress, priv ...cryptotypes.PrivKey, +) (sdk.Tx, error) { sigs := make([]signing.SignatureV2, len(priv)) // create a random length memo diff --git a/x/auth/middleware/gas_test.go b/x/auth/middleware/gas_test.go index 480077762149..be7e7e9ebb97 100644 --- a/x/auth/middleware/gas_test.go +++ b/x/auth/middleware/gas_test.go @@ -102,10 +102,12 @@ var _ tx.Handler = customTxHandler{} func (h customTxHandler) DeliverTx(ctx context.Context, req tx.Request) (tx.Response, error) { return h.fn(ctx, req) } + func (h customTxHandler) CheckTx(ctx context.Context, req tx.Request, _ tx.RequestCheckTx) (tx.Response, tx.ResponseCheckTx, error) { res, err := h.fn(ctx, req) return res, tx.ResponseCheckTx{}, err } + func (h customTxHandler) SimulateTx(ctx context.Context, req tx.Request) (tx.Response, error) { return h.fn(ctx, req) } diff --git a/x/auth/middleware/middleware_test.go b/x/auth/middleware/middleware_test.go index d923b84b2c3d..764966a87431 100644 --- a/x/auth/middleware/middleware_test.go +++ b/x/auth/middleware/middleware_test.go @@ -949,7 +949,8 @@ func TestCountSubkeys(t *testing.T) { multiLevelSubKey1 := kmultisig.NewLegacyAminoPubKey(4, genPubKeys(5)) multiLevelSubKey2 := kmultisig.NewLegacyAminoPubKey(4, genPubKeys(5)) multiLevelMultiKey := kmultisig.NewLegacyAminoPubKey(2, []cryptotypes.PubKey{ - multiLevelSubKey1, multiLevelSubKey2, secp256k1.GenPrivKey().PubKey()}) + multiLevelSubKey1, multiLevelSubKey2, secp256k1.GenPrivKey().PubKey(), + }) type args struct { pub cryptotypes.PubKey } diff --git a/x/auth/middleware/sigverify.go b/x/auth/middleware/sigverify.go index 0e13b4142a29..33b057427546 100644 --- a/x/auth/middleware/sigverify.go +++ b/x/auth/middleware/sigverify.go @@ -263,7 +263,6 @@ func ConsumeMultisignatureVerificationGas( meter sdk.GasMeter, sig *signing.MultiSignatureData, pubkey multisig.PubKey, params types.Params, accSeq uint64, ) error { - size := sig.BitArray.Count() sigIndex := 0 diff --git a/x/auth/middleware/tips_test.go b/x/auth/middleware/tips_test.go index 7fb50f7e0f0f..28acbee205b4 100644 --- a/x/auth/middleware/tips_test.go +++ b/x/auth/middleware/tips_test.go @@ -18,8 +18,10 @@ import ( minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" ) -var initialRegens = sdk.NewCoins(sdk.NewCoin("regen", sdk.NewInt(1000))) -var initialAtoms = sdk.NewCoins(sdk.NewCoin("atom", sdk.NewInt(1000))) +var ( + initialRegens = sdk.NewCoins(sdk.NewCoin("regen", sdk.NewInt(1000))) + initialAtoms = sdk.NewCoins(sdk.NewCoin("atom", sdk.NewInt(1000))) +) // setupAcctsForTips sets up 2 accounts: // - tipper has 1000 regens @@ -182,7 +184,8 @@ func (s *MWTestSuite) mkFeePayerTxBuilder( Data: &signing.SingleSignatureData{ SignMode: signMode, Signature: nil, - }} + }, + } sigsV2 := append([]signing.SignatureV2{tipperSigsV2}, feePayerSigV2) txBuilder.SetSignatures(sigsV2...) diff --git a/x/auth/migrations/legacytx/stdtx_builder.go b/x/auth/migrations/legacytx/stdtx_builder.go index 0c0454034947..35d26ce02e1f 100644 --- a/x/auth/migrations/legacytx/stdtx_builder.go +++ b/x/auth/migrations/legacytx/stdtx_builder.go @@ -190,7 +190,7 @@ func mkDecoder(unmarshaler Unmarshaler) sdk.TxDecoder { if len(txBytes) == 0 { return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "tx bytes are empty") } - var tx = StdTx{} + tx := StdTx{} // StdTx.Msg is an interface. The concrete types // are registered by MakeTxCodec err := unmarshaler(txBytes, &tx) diff --git a/x/auth/migrations/legacytx/stdtx_test.go b/x/auth/migrations/legacytx/stdtx_test.go index c883a2faa2ea..2e69427c5af2 100644 --- a/x/auth/migrations/legacytx/stdtx_test.go +++ b/x/auth/migrations/legacytx/stdtx_test.go @@ -26,7 +26,7 @@ var ( ) func init() { - var amino = codec.NewLegacyAmino() + amino := codec.NewLegacyAmino() RegisterLegacyAminoCodec(amino) } diff --git a/x/auth/migrations/v043/store.go b/x/auth/migrations/v043/store.go index f95f1b3a1bb7..a097d0ef0400 100644 --- a/x/auth/migrations/v043/store.go +++ b/x/auth/migrations/v043/store.go @@ -48,7 +48,6 @@ const ( // PLEASE DO NOT REPLICATE THIS PATTERN IN YOUR OWN APP. func migrateVestingAccounts(ctx sdk.Context, account types.AccountI, queryServer grpc.Server) (types.AccountI, error) { bondDenom, err := getBondDenom(ctx, queryServer) - if err != nil { return nil, err } @@ -64,7 +63,6 @@ func migrateVestingAccounts(ctx sdk.Context, account types.AccountI, queryServer addr, queryServer, ) - if err != nil { return nil, err } @@ -74,7 +72,6 @@ func migrateVestingAccounts(ctx sdk.Context, account types.AccountI, queryServer addr, queryServer, ) - if err != nil { return nil, err } @@ -85,7 +82,6 @@ func migrateVestingAccounts(ctx sdk.Context, account types.AccountI, queryServer bondDenom, queryServer, ) - if err != nil { return nil, err } diff --git a/x/auth/migrations/v043/store_test.go b/x/auth/migrations/v043/store_test.go index cae87b96885c..df7902c191bd 100644 --- a/x/auth/migrations/v043/store_test.go +++ b/x/auth/migrations/v043/store_test.go @@ -32,7 +32,6 @@ func TestMigrateVestingAccounts(t *testing.T) { { "delayed vesting has vested, multiple delegations less than the total account balance", func(app *simapp.SimApp, ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) vestedCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), sdk.NewInt(200))) delayedAccount := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().Unix()) @@ -57,7 +56,6 @@ func TestMigrateVestingAccounts(t *testing.T) { { "delayed vesting has vested, single delegations which exceed the vested amount", func(app *simapp.SimApp, ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) vestedCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), sdk.NewInt(200))) delayedAccount := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().Unix()) @@ -78,7 +76,6 @@ func TestMigrateVestingAccounts(t *testing.T) { { "delayed vesting has vested, multiple delegations which exceed the vested amount", func(app *simapp.SimApp, ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) vestedCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), sdk.NewInt(200))) delayedAccount := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().Unix()) @@ -103,7 +100,6 @@ func TestMigrateVestingAccounts(t *testing.T) { { "delayed vesting has not vested, single delegations which exceed the vested amount", func(app *simapp.SimApp, ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) vestedCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), sdk.NewInt(200))) delayedAccount := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(1, 0, 0).Unix()) @@ -122,7 +118,6 @@ func TestMigrateVestingAccounts(t *testing.T) { { "delayed vesting has not vested, multiple delegations which exceed the vested amount", func(app *simapp.SimApp, ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) vestedCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), sdk.NewInt(200))) delayedAccount := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().AddDate(1, 0, 0).Unix()) @@ -185,7 +180,6 @@ func TestMigrateVestingAccounts(t *testing.T) { { "delayed vesting has vested, single delegation greater than the total account balance", func(app *simapp.SimApp, ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) vestedCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), sdk.NewInt(300))) delayedAccount := types.NewDelayedVestingAccount(baseAccount, vestedCoins, ctx.BlockTime().Unix()) @@ -206,7 +200,6 @@ func TestMigrateVestingAccounts(t *testing.T) { { "continuous vesting, start time after blocktime", func(app *simapp.SimApp, ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - startTime := ctx.BlockTime().AddDate(1, 0, 0).Unix() endTime := ctx.BlockTime().AddDate(2, 0, 0).Unix() baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) @@ -229,7 +222,6 @@ func TestMigrateVestingAccounts(t *testing.T) { { "continuous vesting, start time passed but not ended", func(app *simapp.SimApp, ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - startTime := ctx.BlockTime().AddDate(-1, 0, 0).Unix() endTime := ctx.BlockTime().AddDate(2, 0, 0).Unix() baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) @@ -252,7 +244,6 @@ func TestMigrateVestingAccounts(t *testing.T) { { "continuous vesting, start time and endtime passed", func(app *simapp.SimApp, ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - startTime := ctx.BlockTime().AddDate(-2, 0, 0).Unix() endTime := ctx.BlockTime().AddDate(-1, 0, 0).Unix() baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) @@ -275,7 +266,6 @@ func TestMigrateVestingAccounts(t *testing.T) { { "periodic vesting account, yet to be vested, some rewards delegated", func(app *simapp.SimApp, ctx sdk.Context, validator stakingtypes.Validator, delegatorAddr sdk.AccAddress) { - baseAccount := authtypes.NewBaseAccountWithAddress(delegatorAddr) vestedCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), sdk.NewInt(100))) @@ -597,7 +587,6 @@ func TestMigrateVestingAccounts(t *testing.T) { ) }) } - } func trackingCorrected(ctx sdk.Context, t *testing.T, ak authkeeper.AccountKeeper, addr sdk.AccAddress, expDelVesting sdk.Coins, expDelFree sdk.Coins) { diff --git a/x/auth/testutil/suite.go b/x/auth/testutil/suite.go index d1ef1ba5f7c9..924f2366ca3b 100644 --- a/x/auth/testutil/suite.go +++ b/x/auth/testutil/suite.go @@ -154,9 +154,11 @@ func (s *TxConfigTestSuite) TestTxBuilderSetSignatures() { s.Require().NoError(err) msigData = multisig.NewMultisig(2) multisig.AddSignature(msigData, &signingtypes.SingleSignatureData{ - SignMode: signModeHandler.DefaultMode(), Signature: mSigBz1}, 0) + SignMode: signModeHandler.DefaultMode(), Signature: mSigBz1, + }, 0) multisig.AddSignature(msigData, &signingtypes.SingleSignatureData{ - SignMode: signModeHandler.DefaultMode(), Signature: mSigBz2}, 0) + SignMode: signModeHandler.DefaultMode(), Signature: mSigBz2, + }, 0) // set signature sigData1.Signature = sigBz diff --git a/x/auth/tx/direct_aux.go b/x/auth/tx/direct_aux.go index 475b4e2e3522..636130981377 100644 --- a/x/auth/tx/direct_aux.go +++ b/x/auth/tx/direct_aux.go @@ -30,7 +30,6 @@ func (signModeDirectAuxHandler) Modes() []signingtypes.SignMode { func (signModeDirectAuxHandler) GetSignBytes( mode signingtypes.SignMode, data signing.SignerData, tx sdk.Tx, ) ([]byte, error) { - if mode != signingtypes.SignMode_SIGN_MODE_DIRECT_AUX { return nil, fmt.Errorf("expected %s, got %s", signingtypes.SignMode_SIGN_MODE_DIRECT_AUX, mode) } diff --git a/x/auth/tx/encode_decode_test.go b/x/auth/tx/encode_decode_test.go index 5991f6653450..db6c3d995ed9 100644 --- a/x/auth/tx/encode_decode_test.go +++ b/x/auth/tx/encode_decode_test.go @@ -198,7 +198,7 @@ func TestRejectNonADR027(t *testing.T) { // bodyBz's length prefix is 5, with `5` as varint encoding. We also try a // longer varint encoding for 5: `133 00`. - longVarintBodyBz := append(append([]byte{bodyBz[0]}, byte(133), byte(00)), bodyBz[2:]...) + longVarintBodyBz := append(append([]byte{bodyBz[0]}, byte(133), byte(0o0)), bodyBz[2:]...) tests := []struct { name string @@ -259,15 +259,24 @@ func TestVarintMinLength(t *testing.T) { tests := []struct { n uint64 }{ - {1<<7 - 1}, {1 << 7}, - {1<<14 - 1}, {1 << 14}, - {1<<21 - 1}, {1 << 21}, - {1<<28 - 1}, {1 << 28}, - {1<<35 - 1}, {1 << 35}, - {1<<42 - 1}, {1 << 42}, - {1<<49 - 1}, {1 << 49}, - {1<<56 - 1}, {1 << 56}, - {1<<63 - 1}, {1 << 63}, + {1<<7 - 1}, + {1 << 7}, + {1<<14 - 1}, + {1 << 14}, + {1<<21 - 1}, + {1 << 21}, + {1<<28 - 1}, + {1 << 28}, + {1<<35 - 1}, + {1 << 35}, + {1<<42 - 1}, + {1 << 42}, + {1<<49 - 1}, + {1 << 49}, + {1<<56 - 1}, + {1 << 56}, + {1<<63 - 1}, + {1 << 63}, {math.MaxUint64}, } diff --git a/x/auth/tx/encoder.go b/x/auth/tx/encoder.go index 35cecac556eb..e594ee24cfc8 100644 --- a/x/auth/tx/encoder.go +++ b/x/auth/tx/encoder.go @@ -42,6 +42,5 @@ func DefaultJSONTxEncoder(cdc codec.ProtoCodecMarshaler) sdk.TxEncoder { } return nil, fmt.Errorf("expected %T, got %T", &wrapper{}, tx) - } } diff --git a/x/auth/tx/query.go b/x/auth/tx/query.go index a508bd32f0a0..837170a3e20b 100644 --- a/x/auth/tx/query.go +++ b/x/auth/tx/query.go @@ -77,7 +77,7 @@ func QueryTx(clientCtx client.Context, hashHexStr string) (*sdk.TxResponse, erro return nil, err } - //TODO: this may not always need to be proven + // TODO: this may not always need to be proven // https://github.com/cosmos/cosmos-sdk/issues/6807 resTx, err := node.Tx(context.Background(), hash, true) if err != nil { diff --git a/x/auth/tx/service.go b/x/auth/tx/service.go index 293542f4d383..e00b7a519aa2 100644 --- a/x/auth/tx/service.go +++ b/x/auth/tx/service.go @@ -3,9 +3,10 @@ package tx import ( "context" "fmt" + "strings" + "github.com/cosmos/cosmos-sdk/client/grpc/tmservice" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "strings" gogogrpc "github.com/gogo/protobuf/grpc" "github.com/golang/protobuf/proto" // nolint: staticcheck @@ -235,7 +236,6 @@ func (s txServer) GetBlockWithTxs(ctx context.Context, req *txtypes.GetBlockWith Total: blockTxsLn, }, }, nil - } func (s txServer) BroadcastTx(ctx context.Context, req *txtypes.BroadcastTxRequest) (*txtypes.BroadcastTxResponse, error) { diff --git a/x/auth/types/genesis_test.go b/x/auth/types/genesis_test.go index 1030885e799e..7e96036053fc 100644 --- a/x/auth/types/genesis_test.go +++ b/x/auth/types/genesis_test.go @@ -81,9 +81,7 @@ func TestGenesisAccountIterator(t *testing.T) { } func TestPackAccountsAny(t *testing.T) { - var ( - accounts []*codectypes.Any - ) + var accounts []*codectypes.Any testCases := []struct { msg string diff --git a/x/auth/types/permissions_test.go b/x/auth/types/permissions_test.go index 75281a689ec3..de5c25645769 100644 --- a/x/auth/types/permissions_test.go +++ b/x/auth/types/permissions_test.go @@ -26,7 +26,6 @@ func TestHasPermission(t *testing.T) { has = permAddr.HasPermission(tc.permission) require.Equal(t, tc.expectHas, has, "test case #%d", i) } - } func TestValidatePermissions(t *testing.T) { diff --git a/x/auth/vesting/client/testutil/cli_test.go b/x/auth/vesting/client/testutil/cli_test.go index dd36a6af2d3e..1035ca750264 100644 --- a/x/auth/vesting/client/testutil/cli_test.go +++ b/x/auth/vesting/client/testutil/cli_test.go @@ -1,3 +1,4 @@ +//go:build norace // +build norace package testutil diff --git a/x/auth/vesting/msg_server.go b/x/auth/vesting/msg_server.go index aa7d391ea46d..90377947a002 100644 --- a/x/auth/vesting/msg_server.go +++ b/x/auth/vesting/msg_server.go @@ -222,5 +222,4 @@ func (s msgServer) CreatePeriodicVestingAccount(goCtx context.Context, msg *type ), ) return &types.MsgCreatePeriodicVestingAccountResponse{}, nil - } diff --git a/x/auth/vesting/types/msgs.go b/x/auth/vesting/types/msgs.go index 6c56ab3208d0..2387513cb3dd 100644 --- a/x/auth/vesting/types/msgs.go +++ b/x/auth/vesting/types/msgs.go @@ -2,6 +2,7 @@ package types import ( "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) diff --git a/x/auth/vesting/types/vesting_account.go b/x/auth/vesting/types/vesting_account.go index 342ddce28b0d..6db8d7b29922 100644 --- a/x/auth/vesting/types/vesting_account.go +++ b/x/auth/vesting/types/vesting_account.go @@ -193,8 +193,10 @@ func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) { // Continuous Vesting Account -var _ vestexported.VestingAccount = (*ContinuousVestingAccount)(nil) -var _ authtypes.GenesisAccount = (*ContinuousVestingAccount)(nil) +var ( + _ vestexported.VestingAccount = (*ContinuousVestingAccount)(nil) + _ authtypes.GenesisAccount = (*ContinuousVestingAccount)(nil) +) // NewContinuousVestingAccountRaw creates a new ContinuousVestingAccount object from BaseVestingAccount func NewContinuousVestingAccountRaw(bva *BaseVestingAccount, startTime int64) *ContinuousVestingAccount { @@ -307,8 +309,10 @@ func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) { // Periodic Vesting Account -var _ vestexported.VestingAccount = (*PeriodicVestingAccount)(nil) -var _ authtypes.GenesisAccount = (*PeriodicVestingAccount)(nil) +var ( + _ vestexported.VestingAccount = (*PeriodicVestingAccount)(nil) + _ authtypes.GenesisAccount = (*PeriodicVestingAccount)(nil) +) // NewPeriodicVestingAccountRaw creates a new PeriodicVestingAccount object from BaseVestingAccount func NewPeriodicVestingAccountRaw(bva *BaseVestingAccount, startTime int64, periods Periods) *PeriodicVestingAccount { @@ -451,8 +455,10 @@ func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) { // Delayed Vesting Account -var _ vestexported.VestingAccount = (*DelayedVestingAccount)(nil) -var _ authtypes.GenesisAccount = (*DelayedVestingAccount)(nil) +var ( + _ vestexported.VestingAccount = (*DelayedVestingAccount)(nil) + _ authtypes.GenesisAccount = (*DelayedVestingAccount)(nil) +) // NewDelayedVestingAccountRaw creates a new DelayedVestingAccount object from BaseVestingAccount func NewDelayedVestingAccountRaw(bva *BaseVestingAccount) *DelayedVestingAccount { @@ -519,8 +525,10 @@ func (dva DelayedVestingAccount) String() string { //----------------------------------------------------------------------------- // Permanent Locked Vesting Account -var _ vestexported.VestingAccount = (*PermanentLockedAccount)(nil) -var _ authtypes.GenesisAccount = (*PermanentLockedAccount)(nil) +var ( + _ vestexported.VestingAccount = (*PermanentLockedAccount)(nil) + _ authtypes.GenesisAccount = (*PermanentLockedAccount)(nil) +) // NewPermanentLockedAccount returns a PermanentLockedAccount func NewPermanentLockedAccount(baseAcc *authtypes.BaseAccount, coins sdk.Coins) *PermanentLockedAccount { diff --git a/x/auth/vesting/types/vesting_account_test.go b/x/auth/vesting/types/vesting_account_test.go index db2d52141014..3607b881a478 100644 --- a/x/auth/vesting/types/vesting_account_test.go +++ b/x/auth/vesting/types/vesting_account_test.go @@ -362,7 +362,8 @@ func TestGetVestedCoinsPeriodicVestingAcc(t *testing.T) { vestedCoins = pva.GetVestedCoins(now.Add(18 * time.Hour)) require.Equal(t, sdk.Coins{ - sdk.NewInt64Coin(feeDenom, 750), sdk.NewInt64Coin(stakeDenom, 75)}, vestedCoins) + sdk.NewInt64Coin(feeDenom, 750), sdk.NewInt64Coin(stakeDenom, 75), + }, vestedCoins) // require 100% of coins vested vestedCoins = pva.GetVestedCoins(now.Add(48 * time.Hour)) @@ -809,6 +810,7 @@ func (s *VestingAccountTestSuite) TestDelayedVestingAccountMarshal() { _, err = app.AccountKeeper.UnmarshalAccount(bz[:len(bz)/2]) require.NotNil(err) } + func (s *VestingAccountTestSuite) TestPermanentLockedAccountMarshal() { app := s.app require := s.Require() diff --git a/x/authz/authorization_grant.go b/x/authz/authorization_grant.go index b364ce8bb591..4344bd3b7b58 100644 --- a/x/authz/authorization_grant.go +++ b/x/authz/authorization_grant.go @@ -30,9 +30,7 @@ func NewGrant(blockTime time.Time, a Authorization, expiration *time.Time) (Gran }, nil } -var ( - _ cdctypes.UnpackInterfacesMessage = &Grant{} -) +var _ cdctypes.UnpackInterfacesMessage = &Grant{} // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces func (g Grant) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { diff --git a/x/authz/authorization_grant_test.go b/x/authz/authorization_grant_test.go index 2501b5de1dba..ce14692c0b5a 100644 --- a/x/authz/authorization_grant_test.go +++ b/x/authz/authorization_grant_test.go @@ -19,7 +19,7 @@ func expecError(r *require.Assertions, expected string, received error) { func TestNewGrant(t *testing.T) { a := NewGenericAuthorization("some-type") - var tcs = []struct { + tcs := []struct { title string a Authorization blockTime time.Time @@ -40,7 +40,6 @@ func TestNewGrant(t *testing.T) { expecError(require.New(t), tc.err, err) }) } - } func unixTime(s, ns int64) *time.Time { diff --git a/x/authz/client/cli/query.go b/x/authz/client/cli/query.go index dfc997c445e4..a197f89b1d6e 100644 --- a/x/authz/client/cli/query.go +++ b/x/authz/client/cli/query.go @@ -65,7 +65,7 @@ $ %s query %s grants cosmos1skjw.. cosmos1skjwj.. %s if err != nil { return err } - var msgAuthorized = "" + msgAuthorized := "" if len(args) >= 3 { msgAuthorized = args[2] } @@ -80,7 +80,8 @@ $ %s query %s grants cosmos1skjw.. cosmos1skjwj.. %s Granter: granter.String(), Grantee: grantee.String(), MsgTypeUrl: msgAuthorized, - Pagination: pageReq}, + Pagination: pageReq, + }, ) if err != nil { return err diff --git a/x/authz/client/cli/tx.go b/x/authz/client/cli/tx.go index 088eac05ac27..f094faea46d3 100644 --- a/x/authz/client/cli/tx.go +++ b/x/authz/client/cli/tx.go @@ -245,7 +245,6 @@ Example: ), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err diff --git a/x/authz/client/testutil/grpc.go b/x/authz/client/testutil/grpc.go index 6cf5e65ab76a..20a0f7c903fc 100644 --- a/x/authz/client/testutil/grpc.go +++ b/x/authz/client/testutil/grpc.go @@ -160,7 +160,6 @@ func (s *IntegrationTestSuite) TestQueryGrantsGRPC() { s.Require().NoError(err) tc.postRun(&authorizations) } - }) } } @@ -213,7 +212,6 @@ func (s *IntegrationTestSuite) TestQueryGranterGrantsGRPC() { // FIXME: https://github.com/cosmos/cosmos-sdk/issues/10965 require.Len(authorizations.Grants, tc.numItems) } - }) } } @@ -266,7 +264,6 @@ func (s *IntegrationTestSuite) TestQueryGranteeGrantsGRPC() { // FIXME: https://github.com/cosmos/cosmos-sdk/issues/10965 require.Len(authorizations.Grants, tc.numItems) } - }) } } diff --git a/x/authz/client/testutil/tx.go b/x/authz/client/testutil/tx.go index e0a2ff95c2f5..ecac6abce78e 100644 --- a/x/authz/client/testutil/tx.go +++ b/x/authz/client/testutil/tx.go @@ -105,7 +105,6 @@ func (s *IntegrationTestSuite) SetupSuite() { s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &response), out.String()) s.Require().Equal(int(response.Code), 0) s.Require().NotEqual(int(response.Height), 0) - } func (s *IntegrationTestSuite) createAccount(uid string) sdk.AccAddress { @@ -140,9 +139,11 @@ func (s *IntegrationTestSuite) TearDownSuite() { s.network.Cleanup() } -var typeMsgSend = bank.SendAuthorization{}.MsgTypeURL() -var typeMsgVote = sdk.MsgTypeURL(&govv1.MsgVote{}) -var typeMsgSubmitProposal = sdk.MsgTypeURL(&govv1.MsgSubmitProposal{}) +var ( + typeMsgSend = bank.SendAuthorization{}.MsgTypeURL() + typeMsgVote = sdk.MsgTypeURL(&govv1.MsgVote{}) + typeMsgSubmitProposal = sdk.MsgTypeURL(&govv1.MsgSubmitProposal{}) +) func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() { val := s.network.Validators[0] @@ -752,7 +753,6 @@ func (s *IntegrationTestSuite) TestNewExecGenericAuthorized() { for _, tc := range testCases { tc := tc s.Run(tc.name, func() { - cmd := cli.NewCmdExecAuthorization() clientCtx := val.ClientCtx diff --git a/x/authz/codec.go b/x/authz/codec.go index da8222c8ec45..77a6fa24e4f9 100644 --- a/x/authz/codec.go +++ b/x/authz/codec.go @@ -36,6 +36,7 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, MsgServiceDesc()) } + func init() { // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be // used to properly serialize MsgGrant and MsgExec instances diff --git a/x/authz/errors.go b/x/authz/errors.go index 8d104d0c920e..2aaac7122f9c 100644 --- a/x/authz/errors.go +++ b/x/authz/errors.go @@ -6,7 +6,7 @@ import ( // x/authz module sentinel errors var ( - //ErrNoAuthorizationFound error if there is no authorization found given a grant key + // ErrNoAuthorizationFound error if there is no authorization found given a grant key ErrNoAuthorizationFound = sdkerrors.Register(ModuleName, 2, "authorization not found") // ErrInvalidExpirationTime error if the set expiration time is in the past ErrInvalidExpirationTime = sdkerrors.Register(ModuleName, 3, "expiration time of authorization should be more than current time") diff --git a/x/authz/generic_authorization.go b/x/authz/generic_authorization.go index d6249b137a28..23853d250a7a 100644 --- a/x/authz/generic_authorization.go +++ b/x/authz/generic_authorization.go @@ -4,9 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -var ( - _ Authorization = &GenericAuthorization{} -) +var _ Authorization = &GenericAuthorization{} // NewGenericAuthorization creates a new GenericAuthorization object. func NewGenericAuthorization(msgTypeURL string) *GenericAuthorization { diff --git a/x/authz/keeper/grpc_query.go b/x/authz/keeper/grpc_query.go index 634a0f6e2313..1156ac23521d 100644 --- a/x/authz/keeper/grpc_query.go +++ b/x/authz/keeper/grpc_query.go @@ -119,8 +119,7 @@ func (k Keeper) GranterGrants(c context.Context, req *authz.QueryGranterGrantsRe authzStore := prefix.NewStore(store, grantStoreKey(nil, granter, "")) var grants []*authz.GrantAuthorization - pageRes, err := query.FilteredPaginate(authzStore, req.Pagination, func(key []byte, value []byte, - accumulate bool) (bool, error) { + pageRes, err := query.FilteredPaginate(authzStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { auth, err := unmarshalAuthorization(k.cdc, value) if err != nil { return false, err @@ -172,8 +171,7 @@ func (k Keeper) GranteeGrants(c context.Context, req *authz.QueryGranteeGrantsRe store := prefix.NewStore(ctx.KVStore(k.storeKey), GrantKey) var authorizations []*authz.GrantAuthorization - pageRes, err := query.FilteredPaginate(store, req.Pagination, func(key []byte, value []byte, - accumulate bool) (bool, error) { + pageRes, err := query.FilteredPaginate(store, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { auth, err := unmarshalAuthorization(k.cdc, value) if err != nil { return false, err diff --git a/x/authz/keeper/keeper.go b/x/authz/keeper/keeper.go index 0a5f28234133..a1fd37d57deb 100644 --- a/x/authz/keeper/keeper.go +++ b/x/authz/keeper/keeper.go @@ -83,7 +83,7 @@ func (k Keeper) update(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccA // DispatchActions attempts to execute the provided messages via authorization // grants from the message signer to the grantee. func (k Keeper) DispatchActions(ctx sdk.Context, grantee sdk.AccAddress, msgs []sdk.Msg) ([][]byte, error) { - var results = make([][]byte, len(msgs)) + results := make([][]byte, len(msgs)) now := ctx.BlockTime() for i, msg := range msgs { signers := msg.GetSigners() @@ -245,7 +245,8 @@ func (k Keeper) GetAuthorizations(ctx sdk.Context, grantee sdk.AccAddress, grant // It should not be used in query or msg services without charging additional gas. // The iteration stops when the handler function returns true or the iterator exhaust. func (k Keeper) IterateGrants(ctx sdk.Context, - handler func(granterAddr sdk.AccAddress, granteeAddr sdk.AccAddress, grant authz.Grant) bool) { + handler func(granterAddr sdk.AccAddress, granteeAddr sdk.AccAddress, grant authz.Grant) bool, +) { store := ctx.KVStore(k.storeKey) iter := sdk.KVStorePrefixIterator(store, GrantKey) defer iter.Close() @@ -274,7 +275,8 @@ func (keeper Keeper) getGrantQueueItem(ctx sdk.Context, expiration time.Time, gr } func (k Keeper) setGrantQueueItem(ctx sdk.Context, expiration time.Time, - granter sdk.AccAddress, grantee sdk.AccAddress, queueItems *authz.GrantQueueItem) error { + granter sdk.AccAddress, grantee sdk.AccAddress, queueItems *authz.GrantQueueItem, +) error { store := ctx.KVStore(k.storeKey) bz, err := k.cdc.Marshal(queueItems) if err != nil { @@ -286,8 +288,7 @@ func (k Keeper) setGrantQueueItem(ctx sdk.Context, expiration time.Time, } // insertIntoGrantQueue inserts a grant key into the grant queue -func (keeper Keeper) insertIntoGrantQueue(ctx sdk.Context, granter, grantee sdk.AccAddress, msgType string, - expiration time.Time) error { +func (keeper Keeper) insertIntoGrantQueue(ctx sdk.Context, granter, grantee sdk.AccAddress, msgType string, expiration time.Time) error { queueItems, err := keeper.getGrantQueueItem(ctx, expiration, granter, grantee) if err != nil { return err diff --git a/x/authz/keeper/keeper_test.go b/x/authz/keeper/keeper_test.go index 223e3ad32617..b9f41bc74919 100644 --- a/x/authz/keeper/keeper_test.go +++ b/x/authz/keeper/keeper_test.go @@ -118,7 +118,6 @@ func (s *TestSuite) TestKeeperIter() { s.Require().Contains([]sdk.AccAddress{granterAddr, granter2Addr}, granter) return true }) - } func (s *TestSuite) TestDispatchAction() { @@ -265,7 +264,6 @@ func (s *TestSuite) TestDispatchAction() { tc.postRun() }) } - } // Tests that all msg events included in an authz MsgExec tx diff --git a/x/authz/keeper/keys_test.go b/x/authz/keeper/keys_test.go index 7a7858f704ff..531e441511c0 100644 --- a/x/authz/keeper/keys_test.go +++ b/x/authz/keeper/keys_test.go @@ -12,9 +12,11 @@ import ( bank "github.com/cosmos/cosmos-sdk/x/bank/types" ) -var granter = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) -var grantee = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) -var msgType = bank.SendAuthorization{}.MsgTypeURL() +var ( + granter = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + grantee = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + msgType = bank.SendAuthorization{}.MsgTypeURL() +) func TestGrantkey(t *testing.T) { require := require.New(t) diff --git a/x/authz/migrations/v046/keys.go b/x/authz/migrations/v046/keys.go index b4348df3bec1..9b4c74fb9f3d 100644 --- a/x/authz/migrations/v046/keys.go +++ b/x/authz/migrations/v046/keys.go @@ -30,7 +30,7 @@ func GrantQueueKey(expiration time.Time, granter sdk.AccAddress, grantee sdk.Acc grantee = address.MustLengthPrefix(grantee) l := 1 + len(exp) + len(granter) + len(grantee) - var key = make([]byte, l) + key := make([]byte, l) copy(key, GrantQueuePrefix) copy(key[1:], exp) copy(key[1+len(exp):], granter) @@ -48,7 +48,7 @@ func GrantStoreKey(grantee sdk.AccAddress, granter sdk.AccAddress, msgType strin grantee = address.MustLengthPrefix(grantee) l := 1 + len(grantee) + len(granter) + len(m) - var key = make([]byte, l) + key := make([]byte, l) copy(key, GrantPrefix) copy(key[1:], granter) copy(key[1+len(granter):], grantee) diff --git a/x/authz/migrations/v046/keys_test.go b/x/authz/migrations/v046/keys_test.go index 05a5bd6b1b6e..9a73edbc32dd 100644 --- a/x/authz/migrations/v046/keys_test.go +++ b/x/authz/migrations/v046/keys_test.go @@ -10,9 +10,11 @@ import ( "github.com/stretchr/testify/require" ) -var granter = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) -var grantee = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) -var msgType = bank.SendAuthorization{}.MsgTypeURL() +var ( + granter = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + grantee = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + msgType = bank.SendAuthorization{}.MsgTypeURL() +) func TestGrantkey(t *testing.T) { require := require.New(t) diff --git a/x/authz/module/abci.go b/x/authz/module/abci.go index e85044a95df4..c9e6fef5e7a6 100644 --- a/x/authz/module/abci.go +++ b/x/authz/module/abci.go @@ -7,7 +7,6 @@ import ( // BeginBlocker is called at the begining of every block func BeginBlocker(ctx sdk.Context, keeper keeper.Keeper) { - // delete all the mature grants if err := keeper.DequeueAndDeleteExpiredGrants(ctx); err != nil { panic(err) diff --git a/x/authz/module/abci_test.go b/x/authz/module/abci_test.go index 5858476aeac5..9b58c5eadbc7 100644 --- a/x/authz/module/abci_test.go +++ b/x/authz/module/abci_test.go @@ -27,7 +27,7 @@ func TestExpiredGrantsQueue(t *testing.T) { expiration2 := expiration.AddDate(1, 0, 0) smallCoins := sdk.NewCoins(sdk.NewInt64Coin("stake", 10)) - var save = func(grantee sdk.AccAddress, exp *time.Time) { + save := func(grantee sdk.AccAddress, exp *time.Time) { err := app.AuthzKeeper.SaveGrant(ctx, grantee, granter, banktypes.NewSendAuthorization(smallCoins), exp) require.NoError(t, err, "Grant from %s", grantee.String()) } @@ -40,7 +40,7 @@ func TestExpiredGrantsQueue(t *testing.T) { authz.RegisterQueryServer(queryHelper, app.AuthzKeeper) queryClient := authz.NewQueryClient(queryHelper) - var checkGrants = func(ctx sdk.Context, expectedNum int) { + checkGrants := func(ctx sdk.Context, expectedNum int) { authzmodule.BeginBlocker(ctx, app.AuthzKeeper) res, err := queryClient.GranterGrants(ctx.Context(), &authz.QueryGranterGrantsRequest{ diff --git a/x/authz/msgs.go b/x/authz/msgs.go index 60961d51a4c2..8fbe17623f52 100644 --- a/x/authz/msgs.go +++ b/x/authz/msgs.go @@ -1,9 +1,10 @@ package authz import ( - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" "time" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" + "github.com/gogo/protobuf/proto" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" diff --git a/x/authz/msgs_test.go b/x/authz/msgs_test.go index 7f85584121ed..0318225df226 100644 --- a/x/authz/msgs_test.go +++ b/x/authz/msgs_test.go @@ -1,10 +1,11 @@ package authz_test import ( - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "testing" "time" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/stretchr/testify/require" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -46,6 +47,7 @@ func TestMsgExecAuthorized(t *testing.T) { } } } + func TestMsgRevokeAuthorization(t *testing.T) { tests := []struct { title string @@ -84,21 +86,35 @@ func TestMsgGrantAuthorization(t *testing.T) { expectErr bool valBasic bool }{ - {"nil granter address", - nil, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, &now, false, false}, - {"nil grantee address", - granter, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, &now, false, false}, - {"nil granter and grantee address", - nil, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, &now, false, false}, - {"nil authorization should fail", - granter, grantee, nil, &now, true, false}, - {"valid test case", - granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, addDatePtr(&now, 1, 0), false, true}, - {"valid test case with nil expire time", - granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, nil, false, true}, + { + "nil granter address", + nil, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, &now, false, false, + }, + { + "nil grantee address", + granter, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, &now, false, false, + }, + { + "nil granter and grantee address", + nil, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, &now, false, false, + }, + { + "nil authorization should fail", + granter, grantee, nil, &now, true, false, + }, + { + "valid test case", + granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, addDatePtr(&now, 1, 0), false, true, + }, + { + "valid test case with nil expire time", + granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, nil, false, true, + }, // we don't access the block time / nor time.Now, so we don't know if it's in the past at this level. - {"past expire time should not fail", - granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, addDatePtr(&now, 0, -1), false, true}, + { + "past expire time should not fail", + granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, addDatePtr(&now, 0, -1), false, true, + }, } for _, tc := range tests { msg, err := authz.NewMsgGrant( diff --git a/x/authz/simulation/operations.go b/x/authz/simulation/operations.go index a20c7f276ca9..956a7b4c325d 100644 --- a/x/authz/simulation/operations.go +++ b/x/authz/simulation/operations.go @@ -41,8 +41,8 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( - appParams simtypes.AppParams, cdc codec.JSONCodec, ak authz.AccountKeeper, bk authz.BankKeeper, k keeper.Keeper, appCdc cdctypes.AnyUnpacker) simulation.WeightedOperations { - + appParams simtypes.AppParams, cdc codec.JSONCodec, ak authz.AccountKeeper, bk authz.BankKeeper, k keeper.Keeper, appCdc cdctypes.AnyUnpacker, +) simulation.WeightedOperations { var ( weightMsgGrant int weightExec int diff --git a/x/authz/simulation/operations_test.go b/x/authz/simulation/operations_test.go index c1cfe27cc26b..fab35b4d63c9 100644 --- a/x/authz/simulation/operations_test.go +++ b/x/authz/simulation/operations_test.go @@ -114,7 +114,6 @@ func (suite *SimTestSuite) TestSimulateGrant() { suite.Require().Equal(granter.Address.String(), msg.Granter) suite.Require().Equal(grantee.Address.String(), msg.Grantee) suite.Require().Len(futureOperations, 0) - } func (suite *SimTestSuite) TestSimulateRevoke() { @@ -128,7 +127,8 @@ func (suite *SimTestSuite) TestSimulateRevoke() { Header: tmproto.Header{ Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash, - }}) + }, + }) initAmt := suite.app.StakingKeeper.TokensFromConsensusPower(suite.ctx, 200000) initCoins := sdk.NewCoins(sdk.NewCoin("stake", initAmt)) @@ -154,7 +154,6 @@ func (suite *SimTestSuite) TestSimulateRevoke() { suite.Require().Equal(grantee.Address.String(), msg.Grantee) suite.Require().Equal(banktypes.SendAuthorization{}.MsgTypeURL(), msg.MsgTypeUrl) suite.Require().Len(futureOperations, 0) - } func (suite *SimTestSuite) TestSimulateExec() { @@ -189,7 +188,6 @@ func (suite *SimTestSuite) TestSimulateExec() { suite.Require().True(operationMsg.OK) suite.Require().Equal(grantee.Address.String(), msg.Grantee) suite.Require().Len(futureOperations, 0) - } func TestSimTestSuite(t *testing.T) { diff --git a/x/bank/keeper/grpc_query.go b/x/bank/keeper/grpc_query.go index 032e9e5ecfff..2afc4c585f70 100644 --- a/x/bank/keeper/grpc_query.go +++ b/x/bank/keeper/grpc_query.go @@ -67,7 +67,6 @@ func (k BaseKeeper) AllBalances(ctx context.Context, req *types.QueryAllBalances balances = append(balances, sdk.NewCoin(string(key), amount)) return nil }) - if err != nil { return nil, status.Errorf(codes.InvalidArgument, "paginate: %v", err) } @@ -167,7 +166,6 @@ func (k BaseKeeper) DenomsMetadata(c context.Context, req *types.QueryDenomsMeta metadatas = append(metadatas, metadata) return nil }) - if err != nil { return nil, status.Error(codes.Internal, err.Error()) } @@ -204,7 +202,6 @@ func (k BaseKeeper) DenomOwners( goCtx context.Context, req *types.QueryDenomOwnersRequest, ) (*types.QueryDenomOwnersResponse, error) { - if req == nil { return nil, status.Errorf(codes.InvalidArgument, "empty request") } @@ -239,7 +236,6 @@ func (k BaseKeeper) DenomOwners( return true, nil }, ) - if err != nil { return nil, status.Error(codes.Internal, err.Error()) } diff --git a/x/bank/keeper/invariants.go b/x/bank/keeper/invariants.go index 52da98381fc6..dead9dca0334 100644 --- a/x/bank/keeper/invariants.go +++ b/x/bank/keeper/invariants.go @@ -52,7 +52,6 @@ func TotalSupply(k Keeper) sdk.Invariant { return func(ctx sdk.Context) (string, bool) { expectedTotal := sdk.Coins{} supply, _, err := k.GetPaginatedTotalSupply(ctx, &query.PageRequest{Limit: query.MaxLimit}) - if err != nil { return sdk.FormatInvariant(types.ModuleName, "query supply", fmt.Sprintf("error querying total supply %v", err)), false diff --git a/x/bank/keeper/keeper.go b/x/bank/keeper/keeper.go index 40492e33a358..e25d8b809097 100644 --- a/x/bank/keeper/keeper.go +++ b/x/bank/keeper/keeper.go @@ -100,7 +100,6 @@ func NewBaseKeeper( paramSpace paramtypes.Subspace, blockedAddrs map[string]bool, ) BaseKeeper { - // set KeyTable if it has not already been set if !paramSpace.HasKeyTable() { paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable()) @@ -318,7 +317,6 @@ func (k BaseKeeper) SetDenomMetaData(ctx sdk.Context, denomMetaData types.Metada func (k BaseKeeper) SendCoinsFromModuleToAccount( ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins, ) error { - senderAddr := k.ak.GetModuleAddress(senderModule) if senderAddr == nil { panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", senderModule)) @@ -336,7 +334,6 @@ func (k BaseKeeper) SendCoinsFromModuleToAccount( func (k BaseKeeper) SendCoinsFromModuleToModule( ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins, ) error { - senderAddr := k.ak.GetModuleAddress(senderModule) if senderAddr == nil { panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", senderModule)) @@ -355,7 +352,6 @@ func (k BaseKeeper) SendCoinsFromModuleToModule( func (k BaseKeeper) SendCoinsFromAccountToModule( ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins, ) error { - recipientAcc := k.ak.GetModuleAccount(ctx, recipientModule) if recipientAcc == nil { panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", recipientModule)) @@ -370,7 +366,6 @@ func (k BaseKeeper) SendCoinsFromAccountToModule( func (k BaseKeeper) DelegateCoinsFromAccountToModule( ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins, ) error { - recipientAcc := k.ak.GetModuleAccount(ctx, recipientModule) if recipientAcc == nil { panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", recipientModule)) @@ -389,7 +384,6 @@ func (k BaseKeeper) DelegateCoinsFromAccountToModule( func (k BaseKeeper) UndelegateCoinsFromModuleToAccount( ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins, ) error { - acc := k.ak.GetModuleAccount(ctx, senderModule) if acc == nil { panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", senderModule)) diff --git a/x/bank/keeper/send.go b/x/bank/keeper/send.go index 109b33bc08e9..356be5ac1c93 100644 --- a/x/bank/keeper/send.go +++ b/x/bank/keeper/send.go @@ -48,7 +48,6 @@ type BaseSendKeeper struct { func NewBaseSendKeeper( cdc codec.BinaryCodec, storeKey storetypes.StoreKey, ak types.AccountKeeper, paramSpace paramtypes.Subspace, blockedAddrs map[string]bool, ) BaseSendKeeper { - return BaseSendKeeper{ BaseViewKeeper: NewBaseViewKeeper(cdc, storeKey, ak), cdc: cdc, diff --git a/x/bank/migrations/v046/keys.go b/x/bank/migrations/v046/keys.go index 6593ad91d811..c86aae935805 100644 --- a/x/bank/migrations/v046/keys.go +++ b/x/bank/migrations/v046/keys.go @@ -1,8 +1,6 @@ package v046 -var ( - DenomAddressPrefix = []byte{0x03} -) +var DenomAddressPrefix = []byte{0x03} // CreateDenomAddressPrefix creates a prefix for a reverse index of denomination // to account balance for that denomination. diff --git a/x/bank/migrations/v046/store.go b/x/bank/migrations/v046/store.go index b24501872aea..8f4e628a11ea 100644 --- a/x/bank/migrations/v046/store.go +++ b/x/bank/migrations/v046/store.go @@ -82,7 +82,7 @@ func migrateDenomMetadata(store sdk.KVStore) error { oldKey := oldDenomMetaDataIter.Key() l := len(oldKey)/2 + 1 - var newKey = make([]byte, len(types.DenomMetadataPrefix)+l) + newKey := make([]byte, len(types.DenomMetadataPrefix)+l) // old key: prefix_bytes | denom_bytes | denom_bytes copy(newKey, types.DenomMetadataPrefix) copy(newKey[len(types.DenomMetadataPrefix):], oldKey[:l]) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 8c0c94f0e62b..56a9919224b7 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -26,7 +26,6 @@ const ( func WeightedOperations( appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, bk keeper.Keeper, ) simulation.WeightedOperations { - var weightMsgSend, weightMsgMultiSend int appParams.GetOrGenerate(cdc, OpWeightMsgSend, &weightMsgSend, nil, func(_ *rand.Rand) { @@ -116,7 +115,6 @@ func sendMsgSend( r *rand.Rand, app *baseapp.BaseApp, bk keeper.Keeper, ak types.AccountKeeper, msg *types.MsgSend, ctx sdk.Context, chainID string, privkeys []cryptotypes.PrivKey, ) error { - var ( fees sdk.Coins err error @@ -167,7 +165,6 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Ope r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - // random number of inputs/outputs between [1, 3] inputs := make([]types.Input, r.Intn(3)+1) outputs := make([]types.Output, r.Intn(3)+1) @@ -256,7 +253,6 @@ func SimulateMsgMultiSendToModuleAccount(ak types.AccountKeeper, bk keeper.Keepe r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - inputs := make([]types.Input, 2) outputs := make([]types.Output, moduleAccCount) // collect signer privKeys @@ -323,7 +319,6 @@ func sendMsgMultiSend( r *rand.Rand, app *baseapp.BaseApp, bk keeper.Keeper, ak types.AccountKeeper, msg *types.MsgMultiSend, ctx sdk.Context, chainID string, privkeys []cryptotypes.PrivKey, ) error { - accountNumbers := make([]uint64, len(msg.Inputs)) sequenceNumbers := make([]uint64, len(msg.Inputs)) @@ -387,7 +382,6 @@ func sendMsgMultiSend( func randomSendFields( r *rand.Rand, ctx sdk.Context, accs []simtypes.Account, bk keeper.Keeper, ak types.AccountKeeper, ) (simtypes.Account, simtypes.Account, sdk.Coins, bool) { - from, _ := simtypes.RandomAcc(r, accs) to, _ := simtypes.RandomAcc(r, accs) @@ -412,7 +406,6 @@ func randomSendFields( } func getModuleAccounts(ak types.AccountKeeper, ctx sdk.Context, moduleAccCount int) []simtypes.Account { - moduleAccounts := make([]simtypes.Account, moduleAccCount) for i := 0; i < moduleAccCount; i++ { diff --git a/x/bank/types/balance.go b/x/bank/types/balance.go index 78539ace6cff..56f73ae98219 100644 --- a/x/bank/types/balance.go +++ b/x/bank/types/balance.go @@ -50,6 +50,7 @@ func (b balanceByAddress) Len() int { return len(b.addresses) } func (b balanceByAddress) Less(i, j int) bool { return bytes.Compare(b.addresses[i], b.addresses[j]) < 0 } + func (b balanceByAddress) Swap(i, j int) { b.addresses[i], b.addresses[j] = b.addresses[j], b.addresses[i] b.balances[i], b.balances[j] = b.balances[j], b.balances[i] diff --git a/x/bank/types/balance_test.go b/x/bank/types/balance_test.go index 10ee2a74bf6e..5219388b7c2e 100644 --- a/x/bank/types/balance_test.go +++ b/x/bank/types/balance_test.go @@ -104,7 +104,6 @@ func TestBalanceValidate(t *testing.T) { for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { - err := tc.balance.Validate() if tc.expErr { diff --git a/x/bank/types/genesis_test.go b/x/bank/types/genesis_test.go index fa1c836c9cbe..f13329f71427 100644 --- a/x/bank/types/genesis_test.go +++ b/x/bank/types/genesis_test.go @@ -9,7 +9,6 @@ import ( ) func TestGenesisStateValidate(t *testing.T) { - testCases := []struct { name string genesisState GenesisState @@ -146,7 +145,6 @@ func TestGenesisStateValidate(t *testing.T) { for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { - err := tc.genesisState.Validate() if tc.expErr { diff --git a/x/bank/types/metadata_test.go b/x/bank/types/metadata_test.go index 3d4fe0a0e634..34ff32f6a0f1 100644 --- a/x/bank/types/metadata_test.go +++ b/x/bank/types/metadata_test.go @@ -218,7 +218,6 @@ func TestMetadataValidate(t *testing.T) { for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { - err := tc.metadata.Validate() if tc.expErr { @@ -240,18 +239,22 @@ func TestMarshalJSONMetaData(t *testing.T) { }{ {"nil metadata", nil, `null`}, {"empty metadata", []types.Metadata{}, `[]`}, - {"non-empty coins", []types.Metadata{{ - Description: "The native staking token of the Cosmos Hub.", - DenomUnits: []*types.DenomUnit{ - {"uatom", uint32(0), []string{"microatom"}}, // The default exponent value 0 is omitted in the json - {"matom", uint32(3), []string{"milliatom"}}, - {"atom", uint32(6), nil}, + { + "non-empty coins", + []types.Metadata{ + { + Description: "The native staking token of the Cosmos Hub.", + DenomUnits: []*types.DenomUnit{ + {"uatom", uint32(0), []string{"microatom"}}, // The default exponent value 0 is omitted in the json + {"matom", uint32(3), []string{"milliatom"}}, + {"atom", uint32(6), nil}, + }, + Base: "uatom", + Display: "atom", + }, }, - Base: "uatom", - Display: "atom", - }, + `[{"description":"The native staking token of the Cosmos Hub.","denom_units":[{"denom":"uatom","aliases":["microatom"]},{"denom":"matom","exponent":3,"aliases":["milliatom"]},{"denom":"atom","exponent":6}],"base":"uatom","display":"atom"}]`, }, - `[{"description":"The native staking token of the Cosmos Hub.","denom_units":[{"denom":"uatom","aliases":["microatom"]},{"denom":"matom","exponent":3,"aliases":["milliatom"]},{"denom":"atom","exponent":6}],"base":"uatom","display":"atom"}]`}, } for _, tc := range testCases { diff --git a/x/bank/types/msgs_test.go b/x/bank/types/msgs_test.go index 8a22d187893e..523a57f28f38 100644 --- a/x/bank/types/msgs_test.go +++ b/x/bank/types/msgs_test.go @@ -13,7 +13,7 @@ func TestMsgSendRoute(t *testing.T) { addr1 := sdk.AccAddress([]byte("from")) addr2 := sdk.AccAddress([]byte("to")) coins := sdk.NewCoins(sdk.NewInt64Coin("atom", 10)) - var msg = NewMsgSend(addr1, addr2, coins) + msg := NewMsgSend(addr1, addr2, coins) require.Equal(t, msg.Route(), RouterKey) require.Equal(t, msg.Type(), "send") @@ -58,7 +58,7 @@ func TestMsgSendGetSignBytes(t *testing.T) { addr1 := sdk.AccAddress([]byte("input")) addr2 := sdk.AccAddress([]byte("output")) coins := sdk.NewCoins(sdk.NewInt64Coin("atom", 10)) - var msg = NewMsgSend(addr1, addr2, coins) + msg := NewMsgSend(addr1, addr2, coins) res := msg.GetSignBytes() expected := `{"type":"cosmos-sdk/MsgSend","value":{"amount":[{"amount":"10","denom":"atom"}],"from_address":"cosmos1d9h8qat57ljhcm","to_address":"cosmos1da6hgur4wsmpnjyg"}}` @@ -70,7 +70,7 @@ func TestMsgMultiSendRoute(t *testing.T) { addr1 := sdk.AccAddress([]byte("input")) addr2 := sdk.AccAddress([]byte("output")) coins := sdk.NewCoins(sdk.NewInt64Coin("atom", 10)) - var msg = MsgMultiSend{ + msg := MsgMultiSend{ Inputs: []Input{NewInput(addr1, coins)}, Outputs: []Output{NewOutput(addr2, coins)}, } @@ -189,7 +189,8 @@ func TestMsgMultiSendValidation(t *testing.T) { false, MsgMultiSend{ Inputs: []Input{NewInput(emptyAddr, atom123)}, // invalid input - Outputs: []Output{output1}}, + Outputs: []Output{output1}, + }, }, { false, @@ -242,7 +243,7 @@ func TestMsgMultiSendGetSignBytes(t *testing.T) { addr1 := sdk.AccAddress([]byte("input")) addr2 := sdk.AccAddress([]byte("output")) coins := sdk.NewCoins(sdk.NewInt64Coin("atom", 10)) - var msg = MsgMultiSend{ + msg := MsgMultiSend{ Inputs: []Input{NewInput(addr1, coins)}, Outputs: []Output{NewOutput(addr2, coins)}, } @@ -260,7 +261,7 @@ func TestMsgMultiSendGetSigners(t *testing.T) { inputs[i] = NewInput(addr, nil) addrs[i] = addr.String() } - var msg = NewMsgMultiSend(inputs, nil) + msg := NewMsgMultiSend(inputs, nil) res := msg.GetSigners() for i, signer := range res { diff --git a/x/bank/types/send_authorization.go b/x/bank/types/send_authorization.go index a8a7855948d5..7eb90b594918 100644 --- a/x/bank/types/send_authorization.go +++ b/x/bank/types/send_authorization.go @@ -6,9 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/authz" ) -var ( - _ authz.Authorization = &SendAuthorization{} -) +var _ authz.Authorization = &SendAuthorization{} // NewSendAuthorization creates a new SendAuthorization object. func NewSendAuthorization(spendLimit sdk.Coins) *SendAuthorization { diff --git a/x/capability/keeper/keeper.go b/x/capability/keeper/keeper.go index cea524563491..708456ed3c64 100644 --- a/x/capability/keeper/keeper.go +++ b/x/capability/keeper/keeper.go @@ -197,7 +197,6 @@ func (k Keeper) GetOwners(ctx sdk.Context, index uint64) (types.CapabilityOwners // and sets the fwd and reverse keys for each owner in the memstore. // It is used during initialization from genesis. func (k Keeper) InitializeCapability(ctx sdk.Context, index uint64, owners types.CapabilityOwners) { - memStore := ctx.KVStore(k.memKey) cap := types.NewCapability(index) @@ -215,7 +214,6 @@ func (k Keeper) InitializeCapability(ctx sdk.Context, index uint64, owners types // Set the mapping from index from index to in-memory capability in the go map k.capMap[index] = cap } - } // NewCapability attempts to create a new capability with a given name. If the diff --git a/x/capability/types/genesis_test.go b/x/capability/types/genesis_test.go index d8a02e019254..5208a2b59043 100644 --- a/x/capability/types/genesis_test.go +++ b/x/capability/types/genesis_test.go @@ -40,7 +40,6 @@ func TestValidateGenesis(t *testing.T) { } genState.Owners = append(genState.Owners, genOwner) - }, expPass: false, }, @@ -55,7 +54,6 @@ func TestValidateGenesis(t *testing.T) { } genState.Owners = append(genState.Owners, genOwner) - }, expPass: false, }, @@ -69,7 +67,6 @@ func TestValidateGenesis(t *testing.T) { } genState.Owners = append(genState.Owners, genOwner) - }, expPass: false, }, @@ -83,7 +80,6 @@ func TestValidateGenesis(t *testing.T) { } genState.Owners = append(genState.Owners, genOwner) - }, expPass: false, }, @@ -97,7 +93,6 @@ func TestValidateGenesis(t *testing.T) { } genState.Owners = append(genState.Owners, genOwner) - }, expPass: false, }, @@ -111,7 +106,6 @@ func TestValidateGenesis(t *testing.T) { } genState.Owners = append(genState.Owners, genOwner) - }, expPass: false, }, diff --git a/x/crisis/client/testsuite/cli_test.go b/x/crisis/client/testsuite/cli_test.go index 3c083e694726..5b3ef61c5a45 100644 --- a/x/crisis/client/testsuite/cli_test.go +++ b/x/crisis/client/testsuite/cli_test.go @@ -1,3 +1,4 @@ +//go:build norace // +build norace package testutil diff --git a/x/crisis/keeper/keeper.go b/x/crisis/keeper/keeper.go index b9c563d5293d..2408b0bd0aa1 100644 --- a/x/crisis/keeper/keeper.go +++ b/x/crisis/keeper/keeper.go @@ -27,7 +27,6 @@ func NewKeeper( paramSpace paramtypes.Subspace, invCheckPeriod uint, supplyKeeper types.SupplyKeeper, feeCollectorName string, ) Keeper { - // set KeyTable if it has not already been set if !paramSpace.HasKeyTable() { paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable()) diff --git a/x/crisis/types/params.go b/x/crisis/types/params.go index 880f350f117c..03c8dd82883f 100644 --- a/x/crisis/types/params.go +++ b/x/crisis/types/params.go @@ -7,10 +7,8 @@ import ( paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) -var ( - // key for constant fee parameter - ParamStoreKeyConstantFee = []byte("ConstantFee") -) +// key for constant fee parameter +var ParamStoreKeyConstantFee = []byte("ConstantFee") // type declaration for parameters func ParamKeyTable() paramtypes.KeyTable { diff --git a/x/distribution/client/cli/tx.go b/x/distribution/client/cli/tx.go index 9971bc938034..f62e9381844c 100644 --- a/x/distribution/client/cli/tx.go +++ b/x/distribution/client/cli/tx.go @@ -52,7 +52,6 @@ func newSplitAndApply( genOrBroadcastFn newGenerateOrBroadcastFunc, clientCtx client.Context, fs *pflag.FlagSet, msgs []sdk.Msg, chunkSize int, ) error { - if chunkSize == 0 { return genOrBroadcastFn(clientCtx, fs, msgs...) } diff --git a/x/distribution/client/common/common_test.go b/x/distribution/client/common/common_test.go index 3a6cf8c9b547..ff9bb88d1766 100644 --- a/x/distribution/client/common/common_test.go +++ b/x/distribution/client/common/common_test.go @@ -1,9 +1,10 @@ package common import ( - "github.com/cosmos/cosmos-sdk/codec/legacy" "testing" + "github.com/cosmos/cosmos-sdk/codec/legacy" + "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" diff --git a/x/distribution/client/testutil/suite.go b/x/distribution/client/testutil/suite.go index ac912952be25..fdf9648b659e 100644 --- a/x/distribution/client/testutil/suite.go +++ b/x/distribution/client/testutil/suite.go @@ -472,7 +472,8 @@ func (s *IntegrationTestSuite) TestNewWithdrawRewardsCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), }, - true, 0, nil, []string{}, + true, 0, nil, + []string{}, }, { "valid transaction", @@ -483,7 +484,8 @@ func (s *IntegrationTestSuite) TestNewWithdrawRewardsCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), }, - false, 0, &sdk.TxResponse{}, []string{ + false, 0, &sdk.TxResponse{}, + []string{ "/cosmos.distribution.v1beta1.MsgWithdrawDelegatorRewardResponse", }, }, @@ -497,7 +499,8 @@ func (s *IntegrationTestSuite) TestNewWithdrawRewardsCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), }, - false, 0, &sdk.TxResponse{}, []string{ + false, 0, &sdk.TxResponse{}, + []string{ "/cosmos.distribution.v1beta1.MsgWithdrawDelegatorRewardResponse", "/cosmos.distribution.v1beta1.MsgWithdrawValidatorCommissionResponse", }, @@ -570,7 +573,8 @@ func (s *IntegrationTestSuite) TestNewWithdrawAllRewardsCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), }, - true, 0, nil, []string{}, + true, 0, nil, + []string{}, }, { "valid transaction", @@ -580,7 +584,8 @@ func (s *IntegrationTestSuite) TestNewWithdrawAllRewardsCmd() { fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), }, - false, 0, &sdk.TxResponse{}, []string{ + false, 0, &sdk.TxResponse{}, + []string{ "/cosmos.distribution.v1beta1.MsgWithdrawDelegatorRewardResponse", }, }, @@ -590,7 +595,6 @@ func (s *IntegrationTestSuite) TestNewWithdrawAllRewardsCmd() { tc := tc s.Run(tc.name, func() { - cmd := cli.NewWithdrawAllRewardsCmd() clientCtx := val.ClientCtx @@ -757,11 +761,13 @@ func (s *IntegrationTestSuite) TestGetCmdSubmitProposal() { }` // fund some tokens to the community pool - args := []string{sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(5431))).String(), + args := []string{ + sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(5431))).String(), fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String())} + fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), + } invalidPropFile := testutil.WriteToNewTempFile(s.T(), invalidProp) cmd := cli.NewFundCommunityPoolCmd() diff --git a/x/distribution/keeper/allocation.go b/x/distribution/keeper/allocation.go index ad9ef55ad07c..273db1314eb8 100644 --- a/x/distribution/keeper/allocation.go +++ b/x/distribution/keeper/allocation.go @@ -17,7 +17,6 @@ func (k Keeper) AllocateTokens( ctx sdk.Context, sumPreviousPrecommitPower, totalPreviousPower int64, previousProposer sdk.ConsAddress, bondedVotes []abci.VoteInfo, ) { - logger := k.Logger(ctx) // fetch and clear the collected fees for distribution, since this is diff --git a/x/distribution/keeper/delegation.go b/x/distribution/keeper/delegation.go index 61631da5dc22..3b158c15585e 100644 --- a/x/distribution/keeper/delegation.go +++ b/x/distribution/keeper/delegation.go @@ -29,7 +29,8 @@ func (k Keeper) initializeDelegation(ctx sdk.Context, val sdk.ValAddress, del sd // calculate the rewards accrued by a delegation between two periods func (k Keeper) calculateDelegationRewardsBetween(ctx sdk.Context, val stakingtypes.ValidatorI, - startingPeriod, endingPeriod uint64, stake sdk.Dec) (rewards sdk.DecCoins) { + startingPeriod, endingPeriod uint64, stake sdk.Dec, +) (rewards sdk.DecCoins) { // sanity check if startingPeriod > endingPeriod { panic("startingPeriod cannot be greater than endingPeriod") diff --git a/x/distribution/keeper/grpc_query.go b/x/distribution/keeper/grpc_query.go index 5cf71bbb102d..2779822293fe 100644 --- a/x/distribution/keeper/grpc_query.go +++ b/x/distribution/keeper/grpc_query.go @@ -93,7 +93,6 @@ func (k Keeper) ValidatorSlashes(c context.Context, req *types.QueryValidatorSla pageRes, err := query.FilteredPaginate(slashesStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { var result types.ValidatorSlashEvent err := k.cdc.Unmarshal(value, &result) - if err != nil { return false, err } @@ -107,7 +106,6 @@ func (k Keeper) ValidatorSlashes(c context.Context, req *types.QueryValidatorSla } return true, nil }) - if err != nil { return nil, err } diff --git a/x/distribution/keeper/hooks.go b/x/distribution/keeper/hooks.go index 0c66d44e33e7..bfae8482da5e 100644 --- a/x/distribution/keeper/hooks.go +++ b/x/distribution/keeper/hooks.go @@ -113,9 +113,11 @@ func (h Hooks) BeforeValidatorModified(_ sdk.Context, _ sdk.ValAddress) error { func (h Hooks) AfterValidatorBonded(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) error { return nil } + func (h Hooks) AfterValidatorBeginUnbonding(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) error { return nil } + func (h Hooks) BeforeDelegationRemoved(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) error { return nil } diff --git a/x/distribution/keeper/invariants.go b/x/distribution/keeper/invariants.go index 0a23d36be8f7..50300b977379 100644 --- a/x/distribution/keeper/invariants.go +++ b/x/distribution/keeper/invariants.go @@ -64,7 +64,6 @@ func NonNegativeOutstandingInvariant(k Keeper) sdk.Invariant { // CanWithdrawInvariant checks that current rewards can be completely withdrawn func CanWithdrawInvariant(k Keeper) sdk.Invariant { return func(ctx sdk.Context) (string, bool) { - // cache, we don't want to write changes ctx, _ = ctx.CacheContext() @@ -106,7 +105,6 @@ func CanWithdrawInvariant(k Keeper) sdk.Invariant { // ReferenceCountInvariant checks that the number of historical rewards records is correct func ReferenceCountInvariant(k Keeper) sdk.Invariant { return func(ctx sdk.Context) (string, bool) { - valCount := uint64(0) k.stakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { valCount++ @@ -137,7 +135,6 @@ func ReferenceCountInvariant(k Keeper) sdk.Invariant { // is consistent with the sum of validator outstanding rewards func ModuleAccountInvariant(k Keeper) sdk.Invariant { return func(ctx sdk.Context) (string, bool) { - var expectedCoins sdk.DecCoins k.IterateValidatorOutstandingRewards(ctx, func(_ sdk.ValAddress, rewards types.ValidatorOutstandingRewards) (stop bool) { expectedCoins = expectedCoins.Add(rewards.Rewards...) diff --git a/x/distribution/keeper/keeper.go b/x/distribution/keeper/keeper.go index 50536b2698e8..6af1ede7e5cd 100644 --- a/x/distribution/keeper/keeper.go +++ b/x/distribution/keeper/keeper.go @@ -31,7 +31,6 @@ func NewKeeper( ak types.AccountKeeper, bk types.BankKeeper, sk types.StakingKeeper, feeCollectorName string, ) Keeper { - // ensure distribution module account is set if addr := ak.GetModuleAddress(types.ModuleName); addr == nil { panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) diff --git a/x/distribution/keeper/store.go b/x/distribution/keeper/store.go index 0203ee13f672..3def35163f5c 100644 --- a/x/distribution/keeper/store.go +++ b/x/distribution/keeper/store.go @@ -331,7 +331,8 @@ func (k Keeper) SetValidatorSlashEvent(ctx sdk.Context, val sdk.ValAddress, heig // iterate over slash events between heights, inclusive func (k Keeper) IterateValidatorSlashEventsBetween(ctx sdk.Context, val sdk.ValAddress, startingHeight uint64, endingHeight uint64, - handler func(height uint64, event types.ValidatorSlashEvent) (stop bool)) { + handler func(height uint64, event types.ValidatorSlashEvent) (stop bool), +) { store := ctx.KVStore(k.storeKey) iter := store.Iterator( types.GetValidatorSlashEventKeyPrefix(val, startingHeight), diff --git a/x/distribution/migrations/v043/helpers.go b/x/distribution/migrations/v043/helpers.go index 23a5ac5a4913..0e846a72ffae 100644 --- a/x/distribution/migrations/v043/helpers.go +++ b/x/distribution/migrations/v043/helpers.go @@ -19,7 +19,7 @@ func MigratePrefixAddress(store sdk.KVStore, prefixBz []byte) { for ; oldStoreIter.Valid(); oldStoreIter.Next() { addr := oldStoreIter.Key() - var newStoreKey = prefixBz + newStoreKey := prefixBz newStoreKey = append(newStoreKey, address.MustLengthPrefix(addr)...) // Set new key on store. Values don't change. diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 9c1976cc2e28..44aa71a8e156 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -28,7 +28,6 @@ func WeightedOperations( appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper, ) simulation.WeightedOperations { - var weightMsgSetWithdrawAddress int appParams.GetOrGenerate(cdc, OpWeightMsgSetWithdrawAddress, &weightMsgSetWithdrawAddress, nil, func(_ *rand.Rand) { @@ -160,7 +159,6 @@ func SimulateMsgWithdrawValidatorCommission(ak types.AccountKeeper, bk types.Ban return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgWithdrawValidatorCommission, "random validator is not ok"), nil, nil @@ -206,7 +204,6 @@ func SimulateMsgFundCommunityPool(ak types.AccountKeeper, bk types.BankKeeper, k return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - funder, _ := simtypes.RandomAcc(r, accs) account := ak.GetAccount(ctx, funder.Address) diff --git a/x/distribution/simulation/operations_test.go b/x/distribution/simulation/operations_test.go index 4d70aab2eacf..fdde63e43caa 100644 --- a/x/distribution/simulation/operations_test.go +++ b/x/distribution/simulation/operations_test.go @@ -58,7 +58,6 @@ func (suite *SimTestSuite) TestWeightedOperations() { // TestSimulateMsgSetWithdrawAddress tests the normal scenario of a valid message of type TypeMsgSetWithdrawAddress. // Abonormal scenarios, where the message is created by an errors, are not tested here. func (suite *SimTestSuite) TestSimulateMsgSetWithdrawAddress() { - // setup 3 accounts s := rand.NewSource(1) r := rand.New(s) @@ -276,7 +275,6 @@ func (suite *SimTestSuite) setupValidatorRewards(valAddress sdk.ValAddress) { // setup current revards currentRewards := distrtypes.NewValidatorCurrentRewards(decCoins, 3) suite.app.DistrKeeper.SetValidatorCurrentRewards(suite.ctx, valAddress, currentRewards) - } func TestSimTestSuite(t *testing.T) { diff --git a/x/distribution/types/fee_pool_test.go b/x/distribution/types/fee_pool_test.go index de774ca3cc0f..7eabc04d0bfa 100644 --- a/x/distribution/types/fee_pool_test.go +++ b/x/distribution/types/fee_pool_test.go @@ -10,7 +10,6 @@ import ( ) func TestValidateGenesis(t *testing.T) { - fp := types.InitialFeePool() require.Nil(t, fp.ValidateGenesis()) diff --git a/x/distribution/types/genesis.go b/x/distribution/types/genesis.go index 3aa251bba997..9ceb0737a13e 100644 --- a/x/distribution/types/genesis.go +++ b/x/distribution/types/genesis.go @@ -10,7 +10,6 @@ func NewGenesisState( acc []ValidatorAccumulatedCommissionRecord, historical []ValidatorHistoricalRewardsRecord, cur []ValidatorCurrentRewardsRecord, dels []DelegatorStartingInfoRecord, slashes []ValidatorSlashEventRecord, ) *GenesisState { - return &GenesisState{ Params: params, FeePool: fp, diff --git a/x/distribution/types/query.go b/x/distribution/types/query.go index caaf2b7860be..ef3d34ceae5a 100644 --- a/x/distribution/types/query.go +++ b/x/distribution/types/query.go @@ -15,8 +15,7 @@ type QueryDelegatorTotalRewardsResponse struct { } // NewQueryDelegatorTotalRewardsResponse constructs a QueryDelegatorTotalRewardsResponse -func NewQueryDelegatorTotalRewardsResponse(rewards []DelegationDelegatorReward, - total sdk.DecCoins) QueryDelegatorTotalRewardsResponse { +func NewQueryDelegatorTotalRewardsResponse(rewards []DelegationDelegatorReward, total sdk.DecCoins) QueryDelegatorTotalRewardsResponse { return QueryDelegatorTotalRewardsResponse{Rewards: rewards, Total: total} } @@ -34,7 +33,6 @@ func (res QueryDelegatorTotalRewardsResponse) String() string { // NewDelegationDelegatorReward constructs a DelegationDelegatorReward. //nolint:interfacer -func NewDelegationDelegatorReward(valAddr sdk.ValAddress, - reward sdk.DecCoins) DelegationDelegatorReward { +func NewDelegationDelegatorReward(valAddr sdk.ValAddress, reward sdk.DecCoins) DelegationDelegatorReward { return DelegationDelegatorReward{ValidatorAddress: valAddr.String(), Reward: reward} } diff --git a/x/evidence/client/cli/query.go b/x/evidence/client/cli/query.go index 9c987fb15e36..bf74325f949f 100644 --- a/x/evidence/client/cli/query.go +++ b/x/evidence/client/cli/query.go @@ -74,7 +74,6 @@ func queryEvidence(clientCtx client.Context, hash string) error { params := &types.QueryEvidenceRequest{EvidenceHash: decodedHash} res, err := queryClient.Evidence(context.Background(), params) - if err != nil { return err } diff --git a/x/evidence/client/testutil/cli_test.go b/x/evidence/client/testutil/cli_test.go index dd36a6af2d3e..1035ca750264 100644 --- a/x/evidence/client/testutil/cli_test.go +++ b/x/evidence/client/testutil/cli_test.go @@ -1,3 +1,4 @@ +//go:build norace // +build norace package testutil diff --git a/x/evidence/keeper/grpc_query.go b/x/evidence/keeper/grpc_query.go index f084c16717a0..06764fc97a64 100644 --- a/x/evidence/keeper/grpc_query.go +++ b/x/evidence/keeper/grpc_query.go @@ -79,7 +79,6 @@ func (k Keeper) AllEvidence(c context.Context, req *types.QueryAllEvidenceReques evidence = append(evidence, evidenceAny) return nil }) - if err != nil { return &types.QueryAllEvidenceResponse{}, err } diff --git a/x/evidence/keeper/grpc_query_test.go b/x/evidence/keeper/grpc_query_test.go index df760c8edfe0..b6856f19c654 100644 --- a/x/evidence/keeper/grpc_query_test.go +++ b/x/evidence/keeper/grpc_query_test.go @@ -80,9 +80,7 @@ func (suite *KeeperTestSuite) TestQueryEvidence() { } func (suite *KeeperTestSuite) TestQueryAllEvidence() { - var ( - req *types.QueryAllEvidenceRequest - ) + var req *types.QueryAllEvidenceRequest testCases := []struct { msg string diff --git a/x/evidence/keeper/keeper.go b/x/evidence/keeper/keeper.go index 366f46b83182..cbab55320d3a 100644 --- a/x/evidence/keeper/keeper.go +++ b/x/evidence/keeper/keeper.go @@ -30,7 +30,6 @@ func NewKeeper( cdc codec.BinaryCodec, storeKey storetypes.StoreKey, stakingKeeper types.StakingKeeper, slashingKeeper types.SlashingKeeper, ) *Keeper { - return &Keeper{ cdc: cdc, storeKey: storeKey, diff --git a/x/evidence/types/genesis_test.go b/x/evidence/types/genesis_test.go index 339696c82e1f..d2b3e655db11 100644 --- a/x/evidence/types/genesis_test.go +++ b/x/evidence/types/genesis_test.go @@ -22,9 +22,7 @@ func TestDefaultGenesisState(t *testing.T) { } func TestNewGenesisState(t *testing.T) { - var ( - evidence []exported.Evidence - ) + var evidence []exported.Evidence testCases := []struct { msg string @@ -126,7 +124,7 @@ func TestGenesisStateValidate(t *testing.T) { } func TestUnpackInterfaces(t *testing.T) { - var gs = types.GenesisState{ + gs := types.GenesisState{ Evidence: []*codectypes.Any{{}}, } @@ -149,7 +147,6 @@ func TestUnpackInterfaces(t *testing.T) { for _, tc := range testCases { t.Run(fmt.Sprintf("Case %s", tc.msg), func(t *testing.T) { - if tc.expPass { require.NoError(t, gs.UnpackInterfaces(tc.unpacker)) } else { diff --git a/x/evidence/types/msgs.go b/x/evidence/types/msgs.go index 94a7546167ee..89b0d414d05d 100644 --- a/x/evidence/types/msgs.go +++ b/x/evidence/types/msgs.go @@ -2,6 +2,7 @@ package types import ( "fmt" + "github.com/gogo/protobuf/proto" "github.com/cosmos/cosmos-sdk/codec/types" diff --git a/x/feegrant/client/cli/query.go b/x/feegrant/client/cli/query.go index 66e26b328e18..cd1727ae81e3 100644 --- a/x/feegrant/client/cli/query.go +++ b/x/feegrant/client/cli/query.go @@ -67,7 +67,6 @@ $ %s query feegrant grant [granter] [grantee] Grantee: granteeAddr.String(), }, ) - if err != nil { return err } @@ -115,7 +114,6 @@ $ %s query feegrant grants [grantee] Pagination: pageReq, }, ) - if err != nil { return err } @@ -164,7 +162,6 @@ $ %s query feegrant grants [granter] Pagination: pageReq, }, ) - if err != nil { return err } diff --git a/x/feegrant/client/cli/tx.go b/x/feegrant/client/cli/tx.go index 38cd58a1a2f6..12a90194ee0b 100644 --- a/x/feegrant/client/cli/tx.go +++ b/x/feegrant/client/cli/tx.go @@ -63,7 +63,6 @@ Examples: ), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - cmd.Flags().Set(flags.FlagFrom, args[0]) clientCtx, err := client.GetClientTxContext(cmd) if err != nil { diff --git a/x/feegrant/filtered_fee.go b/x/feegrant/filtered_fee.go index aeef392feb46..74255757fcfb 100644 --- a/x/feegrant/filtered_fee.go +++ b/x/feegrant/filtered_fee.go @@ -16,8 +16,10 @@ const ( gasCostPerIteration = uint64(10) ) -var _ FeeAllowanceI = (*AllowedMsgAllowance)(nil) -var _ types.UnpackInterfacesMessage = (*AllowedMsgAllowance)(nil) +var ( + _ FeeAllowanceI = (*AllowedMsgAllowance)(nil) + _ types.UnpackInterfacesMessage = (*AllowedMsgAllowance)(nil) +) // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces func (a *AllowedMsgAllowance) UnpackInterfaces(unpacker types.AnyUnpacker) error { diff --git a/x/feegrant/grant.go b/x/feegrant/grant.go index a51e65ab5e1d..f8d7823ff06a 100644 --- a/x/feegrant/grant.go +++ b/x/feegrant/grant.go @@ -8,9 +8,7 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -var ( - _ types.UnpackInterfacesMessage = &Grant{} -) +var _ types.UnpackInterfacesMessage = &Grant{} // NewGrant creates a new FeeAllowanceGrant. //nolint:interfacer diff --git a/x/feegrant/keeper/grpc_query.go b/x/feegrant/keeper/grpc_query.go index 87278c4c59af..8d2b4c31145f 100644 --- a/x/feegrant/keeper/grpc_query.go +++ b/x/feegrant/keeper/grpc_query.go @@ -86,7 +86,6 @@ func (q Keeper) Allowances(c context.Context, req *feegrant.QueryAllowancesReque grants = append(grants, &grant) return nil }) - if err != nil { return nil, status.Error(codes.Internal, err.Error()) } @@ -128,7 +127,6 @@ func (q Keeper) AllowancesByGranter(c context.Context, req *feegrant.QueryAllowa return true, nil }) - if err != nil { return nil, status.Error(codes.Internal, err.Error()) } diff --git a/x/feegrant/keeper/grpc_query_test.go b/x/feegrant/keeper/grpc_query_test.go index 9a7b76ff1a5a..fd46c5ec0653 100644 --- a/x/feegrant/keeper/grpc_query_test.go +++ b/x/feegrant/keeper/grpc_query_test.go @@ -6,7 +6,6 @@ import ( ) func (suite *KeeperTestSuite) TestFeeAllowance() { - testCases := []struct { name string req *feegrant.QueryAllowanceRequest diff --git a/x/feegrant/keeper/keeper.go b/x/feegrant/keeper/keeper.go index 4800d512f242..e8d83842f558 100644 --- a/x/feegrant/keeper/keeper.go +++ b/x/feegrant/keeper/keeper.go @@ -40,7 +40,6 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { // GrantAllowance creates a new grant func (k Keeper) GrantAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress, feeAllowance feegrant.FeeAllowanceI) error { - // create the account if it is not in account state granteeAcc := k.authKeeper.GetAccount(ctx, grantee) if granteeAcc == nil { diff --git a/x/feegrant/keeper/keeper_test.go b/x/feegrant/keeper/keeper_test.go index dfbba8de89c3..4f5500f976d4 100644 --- a/x/feegrant/keeper/keeper_test.go +++ b/x/feegrant/keeper/keeper_test.go @@ -150,7 +150,6 @@ func (suite *KeeperTestSuite) TestKeeperCrud() { _, err = suite.msgSrvr.RevokeAllowance(suite.ctx, &feegrant.MsgRevokeAllowance{Granter: suite.addrs[3].String(), Grantee: accAddr.String()}) suite.Require().NoError(err) - } func (suite *KeeperTestSuite) TestUseGrantedFee() { diff --git a/x/feegrant/keeper/msg_server_test.go b/x/feegrant/keeper/msg_server_test.go index aafebdb7d227..4fa3193e3af9 100644 --- a/x/feegrant/keeper/msg_server_test.go +++ b/x/feegrant/keeper/msg_server_test.go @@ -218,5 +218,4 @@ func (suite *KeeperTestSuite) TestRevokeAllowance() { } }) } - } diff --git a/x/feegrant/key.go b/x/feegrant/key.go index a4838cad8a99..9cf0e4437481 100644 --- a/x/feegrant/key.go +++ b/x/feegrant/key.go @@ -68,7 +68,6 @@ func AllowanceByExpTimeKey(exp *time.Time) []byte { // ParseAddressesFromFeeAllowanceKey extracts and returns the granter, grantee from the given key. func ParseAddressesFromFeeAllowanceKey(key []byte) (granter, grantee sdk.AccAddress) { - // key is of format: // 0x00 granterAddrLen, granterAddrLenEndIndex := sdk.ParseLengthPrefixedBytes(key, 1, 1) // ignore key[0] since it is a prefix key @@ -82,7 +81,7 @@ func ParseAddressesFromFeeAllowanceKey(key []byte) (granter, grantee sdk.AccAddr // ParseAddressesFromFeeAllowanceQueueKey extracts and returns the granter, grantee from the given key. func ParseAddressesFromFeeAllowanceQueueKey(key []byte) (granter, grantee sdk.AccAddress) { - var lenTime = len(sdk.FormatTimeBytes(time.Now())) + lenTime := len(sdk.FormatTimeBytes(time.Now())) // key is of format: // <0x01> diff --git a/x/feegrant/simulation/operations.go b/x/feegrant/simulation/operations.go index 58095c138454..021e5ee79c96 100644 --- a/x/feegrant/simulation/operations.go +++ b/x/feegrant/simulation/operations.go @@ -28,7 +28,6 @@ func WeightedOperations( appParams simtypes.AppParams, cdc codec.JSONCodec, ak feegrant.AccountKeeper, bk feegrant.BankKeeper, k keeper.Keeper, ) simulation.WeightedOperations { - var ( weightMsgGrantAllowance int weightMsgRevokeAllowance int @@ -85,7 +84,6 @@ func SimulateMsgGrantAllowance(ak feegrant.AccountKeeper, bk feegrant.BankKeeper SpendLimit: spendableCoins, Expiration: &oneYear, }, granter.Address, grantee.Address) - if err != nil { return simtypes.NoOpMsg(feegrant.ModuleName, TypeMsgGrantAllowance, err.Error()), nil, err } @@ -114,12 +112,10 @@ func SimulateMsgRevokeAllowance(ak feegrant.AccountKeeper, bk feegrant.BankKeepe return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - hasGrant := false var granterAddr sdk.AccAddress var granteeAddr sdk.AccAddress k.IterateAllFeeAllowances(ctx, func(grant feegrant.Grant) bool { - granter, err := sdk.AccAddressFromBech32(grant.Granter) if err != nil { panic(err) diff --git a/x/feegrant/simulation/operations_test.go b/x/feegrant/simulation/operations_test.go index f958330d9810..71721becc0e7 100644 --- a/x/feegrant/simulation/operations_test.go +++ b/x/feegrant/simulation/operations_test.go @@ -32,7 +32,6 @@ func (suite *SimTestSuite) SetupTest() { suite.ctx = app.BaseApp.NewContext(checkTx, tmproto.Header{ Time: time.Now(), }) - } func (suite *SimTestSuite) getTestingAccounts(r *rand.Rand, n int) []simtypes.Account { diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 533be0fd1fdf..4880fa375503 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -218,7 +218,7 @@ $ %s gentx my-key-name 1000000stake --home=/path/to/home/dir --keyring-backend=o func makeOutputFilepath(rootDir, nodeID string) (string, error) { writePath := filepath.Join(rootDir, "config", "gentx") - if err := tmos.EnsureDir(writePath, 0700); err != nil { + if err := tmos.EnsureDir(writePath, 0o700); err != nil { return "", err } @@ -240,7 +240,7 @@ func readUnsignedGenTxFile(clientCtx client.Context, r io.Reader) (sdk.Tx, error } func writeSignedGenTx(clientCtx client.Context, outputDocument string, tx sdk.Tx) error { - outputFile, err := os.OpenFile(outputDocument, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644) + outputFile, err := os.OpenFile(outputDocument, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) if err != nil { return err } diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index d5004d960d5a..705af61cace3 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -87,7 +87,6 @@ func TestInitCmd(t *testing.T) { } }) } - } func TestInitRecover(t *testing.T) { @@ -286,7 +285,7 @@ func TestInitConfig(t *testing.T) { // custom tx codec func makeCodec() *codec.LegacyAmino { - var cdc = codec.NewLegacyAmino() + cdc := codec.NewLegacyAmino() sdk.RegisterLegacyAminoCodec(cdc) cryptocodec.RegisterCrypto(cdc) return cdc diff --git a/x/genutil/client/testutil/cli_test.go b/x/genutil/client/testutil/cli_test.go index dd36a6af2d3e..1035ca750264 100644 --- a/x/genutil/client/testutil/cli_test.go +++ b/x/genutil/client/testutil/cli_test.go @@ -1,3 +1,4 @@ +//go:build norace // +build norace package testutil diff --git a/x/genutil/client/testutil/validate_genesis.go b/x/genutil/client/testutil/validate_genesis.go index fe34e04bbc8a..c537dbf9dcf6 100644 --- a/x/genutil/client/testutil/validate_genesis.go +++ b/x/genutil/client/testutil/validate_genesis.go @@ -93,7 +93,6 @@ func (s *IntegrationTestSuite) TestValidateGenesis() { _, err := clitestutil.ExecTestCLICmd(val0.ClientCtx, cli.ValidateGenesisCmd(nil), []string{genesisFile.Name()}) if tc.expErr { s.Require().Contains(err.Error(), "Make sure that you have correctly migrated all Tendermint consensus params") - } else { s.Require().NoError(err) } diff --git a/x/genutil/collect.go b/x/genutil/collect.go index 8b06c12f7740..8f9fd611c764 100644 --- a/x/genutil/collect.go +++ b/x/genutil/collect.go @@ -27,7 +27,6 @@ import ( func GenAppStateFromConfig(cdc codec.JSONCodec, txEncodingConfig client.TxEncodingConfig, config *cfg.Config, initCfg types.InitConfig, genDoc tmtypes.GenesisDoc, genBalIterator types.GenesisBalancesIterator, ) (appState json.RawMessage, err error) { - // process genesis transactions, else create default genesis.json appGenTxs, persistentPeers, err := CollectTxs( cdc, txEncodingConfig.TxJSONDecoder(), config.Moniker, initCfg.GenTxsDir, genDoc, genBalIterator, diff --git a/x/genutil/collect_test.go b/x/genutil/collect_test.go index 837e16e6fc9b..c9befdd54720 100644 --- a/x/genutil/collect_test.go +++ b/x/genutil/collect_test.go @@ -45,7 +45,7 @@ func TestCollectTxsHandlesDirectories(t *testing.T) { // 1. We'll insert a directory as the first element before JSON file. subDirPath := filepath.Join(testDir, "_adir") - if err := os.MkdirAll(subDirPath, 0755); err != nil { + if err := os.MkdirAll(subDirPath, 0o755); err != nil { t.Fatal(err) } diff --git a/x/genutil/gentx.go b/x/genutil/gentx.go index 39fa600750d1..f7e4250def1d 100644 --- a/x/genutil/gentx.go +++ b/x/genutil/gentx.go @@ -18,7 +18,6 @@ import ( func SetGenTxsInAppGenesisState( cdc codec.JSONCodec, txJSONEncoder sdk.TxEncoder, appGenesisState map[string]json.RawMessage, genTxs []sdk.Tx, ) (map[string]json.RawMessage, error) { - genesisState := types.GetGenesisStateFromAppState(cdc, appGenesisState) genTxsBz := make([]json.RawMessage, 0, len(genTxs)) @@ -41,7 +40,6 @@ func ValidateAccountInGenesis( appGenesisState map[string]json.RawMessage, genBalIterator types.GenesisBalancesIterator, addr sdk.Address, coins sdk.Coins, cdc codec.JSONCodec, ) error { - var stakingData stakingtypes.GenesisState cdc.MustUnmarshalJSON(appGenesisState[stakingtypes.ModuleName], &stakingData) bondDenom := stakingData.Params.BondDenom @@ -96,7 +94,6 @@ func DeliverGenTxs( stakingKeeper types.StakingKeeper, deliverTx deliverTxfn, txEncodingConfig client.TxEncodingConfig, ) ([]abci.ValidatorUpdate, error) { - for _, genTx := range genTxs { tx, err := txEncodingConfig.TxJSONDecoder()(genTx) if err != nil { diff --git a/x/genutil/gentx_test.go b/x/genutil/gentx_test.go index f3f81af59974..a83b310c46d1 100644 --- a/x/genutil/gentx_test.go +++ b/x/genutil/gentx_test.go @@ -197,7 +197,6 @@ func (suite *GenTxTestSuite) TestValidateAccountInGenesis() { } else { suite.Require().Error(err) } - }) } } diff --git a/x/genutil/module.go b/x/genutil/module.go index 9b91849b68c0..1b70eb5a151d 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -77,7 +77,6 @@ func NewAppModule(accountKeeper types.AccountKeeper, stakingKeeper types.StakingKeeper, deliverTx deliverTxfn, txEncodingConfig client.TxEncodingConfig, ) module.AppModule { - return module.NewGenesisOnlyAppModule(AppModule{ AppModuleBasic: AppModuleBasic{}, accountKeeper: accountKeeper, diff --git a/x/genutil/types/genesis_state.go b/x/genutil/types/genesis_state.go index 4a4dc957555a..9a71d50aae69 100644 --- a/x/genutil/types/genesis_state.go +++ b/x/genutil/types/genesis_state.go @@ -57,7 +57,6 @@ func GetGenesisStateFromAppState(cdc codec.JSONCodec, appState map[string]json.R func SetGenesisStateInAppState( cdc codec.JSONCodec, appState map[string]json.RawMessage, genesisState *GenesisState, ) map[string]json.RawMessage { - genesisStateBz := cdc.MustMarshalJSON(genesisState) appState[ModuleName] = genesisStateBz return appState diff --git a/x/genutil/types/genesis_state_test.go b/x/genutil/types/genesis_state_test.go index 01e1db9fd330..9c225fd3f7c4 100644 --- a/x/genutil/types/genesis_state_test.go +++ b/x/genutil/types/genesis_state_test.go @@ -91,5 +91,4 @@ func TestGenesisStateFromGenFile(t *testing.T) { require.Equal(t, "matom", bankGenesis.DenomMetadata[0].GetDenomUnits()[1].GetDenom()) require.Equal(t, []string{"milliatom"}, bankGenesis.DenomMetadata[0].GetDenomUnits()[1].GetAliases()) require.Equal(t, uint32(3), bankGenesis.DenomMetadata[0].GetDenomUnits()[1].GetExponent()) - } diff --git a/x/genutil/utils.go b/x/genutil/utils.go index 251b0f398f0b..0b77990d7cd7 100644 --- a/x/genutil/utils.go +++ b/x/genutil/utils.go @@ -34,7 +34,6 @@ func ExportGenesisFileWithTime( genFile, chainID string, validators []tmtypes.GenesisValidator, appState json.RawMessage, genTime time.Time, ) error { - genDoc := tmtypes.GenesisDoc{ GenesisTime: genTime, ChainID: chainID, @@ -68,12 +67,12 @@ func InitializeNodeValidatorFilesFromMnemonic(config *cfg.Config, mnemonic strin nodeID = string(nodeKey.ID) pvKeyFile := config.PrivValidator.KeyFile() - if err := tmos.EnsureDir(filepath.Dir(pvKeyFile), 0777); err != nil { + if err := tmos.EnsureDir(filepath.Dir(pvKeyFile), 0o777); err != nil { return "", nil, err } pvStateFile := config.PrivValidator.StateFile() - if err := tmos.EnsureDir(filepath.Dir(pvStateFile), 0777); err != nil { + if err := tmos.EnsureDir(filepath.Dir(pvStateFile), 0o777); err != nil { return "", nil, err } diff --git a/x/genutil/utils_test.go b/x/genutil/utils_test.go index 360f930e49b9..3541e29ae386 100644 --- a/x/genutil/utils_test.go +++ b/x/genutil/utils_test.go @@ -27,7 +27,7 @@ func TestInitializeNodeValidatorFilesFromMnemonic(t *testing.T) { cfg := config.TestConfig() cfg.RootDir = t.TempDir() - require.NoError(t, os.MkdirAll(filepath.Join(cfg.RootDir, "config"), 0755)) + require.NoError(t, os.MkdirAll(filepath.Join(cfg.RootDir, "config"), 0o755)) tests := []struct { name string diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index c0f2eeaf329e..4700f8e753fa 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -234,7 +234,6 @@ $ %s query gov vote 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk if vote.Empty() { params := v1.NewQueryVoteParams(proposalID, voterAddr) resByTxQuery, err := gcutils.QueryVoteByTxQuery(clientCtx, params) - if err != nil { return err } @@ -320,13 +319,11 @@ $ %[1]s query gov votes 1 --page=2 --limit=100 ctx, &v1.QueryVotesRequest{ProposalId: proposalID, Pagination: pageReq}, ) - if err != nil { return err } return clientCtx.PrintProto(res) - }, } @@ -440,7 +437,6 @@ $ %s query gov deposits 1 ctx, &v1.QueryDepositsRequest{ProposalId: proposalID, Pagination: pageReq}, ) - if err != nil { return err } diff --git a/x/gov/client/utils/query.go b/x/gov/client/utils/query.go index 97eb7e784cf2..a624d7769556 100644 --- a/x/gov/client/utils/query.go +++ b/x/gov/client/utils/query.go @@ -298,7 +298,6 @@ func QueryVoteByTxQuery(clientCtx client.Context, params v1.QueryVoteParams) ([] // QueryDepositByTxQuery will query for a single deposit via a direct txs tags // query. func QueryDepositByTxQuery(clientCtx client.Context, params v1.QueryDepositParams) ([]byte, error) { - // initial deposit was submitted with proposal, so must be queried separately initialDeposit, err := queryInitialDepositByTxQuery(clientCtx, params.ProposalID) if err != nil { @@ -477,7 +476,6 @@ func queryInitialDepositByTxQuery(clientCtx client.Context, proposalID uint64) ( fmt.Sprintf("%s.%s='%d'", types.EventTypeSubmitProposal, types.AttributeKeyProposalID, proposalID), }, ) - if err != nil { return v1.Deposit{}, err } diff --git a/x/gov/client/utils/query_test.go b/x/gov/client/utils/query_test.go index e5b1e9b115e0..8bc1a8e42a4e 100644 --- a/x/gov/client/utils/query_test.go +++ b/x/gov/client/utils/query_test.go @@ -106,7 +106,8 @@ func TestGetPaginatedVotes(t *testing.T) { }, votes: []v1.Vote{ v1.NewVote(0, acc1, v1.NewNonSplitVoteOption(v1.OptionYes), ""), - v1.NewVote(0, acc2, v1.NewNonSplitVoteOption(v1.OptionYes), "")}, + v1.NewVote(0, acc2, v1.NewNonSplitVoteOption(v1.OptionYes), ""), + }, }, { description: "2MsgPerTx1Chunk", @@ -162,7 +163,7 @@ func TestGetPaginatedVotes(t *testing.T) { tc := tc t.Run(tc.description, func(t *testing.T) { - var marshalled = make([]tmtypes.Tx, len(tc.msgs)) + marshalled := make([]tmtypes.Tx, len(tc.msgs)) cli := TxSearchMock{txs: marshalled, txConfig: encCfg.TxConfig} clientCtx := client.Context{}. WithLegacyAmino(encCfg.Amino). diff --git a/x/gov/common_test.go b/x/gov/common_test.go index ff20ec01cb6b..d4d9bd382d4c 100644 --- a/x/gov/common_test.go +++ b/x/gov/common_test.go @@ -80,10 +80,8 @@ func SortByteArrays(src [][]byte) [][]byte { const contextKeyBadProposal = "contextKeyBadProposal" -var ( - pubkeys = []cryptotypes.PubKey{ - ed25519.GenPrivKey().PubKey(), - ed25519.GenPrivKey().PubKey(), - ed25519.GenPrivKey().PubKey(), - } -) +var pubkeys = []cryptotypes.PubKey{ + ed25519.GenPrivKey().PubKey(), + ed25519.GenPrivKey().PubKey(), + ed25519.GenPrivKey().PubKey(), +} diff --git a/x/gov/keeper/grpc_query.go b/x/gov/keeper/grpc_query.go index b1ed49010f97..3ae97a3d96a1 100644 --- a/x/gov/keeper/grpc_query.go +++ b/x/gov/keeper/grpc_query.go @@ -87,7 +87,6 @@ func (q Keeper) Proposals(c context.Context, req *v1.QueryProposalsRequest) (*v1 return false, nil }) - if err != nil { return nil, status.Error(codes.Internal, err.Error()) } @@ -149,7 +148,6 @@ func (q Keeper) Votes(c context.Context, req *v1.QueryVotesRequest) (*v1.QueryVo votes = append(votes, &vote) return nil }) - if err != nil { return nil, status.Error(codes.Internal, err.Error()) } @@ -238,7 +236,6 @@ func (q Keeper) Deposits(c context.Context, req *v1.QueryDepositsRequest) (*v1.Q deposits = append(deposits, &deposit) return nil }) - if err != nil { return nil, status.Error(codes.Internal, err.Error()) } diff --git a/x/gov/keeper/grpc_query_test.go b/x/gov/keeper/grpc_query_test.go index 14b4286eeb4e..03d93544a628 100644 --- a/x/gov/keeper/grpc_query_test.go +++ b/x/gov/keeper/grpc_query_test.go @@ -315,9 +315,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryProposals() { func (suite *KeeperTestSuite) TestLegacyGRPCQueryProposals() { app, ctx, queryClient := suite.app, suite.ctx, suite.legacyQueryClient - var ( - req *v1beta1.QueryProposalsRequest - ) + var req *v1beta1.QueryProposalsRequest testCases := []struct { msg string diff --git a/x/gov/keeper/hooks_test.go b/x/gov/keeper/hooks_test.go index 89a6a641e126..19be117333ba 100644 --- a/x/gov/keeper/hooks_test.go +++ b/x/gov/keeper/hooks_test.go @@ -37,9 +37,11 @@ func (h *MockGovHooksReceiver) AfterProposalDeposit(ctx sdk.Context, proposalID func (h *MockGovHooksReceiver) AfterProposalVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.AccAddress) { h.AfterProposalVoteValid = true } + func (h *MockGovHooksReceiver) AfterProposalFailedMinDeposit(ctx sdk.Context, proposalID uint64) { h.AfterProposalFailedMinDepositValid = true } + func (h *MockGovHooksReceiver) AfterProposalVotingPeriodEnded(ctx sdk.Context, proposalID uint64) { h.AfterProposalVotingPeriodEndedValid = true } diff --git a/x/gov/keeper/keeper.go b/x/gov/keeper/keeper.go index bb4491eeb329..67b68047d2ac 100644 --- a/x/gov/keeper/keeper.go +++ b/x/gov/keeper/keeper.go @@ -58,7 +58,6 @@ func NewKeeper( legacyRouter v1beta1.Router, router *middleware.MsgServiceRouter, config types.Config, ) Keeper { - // ensure governance module account is set if addr := authKeeper.GetModuleAddress(types.ModuleName); addr == nil { panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) diff --git a/x/gov/keeper/msg_server.go b/x/gov/keeper/msg_server.go index a74dc78c847c..8800d2d79eca 100644 --- a/x/gov/keeper/msg_server.go +++ b/x/gov/keeper/msg_server.go @@ -105,7 +105,6 @@ func (k msgServer) ExecLegacyContent(goCtx context.Context, msg *v1.MsgExecLegac } return &v1.MsgExecLegacyContentResponse{}, nil - } func (k msgServer) Vote(goCtx context.Context, msg *v1.MsgVote) (*v1.MsgVoteResponse, error) { diff --git a/x/gov/keeper/querier_test.go b/x/gov/keeper/querier_test.go index 54a3e9fec49a..d47d87f2a256 100644 --- a/x/gov/keeper/querier_test.go +++ b/x/gov/keeper/querier_test.go @@ -64,7 +64,6 @@ func getQueriedProposals( t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, depositor, voter sdk.AccAddress, status v1.ProposalStatus, page, limit int, ) []*v1.Proposal { - query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, v1.QueryProposals}, "/"), Data: cdc.MustMarshalJSON(v1.NewQueryProposalsParams(page, limit, status, voter, depositor)), @@ -128,8 +127,7 @@ func getQueriedVote(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, queri return vote } -func getQueriedVotes(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, - proposalID uint64, page, limit int) []v1.Vote { +func getQueriedVotes(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, proposalID uint64, page, limit int) []v1.Vote { query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, v1.QueryVote}, "/"), Data: cdc.MustMarshalJSON(v1.NewQueryProposalVotesParams(proposalID, page, limit)), diff --git a/x/gov/keeper/tally.go b/x/gov/keeper/tally.go index 6b2b51f257e3..3f1dd10ec7dd 100644 --- a/x/gov/keeper/tally.go +++ b/x/gov/keeper/tally.go @@ -36,7 +36,6 @@ func (keeper Keeper) Tally(ctx sdk.Context, proposal v1.Proposal) (passes bool, keeper.IterateVotes(ctx, proposal.Id, func(vote v1.Vote) bool { // if validator, just record it in the map voter, err := sdk.AccAddressFromBech32(vote.Voter) - if err != nil { panic(err) } diff --git a/x/gov/migrations/v046/convert_test.go b/x/gov/migrations/v046/convert_test.go index e8cbfedc2670..64375e796aef 100644 --- a/x/gov/migrations/v046/convert_test.go +++ b/x/gov/migrations/v046/convert_test.go @@ -171,5 +171,4 @@ func TestConvertToLegacyDeposit(t *testing.T) { require.Equal(t, v1beta1Deposit.ProposalId, deposit.ProposalId) require.Equal(t, v1beta1Deposit.Depositor, deposit.Depositor) require.Equal(t, v1beta1Deposit.Amount[0], deposit.Amount[0]) - } diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 5963a2d2e6b7..289c9413d6cd 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -39,7 +39,6 @@ func WeightedOperations( appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, wContents []simtypes.WeightedProposalContent, ) simulation.WeightedOperations { - var ( weightMsgDeposit int weightMsgVote int @@ -278,7 +277,8 @@ func SimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keepe } func operationSimulateMsgVote(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, - simAccount simtypes.Account, proposalIDInt int64) simtypes.Operation { + simAccount simtypes.Account, proposalIDInt int64, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -331,7 +331,8 @@ func SimulateMsgVoteWeighted(ak types.AccountKeeper, bk types.BankKeeper, k keep } func operationSimulateMsgVoteWeighted(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, - simAccount simtypes.Account, proposalIDInt int64) simtypes.Operation { + simAccount simtypes.Account, proposalIDInt int64, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, @@ -419,7 +420,8 @@ func randomDeposit(r *rand.Rand, ctx sdk.Context, // that matches a given Status. // It does not provide a default ID. func randomProposalID(r *rand.Rand, k keeper.Keeper, - ctx sdk.Context, status v1.ProposalStatus) (proposalID uint64, found bool) { + ctx sdk.Context, status v1.ProposalStatus, +) (proposalID uint64, found bool) { proposalID, _ = k.GetProposalID(ctx) switch { diff --git a/x/gov/simulation/operations_test.go b/x/gov/simulation/operations_test.go index 3ef0acb9bd49..59c19d870707 100644 --- a/x/gov/simulation/operations_test.go +++ b/x/gov/simulation/operations_test.go @@ -50,10 +50,8 @@ func mockWeightedProposalContent(n int) []simtypes.WeightedProposalContent { wpc := make([]simtypes.WeightedProposalContent, n) for i := 0; i < n; i++ { wpc[i] = MockWeightedProposalContent{i} - } return wpc - } // TestWeightedOperations tests the weights of the operations. diff --git a/x/gov/types/hooks.go b/x/gov/types/hooks.go index e90b19a08395..0a361687d9d2 100644 --- a/x/gov/types/hooks.go +++ b/x/gov/types/hooks.go @@ -30,11 +30,13 @@ func (h MultiGovHooks) AfterProposalVote(ctx sdk.Context, proposalID uint64, vot h[i].AfterProposalVote(ctx, proposalID, voterAddr) } } + func (h MultiGovHooks) AfterProposalFailedMinDeposit(ctx sdk.Context, proposalID uint64) { for i := range h { h[i].AfterProposalFailedMinDeposit(ctx, proposalID) } } + func (h MultiGovHooks) AfterProposalVotingPeriodEnded(ctx sdk.Context, proposalID uint64) { for i := range h { h[i].AfterProposalVotingPeriodEnded(ctx, proposalID) diff --git a/x/gov/types/keys_test.go b/x/gov/types/keys_test.go index 30266f8f4d78..351863e9bfe4 100644 --- a/x/gov/types/keys_test.go +++ b/x/gov/types/keys_test.go @@ -37,7 +37,6 @@ func TestProposalKeys(t *testing.T) { } func TestDepositKeys(t *testing.T) { - key := DepositsKey(2) proposalID := SplitProposalKey(key) require.Equal(t, int(proposalID), 2) @@ -49,7 +48,6 @@ func TestDepositKeys(t *testing.T) { } func TestVoteKeys(t *testing.T) { - key := VotesKey(2) proposalID := SplitProposalKey(key) require.Equal(t, int(proposalID), 2) diff --git a/x/gov/types/v1/genesis_test.go b/x/gov/types/v1/genesis_test.go index eced37795567..16b90087833f 100644 --- a/x/gov/types/v1/genesis_test.go +++ b/x/gov/types/v1/genesis_test.go @@ -74,7 +74,6 @@ func TestValidateGenesis(t *testing.T) { for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { - err := v1.ValidateGenesis(tc.genesisState) if tc.expErr { require.Error(t, err) diff --git a/x/gov/types/v1/proposal.go b/x/gov/types/v1/proposal.go index 514968bf85a4..63982fef0432 100644 --- a/x/gov/types/v1/proposal.go +++ b/x/gov/types/v1/proposal.go @@ -24,7 +24,6 @@ const ( // NewProposal creates a new Proposal instance func NewProposal(messages []sdk.Msg, id uint64, metadata string, submitTime, depositEndTime time.Time) (Proposal, error) { - msgs, err := sdktx.SetMsgs(messages) if err != nil { return Proposal{}, err diff --git a/x/gov/types/v1/tally.go b/x/gov/types/v1/tally.go index cadb33f024e8..6613f640f6e5 100644 --- a/x/gov/types/v1/tally.go +++ b/x/gov/types/v1/tally.go @@ -15,8 +15,8 @@ type ValidatorGovInfo struct { // NewValidatorGovInfo creates a ValidatorGovInfo instance func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens sdk.Int, delegatorShares, - delegatorDeductions sdk.Dec, options WeightedVoteOptions) ValidatorGovInfo { - + delegatorDeductions sdk.Dec, options WeightedVoteOptions, +) ValidatorGovInfo { return ValidatorGovInfo{ Address: address, BondedTokens: bondedTokens, diff --git a/x/gov/types/v1beta1/msgs.go b/x/gov/types/v1beta1/msgs.go index cd5d886aed9c..9083ae9435cf 100644 --- a/x/gov/types/v1beta1/msgs.go +++ b/x/gov/types/v1beta1/msgs.go @@ -2,6 +2,7 @@ package v1beta1 import ( "fmt" + "github.com/gogo/protobuf/proto" "sigs.k8s.io/yaml" diff --git a/x/gov/types/v1beta1/tally.go b/x/gov/types/v1beta1/tally.go index c0f09a88ba0b..616ca6b7bb7c 100644 --- a/x/gov/types/v1beta1/tally.go +++ b/x/gov/types/v1beta1/tally.go @@ -17,8 +17,8 @@ type ValidatorGovInfo struct { // NewValidatorGovInfo creates a ValidatorGovInfo instance func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens sdk.Int, delegatorShares, - delegatorDeductions sdk.Dec, options WeightedVoteOptions) ValidatorGovInfo { - + delegatorDeductions sdk.Dec, options WeightedVoteOptions, +) ValidatorGovInfo { return ValidatorGovInfo{ Address: address, BondedTokens: bondedTokens, diff --git a/x/group/client/testutil/query.go b/x/group/client/testutil/query.go index f9562dfe7190..74c152b50978 100644 --- a/x/group/client/testutil/query.go +++ b/x/group/client/testutil/query.go @@ -770,7 +770,7 @@ func (s *IntegrationTestSuite) TestTallyResult() { member := s.voter - var commonFlags = []string{ + commonFlags := []string{ fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), @@ -872,5 +872,4 @@ func (s *IntegrationTestSuite) TestTallyResult() { } }) } - } diff --git a/x/group/client/testutil/tx.go b/x/group/client/testutil/tx.go index 07c7413ddae2..1458dc4fd338 100644 --- a/x/group/client/testutil/tx.go +++ b/x/group/client/testutil/tx.go @@ -108,7 +108,7 @@ func (s *IntegrationTestSuite) SetupSuite() { ) s.Require().NoError(err, out.String()) - var txResp = sdk.TxResponse{} + txResp := sdk.TxResponse{} s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) s.Require().Equal(uint32(0), txResp.Code, out.String()) @@ -213,6 +213,7 @@ func (s *IntegrationTestSuite) TestTxCreateGroup() { val := s.network.Validators[0] clientCtx := val.ClientCtx + validMembers := fmt.Sprintf(`{"members": [{ "address": "%s", "weight": "1", @@ -365,6 +366,7 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupAdmin() { clientCtx := val.ClientCtx require := s.Require() + groupIDs := make([]string, 2) for i := 0; i < 2; i++ { validMembers := fmt.Sprintf(`{"members": [{ @@ -485,6 +487,7 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupMetadata() { val := s.network.Validators[0] clientCtx := val.ClientCtx + testCases := []struct { name string args []string @@ -565,6 +568,7 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupMembers() { val := s.network.Validators[0] clientCtx := val.ClientCtx + weights := []string{"1", "1", "1"} accounts := s.createAccounts(3) @@ -687,6 +691,9 @@ func (s *IntegrationTestSuite) TestTxCreateGroupWithPolicy() { val := s.network.Validators[0] clientCtx := val.ClientCtx + + + validMembers := fmt.Sprintf(`{"members": [{ "address": "%s", "weight": "1", @@ -892,6 +899,7 @@ func (s *IntegrationTestSuite) TestTxCreateGroupPolicy() { wrongAdmin := s.network.Validators[1].Address clientCtx := val.ClientCtx + groupID := s.group.Id testCases := []struct { @@ -1059,6 +1067,7 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupPolicyAdmin() { clientCtx := val.ClientCtx groupPolicy := s.groupPolicies[3] + commonFlags := s.commonFlags commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) @@ -1159,6 +1168,7 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupPolicyDecisionPolicy() { clientCtx := val.ClientCtx groupPolicy := s.groupPolicies[2] + commonFlags := s.commonFlags commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) @@ -1304,6 +1314,7 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupPolicyMetadata() { clientCtx := val.ClientCtx groupPolicy := s.groupPolicies[2] + commonFlags := s.commonFlags commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) @@ -1417,6 +1428,7 @@ func (s *IntegrationTestSuite) TestTxSubmitProposal() { val := s.network.Validators[0] clientCtx := val.ClientCtx + testCases := []struct { name string args []string @@ -1605,6 +1617,7 @@ func (s *IntegrationTestSuite) TestTxVote() { val := s.network.Validators[0] clientCtx := val.ClientCtx + ids := make([]string, 4) weights := []string{"1", "1", "1"} accounts := s.createAccounts(3) @@ -1798,6 +1811,7 @@ func (s *IntegrationTestSuite) TestTxWithdrawProposal() { val := s.network.Validators[0] clientCtx := val.ClientCtx + ids := make([]string, 2) for i := 0; i < 2; i++ { @@ -1940,6 +1954,7 @@ func (s *IntegrationTestSuite) TestTxExec() { clientCtx := val.ClientCtx require := s.Require() + var proposalIDs []string // create proposals and vote for i := 0; i < 2; i++ { diff --git a/x/group/genesis_test.go b/x/group/genesis_test.go index 99f7a008fa37..cf43ed699d41 100644 --- a/x/group/genesis_test.go +++ b/x/group/genesis_test.go @@ -18,7 +18,6 @@ var ( ) func TestGenesisStateValidate(t *testing.T) { - submittedAt := time.Now().UTC() timeout := submittedAt.Add(time.Second * 1).UTC() @@ -737,7 +736,6 @@ func TestGenesisStateValidate(t *testing.T) { for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { - err := tc.genesisState.Validate() if tc.expErr { require.Error(t, err) diff --git a/x/group/internal/orm/indexer_test.go b/x/group/internal/orm/indexer_test.go index d574fb63fd04..79278418c924 100644 --- a/x/group/internal/orm/indexer_test.go +++ b/x/group/internal/orm/indexer_test.go @@ -239,6 +239,7 @@ func TestIndexerOnDelete(t *testing.T) { }) } } + func TestIndexerOnUpdate(t *testing.T) { myRowID := EncodeSequence(1) @@ -377,7 +378,6 @@ func TestUniqueKeyAddFunc(t *testing.T) { expErr *sdkerrors.Error expExistingEntry []byte }{ - "create when not exists": { srcKey: []byte("my-index-key"), expExistingEntry: append(AddLengthPrefix([]byte("my-index-key")), myRowID...), @@ -421,7 +421,6 @@ func TestMultiKeyAddFunc(t *testing.T) { expErr *sdkerrors.Error expExistingEntry []byte }{ - "create when not exists": { srcKey: []byte("my-index-key"), expExistingEntry: append(AddLengthPrefix([]byte("my-index-key")), myRowID...), diff --git a/x/group/internal/orm/iterator.go b/x/group/internal/orm/iterator.go index ae61d61c48e4..71c3b32272ae 100644 --- a/x/group/internal/orm/iterator.go +++ b/x/group/internal/orm/iterator.go @@ -155,7 +155,7 @@ func Paginate( return nil, err } - var end = offset + limit + end := offset + limit var count uint64 var nextKey []byte for { diff --git a/x/group/internal/orm/iterator_test.go b/x/group/internal/orm/iterator_test.go index b2abbaaa403c..bbafa34a11f7 100644 --- a/x/group/internal/orm/iterator_test.go +++ b/x/group/internal/orm/iterator_test.go @@ -317,7 +317,6 @@ func TestPaginate(t *testing.T) { assert.EqualValues(t, spec.expPageRes.Total, res.Total) assert.EqualValues(t, spec.expPageRes.NextKey, res.NextKey) } - }) } diff --git a/x/group/internal/orm/primary_key_test.go b/x/group/internal/orm/primary_key_test.go index 498e973c0c98..66adb3240d1c 100644 --- a/x/group/internal/orm/primary_key_test.go +++ b/x/group/internal/orm/primary_key_test.go @@ -223,7 +223,6 @@ func TestContains(t *testing.T) { src PrimaryKeyed exp bool }{ - "same object": {src: &obj, exp: true}, "clone": { src: &testdata.TableModel{ diff --git a/x/group/internal/orm/table.go b/x/group/internal/orm/table.go index 89e6a8db1a0d..a25615a965a4 100644 --- a/x/group/internal/orm/table.go +++ b/x/group/internal/orm/table.go @@ -149,7 +149,7 @@ func assertValid(obj codec.ProtoMarshaler) error { func (a table) Delete(store sdk.KVStore, rowID RowID) error { pStore := prefix.NewStore(store, a.prefix[:]) - var oldValue = reflect.New(a.model).Interface().(codec.ProtoMarshaler) + oldValue := reflect.New(a.model).Interface().(codec.ProtoMarshaler) if err := a.GetOne(store, rowID, oldValue); err != nil { return sdkerrors.Wrap(err, "load old value") } diff --git a/x/group/internal/orm/table_test.go b/x/group/internal/orm/table_test.go index 44146c7fea8f..164fecda3648 100644 --- a/x/group/internal/orm/table_test.go +++ b/x/group/internal/orm/table_test.go @@ -97,7 +97,7 @@ func TestCreate(t *testing.T) { ctx := NewMockContext() store := ctx.KVStore(sdk.NewKVStoreKey("test")) - var anyPrefix = [2]byte{0x10} + anyPrefix := [2]byte{0x10} myTable, err := newTable(anyPrefix, &testdata.TableModel{}, cdc) require.NoError(t, err) @@ -154,7 +154,7 @@ func TestUpdate(t *testing.T) { ctx := NewMockContext() store := ctx.KVStore(sdk.NewKVStoreKey("test")) - var anyPrefix = [2]byte{0x10} + anyPrefix := [2]byte{0x10} myTable, err := newTable(anyPrefix, &testdata.TableModel{}, cdc) require.NoError(t, err) @@ -203,7 +203,7 @@ func TestDelete(t *testing.T) { ctx := NewMockContext() store := ctx.KVStore(sdk.NewKVStoreKey("test")) - var anyPrefix = [2]byte{0x10} + anyPrefix := [2]byte{0x10} myTable, err := newTable(anyPrefix, &testdata.TableModel{}, cdc) require.NoError(t, err) diff --git a/x/group/internal/orm/types_test.go b/x/group/internal/orm/types_test.go index 9ef2472611c9..130f31bdde95 100644 --- a/x/group/internal/orm/types_test.go +++ b/x/group/internal/orm/types_test.go @@ -18,7 +18,7 @@ import ( func TestTypeSafeRowGetter(t *testing.T) { storeKey := sdk.NewKVStoreKey("test") ctx := NewMockContext() - var prefixKey = [2]byte{0x2} + prefixKey := [2]byte{0x2} store := prefix.NewStore(ctx.KVStore(storeKey), prefixKey[:]) md := testdata.TableModel{ Id: 1, diff --git a/x/group/keeper/genesis.go b/x/group/keeper/genesis.go index 311809de39c1..2e0766ed716e 100644 --- a/x/group/keeper/genesis.go +++ b/x/group/keeper/genesis.go @@ -40,7 +40,6 @@ func (k Keeper) InitGenesis(ctx types.Context, cdc codec.JSONCodec, data json.Ra } return []abci.ValidatorUpdate{} - } func (k Keeper) ExportGenesis(ctx types.Context, cdc codec.JSONCodec) *group.GenesisState { diff --git a/x/group/keeper/genesis_test.go b/x/group/keeper/genesis_test.go index af0e8497723a..59a101bf3c09 100644 --- a/x/group/keeper/genesis_test.go +++ b/x/group/keeper/genesis_test.go @@ -2,7 +2,6 @@ package keeper_test import ( "context" - "encoding/json" "testing" "time" @@ -192,7 +191,6 @@ func (s *GenesisTestSuite) TestInitExportGenesis() { s.Require().Equal(genesisState.GroupSeq, exportedGenesisState.GroupSeq) s.Require().Equal(genesisState.GroupPolicySeq, exportedGenesisState.GroupPolicySeq) s.Require().Equal(genesisState.ProposalSeq, exportedGenesisState.ProposalSeq) - } func (s *GenesisTestSuite) assertGroupPoliciesEqual(g *group.GroupPolicyInfo, other *group.GroupPolicyInfo) { diff --git a/x/group/keeper/invariants.go b/x/group/keeper/invariants.go index 139991e00dfa..2008fd3c9347 100644 --- a/x/group/keeper/invariants.go +++ b/x/group/keeper/invariants.go @@ -28,7 +28,6 @@ func GroupTotalWeightInvariant(keeper Keeper) sdk.Invariant { } func GroupTotalWeightInvariantHelper(ctx sdk.Context, key storetypes.StoreKey, groupTable orm.AutoUInt64Table, groupMemberByGroupIndex orm.Index) (string, bool) { - var msg string var broken bool diff --git a/x/group/keeper/invariants_test.go b/x/group/keeper/invariants_test.go index c21565203dd8..013f5e3a651b 100644 --- a/x/group/keeper/invariants_test.go +++ b/x/group/keeper/invariants_test.go @@ -47,7 +47,6 @@ func (s *invariantTestSuite) SetupSuite() { s.ctx = sdkCtx s.cdc = cdc s.key = key - } func (s *invariantTestSuite) TestGroupTotalWeightInvariant() { diff --git a/x/group/keeper/keeper.go b/x/group/keeper/keeper.go index 55cdd9de64bb..c61355c17201 100644 --- a/x/group/keeper/keeper.go +++ b/x/group/keeper/keeper.go @@ -211,7 +211,6 @@ func NewKeeper(storeKey storetypes.StoreKey, cdc codec.Codec, router *authmiddle k.config = config return k - } // Logger returns a module-specific logger. @@ -228,7 +227,6 @@ func (k Keeper) GetGroupSequence(ctx sdk.Context) uint64 { func (k Keeper) iterateProposalsByVPEnd(ctx sdk.Context, endTime time.Time, cb func(proposal group.Proposal) (bool, error)) error { timeBytes := sdk.FormatTimeBytes(endTime) it, err := k.proposalsByVotingPeriodEnd.PrefixScan(ctx.KVStore(k.key), nil, timeBytes) - if err != nil { return err } diff --git a/x/group/keeper/keeper_test.go b/x/group/keeper/keeper_test.go index 578718a7a9cc..84ee34bcdf81 100644 --- a/x/group/keeper/keeper_test.go +++ b/x/group/keeper/keeper_test.go @@ -222,7 +222,6 @@ func (s *TestSuite) TestCreateGroup() { } }) } - } func (s *TestSuite) TestUpdateGroupAdmin() { @@ -864,7 +863,6 @@ func (s *TestSuite) TestCreateGroupWithPolicy() { } }) } - } func (s *TestSuite) TestCreateGroupPolicy() { @@ -2831,6 +2829,7 @@ func (s *TestSuite) TestLeaveGroup() { } } + func (s *TestSuite) TestPruneProposals() { addrs := s.addrs expirationTime := time.Hour * 24 * 15 // 15 days @@ -2880,7 +2879,8 @@ func (s *TestSuite) TestPruneProposals() { func submitProposal( ctx context.Context, s *TestSuite, msgs []sdk.Msg, - proposers []string) uint64 { + proposers []string, +) uint64 { proposalReq := &group.MsgSubmitProposal{ GroupPolicyAddress: s.groupPolicyAddr.String(), Proposers: proposers, @@ -2895,7 +2895,8 @@ func submitProposal( func submitProposalAndVote( ctx context.Context, s *TestSuite, msgs []sdk.Msg, - proposers []string, voteOption group.VoteOption) uint64 { + proposers []string, voteOption group.VoteOption, +) uint64 { s.Require().Greater(len(proposers), 0) myProposalID := submitProposal(ctx, s, msgs, proposers) diff --git a/x/group/keeper/msg_server.go b/x/group/keeper/msg_server.go index 81c56d43b072..6a25c5dce3f1 100644 --- a/x/group/keeper/msg_server.go +++ b/x/group/keeper/msg_server.go @@ -105,7 +105,8 @@ func (k Keeper) UpdateGroupMembers(goCtx context.Context, req *group.MsgUpdateGr if err := k.assertMetadataLength(req.MemberUpdates[i].Metadata, "group member metadata"); err != nil { return err } - groupMember := group.GroupMember{GroupId: req.GroupId, + groupMember := group.GroupMember{ + GroupId: req.GroupId, Member: &group.Member{ Address: req.MemberUpdates[i].Address, Weight: req.MemberUpdates[i].Weight, @@ -333,7 +334,7 @@ func (k Keeper) CreateGroupPolicy(goCtx context.Context, req *group.MsgCreateGro // collision with an existing address. for { nextAccVal := k.groupPolicySeq.NextVal(ctx.KVStore(k.key)) - var buf = make([]byte, 8) + buf := make([]byte, 8) binary.BigEndian.PutUint64(buf, nextAccVal) parentAcc := address.Module(group.ModuleName, []byte{GroupPolicyTablePrefix}) @@ -871,8 +872,10 @@ type authNGroupReq interface { GetAdmin() string } -type actionFn func(m *group.GroupInfo) error -type groupPolicyActionFn func(m *group.GroupPolicyInfo) error +type ( + actionFn func(m *group.GroupInfo) error + groupPolicyActionFn func(m *group.GroupPolicyInfo) error +) // doUpdateGroupPolicy first makes sure that the group policy admin initiated the group policy update, // before performing the group policy update and emitting an event. diff --git a/x/group/module/abci_test.go b/x/group/module/abci_test.go index e46767f0f492..fd298c14b54d 100644 --- a/x/group/module/abci_test.go +++ b/x/group/module/abci_test.go @@ -315,7 +315,6 @@ func TestEndBlockerPruning(t *testing.T) { } }) } - } func TestEndBlockerTallying(t *testing.T) { @@ -505,9 +504,7 @@ func TestEndBlockerTallying(t *testing.T) { } } -func submitProposal( - app *simapp.SimApp, ctx context.Context, msgs []sdk.Msg, - proposers []string, groupPolicyAddr sdk.AccAddress) (uint64, error) { +func submitProposal(app *simapp.SimApp, ctx context.Context, msgs []sdk.Msg, proposers []string, groupPolicyAddr sdk.AccAddress) (uint64, error) { proposalReq := &group.MsgSubmitProposal{ GroupPolicyAddress: groupPolicyAddr.String(), Proposers: proposers, @@ -527,7 +524,8 @@ func submitProposal( func submitProposalAndVote( app *simapp.SimApp, ctx context.Context, msgs []sdk.Msg, - proposers []string, groupPolicyAddr sdk.AccAddress, voteOption group.VoteOption) (uint64, error) { + proposers []string, groupPolicyAddr sdk.AccAddress, voteOption group.VoteOption, +) (uint64, error) { myProposalID, err := submitProposal(app, ctx, msgs, proposers, groupPolicyAddr) if err != nil { return 0, err diff --git a/x/group/msgs.go b/x/group/msgs.go index 18d13539af68..04d52903240b 100644 --- a/x/group/msgs.go +++ b/x/group/msgs.go @@ -139,7 +139,6 @@ func (m MsgUpdateGroupMetadata) GetSigners() []sdk.AccAddress { func (m MsgUpdateGroupMetadata) ValidateBasic() error { if m.GroupId == 0 { return sdkerrors.Wrap(errors.ErrEmpty, "group id") - } _, err := sdk.AccAddressFromBech32(m.Admin) if err != nil { @@ -183,7 +182,6 @@ func (m MsgUpdateGroupMembers) GetSigners() []sdk.AccAddress { func (m MsgUpdateGroupMembers) ValidateBasic() error { if m.GroupId == 0 { return sdkerrors.Wrap(errors.ErrEmpty, "group id") - } _, err := sdk.AccAddressFromBech32(m.Admin) if err != nil { @@ -204,8 +202,10 @@ func (m *MsgUpdateGroupMembers) GetGroupID() uint64 { return m.GroupId } -var _ sdk.Msg = &MsgCreateGroupWithPolicy{} -var _ types.UnpackInterfacesMessage = MsgCreateGroupWithPolicy{} +var ( + _ sdk.Msg = &MsgCreateGroupWithPolicy{} + _ types.UnpackInterfacesMessage = MsgCreateGroupWithPolicy{} +) // NewMsgCreateGroupWithPolicy creates a new MsgCreateGroupWithPolicy. func NewMsgCreateGroupWithPolicy(admin string, members []MemberRequest, groupMetadata string, groupPolicyMetadata string, groupPolicyAsAdmin bool, decisionPolicy DecisionPolicy) (*MsgCreateGroupWithPolicy, error) { @@ -379,8 +379,10 @@ func (m MsgUpdateGroupPolicyAdmin) ValidateBasic() error { return nil } -var _ sdk.Msg = &MsgUpdateGroupPolicyDecisionPolicy{} -var _ types.UnpackInterfacesMessage = MsgUpdateGroupPolicyDecisionPolicy{} +var ( + _ sdk.Msg = &MsgUpdateGroupPolicyDecisionPolicy{} + _ types.UnpackInterfacesMessage = MsgUpdateGroupPolicyDecisionPolicy{} +) // NewMsgUpdateGroupPolicyDecisionPolicy creates a new MsgUpdateGroupPolicyDecisionPolicy. func NewMsgUpdateGroupPolicyDecisionPolicy(admin sdk.AccAddress, address sdk.AccAddress, decisionPolicy DecisionPolicy) (*MsgUpdateGroupPolicyDecisionPolicy, error) { @@ -510,8 +512,10 @@ func (m MsgUpdateGroupPolicyMetadata) ValidateBasic() error { return nil } -var _ sdk.Msg = &MsgCreateGroupPolicy{} -var _ types.UnpackInterfacesMessage = MsgCreateGroupPolicy{} +var ( + _ sdk.Msg = &MsgCreateGroupPolicy{} + _ types.UnpackInterfacesMessage = MsgCreateGroupPolicy{} +) // NewMsgCreateGroupPolicy creates a new MsgCreateGroupPolicy. func NewMsgCreateGroupPolicy(admin sdk.AccAddress, group uint64, metadata string, decisionPolicy DecisionPolicy) (*MsgCreateGroupPolicy, error) { diff --git a/x/group/proposal.go b/x/group/proposal.go index e76c05ac283c..3b3870af2829 100644 --- a/x/group/proposal.go +++ b/x/group/proposal.go @@ -8,7 +8,6 @@ import ( func (p *Proposal) GetMsgs() ([]sdk.Msg, error) { return tx.GetMsgs(p.Messages, "proposal") - } func (p *Proposal) SetMsgs(msgs []sdk.Msg) error { diff --git a/x/group/simulation/genesis.go b/x/group/simulation/genesis.go index 59040a502f60..7f30a4fc7303 100644 --- a/x/group/simulation/genesis.go +++ b/x/group/simulation/genesis.go @@ -147,7 +147,6 @@ func getVoteOption(index int) group.VoteOption { // RandomizedGenState generates a random GenesisState for the group module. func RandomizedGenState(simState *module.SimulationState) { - // groups var groups []*group.GroupInfo simState.AppParams.GetOrGenerate( diff --git a/x/group/simulation/genesis_test.go b/x/group/simulation/genesis_test.go index 03d660bf66ab..f87a5eb18f13 100644 --- a/x/group/simulation/genesis_test.go +++ b/x/group/simulation/genesis_test.go @@ -43,5 +43,4 @@ func TestRandomizedGenState(t *testing.T) { require.Equal(t, int(groupGenesis.ProposalSeq), len(simState.Accounts)) require.Len(t, groupGenesis.Proposals, len(simState.Accounts)) require.Len(t, groupGenesis.Votes, len(simState.Accounts)) - } diff --git a/x/group/simulation/operations.go b/x/group/simulation/operations.go index d06570cc04fd..f541393771a3 100644 --- a/x/group/simulation/operations.go +++ b/x/group/simulation/operations.go @@ -81,7 +81,8 @@ const ( // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( appParams simtypes.AppParams, cdc codec.JSONCodec, ak group.AccountKeeper, - bk group.BankKeeper, k keeper.Keeper, appCdc cdctypes.AnyUnpacker) simulation.WeightedOperations { + bk group.BankKeeper, k keeper.Keeper, appCdc cdctypes.AnyUnpacker, +) simulation.WeightedOperations { var ( weightMsgCreateGroup int weightMsgUpdateGroupAdmin int @@ -243,7 +244,8 @@ func WeightedOperations( // SimulateMsgCreateGroup generates a MsgCreateGroup with random values func SimulateMsgCreateGroup(ak group.AccountKeeper, bk group.BankKeeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simtypes.Account, chainID string) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { acc, _ := simtypes.RandomAcc(r, accounts) account := ak.GetAccount(ctx, acc.Address) accAddr := acc.Address.String() @@ -284,7 +286,8 @@ func SimulateMsgCreateGroup(ak group.AccountKeeper, bk group.BankKeeper) simtype // SimulateMsgCreateGroupWithPolicy generates a MsgCreateGroupWithPolicy with random values func SimulateMsgCreateGroupWithPolicy(ak group.AccountKeeper, bk group.BankKeeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simtypes.Account, chainID string) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { acc, _ := simtypes.RandomAcc(r, accounts) account := ak.GetAccount(ctx, acc.Address) accAddr := acc.Address.String() @@ -342,7 +345,8 @@ func SimulateMsgCreateGroupWithPolicy(ak group.AccountKeeper, bk group.BankKeepe // SimulateMsgCreateGroupPolicy generates a NewMsgCreateGroupPolicy with random values func SimulateMsgCreateGroupPolicy(ak group.AccountKeeper, bk group.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { groupInfo, acc, account, err := randomGroup(r, k, ak, sdkCtx, accounts) if err != nil { return simtypes.NoOpMsg(group.ModuleName, TypeMsgCreateGroupPolicy, ""), nil, err @@ -401,7 +405,8 @@ func SimulateMsgCreateGroupPolicy(ak group.AccountKeeper, bk group.BankKeeper, k // SimulateMsgSubmitProposal generates a NewMsgSubmitProposal with random values func SimulateMsgSubmitProposal(ak group.AccountKeeper, bk group.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { g, groupPolicy, _, _, err := randomGroupPolicy(r, k, ak, sdkCtx, accounts) if err != nil { return simtypes.NoOpMsg(group.ModuleName, TypeMsgSubmitProposal, ""), nil, err @@ -474,7 +479,8 @@ func SimulateMsgSubmitProposal(ak group.AccountKeeper, bk group.BankKeeper, k ke // SimulateMsgUpdateGroupAdmin generates a MsgUpdateGroupAdmin with random values func SimulateMsgUpdateGroupAdmin(ak group.AccountKeeper, bk group.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { groupInfo, acc, account, err := randomGroup(r, k, ak, sdkCtx, accounts) if err != nil { return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupAdmin, ""), nil, err @@ -532,7 +538,8 @@ func SimulateMsgUpdateGroupAdmin(ak group.AccountKeeper, bk group.BankKeeper, k // SimulateMsgUpdateGroupMetadata generates a MsgUpdateGroupMetadata with random values func SimulateMsgUpdateGroupMetadata(ak group.AccountKeeper, bk group.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { groupInfo, acc, account, err := randomGroup(r, k, ak, sdkCtx, accounts) if err != nil { return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupMetadata, ""), nil, err @@ -580,9 +587,11 @@ func SimulateMsgUpdateGroupMetadata(ak group.AccountKeeper, bk group.BankKeeper, // SimulateMsgUpdateGroupMembers generates a MsgUpdateGroupMembers with random values func SimulateMsgUpdateGroupMembers(ak group.AccountKeeper, - bk group.BankKeeper, k keeper.Keeper) simtypes.Operation { + bk group.BankKeeper, k keeper.Keeper, +) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { groupInfo, acc, account, err := randomGroup(r, k, ak, sdkCtx, accounts) if err != nil { return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupMembers, ""), nil, err @@ -658,7 +667,8 @@ func SimulateMsgUpdateGroupMembers(ak group.AccountKeeper, // SimulateMsgUpdateGroupPolicyAdmin generates a MsgUpdateGroupPolicyAdmin with random values func SimulateMsgUpdateGroupPolicyAdmin(ak group.AccountKeeper, bk group.BankKeeper, k keeper.Keeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { _, groupPolicy, acc, account, err := randomGroupPolicy(r, k, ak, sdkCtx, accounts) if err != nil { return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyAdmin, ""), nil, err @@ -715,9 +725,11 @@ func SimulateMsgUpdateGroupPolicyAdmin(ak group.AccountKeeper, bk group.BankKeep // // SimulateMsgUpdateGroupPolicyDecisionPolicy generates a NewMsgUpdateGroupPolicyDecisionPolicy with random values func SimulateMsgUpdateGroupPolicyDecisionPolicy(ak group.AccountKeeper, - bk group.BankKeeper, k keeper.Keeper) simtypes.Operation { + bk group.BankKeeper, k keeper.Keeper, +) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { _, groupPolicy, acc, account, err := randomGroupPolicy(r, k, ak, sdkCtx, accounts) if err != nil { return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyDecisionPolicy, ""), nil, err @@ -773,9 +785,11 @@ func SimulateMsgUpdateGroupPolicyDecisionPolicy(ak group.AccountKeeper, // // SimulateMsgUpdateGroupPolicyMetadata generates a MsgUpdateGroupPolicyMetadata with random values func SimulateMsgUpdateGroupPolicyMetadata(ak group.AccountKeeper, - bk group.BankKeeper, k keeper.Keeper) simtypes.Operation { + bk group.BankKeeper, k keeper.Keeper, +) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { _, groupPolicy, acc, account, err := randomGroupPolicy(r, k, ak, sdkCtx, accounts) if err != nil { return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyMetadata, ""), nil, err @@ -823,9 +837,11 @@ func SimulateMsgUpdateGroupPolicyMetadata(ak group.AccountKeeper, // SimulateMsgWithdrawProposal generates a MsgWithdrawProposal with random values func SimulateMsgWithdrawProposal(ak group.AccountKeeper, - bk group.BankKeeper, k keeper.Keeper) simtypes.Operation { + bk group.BankKeeper, k keeper.Keeper, +) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { g, groupPolicy, _, _, err := randomGroupPolicy(r, k, ak, sdkCtx, accounts) if err != nil { return simtypes.NoOpMsg(group.ModuleName, TypeMsgWithdrawProposal, ""), nil, err @@ -908,7 +924,6 @@ func SimulateMsgWithdrawProposal(ak group.AccountKeeper, []uint64{proposerAcc.GetSequence()}, proposer.PrivKey, ) - if err != nil { return simtypes.NoOpMsg(group.ModuleName, TypeMsgUpdateGroupPolicyMetadata, "unable to generate mock tx"), nil, err } @@ -928,9 +943,11 @@ func SimulateMsgWithdrawProposal(ak group.AccountKeeper, // SimulateMsgVote generates a MsgVote with random values func SimulateMsgVote(ak group.AccountKeeper, - bk group.BankKeeper, k keeper.Keeper) simtypes.Operation { + bk group.BankKeeper, k keeper.Keeper, +) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { g, groupPolicy, _, _, err := randomGroupPolicy(r, k, ak, sdkCtx, accounts) if err != nil { return simtypes.NoOpMsg(group.ModuleName, TypeMsgVote, ""), nil, err @@ -1031,9 +1048,11 @@ func SimulateMsgVote(ak group.AccountKeeper, // // SimulateMsgExec generates a MsgExec with random values func SimulateMsgExec(ak group.AccountKeeper, - bk group.BankKeeper, k keeper.Keeper) simtypes.Operation { + bk group.BankKeeper, k keeper.Keeper, +) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { _, groupPolicy, acc, account, err := randomGroupPolicy(r, k, ak, sdkCtx, accounts) if err != nil { return simtypes.NoOpMsg(TypeMsgExec, TypeMsgExec, ""), nil, err @@ -1107,8 +1126,8 @@ func SimulateMsgExec(ak group.AccountKeeper, // SimulateMsgLeaveGroup generates a MsgLeaveGroup with random values func SimulateMsgLeaveGroup(k keeper.Keeper, ak group.AccountKeeper, bk group.BankKeeper) simtypes.Operation { return func( - r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - + r *rand.Rand, app *baseapp.BaseApp, sdkCtx sdk.Context, accounts []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { ctx := sdk.WrapSDKContext(sdkCtx) groupInfo, policyInfo, _, _, err := randomGroupPolicy(r, k, ak, sdkCtx, accounts) if err != nil { @@ -1164,7 +1183,8 @@ func SimulateMsgLeaveGroup(k keeper.Keeper, ak group.AccountKeeper, bk group.Ban } func randomGroup(r *rand.Rand, k keeper.Keeper, ak group.AccountKeeper, - ctx sdk.Context, accounts []simtypes.Account) (groupInfo *group.GroupInfo, acc simtypes.Account, account authtypes.AccountI, err error) { + ctx sdk.Context, accounts []simtypes.Account, +) (groupInfo *group.GroupInfo, acc simtypes.Account, account authtypes.AccountI, err error) { groupID := k.GetGroupSequence(ctx) switch { @@ -1201,7 +1221,8 @@ func randomGroup(r *rand.Rand, k keeper.Keeper, ak group.AccountKeeper, } func randomGroupPolicy(r *rand.Rand, k keeper.Keeper, ak group.AccountKeeper, - ctx sdk.Context, accounts []simtypes.Account) (groupInfo *group.GroupInfo, groupPolicyInfo *group.GroupPolicyInfo, acc simtypes.Account, account authtypes.AccountI, err error) { + ctx sdk.Context, accounts []simtypes.Account, +) (groupInfo *group.GroupInfo, groupPolicyInfo *group.GroupPolicyInfo, acc simtypes.Account, account authtypes.AccountI, err error) { groupInfo, _, _, err = randomGroup(r, k, ak, ctx, accounts) if err != nil { return nil, nil, simtypes.Account{}, nil, err @@ -1232,7 +1253,8 @@ func randomGroupPolicy(r *rand.Rand, k keeper.Keeper, ak group.AccountKeeper, } func randomMember(r *rand.Rand, k keeper.Keeper, ak group.AccountKeeper, - ctx context.Context, accounts []simtypes.Account, groupID uint64) (acc simtypes.Account, account authtypes.AccountI, err error) { + ctx context.Context, accounts []simtypes.Account, groupID uint64, +) (acc simtypes.Account, account authtypes.AccountI, err error) { res, err := k.GroupMembers(ctx, &group.QueryGroupMembersRequest{ GroupId: groupID, }) diff --git a/x/group/types.go b/x/group/types.go index 0d882cbe62fc..86c0dfd9c1d7 100644 --- a/x/group/types.go +++ b/x/group/types.go @@ -231,7 +231,8 @@ var _ orm.Validateable = GroupPolicyInfo{} // NewGroupPolicyInfo creates a new GroupPolicyInfo instance func NewGroupPolicyInfo(address sdk.AccAddress, group uint64, admin sdk.AccAddress, metadata string, - version uint64, decisionPolicy DecisionPolicy, createdAt time.Time) (GroupPolicyInfo, error) { + version uint64, decisionPolicy DecisionPolicy, createdAt time.Time, +) (GroupPolicyInfo, error) { p := GroupPolicyInfo{ Address: address.String(), GroupId: group, @@ -368,7 +369,6 @@ func MemberToMemberRequest(m *Member) MemberRequest { } func (p Proposal) ValidateBasic() error { - if p.Id == 0 { return sdkerrors.Wrap(errors.ErrEmpty, "proposal id") } @@ -412,7 +412,6 @@ func (v Vote) PrimaryKeyFields() []interface{} { var _ orm.Validateable = Vote{} func (v Vote) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(v.Voter) if err != nil { return sdkerrors.Wrap(err, "voter") diff --git a/x/mint/client/cli/query.go b/x/mint/client/cli/query.go index 792fa8a6798f..6bf31ba5a179 100644 --- a/x/mint/client/cli/query.go +++ b/x/mint/client/cli/query.go @@ -45,7 +45,6 @@ func GetCmdQueryParams() *cobra.Command { params := &types.QueryParamsRequest{} res, err := queryClient.Params(cmd.Context(), params) - if err != nil { return err } @@ -75,7 +74,6 @@ func GetCmdQueryInflation() *cobra.Command { params := &types.QueryInflationRequest{} res, err := queryClient.Inflation(cmd.Context(), params) - if err != nil { return err } @@ -105,7 +103,6 @@ func GetCmdQueryAnnualProvisions() *cobra.Command { params := &types.QueryAnnualProvisionsRequest{} res, err := queryClient.AnnualProvisions(cmd.Context(), params) - if err != nil { return err } diff --git a/x/mint/client/testutil/cli_test.go b/x/mint/client/testutil/cli_test.go index dd36a6af2d3e..1035ca750264 100644 --- a/x/mint/client/testutil/cli_test.go +++ b/x/mint/client/testutil/cli_test.go @@ -1,3 +1,4 @@ +//go:build norace // +build norace package testutil diff --git a/x/mint/simulation/params_test.go b/x/mint/simulation/params_test.go index 6bc0f624cf37..3334fbd51a97 100644 --- a/x/mint/simulation/params_test.go +++ b/x/mint/simulation/params_test.go @@ -34,5 +34,4 @@ func TestParamChangest(t *testing.T) { require.Equal(t, expected[i].simValue, p.SimValue()(r)) require.Equal(t, expected[i].subspace, p.Subspace()) } - } diff --git a/x/mint/types/codec.go b/x/mint/types/codec.go index b436c10298d5..a7067d90c2c5 100644 --- a/x/mint/types/codec.go +++ b/x/mint/types/codec.go @@ -5,9 +5,7 @@ import ( cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" ) -var ( - amino = codec.NewLegacyAmino() -) +var amino = codec.NewLegacyAmino() func init() { cryptocodec.RegisterCrypto(amino) diff --git a/x/mint/types/minter_test.go b/x/mint/types/minter_test.go index 4abedb51cd05..04de803a2e5e 100644 --- a/x/mint/types/minter_test.go +++ b/x/mint/types/minter_test.go @@ -25,12 +25,16 @@ func TestNextInflation(t *testing.T) { // 100% bonded, starting at 20% inflation and being reduced // (1 - (1/0.67))*(0.13/8667) - {sdk.OneDec(), sdk.NewDecWithPrec(20, 2), - sdk.OneDec().Sub(sdk.OneDec().Quo(params.GoalBonded)).Mul(params.InflationRateChange).Quo(blocksPerYr)}, + { + sdk.OneDec(), sdk.NewDecWithPrec(20, 2), + sdk.OneDec().Sub(sdk.OneDec().Quo(params.GoalBonded)).Mul(params.InflationRateChange).Quo(blocksPerYr), + }, // 50% bonded, starting at 10% inflation and being increased - {sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(10, 2), - sdk.OneDec().Sub(sdk.NewDecWithPrec(5, 1).Quo(params.GoalBonded)).Mul(params.InflationRateChange).Quo(blocksPerYr)}, + { + sdk.NewDecWithPrec(5, 1), sdk.NewDecWithPrec(10, 2), + sdk.OneDec().Sub(sdk.NewDecWithPrec(5, 1).Quo(params.GoalBonded)).Mul(params.InflationRateChange).Quo(blocksPerYr), + }, // test 7% minimum stop (testing with 100% bonded) {sdk.OneDec(), sdk.NewDecWithPrec(7, 2), sdk.ZeroDec()}, @@ -115,7 +119,6 @@ func BenchmarkNextInflation(b *testing.B) { for n := 0; n < b.N; n++ { minter.NextInflationRate(params, bondedRatio) } - } // Next annual provisions benchmarking @@ -130,5 +133,4 @@ func BenchmarkNextAnnualProvisions(b *testing.B) { for n := 0; n < b.N; n++ { minter.NextAnnualProvisions(params, totalSupply) } - } diff --git a/x/mint/types/params.go b/x/mint/types/params.go index c5bf838ac3f6..56c9b8aa783b 100644 --- a/x/mint/types/params.go +++ b/x/mint/types/params.go @@ -29,7 +29,6 @@ func ParamKeyTable() paramtypes.KeyTable { func NewParams( mintDenom string, inflationRateChange, inflationMax, inflationMin, goalBonded sdk.Dec, blocksPerYear uint64, ) Params { - return Params{ MintDenom: mintDenom, InflationRateChange: inflationRateChange, @@ -80,7 +79,6 @@ func (p Params) Validate() error { } return nil - } // String implements the Stringer interface. diff --git a/x/nft/keeper/genesis.go b/x/nft/keeper/genesis.go index f8cf05184c0c..6018ca2e076d 100644 --- a/x/nft/keeper/genesis.go +++ b/x/nft/keeper/genesis.go @@ -13,7 +13,6 @@ func (k Keeper) InitGenesis(ctx sdk.Context, data *nft.GenesisState) { if err := k.SaveClass(ctx, *class); err != nil { panic(err) } - } for _, entry := range data.Entries { for _, nft := range entry.Nfts { diff --git a/x/nft/keeper/grpc_query.go b/x/nft/keeper/grpc_query.go index f79641326e4c..e22fdf0b4a22 100644 --- a/x/nft/keeper/grpc_query.go +++ b/x/nft/keeper/grpc_query.go @@ -151,7 +151,6 @@ func (k Keeper) NFT(goCtx context.Context, r *nft.QueryNFTRequest) (*nft.QueryNF return nil, nft.ErrNFTNotExists.Wrapf("not found nft: class: %s, id: %s", r.ClassId, r.Id) } return &nft.QueryNFTResponse{Nft: &n}, nil - } // Class return an NFT class based on its id @@ -191,7 +190,6 @@ func (k Keeper) Classes(goCtx context.Context, r *nft.QueryClassesRequest) (*nft classes = append(classes, &class) return nil }) - if err != nil { return nil, err } diff --git a/x/nft/keeper/grpc_query_test.go b/x/nft/keeper/grpc_query_test.go index 20d0f0afbc7c..6f6090e5dd93 100644 --- a/x/nft/keeper/grpc_query_test.go +++ b/x/nft/keeper/grpc_query_test.go @@ -16,9 +16,7 @@ func TestGRPCQuery(t *testing.T) { } func (s *TestSuite) TestBalance() { - var ( - req *nft.QueryBalanceRequest - ) + var req *nft.QueryBalanceRequest testCases := []struct { msg string malleate func(index int, require *require.Assertions) @@ -169,9 +167,7 @@ func (s *TestSuite) TestOwner() { } func (s *TestSuite) TestSupply() { - var ( - req *nft.QuerySupplyRequest - ) + var req *nft.QuerySupplyRequest testCases := []struct { msg string malleate func(index int, require *require.Assertions) @@ -252,6 +248,7 @@ func (s *TestSuite) TestSupply() { }) } } + func (s *TestSuite) TestNFTs() { var ( req *nft.QueryNFTsRequest diff --git a/x/nft/keeper/keeper_test.go b/x/nft/keeper/keeper_test.go index 7e03f79eb582..9f18ab734116 100644 --- a/x/nft/keeper/keeper_test.go +++ b/x/nft/keeper/keeper_test.go @@ -279,7 +279,7 @@ func (s *TestSuite) TestTransfer() { err = s.app.NFTKeeper.Mint(s.ctx, expNFT, s.addrs[0]) s.Require().NoError(err) - //valid owner + // valid owner err = s.app.NFTKeeper.Transfer(s.ctx, testClassID, testID, s.addrs[1]) s.Require().NoError(err) diff --git a/x/nft/keeper/keys.go b/x/nft/keeper/keys.go index 6c65581db2d1..51df6e5c36a5 100644 --- a/x/nft/keeper/keys.go +++ b/x/nft/keeper/keys.go @@ -55,7 +55,7 @@ func nftOfClassByOwnerStoreKey(owner sdk.AccAddress, classID string) []byte { owner = address.MustLengthPrefix(owner) classIDBz := conv.UnsafeStrToBytes(classID) - var key = make([]byte, len(NFTOfClassByOwnerKey)+len(owner)+len(Delimiter)+len(classIDBz)+len(Delimiter)) + key := make([]byte, len(NFTOfClassByOwnerKey)+len(owner)+len(Delimiter)+len(classIDBz)+len(Delimiter)) copy(key, NFTOfClassByOwnerKey) copy(key[len(NFTOfClassByOwnerKey):], owner) copy(key[len(NFTOfClassByOwnerKey)+len(owner):], Delimiter) @@ -70,7 +70,7 @@ func nftOfClassByOwnerStoreKey(owner sdk.AccAddress, classID string) []byte { func prefixNftOfClassByOwnerStoreKey(owner sdk.AccAddress) []byte { owner = address.MustLengthPrefix(owner) - var key = make([]byte, len(NFTOfClassByOwnerKey)+len(owner)+len(Delimiter)) + key := make([]byte, len(NFTOfClassByOwnerKey)+len(owner)+len(Delimiter)) copy(key, NFTOfClassByOwnerKey) copy(key[len(NFTOfClassByOwnerKey):], owner) copy(key[len(NFTOfClassByOwnerKey)+len(owner):], Delimiter) @@ -97,7 +97,7 @@ func ownerStoreKey(classID, nftID string) []byte { classIDBz := conv.UnsafeStrToBytes(classID) nftIDBz := conv.UnsafeStrToBytes(nftID) - var key = make([]byte, len(OwnerKey)+len(classIDBz)+len(Delimiter)+len(nftIDBz)) + key := make([]byte, len(OwnerKey)+len(classIDBz)+len(Delimiter)+len(nftIDBz)) copy(key, OwnerKey) copy(key[len(OwnerKey):], classIDBz) copy(key[len(OwnerKey)+len(classIDBz):], Delimiter) diff --git a/x/nft/keeper/nft.go b/x/nft/keeper/nft.go index 10c9c38df3a6..336aff41b677 100644 --- a/x/nft/keeper/nft.go +++ b/x/nft/keeper/nft.go @@ -73,7 +73,8 @@ func (k Keeper) Update(ctx sdk.Context, token nft.NFT) error { func (k Keeper) Transfer(ctx sdk.Context, classID string, nftID string, - receiver sdk.AccAddress) error { + receiver sdk.AccAddress, +) error { if !k.HasClass(ctx, classID) { return sdkerrors.Wrap(nft.ErrClassNotExists, classID) } diff --git a/x/nft/msgs.go b/x/nft/msgs.go index 4b85199cdc04..ec648e5f498c 100644 --- a/x/nft/msgs.go +++ b/x/nft/msgs.go @@ -10,9 +10,7 @@ const ( TypeMsgSend = "send" ) -var ( - _ sdk.Msg = &MsgSend{} -) +var _ sdk.Msg = &MsgSend{} // ValidateBasic implements the Msg.ValidateBasic method. func (m MsgSend) ValidateBasic() error { diff --git a/x/nft/simulation/operations.go b/x/nft/simulation/operations.go index 975fa57133ea..c71ab17c3175 100644 --- a/x/nft/simulation/operations.go +++ b/x/nft/simulation/operations.go @@ -27,9 +27,7 @@ const ( WeightSend = 100 ) -var ( - TypeMsgSend = sdk.MsgTypeURL(&nft.MsgSend{}) -) +var TypeMsgSend = sdk.MsgTypeURL(&nft.MsgSend{}) // WeightedOperations returns all the operations from the module with their respective weights func WeightedOperations( @@ -38,11 +36,9 @@ func WeightedOperations( cdc codec.JSONCodec, ak nft.AccountKeeper, bk nft.BankKeeper, - k keeper.Keeper) simulation.WeightedOperations { - - var ( - weightMsgSend int - ) + k keeper.Keeper, +) simulation.WeightedOperations { + var weightMsgSend int appParams.GetOrGenerate(cdc, OpWeightMsgSend, &weightMsgSend, nil, func(_ *rand.Rand) { @@ -63,7 +59,8 @@ func SimulateMsgSend( cdc *codec.ProtoCodec, ak nft.AccountKeeper, bk nft.BankKeeper, - k keeper.Keeper) simtypes.Operation { + k keeper.Keeper, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { diff --git a/x/nft/simulation/operations_test.go b/x/nft/simulation/operations_test.go index dd222ecbbc9a..0a500f5a971c 100644 --- a/x/nft/simulation/operations_test.go +++ b/x/nft/simulation/operations_test.go @@ -107,7 +107,6 @@ func (suite *SimTestSuite) TestSimulateMsgSend() { suite.app.AppCodec().UnmarshalJSON(operationMsg.Msg, &msg) suite.Require().True(operationMsg.OK) suite.Require().Len(futureOperations, 0) - } func TestSimTestSuite(t *testing.T) { diff --git a/x/params/client/testutil/cli_test.go b/x/params/client/testutil/cli_test.go index dd36a6af2d3e..1035ca750264 100644 --- a/x/params/client/testutil/cli_test.go +++ b/x/params/client/testutil/cli_test.go @@ -1,3 +1,4 @@ +//go:build norace // +build norace package testutil diff --git a/x/params/keeper/grpc_query.go b/x/params/keeper/grpc_query.go index d918dc002a38..48fd9ec68694 100644 --- a/x/params/keeper/grpc_query.go +++ b/x/params/keeper/grpc_query.go @@ -41,7 +41,6 @@ func (k Keeper) Subspaces( goCtx context.Context, req *proposal.QuerySubspacesRequest, ) (*proposal.QuerySubspacesResponse, error) { - if req == nil { return nil, status.Errorf(codes.InvalidArgument, "empty request") } diff --git a/x/params/module.go b/x/params/module.go index da4679f8789f..ddee65dc5823 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -111,7 +111,6 @@ func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sd // module-specific gRPC queries. func (am AppModule) RegisterServices(cfg module.Configurator) { proposal.RegisterQueryServer(cfg.QueryServer(), am.keeper) - } // ProposalContents returns all the params content functions used to diff --git a/x/simulation/event_stats.go b/x/simulation/event_stats.go index 9618385b8ffc..675380e8215a 100644 --- a/x/simulation/event_stats.go +++ b/x/simulation/event_stats.go @@ -48,7 +48,7 @@ func (es EventStats) ExportJSON(path string) { panic(err) } - err = os.WriteFile(path, bz, 0600) + err = os.WriteFile(path, bz, 0o600) if err != nil { panic(err) } diff --git a/x/simulation/log.go b/x/simulation/log.go index ba22b2af4a7e..b22709b65414 100644 --- a/x/simulation/log.go +++ b/x/simulation/log.go @@ -40,7 +40,6 @@ func (lw *StandardLogWriter) PrintLogs() { for i := 0; i < len(lw.OpEntries); i++ { writeEntry := fmt.Sprintf("%s\n", (lw.OpEntries[i]).MustMarshal()) _, err := f.WriteString(writeEntry) - if err != nil { panic("Failed to write logs to file") } diff --git a/x/simulation/mock_tendermint.go b/x/simulation/mock_tendermint.go index 55c2ca544465..7d7f1dc99725 100644 --- a/x/simulation/mock_tendermint.go +++ b/x/simulation/mock_tendermint.go @@ -86,7 +86,6 @@ func updateValidators( updates []abci.ValidatorUpdate, event func(route, op, evResult string), ) map[string]mockValidator { - for _, update := range updates { str := fmt.Sprintf("%X", update.PubKey.GetEd25519()) @@ -100,7 +99,6 @@ func updateValidators( } else if _, ok := current[str]; ok { // validator already exists event("end_block", "validator_updates", "updated") - } else { // Set this new validator current[str] = mockValidator{ @@ -119,7 +117,8 @@ func updateValidators( func RandomRequestBeginBlock(r *rand.Rand, params Params, validators mockValidators, pastTimes []time.Time, pastVoteInfos [][]abci.VoteInfo, - event func(route, op, evResult string), header tmproto.Header) abci.RequestBeginBlock { + event func(route, op, evResult string), header tmproto.Header, +) abci.RequestBeginBlock { if len(validators) == 0 { return abci.RequestBeginBlock{ Header: header, diff --git a/x/simulation/params_test.go b/x/simulation/params_test.go index d0b538c26e4d..90eb4f22a0a4 100644 --- a/x/simulation/params_test.go +++ b/x/simulation/params_test.go @@ -43,8 +43,7 @@ func TestNewWeightedProposalContent(t *testing.T) { require.Equal(t, content, pContent.ContentSimulatorFn()(nil, ctx, nil)) } -type testContent struct { -} +type testContent struct{} func (t testContent) GetTitle() string { return "" } func (t testContent) GetDescription() string { return "" } diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index 9b8c433be10a..cd792659bd15 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -31,7 +31,6 @@ func initChain( config simulation.Config, cdc codec.JSONCodec, ) (mockValidators, time.Time, []simulation.Account, string) { - appState, accounts, chainID, genesisTimestamp := appStateFn(r, accounts, config) consensusParams := randomConsensusParams(r, appState, cdc) req := abci.RequestInitChain{ @@ -256,8 +255,8 @@ type blockSimFn func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, func createBlockSimulator(testingMode bool, tb testing.TB, w io.Writer, params Params, event func(route, op, evResult string), ops WeightedOperations, operationQueue OperationQueue, timeOperationQueue []simulation.FutureOperation, - logWriter LogWriter, config simulation.Config) blockSimFn { - + logWriter LogWriter, config simulation.Config, +) blockSimFn { lastBlockSizeState := 0 // state for [4 * uniform distribution] blocksize := 0 selectOp := ops.getSelectOpFn() @@ -324,8 +323,8 @@ Comment: %s`, func runQueuedOperations(queueOps map[int][]simulation.Operation, height int, tb testing.TB, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simulation.Account, logWriter LogWriter, - event func(route, op, evResult string), lean bool, chainID string) (numOpsRan int, allFutureOps []simulation.FutureOperation) { - + event func(route, op, evResult string), lean bool, chainID string, +) (numOpsRan int, allFutureOps []simulation.FutureOperation) { queuedOp, ok := queueOps[height] if !ok { return 0, nil @@ -361,8 +360,8 @@ func runQueuedTimeOperations(queueOps []simulation.FutureOperation, height int, currentTime time.Time, tb testing.TB, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simulation.Account, logWriter LogWriter, event func(route, op, evResult string), - lean bool, chainID string) (numOpsRan int, allFutureOps []simulation.FutureOperation) { - + lean bool, chainID string, +) (numOpsRan int, allFutureOps []simulation.FutureOperation) { // Keep all future operations allFutureOps = make([]simulation.FutureOperation, 0) diff --git a/x/simulation/util.go b/x/simulation/util.go index 4b752609f093..3c72f67538cb 100644 --- a/x/simulation/util.go +++ b/x/simulation/util.go @@ -110,7 +110,6 @@ func GenAndDeliverTx(txCtx OperationInput, fees sdk.Coins) (simtypes.OperationMs []uint64{account.GetSequence()}, txCtx.SimAccount.PrivKey, ) - if err != nil { return simtypes.NoOpMsg(txCtx.ModuleName, txCtx.MsgType, "unable to generate mock tx"), nil, err } @@ -121,5 +120,4 @@ func GenAndDeliverTx(txCtx OperationInput, fees sdk.Coins) (simtypes.OperationMs } return simtypes.NewOperationMsg(txCtx.Msg, true, "", txCtx.Cdc), nil, nil - } diff --git a/x/slashing/client/cli/query.go b/x/slashing/client/cli/query.go index 08ae03301fbc..500a490d64eb 100644 --- a/x/slashing/client/cli/query.go +++ b/x/slashing/client/cli/query.go @@ -30,7 +30,6 @@ func GetQueryCmd() *cobra.Command { ) return slashingQueryCmd - } // GetCmdQuerySigningInfo implements the command to query signing info. diff --git a/x/slashing/client/testutil/cli_test.go b/x/slashing/client/testutil/cli_test.go index dd36a6af2d3e..1035ca750264 100644 --- a/x/slashing/client/testutil/cli_test.go +++ b/x/slashing/client/testutil/cli_test.go @@ -1,3 +1,4 @@ +//go:build norace // +build norace package testutil diff --git a/x/slashing/init_test.go b/x/slashing/init_test.go index a2217cfda7b0..b9bbfe694e26 100644 --- a/x/slashing/init_test.go +++ b/x/slashing/init_test.go @@ -4,7 +4,5 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -var ( - // The default power validators are initialized to have within tests - InitTokens = sdk.TokensFromConsensusPower(200, sdk.DefaultPowerReduction) -) +// The default power validators are initialized to have within tests +var InitTokens = sdk.TokensFromConsensusPower(200, sdk.DefaultPowerReduction) diff --git a/x/slashing/keeper/common_test.go b/x/slashing/keeper/common_test.go index 91a972ed1110..4e4be93b91e8 100644 --- a/x/slashing/keeper/common_test.go +++ b/x/slashing/keeper/common_test.go @@ -2,7 +2,5 @@ package keeper_test import sdk "github.com/cosmos/cosmos-sdk/types" -var ( - // The default power validators are initialized to have within tests - InitTokens = sdk.TokensFromConsensusPower(200, sdk.DefaultPowerReduction) -) +// The default power validators are initialized to have within tests +var InitTokens = sdk.TokensFromConsensusPower(200, sdk.DefaultPowerReduction) diff --git a/x/slashing/keeper/grpc_query_test.go b/x/slashing/keeper/grpc_query_test.go index ddb6694d0463..5a8733babeef 100644 --- a/x/slashing/keeper/grpc_query_test.go +++ b/x/slashing/keeper/grpc_query_test.go @@ -91,7 +91,7 @@ func (suite *SlashingTestSuite) TestGRPCSigningInfos() { }) // verify all values are returned without pagination - var infoResp, err = queryClient.SigningInfos(gocontext.Background(), + infoResp, err := queryClient.SigningInfos(gocontext.Background(), &types.QuerySigningInfosRequest{Pagination: nil}) suite.NoError(err) suite.Equal(signingInfos, infoResp.Info) diff --git a/x/slashing/keeper/keeper_test.go b/x/slashing/keeper/keeper_test.go index 08502fa89c94..03869e3a74c9 100644 --- a/x/slashing/keeper/keeper_test.go +++ b/x/slashing/keeper/keeper_test.go @@ -179,7 +179,6 @@ func TestHandleAlreadyJailed(t *testing.T) { // Ensure that missed blocks are tracked correctly and that // the start height of the signing info is reset correctly func TestValidatorDippingInAndOut(t *testing.T) { - // initial setup // TestParams set the SignedBlocksWindow to 1000 and MaxMissedBlocksPerWindow to 500 app := simapp.Setup(t, false) diff --git a/x/slashing/keeper/signing_info.go b/x/slashing/keeper/signing_info.go index ed15ae3e4ff3..d65b773ebc66 100644 --- a/x/slashing/keeper/signing_info.go +++ b/x/slashing/keeper/signing_info.go @@ -39,8 +39,8 @@ func (k Keeper) SetValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress // IterateValidatorSigningInfos iterates over the stored ValidatorSigningInfo func (k Keeper) IterateValidatorSigningInfos(ctx sdk.Context, - handler func(address sdk.ConsAddress, info types.ValidatorSigningInfo) (stop bool)) { - + handler func(address sdk.ConsAddress, info types.ValidatorSigningInfo) (stop bool), +) { store := ctx.KVStore(k.storeKey) iter := sdk.KVStorePrefixIterator(store, types.ValidatorSigningInfoKeyPrefix) defer iter.Close() @@ -71,8 +71,8 @@ func (k Keeper) GetValidatorMissedBlockBitArray(ctx sdk.Context, address sdk.Con // IterateValidatorMissedBlockBitArray iterates over the signed blocks window // and performs a callback function func (k Keeper) IterateValidatorMissedBlockBitArray(ctx sdk.Context, - address sdk.ConsAddress, handler func(index int64, missed bool) (stop bool)) { - + address sdk.ConsAddress, handler func(index int64, missed bool) (stop bool), +) { store := ctx.KVStore(k.storeKey) index := int64(0) // Array may be sparse diff --git a/x/slashing/simulation/genesis_test.go b/x/slashing/simulation/genesis_test.go index 52ac75f7590c..55bce42a84a6 100644 --- a/x/slashing/simulation/genesis_test.go +++ b/x/slashing/simulation/genesis_test.go @@ -53,7 +53,6 @@ func TestRandomizedGenState(t *testing.T) { require.Equal(t, time.Duration(34800000000000), slashingGenesis.Params.DowntimeJailDuration) require.Len(t, slashingGenesis.MissedBlocks, 0) require.Len(t, slashingGenesis.SigningInfos, 0) - } // TestRandomizedGenState tests abnormal scenarios of applying RandomizedGenState. diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index e2f3efd02848..56eef65d8a57 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -26,7 +26,6 @@ func WeightedOperations( appParams simtypes.AppParams, cdc codec.JSONCodec, ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper, sk stakingkeeper.Keeper, ) simulation.WeightedOperations { - var weightMsgUnjail int appParams.GetOrGenerate(cdc, OpWeightMsgUnjail, &weightMsgUnjail, nil, func(_ *rand.Rand) { @@ -48,7 +47,6 @@ func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Kee r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - validator, ok := stakingkeeper.RandomValidator(r, sk, ctx) if !ok { return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgUnjail, "validator is not ok"), nil, nil // skip diff --git a/x/slashing/types/genesis.go b/x/slashing/types/genesis.go index 9b427e725ac3..b891dec80e8b 100644 --- a/x/slashing/types/genesis.go +++ b/x/slashing/types/genesis.go @@ -11,7 +11,6 @@ import ( func NewGenesisState( params Params, signingInfos []SigningInfo, missedBlocks []ValidatorMissedBlocks, ) *GenesisState { - return &GenesisState{ Params: params, SigningInfos: signingInfos, diff --git a/x/slashing/types/params.go b/x/slashing/types/params.go index aa9cd559e7db..ad1d98c37f15 100644 --- a/x/slashing/types/params.go +++ b/x/slashing/types/params.go @@ -39,7 +39,6 @@ func NewParams( signedBlocksWindow int64, minSignedPerWindow sdk.Dec, downtimeJailDuration time.Duration, slashFractionDoubleSign, slashFractionDowntime sdk.Dec, ) Params { - return Params{ SignedBlocksWindow: signedBlocksWindow, MinSignedPerWindow: minSignedPerWindow, diff --git a/x/slashing/types/signing_info.go b/x/slashing/types/signing_info.go index 43a052d22f7d..d9b00da199e6 100644 --- a/x/slashing/types/signing_info.go +++ b/x/slashing/types/signing_info.go @@ -14,7 +14,6 @@ func NewValidatorSigningInfo( condAddr sdk.ConsAddress, startHeight, indexOffset int64, jailedUntil time.Time, tombstoned bool, missedBlocksCounter int64, ) ValidatorSigningInfo { - return ValidatorSigningInfo{ Address: condAddr.String(), StartHeight: startHeight, diff --git a/x/staking/app_test.go b/x/staking/app_test.go index ce737e3b6218..5a3bd723cb9c 100644 --- a/x/staking/app_test.go +++ b/x/staking/app_test.go @@ -26,7 +26,6 @@ func checkDelegation( t *testing.T, app *simapp.SimApp, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, expFound bool, expShares sdk.Dec, ) { - ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{}) delegation, found := app.StakingKeeper.GetDelegation(ctxCheck, delegatorAddr, validatorAddr) if expFound { diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index 6a9d5393120f..1ffe7d89a750 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -549,7 +549,6 @@ func PrepareConfigForTxCreateValidator(flagSet *flag.FlagSet, moniker, nodeID, c func BuildCreateValidatorMsg(clientCtx client.Context, config TxCreateValidatorConfig, txBldr tx.Factory, generateOnly bool) (tx.Factory, sdk.Msg, error) { amounstStr := config.Amount amount, err := sdk.ParseCoinNormalized(amounstStr) - if err != nil { return txBldr, nil, err } @@ -568,7 +567,6 @@ func BuildCreateValidatorMsg(clientCtx client.Context, config TxCreateValidatorC maxRateStr := config.CommissionMaxRate maxChangeRateStr := config.CommissionMaxChangeRate commissionRates, err := buildCommissionRates(rateStr, maxRateStr, maxChangeRateStr) - if err != nil { return txBldr, nil, err } diff --git a/x/staking/client/cli/tx_test.go b/x/staking/client/cli/tx_test.go index a7eb30fde3c2..243780bc6e03 100644 --- a/x/staking/client/cli/tx_test.go +++ b/x/staking/client/cli/tx_test.go @@ -43,25 +43,29 @@ func TestPrepareConfigForTxCreateValidator(t *testing.T) { return }, expectedCfg: mkTxValCfg(defaultAmount, "0.1", "0.2", "0.01", "1"), - }, { + }, + { name: "Custom amount", fsModify: func(fs *pflag.FlagSet) { fs.Set(FlagAmount, "2000stake") }, expectedCfg: mkTxValCfg("2000stake", "0.1", "0.2", "0.01", "1"), - }, { + }, + { name: "Custom commission rate", fsModify: func(fs *pflag.FlagSet) { fs.Set(FlagCommissionRate, "0.54") }, expectedCfg: mkTxValCfg(defaultAmount, "0.54", "0.2", "0.01", "1"), - }, { + }, + { name: "Custom commission max rate", fsModify: func(fs *pflag.FlagSet) { fs.Set(FlagCommissionMaxRate, "0.89") }, expectedCfg: mkTxValCfg(defaultAmount, "0.1", "0.89", "0.01", "1"), - }, { + }, + { name: "Custom commission max change rate", fsModify: func(fs *pflag.FlagSet) { fs.Set(FlagCommissionMaxChangeRate, "0.55") diff --git a/x/staking/client/testutil/test_helpers.go b/x/staking/client/testutil/test_helpers.go index 3a31ea004f3d..0fa752e05720 100644 --- a/x/staking/client/testutil/test_helpers.go +++ b/x/staking/client/testutil/test_helpers.go @@ -18,9 +18,7 @@ var commonArgs = []string{ } // MsgRedelegateExec creates a redelegate message. -func MsgRedelegateExec(clientCtx client.Context, from, src, dst, amount fmt.Stringer, - extraArgs ...string) (testutil.BufferWriter, error) { - +func MsgRedelegateExec(clientCtx client.Context, from, src, dst, amount fmt.Stringer, extraArgs ...string) (testutil.BufferWriter, error) { args := []string{ src.String(), dst.String(), @@ -36,8 +34,8 @@ func MsgRedelegateExec(clientCtx client.Context, from, src, dst, amount fmt.Stri // MsgUnbondExec creates a unbond message. func MsgUnbondExec(clientCtx client.Context, from fmt.Stringer, valAddress, - amount fmt.Stringer, extraArgs ...string) (testutil.BufferWriter, error) { - + amount fmt.Stringer, extraArgs ...string, +) (testutil.BufferWriter, error) { args := []string{ valAddress.String(), amount.String(), diff --git a/x/staking/keeper/alias_functions.go b/x/staking/keeper/alias_functions.go index 36c2d23661c6..59c4d23be2e8 100644 --- a/x/staking/keeper/alias_functions.go +++ b/x/staking/keeper/alias_functions.go @@ -114,7 +114,8 @@ func (k Keeper) Delegation(ctx sdk.Context, addrDel sdk.AccAddress, addrVal sdk. // iterate through all of the delegations from a delegator func (k Keeper) IterateDelegations(ctx sdk.Context, delAddr sdk.AccAddress, - fn func(index int64, del types.DelegationI) (stop bool)) { + fn func(index int64, del types.DelegationI) (stop bool), +) { store := ctx.KVStore(k.storeKey) delegatorPrefixKey := types.GetDelegationsKey(delAddr) diff --git a/x/staking/keeper/common_test.go b/x/staking/keeper/common_test.go index 6833ea4c0baf..ad31204ba43b 100644 --- a/x/staking/keeper/common_test.go +++ b/x/staking/keeper/common_test.go @@ -13,9 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking/types" ) -var ( - PKs = simapp.CreateTestPubKeys(500) -) +var PKs = simapp.CreateTestPubKeys(500) func init() { sdk.DefaultPowerReduction = sdk.NewIntFromBigInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)) diff --git a/x/staking/keeper/delegation.go b/x/staking/keeper/delegation.go index 097c3b037e95..4c99e4adaedb 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -11,8 +11,7 @@ import ( ) // GetDelegation returns a specific delegation. -func (k Keeper) GetDelegation(ctx sdk.Context, - delAddr sdk.AccAddress, valAddr sdk.ValAddress) (delegation types.Delegation, found bool) { +func (k Keeper) GetDelegation(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) (delegation types.Delegation, found bool) { store := ctx.KVStore(k.storeKey) key := types.GetDelegationKey(delAddr, valAddr) @@ -71,8 +70,7 @@ func (k Keeper) GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress) // GetDelegatorDelegations returns a given amount of all the delegations from a // delegator. -func (k Keeper) GetDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress, - maxRetrieve uint16) (delegations []types.Delegation) { +func (k Keeper) GetDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress, maxRetrieve uint16) (delegations []types.Delegation) { delegations = make([]types.Delegation, maxRetrieve) store := ctx.KVStore(k.storeKey) delegatorPrefixKey := types.GetDelegationsKey(delegator) @@ -119,8 +117,7 @@ func (k Keeper) RemoveDelegation(ctx sdk.Context, delegation types.Delegation) e } // GetUnbondingDelegations returns a given amount of all the delegator unbonding-delegations. -func (k Keeper) GetUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAddress, - maxRetrieve uint16) (unbondingDelegations []types.UnbondingDelegation) { +func (k Keeper) GetUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAddress, maxRetrieve uint16) (unbondingDelegations []types.UnbondingDelegation) { unbondingDelegations = make([]types.UnbondingDelegation, maxRetrieve) store := ctx.KVStore(k.storeKey) @@ -140,9 +137,7 @@ func (k Keeper) GetUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAddres } // GetUnbondingDelegation returns a unbonding delegation. -func (k Keeper) GetUnbondingDelegation( - ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, -) (ubd types.UnbondingDelegation, found bool) { +func (k Keeper) GetUnbondingDelegation(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) (ubd types.UnbondingDelegation, found bool) { store := ctx.KVStore(k.storeKey) key := types.GetUBDKey(delAddr, valAddr) value := store.Get(key) @@ -269,8 +264,7 @@ func (k Keeper) IterateDelegatorRedelegations(ctx sdk.Context, delegator sdk.Acc } // HasMaxUnbondingDelegationEntries - check if unbonding delegation has maximum number of entries. -func (k Keeper) HasMaxUnbondingDelegationEntries(ctx sdk.Context, - delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) bool { +func (k Keeper) HasMaxUnbondingDelegationEntries(ctx sdk.Context, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) bool { ubd, found := k.GetUnbondingDelegation(ctx, delegatorAddr, validatorAddr) if !found { return false @@ -359,8 +353,7 @@ func (k Keeper) SetUBDQueueTimeSlice(ctx sdk.Context, timestamp time.Time, keys // InsertUBDQueue inserts an unbonding delegation to the appropriate timeslice // in the unbonding queue. -func (k Keeper) InsertUBDQueue(ctx sdk.Context, ubd types.UnbondingDelegation, - completionTime time.Time) { +func (k Keeper) InsertUBDQueue(ctx sdk.Context, ubd types.UnbondingDelegation, completionTime time.Time) { dvPair := types.DVPair{DelegatorAddress: ubd.DelegatorAddress, ValidatorAddress: ubd.ValidatorAddress} timeSlice := k.GetUBDQueueTimeSlice(ctx, completionTime) @@ -402,8 +395,7 @@ func (k Keeper) DequeueAllMatureUBDQueue(ctx sdk.Context, currTime time.Time) (m } // GetRedelegations returns a given amount of all the delegator redelegations. -func (k Keeper) GetRedelegations(ctx sdk.Context, delegator sdk.AccAddress, - maxRetrieve uint16) (redelegations []types.Redelegation) { +func (k Keeper) GetRedelegations(ctx sdk.Context, delegator sdk.AccAddress, maxRetrieve uint16) (redelegations []types.Redelegation) { redelegations = make([]types.Redelegation, maxRetrieve) store := ctx.KVStore(k.storeKey) @@ -423,8 +415,7 @@ func (k Keeper) GetRedelegations(ctx sdk.Context, delegator sdk.AccAddress, } // GetRedelegation returns a redelegation. -func (k Keeper) GetRedelegation(ctx sdk.Context, - delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) (red types.Redelegation, found bool) { +func (k Keeper) GetRedelegation(ctx sdk.Context, delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) (red types.Redelegation, found bool) { store := ctx.KVStore(k.storeKey) key := types.GetREDKey(delAddr, valSrcAddr, valDstAddr) @@ -457,8 +448,7 @@ func (k Keeper) GetRedelegationsFromSrcValidator(ctx sdk.Context, valAddr sdk.Va } // HasReceivingRedelegation checks if validator is receiving a redelegation. -func (k Keeper) HasReceivingRedelegation(ctx sdk.Context, - delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) bool { +func (k Keeper) HasReceivingRedelegation(ctx sdk.Context, delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) bool { store := ctx.KVStore(k.storeKey) prefix := types.GetREDsByDelToValDstIndexKey(delAddr, valDstAddr) @@ -469,9 +459,7 @@ func (k Keeper) HasReceivingRedelegation(ctx sdk.Context, } // HasMaxRedelegationEntries checks if redelegation has maximum number of entries. -func (k Keeper) HasMaxRedelegationEntries(ctx sdk.Context, - delegatorAddr sdk.AccAddress, validatorSrcAddr, - validatorDstAddr sdk.ValAddress) bool { +func (k Keeper) HasMaxRedelegationEntries(ctx sdk.Context, delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress) bool { red, found := k.GetRedelegation(ctx, delegatorAddr, validatorSrcAddr, validatorDstAddr) if !found { return false @@ -509,7 +497,8 @@ func (k Keeper) SetRedelegationEntry(ctx sdk.Context, delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress, creationHeight int64, minTime time.Time, balance sdk.Int, - sharesSrc, sharesDst sdk.Dec) types.Redelegation { + sharesSrc, sharesDst sdk.Dec, +) types.Redelegation { red, found := k.GetRedelegation(ctx, delegatorAddr, validatorSrcAddr, validatorDstAddr) if found { red.AddEntry(creationHeight, minTime, balance, sharesDst) @@ -588,13 +577,13 @@ func (k Keeper) SetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Ti // InsertRedelegationQueue insert an redelegation delegation to the appropriate // timeslice in the redelegation queue. -func (k Keeper) InsertRedelegationQueue(ctx sdk.Context, red types.Redelegation, - completionTime time.Time) { +func (k Keeper) InsertRedelegationQueue(ctx sdk.Context, red types.Redelegation, completionTime time.Time) { timeSlice := k.GetRedelegationQueueTimeSlice(ctx, completionTime) dvvTriplet := types.DVVTriplet{ DelegatorAddress: red.DelegatorAddress, ValidatorSrcAddress: red.ValidatorSrcAddress, - ValidatorDstAddress: red.ValidatorDstAddress} + ValidatorDstAddress: red.ValidatorDstAddress, + } if len(timeSlice) == 0 { k.SetRedelegationQueueTimeSlice(ctx, completionTime, []types.DVVTriplet{dvvTriplet}) diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index 723caa693e1c..04d67c143c5f 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -31,7 +31,7 @@ func TestDelegation(t *testing.T) { addrDels := simapp.AddTestAddrsIncremental(app, ctx, 3, sdk.NewInt(10000)) valAddrs := simapp.ConvertAddrsToValAddrs(addrDels) - //construct the validators + // construct the validators amts := []sdk.Int{sdk.NewInt(9), sdk.NewInt(8), sdk.NewInt(7)} var validators [3]types.Validator for i, amt := range amts { @@ -325,7 +325,7 @@ func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) { delTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10) delCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), delTokens)) - //create a validator with a self-delegation + // create a validator with a self-delegation validator := teststaking.NewValidator(t, addrVals[0], PKs[0]) validator.MinSelfDelegation = delTokens @@ -385,7 +385,7 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) { addrDels := simapp.AddTestAddrsIncremental(app, ctx, 2, sdk.NewInt(0)) addrVals := simapp.ConvertAddrsToValAddrs(addrDels) - //create a validator with a self-delegation + // create a validator with a self-delegation validator := teststaking.NewValidator(t, addrVals[0], PKs[0]) app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) @@ -557,7 +557,7 @@ func TestUnbondingAllDelegationFromValidator(t *testing.T) { require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), delCoins)) app.AccountKeeper.SetModuleAccount(ctx, notBondedPool) - //create a validator with a self-delegation + // create a validator with a self-delegation validator := teststaking.NewValidator(t, addrVals[0], PKs[0]) app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) @@ -806,7 +806,7 @@ func TestRedelegateSelfDelegation(t *testing.T) { require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), startCoins)) app.AccountKeeper.SetModuleAccount(ctx, notBondedPool) - //create a validator with a self-delegation + // create a validator with a self-delegation validator := teststaking.NewValidator(t, addrVals[0], PKs[0]) app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) @@ -862,7 +862,7 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) { require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), startCoins)) app.AccountKeeper.SetModuleAccount(ctx, notBondedPool) - //create a validator with a self-delegation + // create a validator with a self-delegation validator := teststaking.NewValidator(t, addrVals[0], PKs[0]) app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) @@ -909,7 +909,7 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) { params := app.StakingKeeper.GetParams(ctx) require.True(t, blockTime.Add(params.UnbondingTime).Equal(validator.UnbondingTime)) - //change the context + // change the context header = ctx.BlockHeader() blockHeight2 := int64(20) header.Height = blockHeight2 @@ -944,7 +944,7 @@ func TestRedelegateFromUnbondedValidator(t *testing.T) { require.NoError(t, testutil.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), startCoins)) app.AccountKeeper.SetModuleAccount(ctx, notBondedPool) - //create a validator with a self-delegation + // create a validator with a self-delegation validator := teststaking.NewValidator(t, addrVals[0], PKs[0]) app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) diff --git a/x/staking/keeper/grpc_query.go b/x/staking/keeper/grpc_query.go index 8fa16354d48e..79f9542adf22 100644 --- a/x/staking/keeper/grpc_query.go +++ b/x/staking/keeper/grpc_query.go @@ -53,7 +53,6 @@ func (k Querier) Validators(c context.Context, req *types.QueryValidatorsRequest return true, nil }) - if err != nil { return nil, status.Error(codes.Internal, err.Error()) } @@ -129,7 +128,8 @@ func (k Querier) ValidatorDelegations(c context.Context, req *types.QueryValidat } return &types.QueryValidatorDelegationsResponse{ - DelegationResponses: delResponses, Pagination: pageRes}, nil + DelegationResponses: delResponses, Pagination: pageRes, + }, nil } // ValidatorUnbondingDelegations queries unbonding delegations of a validator @@ -287,7 +287,6 @@ func (k Querier) DelegatorDelegations(c context.Context, req *types.QueryDelegat } return &types.QueryDelegatorDelegationsResponse{DelegationResponses: delegationResps, Pagination: pageRes}, nil - } // DelegatorValidator queries validator info for given delegator validator pair @@ -354,7 +353,8 @@ func (k Querier) DelegatorUnbondingDelegations(c context.Context, req *types.Que } return &types.QueryDelegatorUnbondingDelegationsResponse{ - UnbondingResponses: unbondingDelegations, Pagination: pageRes}, nil + UnbondingResponses: unbondingDelegations, Pagination: pageRes, + }, nil } // HistoricalInfo queries the historical info for given height @@ -439,7 +439,6 @@ func (k Querier) DelegatorValidators(c context.Context, req *types.QueryDelegato validators = append(validators, validator) return nil }) - if err != nil { return nil, status.Error(codes.Internal, err.Error()) } @@ -471,7 +470,6 @@ func (k Querier) Params(c context.Context, _ *types.QueryParamsRequest) (*types. } func queryRedelegation(ctx sdk.Context, k Querier, req *types.QueryRedelegationsRequest) (redels types.Redelegations, err error) { - delAddr, err := sdk.AccAddressFromBech32(req.DelegatorAddr) if err != nil { return nil, err diff --git a/x/staking/keeper/grpc_query_test.go b/x/staking/keeper/grpc_query_test.go index 402e0dc0f2cd..09cdb5e47cea 100644 --- a/x/staking/keeper/grpc_query_test.go +++ b/x/staking/keeper/grpc_query_test.go @@ -56,8 +56,10 @@ func (suite *KeeperTestSuite) TestGRPCQueryValidators() { { "valid request", func() { - req = &types.QueryValidatorsRequest{Status: types.Bonded.String(), - Pagination: &query.PageRequest{Limit: 1, CountTotal: true}} + req = &types.QueryValidatorsRequest{ + Status: types.Bonded.String(), + Pagination: &query.PageRequest{Limit: 1, CountTotal: true}, + } }, true, 1, @@ -149,7 +151,8 @@ func (suite *KeeperTestSuite) TestGRPCQueryDelegatorValidators() { func() { req = &types.QueryDelegatorValidatorsRequest{ DelegatorAddr: addrs[0].String(), - Pagination: &query.PageRequest{Limit: 1, CountTotal: true}} + Pagination: &query.PageRequest{Limit: 1, CountTotal: true}, + } }, true, }, @@ -321,8 +324,10 @@ func (suite *KeeperTestSuite) TestGRPCQueryDelegatorDelegations() { { "valid request", func() { - req = &types.QueryDelegatorDelegationsRequest{DelegatorAddr: addrAcc.String(), - Pagination: &query.PageRequest{Limit: 1, CountTotal: true}} + req = &types.QueryDelegatorDelegationsRequest{ + DelegatorAddr: addrAcc.String(), + Pagination: &query.PageRequest{Limit: 1, CountTotal: true}, + } }, func(suite *KeeperTestSuite, response *types.QueryDelegatorDelegationsResponse) { suite.Equal(uint64(2), response.Pagination.Total) @@ -384,8 +389,10 @@ func (suite *KeeperTestSuite) TestGRPCQueryValidatorDelegations() { { "valid request", func() { - req = &types.QueryValidatorDelegationsRequest{ValidatorAddr: addrVal1, - Pagination: &query.PageRequest{Limit: 1, CountTotal: true}} + req = &types.QueryValidatorDelegationsRequest{ + ValidatorAddr: addrVal1, + Pagination: &query.PageRequest{Limit: 1, CountTotal: true}, + } }, true, false, @@ -451,7 +458,8 @@ func (suite *KeeperTestSuite) TestGRPCQueryUnbondingDelegation() { "valid request", func() { req = &types.QueryUnbondingDelegationRequest{ - DelegatorAddr: addrAcc2.String(), ValidatorAddr: addrVal2} + DelegatorAddr: addrAcc2.String(), ValidatorAddr: addrVal2, + } }, true, }, @@ -515,8 +523,10 @@ func (suite *KeeperTestSuite) TestGRPCQueryDelegatorUnbondingDelegations() { { "valid request", func() { - req = &types.QueryDelegatorUnbondingDelegationsRequest{DelegatorAddr: addrAcc.String(), - Pagination: &query.PageRequest{Limit: 1, CountTotal: true}} + req = &types.QueryDelegatorUnbondingDelegationsRequest{ + DelegatorAddr: addrAcc.String(), + Pagination: &query.PageRequest{Limit: 1, CountTotal: true}, + } }, true, false, @@ -657,8 +667,10 @@ func (suite *KeeperTestSuite) TestGRPCQueryRedelegations() { { "request redelegations with non existent pairs", func() { - req = &types.QueryRedelegationsRequest{DelegatorAddr: addrAcc.String(), SrcValidatorAddr: val3.String(), - DstValidatorAddr: val4.String()} + req = &types.QueryRedelegationsRequest{ + DelegatorAddr: addrAcc.String(), SrcValidatorAddr: val3.String(), + DstValidatorAddr: val4.String(), + } }, false, true, @@ -668,7 +680,8 @@ func (suite *KeeperTestSuite) TestGRPCQueryRedelegations() { func() { req = &types.QueryRedelegationsRequest{ DelegatorAddr: addrAcc1.String(), SrcValidatorAddr: val1.OperatorAddress, - DstValidatorAddr: val2.OperatorAddress, Pagination: &query.PageRequest{}} + DstValidatorAddr: val2.OperatorAddress, Pagination: &query.PageRequest{}, + } }, true, false, @@ -678,7 +691,8 @@ func (suite *KeeperTestSuite) TestGRPCQueryRedelegations() { func() { req = &types.QueryRedelegationsRequest{ DelegatorAddr: addrAcc1.String(), SrcValidatorAddr: val1.OperatorAddress, - Pagination: &query.PageRequest{}} + Pagination: &query.PageRequest{}, + } }, true, false, @@ -688,7 +702,8 @@ func (suite *KeeperTestSuite) TestGRPCQueryRedelegations() { func() { req = &types.QueryRedelegationsRequest{ SrcValidatorAddr: val1.GetOperator().String(), - Pagination: &query.PageRequest{Limit: 1, CountTotal: true}} + Pagination: &query.PageRequest{Limit: 1, CountTotal: true}, + } }, true, false, @@ -746,7 +761,8 @@ func (suite *KeeperTestSuite) TestGRPCQueryValidatorUnbondingDelegations() { func() { req = &types.QueryValidatorUnbondingDelegationsRequest{ ValidatorAddr: val1.GetOperator().String(), - Pagination: &query.PageRequest{Limit: 1, CountTotal: true}} + Pagination: &query.PageRequest{Limit: 1, CountTotal: true}, + } }, true, }, diff --git a/x/staking/keeper/keeper_test.go b/x/staking/keeper/keeper_test.go index f15074d63bb4..610acf4cb030 100644 --- a/x/staking/keeper/keeper_test.go +++ b/x/staking/keeper/keeper_test.go @@ -53,17 +53,18 @@ func (suite *KeeperTestSuite) SetupTest() { suite.app, suite.ctx, suite.queryClient, suite.addrs, suite.vals = app, ctx, queryClient, addrs, validators } + func TestParams(t *testing.T) { app := simapp.Setup(t, false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) expParams := types.DefaultParams() - //check that the empty keeper loads the default + // check that the empty keeper loads the default resParams := app.StakingKeeper.GetParams(ctx) require.True(t, expParams.Equal(resParams)) - //modify a params, save, and retrieve + // modify a params, save, and retrieve expParams.MaxValidators = 777 app.StakingKeeper.SetParams(ctx, expParams) resParams = app.StakingKeeper.GetParams(ctx) diff --git a/x/staking/keeper/querier.go b/x/staking/keeper/querier.go index 06bab770467d..95c26d49a45d 100644 --- a/x/staking/keeper/querier.go +++ b/x/staking/keeper/querier.go @@ -190,7 +190,6 @@ func queryDelegatorDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper, delegations := k.GetAllDelegatorDelegations(ctx, params.DelegatorAddr) delegationResps, err := DelegationsToDelegationResponses(ctx, k, delegations) - if err != nil { return nil, err } diff --git a/x/staking/keeper/slash.go b/x/staking/keeper/slash.go index 734af19f6f44..d09fb56c270f 100644 --- a/x/staking/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -165,7 +165,8 @@ func (k Keeper) Unjail(ctx sdk.Context, consAddr sdk.ConsAddress) { // (the amount actually slashed may be less if there's // insufficient stake remaining) func (k Keeper) SlashUnbondingDelegation(ctx sdk.Context, unbondingDelegation types.UnbondingDelegation, - infractionHeight int64, slashFactor sdk.Dec) (totalSlashAmount sdk.Int) { + infractionHeight int64, slashFactor sdk.Dec, +) (totalSlashAmount sdk.Int) { now := ctx.BlockHeader().Time totalSlashAmount = sdk.ZeroInt() burnedAmount := sdk.ZeroInt() @@ -218,7 +219,8 @@ func (k Keeper) SlashUnbondingDelegation(ctx sdk.Context, unbondingDelegation ty // insufficient stake remaining) // NOTE this is only slashing for prior infractions from the source validator func (k Keeper) SlashRedelegation(ctx sdk.Context, srcValidator types.Validator, redelegation types.Redelegation, - infractionHeight int64, slashFactor sdk.Dec) (totalSlashAmount sdk.Int) { + infractionHeight int64, slashFactor sdk.Dec, +) (totalSlashAmount sdk.Int) { now := ctx.BlockHeader().Time totalSlashAmount = sdk.ZeroInt() bondedBurnedAmount, notBondedBurnedAmount := sdk.ZeroInt(), sdk.ZeroInt() diff --git a/x/staking/keeper/validator.go b/x/staking/keeper/validator.go index 8539cbe0ec8a..9b51577c5a06 100644 --- a/x/staking/keeper/validator.go +++ b/x/staking/keeper/validator.go @@ -96,7 +96,8 @@ func (k Keeper) SetNewValidatorByPowerIndex(ctx sdk.Context, validator types.Val // Update the tokens of an existing validator, update the validators power index key func (k Keeper) AddValidatorTokensAndShares(ctx sdk.Context, validator types.Validator, - tokensToAdd sdk.Int) (valOut types.Validator, addedShares sdk.Dec) { + tokensToAdd sdk.Int, +) (valOut types.Validator, addedShares sdk.Dec) { k.DeleteValidatorByPowerIndex(ctx, validator) validator, addedShares = validator.AddTokensFromDel(tokensToAdd) k.SetValidator(ctx, validator) @@ -107,7 +108,8 @@ func (k Keeper) AddValidatorTokensAndShares(ctx sdk.Context, validator types.Val // Update the tokens of an existing validator, update the validators power index key func (k Keeper) RemoveValidatorTokensAndShares(ctx sdk.Context, validator types.Validator, - sharesToRemove sdk.Dec) (valOut types.Validator, removedTokens sdk.Int) { + sharesToRemove sdk.Dec, +) (valOut types.Validator, removedTokens sdk.Int) { k.DeleteValidatorByPowerIndex(ctx, validator) validator, removedTokens = validator.RemoveDelShares(sharesToRemove) k.SetValidator(ctx, validator) @@ -118,7 +120,8 @@ func (k Keeper) RemoveValidatorTokensAndShares(ctx sdk.Context, validator types. // Update the tokens of an existing validator, update the validators power index key func (k Keeper) RemoveValidatorTokens(ctx sdk.Context, - validator types.Validator, tokensToRemove sdk.Int) types.Validator { + validator types.Validator, tokensToRemove sdk.Int, +) types.Validator { k.DeleteValidatorByPowerIndex(ctx, validator) validator = validator.RemoveTokens(tokensToRemove) k.SetValidator(ctx, validator) @@ -130,7 +133,8 @@ func (k Keeper) RemoveValidatorTokens(ctx sdk.Context, // UpdateValidatorCommission attempts to update a validator's commission rate. // An error is returned if the new commission rate is invalid. func (k Keeper) UpdateValidatorCommission(ctx sdk.Context, - validator types.Validator, newRate sdk.Dec) (types.Commission, error) { + validator types.Validator, newRate sdk.Dec, +) (types.Commission, error) { commission := validator.Commission blockTime := ctx.BlockHeader().Time diff --git a/x/staking/keeper/validator_bench_test.go b/x/staking/keeper/validator_bench_test.go index 54a616c90e50..ea727b72457d 100644 --- a/x/staking/keeper/validator_bench_test.go +++ b/x/staking/keeper/validator_bench_test.go @@ -5,10 +5,10 @@ import "testing" func BenchmarkGetValidator(b *testing.B) { // 900 is the max number we are allowed to use in order to avoid simapp.CreateTestPubKeys // panic: encoding/hex: odd length hex string - var powersNumber = 900 + powersNumber := 900 var totalPower int64 = 0 - var powers = make([]int64, powersNumber) + powers := make([]int64, powersNumber) for i := range powers { powers[i] = int64(i) totalPower += int64(i) diff --git a/x/staking/keeper/validator_test.go b/x/staking/keeper/validator_test.go index 585897ca7929..ffa6d595854f 100644 --- a/x/staking/keeper/validator_test.go +++ b/x/staking/keeper/validator_test.go @@ -252,7 +252,7 @@ func TestSlashToZeroPowerRemoved(t *testing.T) { func TestValidatorBasics(t *testing.T) { app, ctx, _, addrVals := bootstrapValidatorTest(t, 1000, 20) - //construct the validators + // construct the validators var validators [3]types.Validator powers := []int64{9, 8, 7} for i, power := range powers { @@ -357,7 +357,8 @@ func TestGetValidatorSortingUnmixed(t *testing.T) { app.StakingKeeper.PowerReduction(ctx).MulRaw(100), app.StakingKeeper.PowerReduction(ctx), app.StakingKeeper.PowerReduction(ctx).MulRaw(400), - app.StakingKeeper.PowerReduction(ctx).MulRaw(200)} + app.StakingKeeper.PowerReduction(ctx).MulRaw(200), + } n := len(amts) var validators [5]types.Validator for i, amt := range amts { @@ -450,7 +451,8 @@ func TestGetValidatorSortingMixed(t *testing.T) { app.StakingKeeper.PowerReduction(ctx).MulRaw(100), app.StakingKeeper.PowerReduction(ctx), app.StakingKeeper.PowerReduction(ctx).MulRaw(400), - app.StakingKeeper.PowerReduction(ctx).MulRaw(200)} + app.StakingKeeper.PowerReduction(ctx).MulRaw(200), + } var validators [5]types.Validator for i, amt := range amts { diff --git a/x/staking/simulation/genesis_test.go b/x/staking/simulation/genesis_test.go index cbd2196b55a2..dd60652a87bb 100644 --- a/x/staking/simulation/genesis_test.go +++ b/x/staking/simulation/genesis_test.go @@ -97,7 +97,8 @@ func TestRandomizedGenState1(t *testing.T) { Accounts: simtypes.RandomAccounts(r, 3), InitialStake: sdkmath.NewInt(1000), GenState: make(map[string]json.RawMessage), - }, "invalid memory address or nil pointer dereference"}, + }, "invalid memory address or nil pointer dereference", + }, } for _, tt := range tests { diff --git a/x/staking/simulation/operations_test.go b/x/staking/simulation/operations_test.go index 2c04abe875a8..aa07bafe0649 100644 --- a/x/staking/simulation/operations_test.go +++ b/x/staking/simulation/operations_test.go @@ -46,7 +46,8 @@ func TestWeightedOperations(t *testing.T) { weight int opMsgRoute string opMsgName string - }{{simappparams.DefaultWeightMsgCreateValidator, types.ModuleName, types.TypeMsgCreateValidator}, + }{ + {simappparams.DefaultWeightMsgCreateValidator, types.ModuleName, types.TypeMsgCreateValidator}, {simappparams.DefaultWeightMsgEditValidator, types.ModuleName, types.TypeMsgEditValidator}, {simappparams.DefaultWeightMsgDelegate, types.ModuleName, types.TypeMsgDelegate}, {simappparams.DefaultWeightMsgUndelegate, types.ModuleName, types.TypeMsgUndelegate}, @@ -380,5 +381,4 @@ func setupValidatorRewards(app *simapp.SimApp, ctx sdk.Context, valAddress sdk.V // setup current revards currentRewards := distrtypes.NewValidatorCurrentRewards(decCoins, 3) app.DistrKeeper.SetValidatorCurrentRewards(ctx, valAddress, currentRewards) - } diff --git a/x/staking/types/authz.go b/x/staking/types/authz.go index 3a6d60c87544..1f9016cdbb6e 100644 --- a/x/staking/types/authz.go +++ b/x/staking/types/authz.go @@ -10,9 +10,7 @@ import ( // Tracking issues https://github.com/cosmos/cosmos-sdk/issues/9054, https://github.com/cosmos/cosmos-sdk/discussions/9072 const gasCostPerIteration = uint64(10) -var ( - _ authz.Authorization = &StakeAuthorization{} -) +var _ authz.Authorization = &StakeAuthorization{} // NewStakeAuthorization creates a new StakeAuthorization object. func NewStakeAuthorization(allowed []sdk.ValAddress, denied []sdk.ValAddress, authzType AuthorizationType, amount *sdk.Coin) (*StakeAuthorization, error) { @@ -98,8 +96,10 @@ func (a StakeAuthorization) Accept(ctx sdk.Context, msg sdk.Msg) (authz.AcceptRe } if a.MaxTokens == nil { - return authz.AcceptResponse{Accept: true, Delete: false, - Updated: &StakeAuthorization{Validators: a.GetValidators(), AuthorizationType: a.GetAuthorizationType()}}, nil + return authz.AcceptResponse{ + Accept: true, Delete: false, + Updated: &StakeAuthorization{Validators: a.GetValidators(), AuthorizationType: a.GetAuthorizationType()}, + }, nil } limitLeft, err := a.MaxTokens.SafeSub(amount) @@ -109,8 +109,10 @@ func (a StakeAuthorization) Accept(ctx sdk.Context, msg sdk.Msg) (authz.AcceptRe if limitLeft.IsZero() { return authz.AcceptResponse{Accept: true, Delete: true}, nil } - return authz.AcceptResponse{Accept: true, Delete: false, - Updated: &StakeAuthorization{Validators: a.GetValidators(), AuthorizationType: a.GetAuthorizationType(), MaxTokens: &limitLeft}}, nil + return authz.AcceptResponse{ + Accept: true, Delete: false, + Updated: &StakeAuthorization{Validators: a.GetValidators(), AuthorizationType: a.GetAuthorizationType(), MaxTokens: &limitLeft}, + }, nil } func validateAllowAndDenyValidators(allowed []sdk.ValAddress, denied []sdk.ValAddress) ([]string, []string, error) { diff --git a/x/staking/types/authz_test.go b/x/staking/types/authz_test.go index 1f649f0a28a4..b794618b744b 100644 --- a/x/staking/types/authz_test.go +++ b/x/staking/types/authz_test.go @@ -94,7 +94,8 @@ func TestAuthzAuthorizations(t *testing.T) { &stakingtypes.StakeAuthorization{ Validators: &stakingtypes.StakeAuthorization_AllowList{ AllowList: &stakingtypes.StakeAuthorization_Validators{Address: validators1_2}, - }, MaxTokens: &coin50, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE}, + }, MaxTokens: &coin50, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, + }, }, { "delegate: testing with invalid validator", @@ -119,7 +120,8 @@ func TestAuthzAuthorizations(t *testing.T) { &stakingtypes.StakeAuthorization{ Validators: &stakingtypes.StakeAuthorization_AllowList{ AllowList: &stakingtypes.StakeAuthorization_Validators{Address: validators1_2}, - }, MaxTokens: nil, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE}, + }, MaxTokens: nil, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, + }, }, { "delegate: fail validator denied", @@ -144,7 +146,8 @@ func TestAuthzAuthorizations(t *testing.T) { &stakingtypes.StakeAuthorization{ Validators: &stakingtypes.StakeAuthorization_DenyList{ DenyList: &stakingtypes.StakeAuthorization_Validators{Address: []string{val1.String()}}, - }, MaxTokens: nil, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE}, + }, MaxTokens: nil, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_DELEGATE, + }, }, { "undelegate: expect 0 remaining coins", @@ -169,7 +172,8 @@ func TestAuthzAuthorizations(t *testing.T) { &stakingtypes.StakeAuthorization{ Validators: &stakingtypes.StakeAuthorization_AllowList{ AllowList: &stakingtypes.StakeAuthorization_Validators{Address: validators1_2}, - }, MaxTokens: &coin50, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE}, + }, MaxTokens: &coin50, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE, + }, }, { "undelegate: testing with invalid validator", @@ -194,7 +198,8 @@ func TestAuthzAuthorizations(t *testing.T) { &stakingtypes.StakeAuthorization{ Validators: &stakingtypes.StakeAuthorization_AllowList{ AllowList: &stakingtypes.StakeAuthorization_Validators{Address: validators1_2}, - }, MaxTokens: nil, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE}, + }, MaxTokens: nil, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_UNDELEGATE, + }, }, { "undelegate: fail cannot undelegate, permission denied", @@ -231,7 +236,8 @@ func TestAuthzAuthorizations(t *testing.T) { &stakingtypes.StakeAuthorization{ Validators: &stakingtypes.StakeAuthorization_AllowList{ AllowList: &stakingtypes.StakeAuthorization_Validators{Address: validators1_2}, - }, MaxTokens: &coin50, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE}, + }, MaxTokens: &coin50, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE, + }, }, { "redelegate: testing with invalid validator", @@ -256,7 +262,8 @@ func TestAuthzAuthorizations(t *testing.T) { &stakingtypes.StakeAuthorization{ Validators: &stakingtypes.StakeAuthorization_AllowList{ AllowList: &stakingtypes.StakeAuthorization_Validators{Address: validators1_2}, - }, MaxTokens: nil, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE}, + }, MaxTokens: nil, AuthorizationType: stakingtypes.AuthorizationType_AUTHORIZATION_TYPE_REDELEGATE, + }, }, { "redelegate: fail cannot undelegate, permission denied", diff --git a/x/staking/types/delegation.go b/x/staking/types/delegation.go index f3412b5f8344..07438c4f40af 100644 --- a/x/staking/types/delegation.go +++ b/x/staking/types/delegation.go @@ -66,6 +66,7 @@ func (d Delegation) GetDelegatorAddr() sdk.AccAddress { } return delAddr } + func (d Delegation) GetValidatorAddr() sdk.ValAddress { addr, err := sdk.ValAddressFromBech32(d.ValidatorAddress) if err != nil { @@ -350,7 +351,8 @@ func NewRedelegationResponse( // NewRedelegationEntryResponse creates a new RedelegationEntryResponse instance. func NewRedelegationEntryResponse( - creationHeight int64, completionTime time.Time, sharesDst sdk.Dec, initialBalance, balance sdk.Int) RedelegationEntryResponse { + creationHeight int64, completionTime time.Time, sharesDst sdk.Dec, initialBalance, balance sdk.Int, +) RedelegationEntryResponse { return RedelegationEntryResponse{ RedelegationEntry: NewRedelegationEntry(creationHeight, completionTime, initialBalance, sharesDst), Balance: balance, diff --git a/x/staking/types/historical_info_test.go b/x/staking/types/historical_info_test.go index 66d3105897e1..da47623ac0c2 100644 --- a/x/staking/types/historical_info_test.go +++ b/x/staking/types/historical_info_test.go @@ -1,12 +1,13 @@ package types_test import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/legacy" "math/rand" "sort" "testing" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/legacy" + "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" diff --git a/x/staking/types/hooks.go b/x/staking/types/hooks.go index 33838bcaa030..93e0d21cc085 100644 --- a/x/staking/types/hooks.go +++ b/x/staking/types/hooks.go @@ -22,6 +22,7 @@ func (h MultiStakingHooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.Va return nil } + func (h MultiStakingHooks) BeforeValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) error { for i := range h { if err := h[i].BeforeValidatorModified(ctx, valAddr); err != nil { @@ -30,6 +31,7 @@ func (h MultiStakingHooks) BeforeValidatorModified(ctx sdk.Context, valAddr sdk. } return nil } + func (h MultiStakingHooks) AfterValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { for i := range h { if err := h[i].AfterValidatorRemoved(ctx, consAddr, valAddr); err != nil { @@ -38,6 +40,7 @@ func (h MultiStakingHooks) AfterValidatorRemoved(ctx sdk.Context, consAddr sdk.C } return nil } + func (h MultiStakingHooks) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { for i := range h { if err := h[i].AfterValidatorBonded(ctx, consAddr, valAddr); err != nil { @@ -46,6 +49,7 @@ func (h MultiStakingHooks) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.Co } return nil } + func (h MultiStakingHooks) AfterValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { for i := range h { if err := h[i].AfterValidatorBeginUnbonding(ctx, consAddr, valAddr); err != nil { @@ -54,6 +58,7 @@ func (h MultiStakingHooks) AfterValidatorBeginUnbonding(ctx sdk.Context, consAdd } return nil } + func (h MultiStakingHooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { for i := range h { if err := h[i].BeforeDelegationCreated(ctx, delAddr, valAddr); err != nil { @@ -62,6 +67,7 @@ func (h MultiStakingHooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk. } return nil } + func (h MultiStakingHooks) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { for i := range h { if err := h[i].BeforeDelegationSharesModified(ctx, delAddr, valAddr); err != nil { @@ -70,6 +76,7 @@ func (h MultiStakingHooks) BeforeDelegationSharesModified(ctx sdk.Context, delAd } return nil } + func (h MultiStakingHooks) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { for i := range h { if err := h[i].BeforeDelegationRemoved(ctx, delAddr, valAddr); err != nil { @@ -78,6 +85,7 @@ func (h MultiStakingHooks) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk. } return nil } + func (h MultiStakingHooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { for i := range h { if err := h[i].AfterDelegationModified(ctx, delAddr, valAddr); err != nil { @@ -86,6 +94,7 @@ func (h MultiStakingHooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk. } return nil } + func (h MultiStakingHooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdk.Dec) error { for i := range h { if err := h[i].BeforeValidatorSlashed(ctx, valAddr, fraction); err != nil { diff --git a/x/staking/types/keys_test.go b/x/staking/types/keys_test.go index 35667f949da5..20269e671baf 100644 --- a/x/staking/types/keys_test.go +++ b/x/staking/types/keys_test.go @@ -56,12 +56,18 @@ func TestGetREDByValDstIndexKey(t *testing.T) { valDstAddr sdk.ValAddress wantHex string }{ - {sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr1), - "361463d771218209d8bd03c482f69dfba57310f086091463d771218209d8bd03c482f69dfba57310f086091463d771218209d8bd03c482f69dfba57310f08609"}, - {sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr2), sdk.ValAddress(keysAddr3), - "36143ab62f0d93849be495e21e3e9013a517038f45bd1463d771218209d8bd03c482f69dfba57310f08609145ef3b5f25c54946d4a89fc0d09d2f126614540f2"}, - {sdk.AccAddress(keysAddr2), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr3), - "36143ab62f0d93849be495e21e3e9013a517038f45bd145ef3b5f25c54946d4a89fc0d09d2f126614540f21463d771218209d8bd03c482f69dfba57310f08609"}, + { + sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr1), + "361463d771218209d8bd03c482f69dfba57310f086091463d771218209d8bd03c482f69dfba57310f086091463d771218209d8bd03c482f69dfba57310f08609", + }, + { + sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr2), sdk.ValAddress(keysAddr3), + "36143ab62f0d93849be495e21e3e9013a517038f45bd1463d771218209d8bd03c482f69dfba57310f08609145ef3b5f25c54946d4a89fc0d09d2f126614540f2", + }, + { + sdk.AccAddress(keysAddr2), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr3), + "36143ab62f0d93849be495e21e3e9013a517038f45bd145ef3b5f25c54946d4a89fc0d09d2f126614540f21463d771218209d8bd03c482f69dfba57310f08609", + }, } for i, tt := range tests { got := hex.EncodeToString(types.GetREDByValDstIndexKey(tt.delAddr, tt.valSrcAddr, tt.valDstAddr)) @@ -77,12 +83,18 @@ func TestGetREDByValSrcIndexKey(t *testing.T) { valDstAddr sdk.ValAddress wantHex string }{ - {sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr1), - "351463d771218209d8bd03c482f69dfba57310f086091463d771218209d8bd03c482f69dfba57310f086091463d771218209d8bd03c482f69dfba57310f08609"}, - {sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr2), sdk.ValAddress(keysAddr3), - "35145ef3b5f25c54946d4a89fc0d09d2f126614540f21463d771218209d8bd03c482f69dfba57310f08609143ab62f0d93849be495e21e3e9013a517038f45bd"}, - {sdk.AccAddress(keysAddr2), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr3), - "351463d771218209d8bd03c482f69dfba57310f08609145ef3b5f25c54946d4a89fc0d09d2f126614540f2143ab62f0d93849be495e21e3e9013a517038f45bd"}, + { + sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr1), + "351463d771218209d8bd03c482f69dfba57310f086091463d771218209d8bd03c482f69dfba57310f086091463d771218209d8bd03c482f69dfba57310f08609", + }, + { + sdk.AccAddress(keysAddr1), sdk.ValAddress(keysAddr2), sdk.ValAddress(keysAddr3), + "35145ef3b5f25c54946d4a89fc0d09d2f126614540f21463d771218209d8bd03c482f69dfba57310f08609143ab62f0d93849be495e21e3e9013a517038f45bd", + }, + { + sdk.AccAddress(keysAddr2), sdk.ValAddress(keysAddr1), sdk.ValAddress(keysAddr3), + "351463d771218209d8bd03c482f69dfba57310f08609145ef3b5f25c54946d4a89fc0d09d2f126614540f2143ab62f0d93849be495e21e3e9013a517038f45bd", + }, } for i, tt := range tests { got := hex.EncodeToString(types.GetREDByValSrcIndexKey(tt.delAddr, tt.valSrcAddr, tt.valDstAddr)) diff --git a/x/staking/types/params.go b/x/staking/types/params.go index cb9def63e00e..191b66e4c809 100644 --- a/x/staking/types/params.go +++ b/x/staking/types/params.go @@ -32,10 +32,8 @@ const ( DefaultHistoricalEntries uint32 = 10000 ) -var ( - // DefaultMinCommissionRate is set to 0% - DefaultMinCommissionRate = sdk.ZeroDec() -) +// DefaultMinCommissionRate is set to 0% +var DefaultMinCommissionRate = sdk.ZeroDec() var ( KeyUnbondingTime = []byte("UnbondingTime") diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index 88efb213f3ff..4296181ec9b5 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -452,7 +452,6 @@ func (v *Validator) MinEqual(other *Validator) bool { v.Jailed == other.Jailed && v.MinSelfDelegation.Equal(other.MinSelfDelegation) && v.ConsensusPubkey.Equal(other.ConsensusPubkey) - } // Equal checks if the receiver equals the parameter @@ -484,7 +483,6 @@ func (v Validator) ConsPubKey() (cryptotypes.PubKey, error) { } return pk, nil - } // TmConsPublicKey casts Validator.ConsensusPubkey to tmprotocrypto.PubKey. diff --git a/x/staking/types/validator_test.go b/x/staking/types/validator_test.go index 8601fbeec723..6e3172e51db2 100644 --- a/x/staking/types/validator_test.go +++ b/x/staking/types/validator_test.go @@ -121,7 +121,6 @@ func TestAddTokensValidatorUnbonding(t *testing.T) { } func TestAddTokensValidatorUnbonded(t *testing.T) { - validator := newValidator(t, valAddr1, pk1) validator = validator.UpdateStatus(types.Unbonded) validator, delShares := validator.AddTokensFromDel(sdk.NewInt(10)) diff --git a/x/upgrade/client/proposal_handler.go b/x/upgrade/client/proposal_handler.go index 082924787441..fb4a879fffec 100644 --- a/x/upgrade/client/proposal_handler.go +++ b/x/upgrade/client/proposal_handler.go @@ -5,5 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/upgrade/client/cli" ) -var LegacyProposalHandler = govclient.NewProposalHandler(cli.NewCmdSubmitLegacyUpgradeProposal) -var LegacyCancelProposalHandler = govclient.NewProposalHandler(cli.NewCmdSubmitLegacyCancelUpgradeProposal) +var ( + LegacyProposalHandler = govclient.NewProposalHandler(cli.NewCmdSubmitLegacyUpgradeProposal) + LegacyCancelProposalHandler = govclient.NewProposalHandler(cli.NewCmdSubmitLegacyCancelUpgradeProposal) +) diff --git a/x/upgrade/client/testutil/suite.go b/x/upgrade/client/testutil/suite.go index 7611c8bb8fd5..d5e21ce47ae6 100644 --- a/x/upgrade/client/testutil/suite.go +++ b/x/upgrade/client/testutil/suite.go @@ -86,7 +86,6 @@ func (s *IntegrationTestSuite) TestModuleVersionsCLI() { for _, tc := range testCases { s.Run(fmt.Sprintf("Case %s", tc.msg), func() { - expect := mv if tc.expPass { if tc.single { diff --git a/x/upgrade/keeper/keeper_test.go b/x/upgrade/keeper/keeper_test.go index fc8f0ecccbf7..19fee1054ec9 100644 --- a/x/upgrade/keeper/keeper_test.go +++ b/x/upgrade/keeper/keeper_test.go @@ -198,7 +198,6 @@ func (s *KeeperTestSuite) TestSetUpgradedClient() { s.Require().False(exists, "invalid case: %s retrieved valid client state", tc.name) } } - } // Test that the protocol version successfully increments after an diff --git a/x/upgrade/plan/downloader.go b/x/upgrade/plan/downloader.go index 0879b8badbfe..7686b7aec823 100644 --- a/x/upgrade/plan/downloader.go +++ b/x/upgrade/plan/downloader.go @@ -88,7 +88,7 @@ func EnsureBinary(path string) error { } // Make sure all executable bits are set. oldMode := info.Mode().Perm() - newMode := oldMode | 0111 // Set the three execute bits to on (a+x). + newMode := oldMode | 0o111 // Set the three execute bits to on (a+x). if oldMode != newMode { return os.Chmod(path, newMode) } diff --git a/x/upgrade/plan/downloader_test.go b/x/upgrade/plan/downloader_test.go index 6e10b6de4c78..3d50e9f13a44 100644 --- a/x/upgrade/plan/downloader_test.go +++ b/x/upgrade/plan/downloader_test.go @@ -24,7 +24,7 @@ type DownloaderTestSuite struct { func (s *DownloaderTestSuite) SetupTest() { s.Home = s.T().TempDir() - s.Assert().NoError(os.MkdirAll(filepath.Join(s.Home, "src"), 0777), "creating src/ dir") + s.Assert().NoError(os.MkdirAll(filepath.Join(s.Home, "src"), 0o777), "creating src/ dir") s.T().Logf("Home: [%s]", s.Home) } @@ -115,7 +115,7 @@ func requireFileExistsAndIsExecutable(t *testing.T, path string) { require.NoError(t, err, "stat error") perm := info.Mode().Perm() // Checks if at least one executable bit is set (user, group, or other) - isExe := perm&0111 != 0 + isExe := perm&0o111 != 0 require.True(t, isExe, "is executable: permissions = %s", perm) } @@ -219,9 +219,9 @@ func (s *DownloaderTestSuite) TestDownloadUpgrade() { func (s *DownloaderTestSuite) TestEnsureBinary() { nonExeName := s.saveSrcTestFile(NewTestFile("non-exe.txt", "Not executable")) - s.Require().NoError(os.Chmod(nonExeName, 0600), "chmod error nonExeName") + s.Require().NoError(os.Chmod(nonExeName, 0o600), "chmod error nonExeName") isExeName := s.saveSrcTestFile(NewTestFile("is-exe.sh", "#!/bin/bash\necho 'executing'\n")) - s.Require().NoError(os.Chmod(isExeName, 0777), "chmod error isExeName") + s.Require().NoError(os.Chmod(isExeName, 0o777), "chmod error isExeName") s.T().Run("file does not exist", func(t *testing.T) { name := filepath.Join(s.Home, "does-not-exist.txt") diff --git a/x/upgrade/types/plan_test.go b/x/upgrade/types/plan_test.go index bbd969eae0b3..724f68bf0525 100644 --- a/x/upgrade/types/plan_test.go +++ b/x/upgrade/types/plan_test.go @@ -105,7 +105,6 @@ func TestPlanValid(t *testing.T) { } }) } - } func TestShouldExecute(t *testing.T) { @@ -115,7 +114,6 @@ func TestShouldExecute(t *testing.T) { ctxHeight int64 expected bool }{ - "past height": { p: types.Plan{ Name: "do-good", diff --git a/x/upgrade/types/proposal.go b/x/upgrade/types/proposal.go index 987ccf978824..60a11fe7e8fd 100644 --- a/x/upgrade/types/proposal.go +++ b/x/upgrade/types/proposal.go @@ -54,6 +54,7 @@ func (csup *CancelSoftwareUpgradeProposal) ProposalRoute() string { return Rout func (csup *CancelSoftwareUpgradeProposal) ProposalType() string { return ProposalTypeCancelSoftwareUpgrade } + func (csup *CancelSoftwareUpgradeProposal) ValidateBasic() error { return gov.ValidateAbstract(csup) } diff --git a/x/upgrade/types/proposal_test.go b/x/upgrade/types/proposal_test.go index 7f56c6beaac9..4e6233a2d373 100644 --- a/x/upgrade/types/proposal_test.go +++ b/x/upgrade/types/proposal_test.go @@ -71,7 +71,6 @@ func TestContentAccessors(t *testing.T) { assert.Equal(t, tc.typ, unwrap.Prop.ProposalType()) assert.Equal(t, "upgrade", unwrap.Prop.ProposalRoute()) assert.Equal(t, tc.str, unwrap.Prop.String()) - }) } diff --git a/x/upgrade/types/storeloader_test.go b/x/upgrade/types/storeloader_test.go index ba3d772039b7..2bdf36c22a05 100644 --- a/x/upgrade/types/storeloader_test.go +++ b/x/upgrade/types/storeloader_test.go @@ -82,7 +82,7 @@ func TestSetLoader(t *testing.T) { data, err := json.Marshal(upgradeInfo) require.NoError(t, err) - err = os.WriteFile(upgradeInfoFilePath, data, 0644) + err = os.WriteFile(upgradeInfoFilePath, data, 0o644) require.NoError(t, err) // make sure it exists before running everything