From 237cb84cf703375982f28d3a591ee81b417c9e93 Mon Sep 17 00:00:00 2001 From: Jaeseung Lee <41176085+tkxkd0159@users.noreply.github.com> Date: Mon, 24 Jun 2024 10:17:54 +0900 Subject: [PATCH] style: Lint all files based on latest setting (backport #1171, #1414) (#1427) * Backport #1171 * Apply `gci` * Backport #1414 * Add CHANGELOG --- .golangci.yml | 159 +++++++++++++++--- CHANGELOG.md | 4 +- Makefile | 2 +- baseapp/abci.go | 14 +- baseapp/abci_test.go | 16 +- baseapp/baseapp.go | 9 +- baseapp/baseapp_test.go | 16 +- baseapp/block_gas_test.go | 7 +- baseapp/deliver_tx_test.go | 17 +- baseapp/msg_service_router_test.go | 5 +- baseapp/queryrouter_test.go | 1 - baseapp/reactor.go | 1 - baseapp/streaming.go | 3 +- baseapp/xxx_msg_test.go | 3 +- client/account_retriever.go | 2 +- client/broadcast.go | 5 +- client/cmd_test.go | 2 - client/config/cmd.go | 9 +- client/config/config.go | 10 +- client/config/config_test.go | 15 +- client/context.go | 7 +- client/debug/main.go | 2 +- client/flags/flags.go | 7 +- client/flags/flags_test.go | 2 - client/grpc/ocservice/service.go | 5 +- client/grpc/ocservice/service_test.go | 33 ++-- client/grpc/tmservice/block_test.go | 6 +- client/grpc/tmservice/service.go | 13 +- client/grpc/tmservice/service_test.go | 22 +-- client/keys/add.go | 2 +- client/keys/add_ledger_test.go | 1 - client/keys/add_test.go | 100 +++++------ client/keys/codec_test.go | 2 - client/keys/delete.go | 4 +- client/keys/export_test.go | 5 +- client/keys/import_test.go | 2 +- client/keys/list_test.go | 7 - client/keys/parse_test.go | 1 - client/keys/show.go | 4 +- client/keys/show_test.go | 8 +- client/keys/utils_test.go | 3 +- client/pruning/main.go | 3 +- client/query.go | 7 +- client/rpc/status.go | 3 +- client/test_helpers.go | 2 +- client/tx/legacy_test.go | 1 + client/tx/tx.go | 2 +- client/tx/tx_test.go | 11 +- client/utils.go | 2 +- client/utils_test.go | 7 +- codec/amino_codec_test.go | 6 +- codec/any_test.go | 8 +- codec/codec_common_test.go | 5 +- codec/proto_codec.go | 4 +- codec/proto_codec_test.go | 2 - codec/types/compat.go | 1 - codec/types/interface_registry.go | 1 - codec/unknownproto/benchmarks_test.go | 2 + codec/unknownproto/unit_helpers_test.go | 1 - codec/unknownproto/unknown_fields_test.go | 11 +- codec/yaml_test.go | 3 +- crypto/armor.go | 10 +- crypto/armor_test.go | 2 +- crypto/codec/oc.go | 3 +- crypto/hd/algo.go | 6 +- crypto/hd/fundraiser_test.go | 9 +- crypto/hd/hdpath.go | 8 +- crypto/hd/hdpath_test.go | 32 ++-- crypto/keyring/keyring.go | 18 +- crypto/keyring/keyring_test.go | 5 +- crypto/keyring/signing_algorithms_test.go | 1 - crypto/keyring/types.go | 2 +- crypto/keyring/types_test.go | 2 +- crypto/keys/ed25519/ed25519.go | 18 +- crypto/keys/ed25519/ed25519_test.go | 4 +- crypto/keys/internal/ecdsa/privkey.go | 2 +- .../internal/ecdsa/privkey_internal_test.go | 8 +- crypto/keys/internal/ecdsa/pubkey.go | 2 +- crypto/keys/multisig/codec.go | 1 - crypto/keys/multisig/multisig.go | 2 +- crypto/keys/multisig/multisig_test.go | 11 +- crypto/keys/secp256k1/secp256k1.go | 19 +-- .../keys/secp256k1/secp256k1_internal_test.go | 3 +- crypto/keys/secp256k1/secp256k1_nocgo.go | 5 +- crypto/keys/secp256k1/secp256k1_test.go | 8 +- .../keys/secp256r1/privkey_internal_test.go | 6 +- crypto/keys/secp256r1/pubkey.go | 2 +- crypto/keys/secp256r1/pubkey_internal_test.go | 12 +- crypto/ledger/encode_test.go | 29 ++-- crypto/ledger/ledger_mock.go | 14 +- crypto/ledger/ledger_secp256k1.go | 7 +- crypto/ledger/ledger_test.go | 1 + crypto/types/compact_bit_array_test.go | 9 +- crypto/types/types.go | 2 +- server/api/server.go | 14 +- server/config/config.go | 1 - server/config/toml.go | 2 +- server/export.go | 2 +- server/export_test.go | 8 +- .../grpc/gogoreflection/serverreflection.go | 20 +-- server/mock/app_test.go | 5 +- server/mock/store_test.go | 5 +- server/mock/tx.go | 1 - server/oc_cmds.go | 7 +- server/oc_cmds_test.go | 43 +++-- server/pruning_test.go | 2 - server/rollback.go | 3 +- server/start.go | 13 +- server/start_test.go | 5 +- server/types/app.go | 7 +- server/util.go | 8 +- server/util_test.go | 34 ++-- simapp/app.go | 12 +- simapp/app_test.go | 4 +- simapp/export.go | 2 +- simapp/genesis_account_test.go | 7 +- simapp/sim_bench_test.go | 1 - simapp/sim_test.go | 3 +- simapp/simd/cmd/genaccounts_test.go | 4 +- simapp/simd/cmd/root.go | 5 +- simapp/simd/cmd/root_test.go | 7 +- simapp/simd/cmd/testnet.go | 9 +- simapp/simd/cmd/testnet_test.go | 3 +- simapp/simd/main.go | 7 +- simapp/test_access.go | 9 +- simapp/test_helpers.go | 16 +- simapp/utils_test.go | 1 - snapshots/chunk.go | 3 +- snapshots/helpers_test.go | 22 ++- snapshots/manager.go | 2 +- snapshots/manager_test.go | 4 +- snapshots/store.go | 10 +- snapshots/store_test.go | 12 +- store/cache/cache.go | 3 +- store/cache/cache_test.go | 3 +- store/cache/metrics.go | 4 +- store/cachekv/bench_helper_test.go | 2 +- store/cachekv/search_test.go | 2 - store/cachekv/store.go | 12 +- store/cachekv/store_bench_test.go | 4 + store/cachekv/store_test.go | 11 +- store/dbadapter/store_test.go | 3 +- store/gaskv/store.go | 4 +- store/gaskv/store_test.go | 1 - store/iavl/store.go | 13 +- store/iavl/store_test.go | 30 ++-- store/iavl/tree_test.go | 8 +- store/internal/maps/maps.go | 3 +- store/internal/proofs/helpers.go | 3 +- store/listenkv/store.go | 9 +- store/listenkv/store_test.go | 9 +- store/mem/mem_test.go | 3 +- store/prefix/store.go | 4 +- store/prefix/store_test.go | 19 ++- store/rootmulti/proof_test.go | 5 +- store/rootmulti/rollback_test.go | 5 +- store/rootmulti/snapshot_test.go | 22 ++- store/rootmulti/store.go | 28 +-- store/rootmulti/store_test.go | 94 ++--------- store/streaming/constructor.go | 9 +- store/streaming/file/service.go | 5 +- store/streaming/file/service_test.go | 55 +++--- store/tracekv/store.go | 9 +- store/tracekv/store_test.go | 1 - store/types/gas_test.go | 1 - store/types/iterator_test.go | 5 +- store/types/listening.go | 4 +- store/types/listening_test.go | 6 +- store/types/proof.go | 5 +- store/types/store_test.go | 1 - store/types/utils.go | 2 +- store/types/utils_test.go | 4 +- testutil/context.go | 5 +- testutil/ioutil.go | 16 +- testutil/network/network.go | 3 + testutil/network/util.go | 6 +- testutil/rest/rest.go | 2 +- types/abci.go | 3 +- types/address.go | 41 +++-- types/address/hash.go | 2 +- types/address/hash_test.go | 3 +- types/address/store_key_test.go | 1 - types/address_race_test.go | 3 +- types/address_test.go | 57 ++++--- types/bech32/legacybech32/pk_test.go | 1 - types/coin_benchmark_test.go | 6 +- types/coin_test.go | 6 - types/context.go | 5 +- types/context_test.go | 7 - types/dec_coin.go | 2 +- types/dec_coin_test.go | 7 - types/decimal.go | 9 +- types/decimal_internal_test.go | 7 +- types/decimal_test.go | 7 +- types/denom_internal_test.go | 1 + types/errors/abci.go | 3 +- types/errors/abci_test.go | 5 +- types/errors/errors.go | 4 +- types/events.go | 5 +- types/events_test.go | 1 - types/int.go | 27 +-- types/int_test.go | 1 - types/module/configurator.go | 2 +- types/module/module.go | 3 +- types/module/module_int_test.go | 6 +- types/module/module_test.go | 6 +- types/query/filtered_pagination.go | 4 +- types/query/filtered_pagination_test.go | 10 +- types/query/pagination.go | 5 +- types/query/pagination_test.go | 11 +- types/result.go | 3 +- types/result_test.go | 7 +- types/simulation/account_test.go | 3 - types/simulation/rand_util_test.go | 3 - types/staking.go | 2 +- types/store.go | 2 +- types/store_test.go | 5 +- types/tx/types.go | 6 +- types/uint.go | 6 +- types/uint_test.go | 2 - types/utils_test.go | 2 - x/auth/ante/ante_test.go | 9 +- x/auth/ante/basic_test.go | 2 - x/auth/ante/fee_test.go | 3 +- x/auth/ante/sigverify.go | 6 +- x/auth/ante/sigverify_test.go | 5 +- x/auth/ante/testutil_test.go | 5 +- x/auth/client/cli/query.go | 2 +- x/auth/client/cli/tx_sign.go | 8 +- x/auth/client/testutil/helpers.go | 4 +- x/auth/client/testutil/suite.go | 15 +- x/auth/client/tx.go | 4 +- x/auth/client/tx_test.go | 8 +- x/auth/keeper/grpc_query.go | 5 +- x/auth/keeper/grpc_query_test.go | 1 + x/auth/keeper/querier_test.go | 4 +- x/auth/legacy/legacytx/stdtx_test.go | 12 +- x/auth/legacy/v043/store_test.go | 6 +- x/auth/module.go | 1 - x/auth/signing/handler_map.go | 3 +- x/auth/signing/verify_test.go | 13 +- x/auth/simulation/decoder_test.go | 1 - x/auth/tx/builder_test.go | 2 +- x/auth/tx/config.go | 6 +- x/auth/tx/direct.go | 3 +- x/auth/tx/encode_decode_test.go | 4 +- x/auth/tx/legacy_amino_json_test.go | 5 +- x/auth/tx/service.go | 2 +- x/auth/tx/service_test.go | 33 ++-- x/auth/tx/sigs_test.go | 1 - x/auth/tx2/service_test.go | 4 +- x/auth/types/account_test.go | 3 - x/auth/types/common_test.go | 6 +- x/auth/types/params_test.go | 1 - x/auth/types/permissions_test.go | 1 - x/auth/vesting/client/testutil/suite.go | 2 - x/auth/vesting/exported/exported.go | 3 +- x/auth/vesting/handler_test.go | 2 - x/auth/vesting/types/expected_keepers.go | 2 +- x/auth/vesting/types/test_common.go | 1 - x/auth/vesting/types/vesting_account_test.go | 2 - x/authz/client/testutil/grpc.go | 6 +- x/authz/client/testutil/query.go | 4 - x/authz/client/testutil/tx.go | 8 - x/authz/codec.go | 1 + x/authz/keeper/genesis_test.go | 3 +- x/authz/keeper/keeper.go | 17 +- x/authz/keeper/keeper_test.go | 3 +- x/authz/keeper/keys.go | 2 +- x/authz/module/module.go | 1 - x/authz/msgs.go | 4 +- x/authz/msgs_test.go | 3 +- x/authz/simulation/decoder_test.go | 3 +- x/authz/simulation/operations.go | 7 +- x/authz/simulation/operations_test.go | 14 +- x/bank/bench_test.go | 6 +- x/bank/client/testutil/grpc.go | 3 - x/bank/client/testutil/suite.go | 11 +- x/bank/keeper/genesis.go | 2 +- x/bank/keeper/genesis_test.go | 1 - x/bank/keeper/grpc_query_test.go | 1 + x/bank/keeper/keeper.go | 8 +- x/bank/keeper/keeper_test.go | 24 +-- x/bank/keeper/send.go | 4 +- x/bank/legacy/v040/types.go | 4 +- x/bank/legacy/v043/store.go | 2 +- x/bank/legacy/v043/store_test.go | 3 +- x/bank/simulation/operations.go | 5 +- x/bank/simulation/operations_test.go | 15 +- x/bank/simulation/params.go | 3 +- x/bank/types/balance_test.go | 3 +- x/bank/types/genesis_test.go | 1 - x/bank/types/key.go | 2 +- x/bank/types/key_test.go | 3 +- x/bank/types/metadata_test.go | 2 - x/bank/types/params_test.go | 1 - x/bankplus/keeper/inactive.go | 2 - x/bankplus/keeper/inactive_test.go | 11 +- x/bankplus/keeper/keeper.go | 2 +- x/bankplus/keeper/keeper_test.go | 1 - x/capability/capability_test.go | 2 +- x/capability/genesis_test.go | 3 +- x/capability/keeper/keeper.go | 6 +- x/capability/keeper/keeper_test.go | 5 +- x/capability/module.go | 3 +- x/capability/simulation/decoder_test.go | 1 - x/capability/types/genesis_test.go | 1 - x/capability/types/keys_test.go | 2 +- x/collection/client/cli/tx.go | 6 +- x/collection/client/testutil/query.go | 32 ---- x/collection/client/testutil/suite.go | 8 +- x/collection/client/testutil/tx.go | 44 ----- x/collection/collection_test.go | 18 +- x/collection/genesis.go | 1 - x/collection/keeper/alias.go | 12 +- x/collection/keeper/grpc_query.go | 19 +-- x/collection/keeper/keys.go | 31 ++-- x/collection/keeper/migrations/v2/keys.go | 2 +- .../keeper/migrations/v2/store_test.go | 1 - x/collection/keeper/msg_server_test.go | 95 +++++++---- x/collection/keeper/nft.go | 55 +++--- x/collection/keeper/supply.go | 24 +-- x/collection/keeper/supply_test.go | 6 +- x/collection/module/module.go | 2 +- x/collection/msgs_test.go | 7 +- x/crisis/client/testsuite/suite.go | 2 - x/crisis/handler_test.go | 1 - x/crisis/keeper/keeper_test.go | 3 +- x/distribution/client/cli/tx_test.go | 9 +- x/distribution/client/common/common_test.go | 1 - x/distribution/client/testutil/grpc.go | 8 - x/distribution/client/testutil/suite.go | 25 +-- x/distribution/keeper/allocation_test.go | 4 +- x/distribution/keeper/delegation.go | 2 +- x/distribution/keeper/genesis.go | 2 +- x/distribution/keeper/grpc_query.go | 2 +- x/distribution/keeper/keeper.go | 2 +- x/distribution/keeper/querier_test.go | 9 +- x/distribution/keeper/store.go | 4 +- x/distribution/keeper/validator.go | 1 - x/distribution/legacy/v043/store_test.go | 1 - x/distribution/module.go | 3 +- x/distribution/proposal_handler_test.go | 3 +- x/distribution/simulation/decoder_test.go | 1 - x/distribution/simulation/operations.go | 9 +- x/distribution/simulation/operations_test.go | 52 +++--- x/distribution/simulation/params.go | 3 +- x/distribution/types/expected_keepers.go | 4 +- x/distribution/types/params_internal_test.go | 1 - x/distribution/types/querier.go | 2 +- x/evidence/client/cli/tx.go | 4 +- x/evidence/client/testutil/suite.go | 2 - x/evidence/handler_test.go | 3 +- x/evidence/keeper/grpc_query.go | 10 +- x/evidence/keeper/grpc_query_test.go | 4 +- x/evidence/keeper/infraction.go | 1 - x/evidence/keeper/querier.go | 4 +- x/evidence/keeper/querier_test.go | 5 +- x/evidence/module.go | 4 +- x/evidence/simulation/decoder_test.go | 1 - x/evidence/types/evidence_test.go | 1 - x/evidence/types/msgs_test.go | 1 + x/fbridge/keeper/transfer.go | 2 +- x/fbridge/types/msgs_test.go | 1 - x/feegrant/client/testutil/suite.go | 17 +- x/feegrant/filtered_fee_test.go | 9 +- x/feegrant/grant_test.go | 1 - x/feegrant/keeper/genesis_test.go | 1 - x/feegrant/keeper/grpc_query.go | 4 +- x/feegrant/keeper/keeper.go | 4 +- x/feegrant/keeper/keeper_test.go | 11 +- x/feegrant/keeper/msg_server_test.go | 4 +- x/feegrant/key.go | 2 +- x/feegrant/module/module.go | 2 +- x/feegrant/msgs.go | 2 +- x/feegrant/simulation/decoder_test.go | 3 +- x/feegrant/simulation/operations.go | 8 +- x/feegrant/simulation/operations_test.go | 9 +- x/feegrant/types/grant_test.go | 1 - x/foundation/authz_test.go | 3 +- x/foundation/client/cli/tx.go | 3 +- x/foundation/client/testutil/grpc.go | 2 - x/foundation/client/testutil/query.go | 24 --- x/foundation/client/testutil/suite.go | 8 +- x/foundation/client/testutil/tx.go | 22 --- x/foundation/foundation_test.go | 9 +- x/foundation/genesis_test.go | 7 +- .../keeper/internal/censorship_test.go | 6 +- x/foundation/keeper/internal/exec.go | 1 - x/foundation/keeper/internal/genesis_test.go | 1 - x/foundation/keeper/internal/grpc_query.go | 15 +- x/foundation/keeper/internal/keeper_test.go | 1 - x/foundation/keeper/internal/member.go | 2 +- .../keeper/internal/migrations/v2/keys.go | 4 +- .../internal/migrations/v2/store_test.go | 1 - x/foundation/keeper/internal/params.go | 1 - x/foundation/keeper/internal/proposal.go | 2 - x/foundation/keeper/internal/treasury_test.go | 8 +- x/foundation/module/module.go | 4 +- x/foundation/msgs_test.go | 15 +- x/fswap/client/testutil/grpc.go | 4 - x/fswap/client/testutil/query.go | 8 - x/fswap/client/testutil/tx.go | 6 - x/fswap/types/msgs_test.go | 1 - x/genutil/client/cli/gentx.go | 2 +- x/genutil/client/cli/init.go | 7 +- x/genutil/client/cli/init_test.go | 8 +- x/genutil/client/testutil/helpers.go | 2 +- x/genutil/client/testutil/migrate.go | 1 - x/genutil/client/testutil/suite.go | 2 - x/genutil/client/testutil/validate_genesis.go | 1 - x/genutil/collect_test.go | 3 +- x/genutil/gentx_test.go | 4 +- x/genutil/module.go | 1 - x/genutil/utils.go | 4 +- x/genutil/utils_test.go | 1 - x/gov/abci_test.go | 5 +- x/gov/client/cli/parse_test.go | 20 +-- x/gov/client/cli/query.go | 10 +- x/gov/client/testutil/deposits.go | 3 +- x/gov/client/testutil/grpc.go | 8 - x/gov/client/testutil/suite.go | 24 +-- x/gov/client/utils/query.go | 4 +- x/gov/client/utils/query_test.go | 11 +- x/gov/common_test.go | 2 + x/gov/genesis_test.go | 5 +- x/gov/keeper/common_test.go | 10 +- x/gov/keeper/deposit_test.go | 6 +- x/gov/keeper/grpc_query.go | 6 +- x/gov/keeper/querier_test.go | 8 +- x/gov/keeper/tally.go | 2 +- x/gov/keeper/vote.go | 6 +- x/gov/legacy/v043/store.go | 2 +- x/gov/legacy/v043/store_test.go | 1 - x/gov/module.go | 1 - x/gov/simulation/decoder_test.go | 1 - x/gov/simulation/operations.go | 8 +- x/gov/simulation/operations_test.go | 1 + x/gov/types/proposal.go | 13 +- x/gov/types/vote.go | 15 +- x/mint/client/testutil/grpc.go | 6 +- x/mint/client/testutil/suite.go | 9 +- x/mint/keeper/querier_test.go | 6 +- x/mint/simulation/decoder_test.go | 1 - x/mint/simulation/params.go | 3 +- x/params/client/testutil/grpc.go | 1 - x/params/client/testutil/suite.go | 2 - x/params/keeper/keeper_test.go | 13 +- x/params/module.go | 1 - x/params/proposal_handler_test.go | 1 - x/params/simulation/operations.go | 2 +- x/params/types/subspace.go | 4 +- x/params/types/subspace_test.go | 6 +- x/simulation/mock_ostracon.go | 6 +- x/simulation/operation.go | 3 +- x/simulation/simulate.go | 27 +-- x/simulation/util.go | 1 + x/slashing/abci_test.go | 3 +- x/slashing/app_test.go | 5 +- x/slashing/client/testutil/grpc.go | 2 - x/slashing/client/testutil/suite.go | 6 - x/slashing/genesis_test.go | 6 +- x/slashing/keeper/grpc_query.go | 2 +- x/slashing/keeper/hooks.go | 5 +- x/slashing/keeper/keeper_test.go | 2 - x/slashing/keeper/signing_info_test.go | 4 +- x/slashing/legacy/v043/store_test.go | 1 - x/slashing/module.go | 4 +- x/slashing/simulation/decoder_test.go | 1 - x/slashing/simulation/operations.go | 3 +- x/slashing/simulation/operations_test.go | 12 +- x/slashing/types/expected_keepers.go | 2 +- x/staking/app_test.go | 5 +- x/staking/bench_test.go | 1 + x/staking/client/cli/query.go | 2 +- x/staking/client/cli/tx.go | 2 +- x/staking/client/cli/tx_test.go | 22 +-- x/staking/client/testutil/grpc.go | 14 -- x/staking/client/testutil/suite.go | 33 +--- x/staking/client/testutil/test_helpers.go | 5 +- x/staking/genesis_test.go | 1 - x/staking/handler_test.go | 35 ++-- x/staking/keeper/common_test.go | 1 + x/staking/keeper/delegation_test.go | 51 +++--- x/staking/keeper/grpc_query.go | 16 +- x/staking/keeper/grpc_query_test.go | 9 +- x/staking/keeper/historical_info_test.go | 4 +- x/staking/keeper/querier_test.go | 8 +- x/staking/keeper/slash.go | 4 +- x/staking/keeper/slash_test.go | 36 ++-- x/staking/keeper/val_state_change_test.go | 8 +- x/staking/keeper/validator_test.go | 26 +-- x/staking/legacy/v043/store_test.go | 3 +- x/staking/module.go | 3 +- x/staking/simulation/decoder_test.go | 11 -- x/staking/simulation/operations.go | 11 +- x/staking/simulation/operations_test.go | 22 ++- x/staking/teststaking/helper.go | 1 + x/staking/teststaking/validator.go | 5 +- x/staking/types/authz.go | 4 +- x/staking/types/authz_test.go | 4 +- x/staking/types/data_test.go | 3 - x/staking/types/expected_keepers.go | 2 +- x/staking/types/historical_info_test.go | 7 +- x/staking/types/validator.go | 1 - x/staking/types/validator_test.go | 5 +- x/stakingplus/authz_test.go | 6 +- x/stakingplus/keeper/msg_server.go | 7 +- x/stakingplus/module/module.go | 11 +- x/token/client/testutil/query.go | 10 -- x/token/client/testutil/suite.go | 7 +- x/token/client/testutil/tx.go | 22 --- x/token/keeper/grpc_query.go | 6 +- x/token/keeper/msg_server_test.go | 25 +-- x/token/module/module.go | 4 +- x/token/msgs_test.go | 4 +- x/upgrade/abci_test.go | 19 ++- x/upgrade/client/cli/tx.go | 4 +- x/upgrade/client/testutil/suite.go | 2 +- x/upgrade/doc.go | 2 +- x/upgrade/keeper/grpc_query_test.go | 6 +- x/upgrade/keeper/keeper.go | 4 +- x/upgrade/keeper/keeper_test.go | 10 +- x/upgrade/keeper/querier.go | 6 +- x/upgrade/types/plan_test.go | 6 +- x/upgrade/types/proposal_test.go | 2 - x/upgrade/types/storeloader_test.go | 10 +- 527 files changed, 1864 insertions(+), 2196 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 915dac203e..19a9ce33b0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,36 +1,59 @@ run: - tests: false -# # timeout for analysis, e.g. 30s, 5m, default is 1m -# timeout: 5m + tests: true + timeout: 15m + allow-parallel-runners: true + build-tags: + - ledger + - goleveldb + - test_ledger_mock + +output: + sort-results: true linters: - disable-all: false + disable-all: true enable: - - gofmt - - goconst - - goimports - - gosec + - errcheck - gosimple - govet - ineffassign - - misspell - - nakedret - - prealloc - staticcheck - - stylecheck - - typecheck - - unconvert - unused - - unparam - - misspell - disable: + - dogsled + - gosec + - gci + - gofumpt + - goconst - gocritic - - errcheck - - interfacer - - wsl + - nakedret - nolintlint + - revive + - misspell + - stylecheck + - typecheck + - thelper + - unconvert + - asasalint + - asciicheck + - bidichk + - bodyclose + - copyloopvar + - errchkjson + - errorlint + - tenv + - wastedassign + - fatcontext issues: + exclude-dirs: + - "testdata$" + exclude-files: + - server/grpc/gogoreflection/fix_registration.go + - "fix_registration.go" + - ".*\\.pb\\.go$" + - ".*\\.pb\\.gw\\.go$" + - ".*\\.pulsar\\.go$" + - crypto/keys/secp256k1/internal/* exclude-rules: - text: "Use of weak random number generator" linters: @@ -54,13 +77,105 @@ issues: text: "SA1019: token." linters: - staticcheck + - path: "legacy" + text: "SA1019:" + linters: + - staticcheck + - text: "SA1019: codec.NewAminoCodec is deprecated" # TODO remove once migration path is set out + linters: + - staticcheck + - text: "SA1019: legacybech32.MustMarshalPubKey" # TODO remove once ready to remove from the sdk + linters: + - staticcheck + - text: "SA1019: legacybech32.MarshalPubKey" # TODO remove once ready to remove from the sdk + linters: + - staticcheck + - text: "SA1019: legacybech32.UnmarshalPubKey" # TODO remove once ready to remove from the sdk + linters: + - staticcheck + - text: "SA1019: params.SendEnabled is deprecated" # TODO remove once ready to remove from the sdk + linters: + - staticcheck + - text: "SA1019: \"github.com/golang/protobuf/proto\" is deprecated" # TODO remove once ready to remove from the sdk + linters: + - staticcheck + - text: "SA1019: vote.Option is deprecated" # TODO remove once ready to remove from the sdk + linters: + - staticcheck + - text: "SA1019: types.QueryNextAccountNumberRequest is deprecated" # TODO remove once ready to remove from the sdk + linters: + - staticcheck + - text: "leading space" + linters: + - nolintlint + - path: _test\.go + linters: + - goconst max-issues-per-linter: 10000 max-same-issues: 10000 linters-settings: + gci: + custom-order: true + sections: + - standard # Standard section: captures all standard packages. + - default # Default section: contains all imports that could not be matched to another section type. + - prefix(github.com/Finschia/finschia-sdk) + revive: + rules: + - name: redefines-builtin-id + disabled: true + + gosec: + includes: + # - G101 # Look for hard coded credentials + - G102 # Bind to all interfaces + - G103 # Audit the use of unsafe block + - G104 # Audit errors not checked + - G106 # Audit the use of ssh.InsecureIgnoreHostKey + - G107 # Url provided to HTTP request as taint input + - G108 # Profiling endpoint automatically exposed on /debug/pprof + - G109 # Potential Integer overflow made by strconv.Atoi result conversion to int16/32 + - G110 # Potential DoS vulnerability via decompression bomb + - G111 # Potential directory traversal + - G112 # Potential slowloris attack + - G113 # Usage of Rat.SetString in math/big with an overflow (CVE-2022-23772) + - G114 # Use of net/http serve function that has no support for setting timeouts + - G201 # SQL query construction using format string + - G202 # SQL query construction using string concatenation + - G203 # Use of unescaped data in HTML templates + - G204 # Audit use of command execution + - G301 # Poor file permissions used when creating a directory + - G302 # Poor file permissions used with chmod + - G303 # Creating tempfile using a predictable path + - G304 # File path provided as taint input + - G305 # File traversal when extracting zip/tar archive + - G306 # Poor file permissions used when writing to a new file + - G307 # Deferring a method which returns an error + - G401 # Detect the usage of DES, RC4, MD5 or SHA1 + - G402 # Look for bad TLS connection settings + - G403 # Ensure minimum RSA key length of 2048 bits + - G404 # Insecure random number source (rand) + - G501 # Import blocklist: crypto/md5 + - G502 # Import blocklist: crypto/des + - G503 # Import blocklist: crypto/rc4 + - G504 # Import blocklist: net/http/cgi + - G505 # Import blocklist: crypto/sha1 + - G601 # Implicit memory aliasing of items from a range statement + misspell: + locale: US + gofumpt: + extra-rules: true dogsled: - max-blank-identifiers: 3 + max-blank-identifiers: 6 nolintlint: allow-unused: false require-explanation: false - require-specific: false \ No newline at end of file + require-specific: false + gosimple: + checks: ["all"] + gocritic: + disabled-checks: + - regexpMust + - appendAssign + - ifElseChain diff --git a/CHANGELOG.md b/CHANGELOG.md index 522b49fd5c..674de0a157 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,7 +42,8 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Improvements * (x/fswap) [\#1415](https://github.com/Finschia/finschia-sdk/pull/1415) add more testcases for fswap module - +* (style) [\#1427](https://github.com/Finschia/finschia-sdk/pull/1427) Lint all files based on latest setting + ### Bug Fixes ### Removed @@ -57,4 +58,5 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Build, CI * (build, ci) [\#1410](https://github.com/Finschia/finschia-sdk/pull/1410) Bump Go from 1.20 to 1.22 * (build) [\#1413](https://github.com/Finschia/finschia-sdk/pull/1413) Update outdated dependencies for v0.49.x + ### Document Updates diff --git a/Makefile b/Makefile index 2f9eb0198f..8d8539b4a7 100644 --- a/Makefile +++ b/Makefile @@ -354,7 +354,7 @@ lint: golangci-lint find . -name '*.go' -type f -not -path "*.git*" | xargs gofmt -d -s golangci-lint: - @go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.51.2 + @go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.59 lint-fix: golangci-lint golangci-lint run --fix --out-format=tab --issues-exit-code=0 diff --git a/baseapp/abci.go b/baseapp/abci.go index f347f3ef87..c4b55ea10a 100644 --- a/baseapp/abci.go +++ b/baseapp/abci.go @@ -11,24 +11,23 @@ import ( "syscall" "time" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/gogo/protobuf/proto" - "google.golang.org/grpc/codes" - grpcstatus "google.golang.org/grpc/status" - abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + "google.golang.org/grpc/codes" + grpcstatus "google.golang.org/grpc/status" "github.com/Finschia/finschia-sdk/codec" snapshottypes "github.com/Finschia/finschia-sdk/snapshots/types" "github.com/Finschia/finschia-sdk/telemetry" sdk "github.com/Finschia/finschia-sdk/types" sdkerrors "github.com/Finschia/finschia-sdk/types/errors" - ocabci "github.com/Finschia/ostracon/abci/types" ) // InitChain implements the ABCI interface. It runs the initialization logic // directly on the CommitMultiStore. -func (app *BaseApp) InitChain(req abci.RequestInitChain) (res abci.ResponseInitChain) { +func (app *BaseApp) InitChain(req abci.RequestInitChain) abci.ResponseInitChain { // On a new chain, we consider the init chain block height as 0, even though // req.InitialHeight is 1 by default. initHeader := tmproto.Header{ChainID: req.ChainId, Time: req.Time} @@ -56,13 +55,13 @@ func (app *BaseApp) InitChain(req abci.RequestInitChain) (res abci.ResponseInitC } if app.initChainer == nil { - return res + return abci.ResponseInitChain{} } // add block gas meter for any genesis transactions (allow infinite gas) app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) - res = app.initChainer(app.deliverState.ctx, req) + res := app.initChainer(app.deliverState.ctx, req) // sanity check if len(req.Validators) > 0 { @@ -925,7 +924,6 @@ func splitPath(requestPath string) (path []string) { // createQueryContext creates a new sdk.Context for a query, taking as args // the block height and whether the query needs a proof or not. func (app *BaseApp) createQueryContextWithCheckState() sdk.Context { - cacheMS := app.checkState.CacheMultiStore() // branch the commit-multistore for safety diff --git a/baseapp/abci_test.go b/baseapp/abci_test.go index 028282be22..ba4b469c13 100644 --- a/baseapp/abci_test.go +++ b/baseapp/abci_test.go @@ -4,13 +4,12 @@ import ( "encoding/json" "testing" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - ocabci "github.com/Finschia/ostracon/abci/types" - sdk "github.com/Finschia/finschia-sdk/types" ) @@ -112,8 +111,6 @@ func TestGetBlockRentionHeight(t *testing.T) { } for name, tc := range testCases { - tc := tc - tc.bapp.SetParamStore(¶mStore{db: dbm.NewMemDB()}) tc.bapp.InitChain(abci.RequestInitChain{ ConsensusParams: &abci.ConsensusParams{ @@ -140,7 +137,8 @@ func TestBaseAppCreateQueryContext(t *testing.T) { db := dbm.NewMemDB() name := t.Name() app := NewBaseApp(name, logger, db, nil) - app.init() + err := app.init() + require.NoError(t, err) app.BeginBlock(ocabci.RequestBeginBlock{Header: tmproto.Header{Height: 1}}) app.Commit() @@ -190,7 +188,8 @@ func TestBaseAppBeginBlockConsensusParams(t *testing.T) { }, }, }) - app.init() + err := app.init() + require.NoError(t, err) // set block params app.BeginBlock(ocabci.RequestBeginBlock{Header: tmproto.Header{Height: 1}}) @@ -218,7 +217,10 @@ func (ps *paramStore) Set(_ sdk.Context, key []byte, value interface{}) { panic(err) } - ps.db.Set(key, bz) + err = ps.db.Set(key, bz) + if err != nil { + panic(err) + } } func (ps *paramStore) Has(_ sdk.Context, key []byte) bool { diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 422b63db43..ce64610418 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -8,14 +8,12 @@ import ( "strings" "sync" - "github.com/gogo/protobuf/proto" - - abci "github.com/tendermint/tendermint/abci/types" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" "github.com/Finschia/ostracon/crypto/tmhash" "github.com/Finschia/ostracon/libs/log" + "github.com/gogo/protobuf/proto" + abci "github.com/tendermint/tendermint/abci/types" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" "golang.org/x/exp/maps" @@ -672,7 +670,6 @@ func (app *BaseApp) anteTx(ctx sdk.Context, txBytes []byte, tx sdk.Tx, simulate anteCtx, msCache := app.cacheTxContext(ctx, txBytes) anteCtx = anteCtx.WithEventManager(sdk.NewEventManager()) newCtx, err := app.anteHandler(anteCtx, tx, simulate) - if err != nil { return newCtx, err } diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index c9366eff08..23c5fd8b00 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -5,6 +5,8 @@ import ( "os" "testing" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/ostracon/libs/log" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -12,9 +14,6 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/codec" "github.com/Finschia/finschia-sdk/codec/legacy" "github.com/Finschia/finschia-sdk/server/config" @@ -63,6 +62,7 @@ func aminoTxEncoder() sdk.TxEncoder { // simple one store baseapp func setupBaseApp(t *testing.T, options ...func(*BaseApp)) *BaseApp { + t.Helper() app := newBaseApp(t.Name(), options...) require.Equal(t, t.Name(), app.Name()) @@ -132,6 +132,7 @@ func TestLoadVersionPruning(t *testing.T) { } func testLoadVersionHelper(t *testing.T, app *BaseApp, expectedHeight int64, expectedID sdk.CommitID) { + t.Helper() lastHeight := app.LastBlockHeight() lastID := app.LastCommitID() require.Equal(t, expectedHeight, lastHeight) @@ -163,13 +164,6 @@ func TestGetMaximumBlockGas(t *testing.T) { } func TestListSnapshots(t *testing.T) { - type setupConfig struct { - blocks uint64 - blockTxs int - snapshotInterval uint64 - snapshotKeepEvery uint32 - } - app, _ := setupBaseAppWithSnapshots(t, 2, 5) expected := abci.ResponseListSnapshots{Snapshots: []*abci.Snapshot{ @@ -222,7 +216,7 @@ func TestSetChanCheckTxSize(t *testing.T) { logger := defaultLogger() db := dbm.NewMemDB() - var size = uint(100) + size := uint(100) app := NewBaseApp(t.Name(), logger, db, nil, SetChanCheckTxSize(size)) require.Equal(t, int(size), cap(app.chCheckTx)) diff --git a/baseapp/block_gas_test.go b/baseapp/block_gas_test.go index 854bda5f69..f8ca3dd189 100644 --- a/baseapp/block_gas_test.go +++ b/baseapp/block_gas_test.go @@ -6,14 +6,13 @@ import ( "math" "testing" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/ostracon/libs/log" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/baseapp" "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/tx" @@ -142,7 +141,7 @@ func TestBaseApp_BlockGas(t *testing.T) { } } -func createTestTx(txConfig client.TxConfig, txBuilder client.TxBuilder, privs []cryptotypes.PrivKey, accNums []uint64, accSeqs []uint64, chainID string) (xauthsigning.Tx, []byte, error) { +func createTestTx(txConfig client.TxConfig, txBuilder client.TxBuilder, privs []cryptotypes.PrivKey, accNums, accSeqs []uint64, chainID string) (xauthsigning.Tx, []byte, error) { // First round: we gather all the signer infos. We use the "set empty // signature" hack to do that. var sigsV2 []signing.SignatureV2 diff --git a/baseapp/deliver_tx_test.go b/baseapp/deliver_tx_test.go index 24cfc03426..6fd1ae676b 100644 --- a/baseapp/deliver_tx_test.go +++ b/baseapp/deliver_tx_test.go @@ -11,6 +11,8 @@ import ( "testing" "time" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/ostracon/libs/log" "github.com/gogo/protobuf/jsonpb" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -18,9 +20,6 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/codec" codectypes "github.com/Finschia/finschia-sdk/codec/types" "github.com/Finschia/finschia-sdk/snapshots" @@ -51,7 +50,6 @@ func TestLoadSnapshotChunk(t *testing.T) { "Zero chunk": {2, 1, 0, false}, } for name, tc := range testcases { - tc := tc t.Run(name, func(t *testing.T) { resp := app.LoadSnapshotChunk(abci.RequestLoadSnapshotChunk{ Height: tc.height, @@ -96,7 +94,6 @@ func TestOfferSnapshot_Errors(t *testing.T) { }, abci.ResponseOfferSnapshot_REJECT}, } for name, tc := range testcases { - tc := tc t.Run(name, func(t *testing.T) { resp := app.OfferSnapshot(abci.RequestOfferSnapshot{Snapshot: tc.snapshot}) assert.Equal(t, tc.result, resp.Result) @@ -869,7 +866,7 @@ func TestCustomRunTxPanicHandler(t *testing.T) { { tx := newTxCounter(0, 0) - require.PanicsWithValue(t, customPanicMsg, func() { app.Deliver(aminoTxEncoder(), tx) }) + require.PanicsWithValue(t, customPanicMsg, func() { app.Deliver(aminoTxEncoder(), tx) }) //nolint:errcheck } } @@ -1284,6 +1281,7 @@ func testTxDecoder(cdc *codec.LegacyAmino) sdk.TxDecoder { } func anteHandlerTxTest(t *testing.T, capKey sdk.StoreKey, storeKey []byte) sdk.AnteHandler { + t.Helper() return func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { store := ctx.KVStore(capKey) txTest := tx.(txTest) @@ -1307,6 +1305,7 @@ func anteHandlerTxTest(t *testing.T, capKey sdk.StoreKey, storeKey []byte) sdk.A // TODO(dudong2): remove this func after reverting CheckTx logic func anteHandlerTxTest2(t *testing.T, capKey sdk.StoreKey, storeKey []byte) sdk.AnteHandler { + t.Helper() return func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { store := ctx.KVStore(capKey) txTest := tx.(*txTest) @@ -1338,6 +1337,7 @@ func counterEvent(evType string, msgCount int64) sdk.Events { } func handlerMsgCounter(t *testing.T, capKey sdk.StoreKey, deliverKey []byte) sdk.Handler { + t.Helper() return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { ctx = ctx.WithEventManager(sdk.NewEventManager()) store := ctx.KVStore(capKey) @@ -1389,6 +1389,7 @@ func setIntOnStore(store sdk.KVStore, key []byte, i int64) { // check counter matches what's in store. // increment and store func incrementingCounter(t *testing.T, store sdk.KVStore, counterKey []byte, counter int64) (*sdk.Result, error) { + t.Helper() storedCounter := getIntFromStore(store, counterKey) require.Equal(t, storedCounter, counter) setIntOnStore(store, counterKey, counter+1) @@ -1649,6 +1650,7 @@ func TestLoadVersionInvalid(t *testing.T) { // simple one store baseapp with data and snapshots. Each tx is 1 MB in size (uncompressed). func setupBaseAppWithSnapshots(t *testing.T, blocks uint, blockTxs int, options ...func(*BaseApp)) (*BaseApp, func()) { + t.Helper() codec := codec.NewLegacyAmino() registerTestCodec(codec) routerOpt := func(bapp *BaseApp) { @@ -1785,6 +1787,7 @@ func useDefaultLoader(app *BaseApp) { } func initStore(t *testing.T, db dbm.DB, storeKey string, k, v []byte) { + t.Helper() rs := rootmulti.NewStore(db, log.NewNopLogger()) rs.SetPruning(store.PruneNothing) key := sdk.NewKVStoreKey(storeKey) @@ -1802,6 +1805,7 @@ func initStore(t *testing.T, db dbm.DB, storeKey string, k, v []byte) { } func checkStore(t *testing.T, db dbm.DB, ver int64, storeKey string, k, v []byte) { + t.Helper() rs := rootmulti.NewStore(db, log.NewNopLogger()) rs.SetPruning(store.PruneDefault) key := sdk.NewKVStoreKey(storeKey) @@ -1839,7 +1843,6 @@ func TestSetLoader(t *testing.T) { v := []byte("value") for name, tc := range cases { - tc := tc t.Run(name, func(t *testing.T) { // prepare a db with some data db := dbm.NewMemDB() diff --git a/baseapp/msg_service_router_test.go b/baseapp/msg_service_router_test.go index 4c0363e0f5..9f984630eb 100644 --- a/baseapp/msg_service_router_test.go +++ b/baseapp/msg_service_router_test.go @@ -4,14 +4,13 @@ import ( "os" "testing" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/ostracon/libs/log" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/baseapp" "github.com/Finschia/finschia-sdk/client/tx" "github.com/Finschia/finschia-sdk/simapp" diff --git a/baseapp/queryrouter_test.go b/baseapp/queryrouter_test.go index c8b7851f20..4ea088028f 100644 --- a/baseapp/queryrouter_test.go +++ b/baseapp/queryrouter_test.go @@ -4,7 +4,6 @@ import ( "testing" "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" sdk "github.com/Finschia/finschia-sdk/types" diff --git a/baseapp/reactor.go b/baseapp/reactor.go index aa1d27b740..4211091cce 100644 --- a/baseapp/reactor.go +++ b/baseapp/reactor.go @@ -46,7 +46,6 @@ func (app *BaseApp) checkTxAsync(req *RequestCheckTxAsync, waits []*sync.WaitGro defer app.checkAccountWGs.Done(signals) gInfo, err := app.checkTx(req.txBytes, req.tx, req.recheck) - if err != nil { req.callback(sdkerrors.ResponseCheckTx(err, gInfo.GasWanted, gInfo.GasUsed, app.trace)) return diff --git a/baseapp/streaming.go b/baseapp/streaming.go index aeaec29a93..6587b2cd1f 100644 --- a/baseapp/streaming.go +++ b/baseapp/streaming.go @@ -4,9 +4,8 @@ import ( "io" "sync" - abci "github.com/tendermint/tendermint/abci/types" - ocabci "github.com/Finschia/ostracon/abci/types" + abci "github.com/tendermint/tendermint/abci/types" store "github.com/Finschia/finschia-sdk/store/types" "github.com/Finschia/finschia-sdk/types" diff --git a/baseapp/xxx_msg_test.go b/baseapp/xxx_msg_test.go index 79ed2873f1..fb13e8af81 100644 --- a/baseapp/xxx_msg_test.go +++ b/baseapp/xxx_msg_test.go @@ -3,8 +3,9 @@ package baseapp import ( reflect "reflect" - types "github.com/Finschia/finschia-sdk/types" gomock "github.com/golang/mock/gomock" + + types "github.com/Finschia/finschia-sdk/types" ) // MockXXXMessage is a mock of XXXMessage interface. diff --git a/client/account_retriever.go b/client/account_retriever.go index adb61c1f15..753cb724f6 100644 --- a/client/account_retriever.go +++ b/client/account_retriever.go @@ -20,5 +20,5 @@ type AccountRetriever interface { GetAccount(clientCtx Context, addr sdk.AccAddress) (Account, error) GetAccountWithHeight(clientCtx Context, addr sdk.AccAddress) (Account, int64, error) EnsureExists(clientCtx Context, addr sdk.AccAddress) error - GetAccountNumberSequence(clientCtx Context, addr sdk.AccAddress) (accNum uint64, accSeq uint64, err error) + GetAccountNumberSequence(clientCtx Context, addr sdk.AccAddress) (accNum, accSeq uint64, err error) } diff --git a/client/broadcast.go b/client/broadcast.go index bea58f1f4a..1afe9634f4 100644 --- a/client/broadcast.go +++ b/client/broadcast.go @@ -5,11 +5,10 @@ import ( "fmt" "strings" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "github.com/Finschia/ostracon/mempool" octypes "github.com/Finschia/ostracon/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "github.com/Finschia/finschia-sdk/client/flags" sdk "github.com/Finschia/finschia-sdk/types" diff --git a/client/cmd_test.go b/client/cmd_test.go index d3bfcfd9f9..54ec9a41ef 100644 --- a/client/cmd_test.go +++ b/client/cmd_test.go @@ -94,8 +94,6 @@ func TestSetCmdClientContextHandler(t *testing.T) { } for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { ctx := context.WithValue(context.Background(), client.ClientContextKey, &client.Context{}) diff --git a/client/config/cmd.go b/client/config/cmd.go index 8a39ae13df..c233757561 100644 --- a/client/config/cmd.go +++ b/client/config/cmd.go @@ -5,9 +5,8 @@ import ( "fmt" "path/filepath" - "github.com/spf13/cobra" - ostcli "github.com/Finschia/ostracon/libs/cli" + "github.com/spf13/cobra" "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" @@ -31,7 +30,7 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { conf, err := getClientConfig(configPath, clientCtx.Viper) if err != nil { - return fmt.Errorf("couldn't get client config: %v", err) + return fmt.Errorf("couldn't get client config: %w", err) } switch len(args) { @@ -60,7 +59,7 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { cmd.Println(conf.BroadcastMode) default: err := errUnknownConfigKey(key) - return fmt.Errorf("couldn't get the value for the key: %v, error: %v", key, err) + return fmt.Errorf("couldn't get the value for the key: %v, error: %w", key, err) } case 2: @@ -84,7 +83,7 @@ func runConfigCmd(cmd *cobra.Command, args []string) error { confFile := filepath.Join(configPath, "client.toml") if err := writeConfigToFile(confFile, conf); err != nil { - return fmt.Errorf("could not write client config to the file: %v", err) + return fmt.Errorf("could not write client config to the file: %w", err) } default: diff --git a/client/config/config.go b/client/config/config.go index bfc4c92d78..c98ab9840b 100644 --- a/client/config/config.go +++ b/client/config/config.go @@ -59,17 +59,17 @@ func ReadFromClientConfig(ctx client.Context) (client.Context, error) { // if config.toml file does not exist we create it and write default ClientConfig values into it. if _, err := os.Stat(configFilePath); os.IsNotExist(err) { if err := ensureConfigPath(configPath); err != nil { - return ctx, fmt.Errorf("couldn't make client config: %v", err) + return ctx, fmt.Errorf("couldn't make client config: %w", err) } if err := writeConfigToFile(configFilePath, conf); err != nil { - return ctx, fmt.Errorf("could not write client config to the file: %v", err) + return ctx, fmt.Errorf("could not write client config to the file: %w", err) } } conf, err := getClientConfig(configPath, ctx.Viper) if err != nil { - return ctx, fmt.Errorf("couldn't get client config: %v", err) + return ctx, fmt.Errorf("couldn't get client config: %w", err) } // we need to update KeyringDir field on Client Context first cause it is used in NewKeyringFromBackend ctx = ctx.WithOutputFormat(conf.Output). @@ -78,7 +78,7 @@ func ReadFromClientConfig(ctx client.Context) (client.Context, error) { keyring, err := client.NewKeyringFromBackend(ctx, conf.KeyringBackend) if err != nil { - return ctx, fmt.Errorf("couldn't get key ring: %v", err) + return ctx, fmt.Errorf("couldn't get key ring: %w", err) } ctx = ctx.WithKeyring(keyring) @@ -86,7 +86,7 @@ func ReadFromClientConfig(ctx client.Context) (client.Context, error) { // https://github.com/cosmos/cosmos-sdk/issues/8986 client, err := client.NewClientFromNode(conf.Node) if err != nil { - return ctx, fmt.Errorf("couldn't get client from nodeURI: %v", err) + return ctx, fmt.Errorf("couldn't get client from nodeURI: %w", err) } ctx = ctx.WithNodeURI(conf.Node). diff --git a/client/config/config_test.go b/client/config/config_test.go index 46a1dadc89..e7b46274c6 100644 --- a/client/config/config_test.go +++ b/client/config/config_test.go @@ -26,15 +26,17 @@ const ( // initClientContext initiates client Context for tests func initClientContext(t *testing.T, envVar string) (client.Context, func()) { + t.Helper() home := t.TempDir() clientCtx := client.Context{}. WithHomeDir(home). WithViper(""). WithCodec(codec.NewProtoCodec(codectypes.NewInterfaceRegistry())) - clientCtx.Viper.BindEnv(nodeEnv) + _ = clientCtx.Viper.BindEnv(nodeEnv) if envVar != "" { - os.Setenv(nodeEnv, envVar) + err := os.Setenv(nodeEnv, envVar) + require.NoError(t, err) } clientCtx, err := config.ReadFromClientConfig(clientCtx) @@ -46,7 +48,8 @@ func initClientContext(t *testing.T, envVar string) (client.Context, func()) { func TestConfigCmd(t *testing.T) { clientCtx, cleanup := initClientContext(t, testNode1) defer func() { - os.Unsetenv(nodeEnv) + err := os.Unsetenv(nodeEnv) + require.NoError(t, err) cleanup() }() @@ -56,11 +59,12 @@ func TestConfigCmd(t *testing.T) { _, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, args) require.NoError(t, err) - //./build/simd config node //http://localhost:1 + // ./build/simd config node //http://localhost:1 b := bytes.NewBufferString("") cmd.SetOut(b) cmd.SetArgs([]string{"node"}) - cmd.Execute() + err = cmd.Execute() + require.NoError(t, err) out, err := io.ReadAll(b) require.NoError(t, err) require.Equal(t, string(out), testNode1+"\n") @@ -84,7 +88,6 @@ func TestConfigCmdEnvFlag(t *testing.T) { } for _, tc := range tt { - tc := tc t.Run(tc.name, func(t *testing.T) { clientCtx, cleanup := initClientContext(t, tc.envVar) defer func() { diff --git a/client/context.go b/client/context.go index 74cff41775..a4b6177d89 100644 --- a/client/context.go +++ b/client/context.go @@ -6,13 +6,12 @@ import ( "io" "os" - "github.com/spf13/viper" - "google.golang.org/grpc" - "gopkg.in/yaml.v2" - rpcclient "github.com/Finschia/ostracon/rpc/client" "github.com/gogo/protobuf/proto" "github.com/pkg/errors" + "github.com/spf13/viper" + "google.golang.org/grpc" + "gopkg.in/yaml.v2" "github.com/Finschia/finschia-sdk/codec" codectypes "github.com/Finschia/finschia-sdk/codec/types" diff --git a/client/debug/main.go b/client/debug/main.go index 163aa87f8f..1b443b5d49 100644 --- a/client/debug/main.go +++ b/client/debug/main.go @@ -84,7 +84,7 @@ $ %s debug addr link19wgf6ymq2ur6r59st95e04e49m69z4al4fc982 addr, err3 = sdk.ValAddressFromBech32(addrString) if err3 != nil { - return fmt.Errorf("expected hex or bech32. Got errors: hex: %v, bech32 acc: %v, bech32 val: %v", err, err2, err3) + return fmt.Errorf("expected hex or bech32. Got errors: hex: %w, bech32 acc: %w, bech32 val: %w", err, err2, err3) } } } diff --git a/client/flags/flags.go b/client/flags/flags.go index ce79cdd2be..b8a4aef9e8 100644 --- a/client/flags/flags.go +++ b/client/flags/flags.go @@ -4,9 +4,8 @@ import ( "fmt" "strconv" - "github.com/spf13/cobra" - ostcli "github.com/Finschia/ostracon/libs/cli" + "github.com/spf13/cobra" "github.com/Finschia/finschia-sdk/crypto/keyring" ) @@ -95,7 +94,7 @@ func AddQueryFlagsToCmd(cmd *cobra.Command) { cmd.Flags().Int64(FlagHeight, 0, "Use a specific height to query state at (this can error if the node is pruning state)") cmd.Flags().StringP(ostcli.OutputFlag, "o", "text", "Output format (text|json)") - cmd.MarkFlagRequired(FlagChainID) + _ = cmd.MarkFlagRequired(FlagChainID) } // AddTxFlagsToCmd adds common flags to a module tx command. @@ -124,7 +123,7 @@ func AddTxFlagsToCmd(cmd *cobra.Command) { // --gas can accept integers and "auto" cmd.Flags().String(FlagGas, "", fmt.Sprintf("gas limit to set per-transaction; set to %q to calculate sufficient gas automatically (default %d)", GasFlagAuto, DefaultGasLimit)) - cmd.MarkFlagRequired(FlagChainID) + _ = cmd.MarkFlagRequired(FlagChainID) } // AddPaginationFlagsToCmd adds common pagination flags to cmd diff --git a/client/flags/flags_test.go b/client/flags/flags_test.go index f86ff64a58..54aa591e0d 100644 --- a/client/flags/flags_test.go +++ b/client/flags/flags_test.go @@ -23,8 +23,6 @@ func TestParseGasSetting(t *testing.T) { } for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { gs, err := flags.ParseGasSetting(tc.input) diff --git a/client/grpc/ocservice/service.go b/client/grpc/ocservice/service.go index 6575b5c3b7..2ce793e5ff 100644 --- a/client/grpc/ocservice/service.go +++ b/client/grpc/ocservice/service.go @@ -256,5 +256,8 @@ func RegisterTendermintService( // RegisterGRPCGatewayRoutes mounts the tendermint service's GRPC-gateway routes on the // given Mux. func RegisterGRPCGatewayRoutes(clientConn gogogrpc.ClientConn, mux *runtime.ServeMux) { - RegisterServiceHandlerClient(context.Background(), mux, NewServiceClient(clientConn)) + err := RegisterServiceHandlerClient(context.Background(), mux, NewServiceClient(clientConn)) + if err != nil { + panic(err) + } } diff --git a/client/grpc/ocservice/service_test.go b/client/grpc/ocservice/service_test.go index edfc5afa4f..f4df59afcc 100644 --- a/client/grpc/ocservice/service_test.go +++ b/client/grpc/ocservice/service_test.go @@ -6,9 +6,8 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/suite" - "github.com/Finschia/ostracon/libs/bytes" + "github.com/stretchr/testify/suite" "github.com/Finschia/finschia-sdk/client/grpc/ocservice" codectypes "github.com/Finschia/finschia-sdk/codec/types" @@ -50,7 +49,7 @@ func (s *IntegrationTestSuite) TearDownSuite() { s.network.Cleanup() } -func (s IntegrationTestSuite) TestQueryNodeInfo() { +func (s *IntegrationTestSuite) TestQueryNodeInfo() { val := s.network.Validators[0] res, err := s.queryClient.GetNodeInfo(context.Background(), &ocservice.GetNodeInfoRequest{}) @@ -64,7 +63,7 @@ func (s IntegrationTestSuite) TestQueryNodeInfo() { s.Require().Equal(getInfoRes.ApplicationVersion.AppName, version.NewInfo().AppName) } -func (s IntegrationTestSuite) TestQuerySyncing() { +func (s *IntegrationTestSuite) TestQuerySyncing() { val := s.network.Validators[0] _, err := s.queryClient.GetSyncing(context.Background(), &ocservice.GetSyncingRequest{}) @@ -76,7 +75,7 @@ func (s IntegrationTestSuite) TestQuerySyncing() { s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(restRes, &syncingRes)) } -func (s IntegrationTestSuite) TestQueryLatestBlock() { +func (s *IntegrationTestSuite) TestQueryLatestBlock() { val := s.network.Validators[0] _, err := s.queryClient.GetLatestBlock(context.Background(), &ocservice.GetLatestBlockRequest{}) s.Require().NoError(err) @@ -87,7 +86,7 @@ func (s IntegrationTestSuite) TestQueryLatestBlock() { s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(restRes, &blockInfoRes)) } -func (s IntegrationTestSuite) TestQueryBlockByHash() { +func (s *IntegrationTestSuite) TestQueryBlockByHash() { val := s.network.Validators[0] node, _ := val.ClientCtx.GetNode() blk, _ := node.Block(context.Background(), nil) @@ -124,7 +123,7 @@ func (s IntegrationTestSuite) TestQueryBlockByHash() { s.Require().Equal(val.ClientCtx.ChainID, block.Header.ChainID) } -func (s IntegrationTestSuite) TestGetLatestBlock() { +func (s *IntegrationTestSuite) TestGetLatestBlock() { val := s.network.Validators[0] latestHeight, err := s.network.LatestHeight() s.Require().NoError(err) @@ -141,7 +140,7 @@ func (s IntegrationTestSuite) TestGetLatestBlock() { s.Require().Equal(blockRes.Block.Header.Height, blockInfoRes.Block.Header.Height) } -func (s IntegrationTestSuite) TestQueryBlockByHeight() { +func (s *IntegrationTestSuite) TestQueryBlockByHeight() { val := s.network.Validators[0] _, err := s.queryClient.GetBlockByHeight(context.Background(), &ocservice.GetBlockByHeightRequest{}) s.Require().Error(err) @@ -158,7 +157,7 @@ func (s IntegrationTestSuite) TestQueryBlockByHeight() { s.Require().Equal(int64(1), block.Header.Height) } -func (s IntegrationTestSuite) TestQueryBlockResultsByHeight() { +func (s *IntegrationTestSuite) TestQueryBlockResultsByHeight() { val := s.network.Validators[0] _, err := s.queryClient.GetBlockResultsByHeight(context.Background(), &ocservice.GetBlockResultsByHeightRequest{Height: 1}) s.Require().NoError(err) @@ -166,7 +165,7 @@ func (s IntegrationTestSuite) TestQueryBlockResultsByHeight() { restRes, err := rest.GetRequest(fmt.Sprintf("%s/lbm/base/ostracon/v1/blockresults/%d", val.APIAddress, 1)) s.Require().NoError(err) var blockResultsRes ocservice.GetBlockResultsByHeightResponse - s.Require().NoError(val.ClientCtx.JSONCodec.UnmarshalJSON(restRes, &blockResultsRes)) + s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(restRes, &blockResultsRes)) txResult := blockResultsRes.GetTxsResults() s.Require().Equal(0, len(txResult)) @@ -178,7 +177,7 @@ func (s IntegrationTestSuite) TestQueryBlockResultsByHeight() { s.Require().Equal(0, len(endBlock.Events)) } -func (s IntegrationTestSuite) TestQueryLatestValidatorSet() { +func (s *IntegrationTestSuite) TestQueryLatestValidatorSet() { val := s.network.Validators[0] // nil pagination @@ -213,7 +212,7 @@ func (s IntegrationTestSuite) TestQueryLatestValidatorSet() { s.Require().Equal(validatorSetRes.Validators[0].PubKey, anyPub) } -func (s IntegrationTestSuite) TestLatestValidatorSet_GRPC() { +func (s *IntegrationTestSuite) TestLatestValidatorSet_GRPC() { vals := s.network.Validators testCases := []struct { name string @@ -226,7 +225,6 @@ func (s IntegrationTestSuite) TestLatestValidatorSet_GRPC() { {"with pagination", &ocservice.GetLatestValidatorSetRequest{Pagination: &qtypes.PageRequest{Offset: 0, Limit: uint64(len(vals))}}, false, ""}, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { grpcRes, err := s.queryClient.GetLatestValidatorSet(context.Background(), tc.req) if tc.expErr { @@ -244,7 +242,7 @@ func (s IntegrationTestSuite) TestLatestValidatorSet_GRPC() { } } -func (s IntegrationTestSuite) TestLatestValidatorSet_GRPCGateway() { +func (s *IntegrationTestSuite) TestLatestValidatorSet_GRPCGateway() { vals := s.network.Validators testCases := []struct { name string @@ -257,7 +255,6 @@ func (s IntegrationTestSuite) TestLatestValidatorSet_GRPCGateway() { {"with pagination", fmt.Sprintf("%s/lbm/base/ostracon/v1/validatorsets/latest?pagination.offset=0&pagination.limit=2", vals[0].APIAddress), false, ""}, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { res, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -276,7 +273,7 @@ func (s IntegrationTestSuite) TestLatestValidatorSet_GRPCGateway() { } } -func (s IntegrationTestSuite) TestValidatorSetByHeight_GRPC() { +func (s *IntegrationTestSuite) TestValidatorSetByHeight_GRPC() { vals := s.network.Validators testCases := []struct { name string @@ -290,7 +287,6 @@ func (s IntegrationTestSuite) TestValidatorSetByHeight_GRPC() { {"with pagination", &ocservice.GetValidatorSetByHeightRequest{Height: 1, Pagination: &qtypes.PageRequest{Offset: 0, Limit: 1}}, false, ""}, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { grpcRes, err := s.queryClient.GetValidatorSetByHeight(context.Background(), tc.req) if tc.expErr { @@ -305,7 +301,7 @@ func (s IntegrationTestSuite) TestValidatorSetByHeight_GRPC() { } } -func (s IntegrationTestSuite) TestValidatorSetByHeight_GRPCGateway() { +func (s *IntegrationTestSuite) TestValidatorSetByHeight_GRPCGateway() { vals := s.network.Validators testCases := []struct { name string @@ -319,7 +315,6 @@ func (s IntegrationTestSuite) TestValidatorSetByHeight_GRPCGateway() { {"with pagination", fmt.Sprintf("%s/lbm/base/ostracon/v1/validatorsets/%d?pagination.offset=0&pagination.limit=2", vals[0].APIAddress, 1), false, ""}, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { res, err := rest.GetRequest(tc.url) s.Require().NoError(err) diff --git a/client/grpc/tmservice/block_test.go b/client/grpc/tmservice/block_test.go index 35840bf63a..e71765a68e 100644 --- a/client/grpc/tmservice/block_test.go +++ b/client/grpc/tmservice/block_test.go @@ -7,7 +7,7 @@ import ( "github.com/Finschia/finschia-sdk/simapp" ) -func (s IntegrationTestSuite) TestGetProtoBlock() { +func (s *IntegrationTestSuite) TestGetProtoBlock() { val := s.network.Validators[0] app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) @@ -23,7 +23,7 @@ func (s IntegrationTestSuite) TestGetProtoBlock() { s.Require().NoError(err) } -func (s IntegrationTestSuite) TestGetBlocksByHash() { +func (s *IntegrationTestSuite) TestGetBlocksByHash() { val := s.network.Validators[0] app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{}) @@ -38,7 +38,7 @@ func (s IntegrationTestSuite) TestGetBlocksByHash() { s.Require().Equal(blockResult2.Block.Height, blockResult.Block.Height) } -func (s IntegrationTestSuite) TestGetBlockResultsByHeight() { +func (s *IntegrationTestSuite) TestGetBlockResultsByHeight() { val := s.network.Validators[0] height := int64(1) diff --git a/client/grpc/tmservice/service.go b/client/grpc/tmservice/service.go index 9bd2017e9f..34739c6011 100644 --- a/client/grpc/tmservice/service.go +++ b/client/grpc/tmservice/service.go @@ -3,14 +3,12 @@ package tmservice import ( "context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - + octypes "github.com/Finschia/ostracon/proto/ostracon/types" gogogrpc "github.com/gogo/protobuf/grpc" "github.com/grpc-ecosystem/grpc-gateway/runtime" tmtypes "github.com/tendermint/tendermint/proto/tendermint/types" - - octypes "github.com/Finschia/ostracon/proto/ostracon/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/rpc" @@ -223,5 +221,8 @@ func RegisterTendermintService( // RegisterGRPCGatewayRoutes mounts the tendermint service's GRPC-gateway routes on the // given Mux. func RegisterGRPCGatewayRoutes(clientConn gogogrpc.ClientConn, mux *runtime.ServeMux) { - RegisterServiceHandlerClient(context.Background(), mux, NewServiceClient(clientConn)) + err := RegisterServiceHandlerClient(context.Background(), mux, NewServiceClient(clientConn)) + if err != nil { + panic(err) + } } diff --git a/client/grpc/tmservice/service_test.go b/client/grpc/tmservice/service_test.go index 68d300de32..c05e86a135 100644 --- a/client/grpc/tmservice/service_test.go +++ b/client/grpc/tmservice/service_test.go @@ -47,7 +47,7 @@ func (s *IntegrationTestSuite) TearDownSuite() { s.network.Cleanup() } -func (s IntegrationTestSuite) TestQueryNodeInfo() { +func (s *IntegrationTestSuite) TestQueryNodeInfo() { val := s.network.Validators[0] res, err := s.queryClient.GetNodeInfo(context.Background(), &tmservice.GetNodeInfoRequest{}) @@ -61,7 +61,7 @@ func (s IntegrationTestSuite) TestQueryNodeInfo() { s.Require().Equal(getInfoRes.ApplicationVersion.AppName, version.NewInfo().AppName) } -func (s IntegrationTestSuite) TestQuerySyncing() { +func (s *IntegrationTestSuite) TestQuerySyncing() { val := s.network.Validators[0] _, err := s.queryClient.GetSyncing(context.Background(), &tmservice.GetSyncingRequest{}) @@ -73,7 +73,7 @@ func (s IntegrationTestSuite) TestQuerySyncing() { s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(restRes, &syncingRes)) } -func (s IntegrationTestSuite) TestQueryLatestBlock() { +func (s *IntegrationTestSuite) TestQueryLatestBlock() { val := s.network.Validators[0] _, err := s.queryClient.GetLatestBlock(context.Background(), &tmservice.GetLatestBlockRequest{}) s.Require().NoError(err) @@ -84,7 +84,7 @@ func (s IntegrationTestSuite) TestQueryLatestBlock() { s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(restRes, &blockInfoRes)) } -func (s IntegrationTestSuite) TestQueryBlockByHeight() { +func (s *IntegrationTestSuite) TestQueryBlockByHeight() { val := s.network.Validators[0] _, err := s.queryClient.GetBlockByHeight(context.Background(), &tmservice.GetBlockByHeightRequest{Height: 1}) s.Require().NoError(err) @@ -98,7 +98,7 @@ func (s IntegrationTestSuite) TestQueryBlockByHeight() { s.Require().Equal(int64(1), block.Header.Height) } -func (s IntegrationTestSuite) TestQueryLatestValidatorSet() { +func (s *IntegrationTestSuite) TestQueryLatestValidatorSet() { val := s.network.Validators[0] // nil pagination @@ -133,7 +133,7 @@ func (s IntegrationTestSuite) TestQueryLatestValidatorSet() { s.Require().Equal(validatorSetRes.Validators[0].PubKey, anyPub) } -func (s IntegrationTestSuite) TestLatestValidatorSet_GRPC() { +func (s *IntegrationTestSuite) TestLatestValidatorSet_GRPC() { vals := s.network.Validators testCases := []struct { name string @@ -146,7 +146,6 @@ func (s IntegrationTestSuite) TestLatestValidatorSet_GRPC() { {"with pagination", &tmservice.GetLatestValidatorSetRequest{Pagination: &qtypes.PageRequest{Offset: 0, Limit: uint64(len(vals))}}, false, ""}, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { grpcRes, err := s.queryClient.GetLatestValidatorSet(context.Background(), tc.req) if tc.expErr { @@ -164,7 +163,7 @@ func (s IntegrationTestSuite) TestLatestValidatorSet_GRPC() { } } -func (s IntegrationTestSuite) TestLatestValidatorSet_GRPCGateway() { +func (s *IntegrationTestSuite) TestLatestValidatorSet_GRPCGateway() { vals := s.network.Validators testCases := []struct { name string @@ -177,7 +176,6 @@ func (s IntegrationTestSuite) TestLatestValidatorSet_GRPCGateway() { {"with pagination", fmt.Sprintf("%s/cosmos/base/tendermint/v1beta1/validatorsets/latest?pagination.offset=0&pagination.limit=2", vals[0].APIAddress), false, ""}, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { res, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -196,7 +194,7 @@ func (s IntegrationTestSuite) TestLatestValidatorSet_GRPCGateway() { } } -func (s IntegrationTestSuite) TestValidatorSetByHeight_GRPC() { +func (s *IntegrationTestSuite) TestValidatorSetByHeight_GRPC() { vals := s.network.Validators testCases := []struct { name string @@ -210,7 +208,6 @@ func (s IntegrationTestSuite) TestValidatorSetByHeight_GRPC() { {"with pagination", &tmservice.GetValidatorSetByHeightRequest{Height: 1, Pagination: &qtypes.PageRequest{Offset: 0, Limit: 1}}, false, ""}, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { grpcRes, err := s.queryClient.GetValidatorSetByHeight(context.Background(), tc.req) if tc.expErr { @@ -225,7 +222,7 @@ func (s IntegrationTestSuite) TestValidatorSetByHeight_GRPC() { } } -func (s IntegrationTestSuite) TestValidatorSetByHeight_GRPCGateway() { +func (s *IntegrationTestSuite) TestValidatorSetByHeight_GRPCGateway() { vals := s.network.Validators testCases := []struct { name string @@ -239,7 +236,6 @@ func (s IntegrationTestSuite) TestValidatorSetByHeight_GRPCGateway() { {"with pagination", fmt.Sprintf("%s/cosmos/base/tendermint/v1beta1/validatorsets/%d?pagination.offset=0&pagination.limit=2", vals[0].APIAddress, 1), false, ""}, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { res, err := rest.GetRequest(tc.url) s.Require().NoError(err) diff --git a/client/keys/add.go b/client/keys/add.go index b707a984a2..059d544c36 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -300,7 +300,7 @@ func runAddCmd(ctx client.Context, cmd *cobra.Command, args []string, inBuf *buf return printCreate(cmd, info, showMnemonic, mnemonic, outputFormat) } -func printCreate(cmd *cobra.Command, info keyring.Info, showMnemonic bool, mnemonic string, outputFormat string) error { +func printCreate(cmd *cobra.Command, info keyring.Info, showMnemonic bool, mnemonic, outputFormat string) error { switch outputFormat { case OutputFormatText: cmd.PrintErrln() diff --git a/client/keys/add_ledger_test.go b/client/keys/add_ledger_test.go index 4895cfd000..a894e119e8 100644 --- a/client/keys/add_ledger_test.go +++ b/client/keys/add_ledger_test.go @@ -154,7 +154,6 @@ func Test_runAddCmdLedgerDryRun(t *testing.T) { }, } for _, tt := range testData { - tt := tt t.Run(tt.name, func(t *testing.T) { cmd := AddKeyCommand() cmd.Flags().AddFlagSet(Commands("home").PersistentFlags()) diff --git a/client/keys/add_test.go b/client/keys/add_test.go index dd0bb56298..783b707086 100644 --- a/client/keys/add_test.go +++ b/client/keys/add_test.go @@ -7,12 +7,11 @@ import ( "io" "testing" + "github.com/Finschia/ostracon/libs/cli" "github.com/cosmos/go-bip39" "github.com/spf13/pflag" "github.com/stretchr/testify/require" - "github.com/Finschia/ostracon/libs/cli" - "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/crypto/hd" @@ -83,57 +82,62 @@ func Test_runAddCmdBasic(t *testing.T) { args []string err string }{ - {[]string{ - "keyname1", - fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), - fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), - fmt.Sprintf("--%s=%s", flags.FlagKeyAlgorithm, string(hd.Secp256k1Type)), - fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), - fmt.Sprintf("--%s=%s", flagMultisig, "keyname1,keyname2"), - }, + { + []string{ + "keyname1", + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flags.FlagKeyAlgorithm, string(hd.Secp256k1Type)), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--%s=%s", flagMultisig, "keyname1,keyname2"), + }, "you cannot specify a new key as one of the names of the keys that make up a multisig", }, - {[]string{ - "keyname-multi", - fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), - fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), - fmt.Sprintf("--%s=%s", flags.FlagKeyAlgorithm, string(hd.Secp256k1Type)), - fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), - fmt.Sprintf("--%s=%s", flagMultisig, "keyname1,keyname11"), - }, + { + []string{ + "keyname-multi", + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flags.FlagKeyAlgorithm, string(hd.Secp256k1Type)), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--%s=%s", flagMultisig, "keyname1,keyname11"), + }, "part of the multisig target key does not exist", }, - {[]string{ - "keyname-multi", - fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), - fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), - fmt.Sprintf("--%s=%s", flags.FlagKeyAlgorithm, string(hd.Secp256k1Type)), - fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), - fmt.Sprintf("--%s=%s", flagMultisig, "keyname1,keyname2"), - fmt.Sprintf("--%s=%d", flagMultiSigThreshold, 3), - }, + { + []string{ + "keyname-multi", + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flags.FlagKeyAlgorithm, string(hd.Secp256k1Type)), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--%s=%s", flagMultisig, "keyname1,keyname2"), + fmt.Sprintf("--%s=%d", flagMultiSigThreshold, 3), + }, "threshold k of n multisignature", }, - {[]string{ - "keyname-multi", - fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), - fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), - fmt.Sprintf("--%s=%s", flags.FlagKeyAlgorithm, string(hd.Secp256k1Type)), - fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), - fmt.Sprintf("--%s=%s", flagMultisig, "keyname1,keyname2"), - fmt.Sprintf("--%s=%d", flagMultiSigThreshold, -1), - }, + { + []string{ + "keyname-multi", + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flags.FlagKeyAlgorithm, string(hd.Secp256k1Type)), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--%s=%s", flagMultisig, "keyname1,keyname2"), + fmt.Sprintf("--%s=%d", flagMultiSigThreshold, -1), + }, "threshold must be a positive integer", }, - {[]string{ - "keyname-multi", - fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), - fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), - fmt.Sprintf("--%s=%s", flags.FlagKeyAlgorithm, string(hd.Secp256k1Type)), - fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), - fmt.Sprintf("--%s=%s", flagMultisig, "keyname1,keyname2"), - fmt.Sprintf("--%s=%d", flagMultiSigThreshold, 2), - }, + { + []string{ + "keyname-multi", + fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), + fmt.Sprintf("--%s=%s", cli.OutputFlag, OutputFormatText), + fmt.Sprintf("--%s=%s", flags.FlagKeyAlgorithm, string(hd.Secp256k1Type)), + fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), + fmt.Sprintf("--%s=%s", flagMultisig, "keyname1,keyname2"), + fmt.Sprintf("--%s=%d", flagMultiSigThreshold, 2), + }, "", }, } @@ -148,7 +152,8 @@ func Test_runAddCmdBasic(t *testing.T) { cmd.Flags().Visit(func(f *pflag.Flag) { if f.Name == flagMultisig { - f.Value.(pflag.SliceValue).Replace([]string{}) + err = f.Value.(pflag.SliceValue).Replace([]string{}) + require.NoError(t, err) } }) } @@ -302,7 +307,6 @@ func Test_runAddCmdDryRun(t *testing.T) { }, } for _, tt := range testData { - tt := tt t.Run(tt.name, func(t *testing.T) { cmd := AddKeyCommand() cmd.Flags().AddFlagSet(Commands("home").PersistentFlags()) @@ -314,7 +318,7 @@ func Test_runAddCmdDryRun(t *testing.T) { appCodec := simapp.MakeTestEncodingConfig().Marshaler clientCtx := client.Context{}. - WithJSONCodec(appCodec). + WithCodec(appCodec). WithKeyringDir(kbHome). WithKeyring(kb) ctx := context.WithValue(context.Background(), client.ClientContextKey, &clientCtx) diff --git a/client/keys/codec_test.go b/client/keys/codec_test.go index 7d91884a13..eb4a5abc0c 100644 --- a/client/keys/codec_test.go +++ b/client/keys/codec_test.go @@ -56,7 +56,6 @@ func TestMarshalJSON(t *testing.T) { {"empty object", args{data.Keys[3]}, data.JSON[3], false}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { got, err := keys.MarshalJSON(tt.args.o) require.Equal(t, tt.wantErr, err != nil) @@ -86,7 +85,6 @@ func TestUnmarshalJSON(t *testing.T) { {"empty object", args{data.JSON[3], &data.Answers[3]}, false}, } for idx, tt := range tests { - idx, tt := idx, tt t.Run(tt.name, func(t *testing.T) { err := keys.UnmarshalJSON(tt.args.bz, tt.args.ptr) require.Equal(t, tt.wantErr, err != nil) diff --git a/client/keys/delete.go b/client/keys/delete.go index a7fb35158d..532e14edd0 100644 --- a/client/keys/delete.go +++ b/client/keys/delete.go @@ -3,11 +3,11 @@ package keys import ( "bufio" + "github.com/spf13/cobra" + "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/input" "github.com/Finschia/finschia-sdk/crypto/keyring" - - "github.com/spf13/cobra" ) const ( diff --git a/client/keys/export_test.go b/client/keys/export_test.go index 17f322c5e6..7ec4e766bf 100644 --- a/client/keys/export_test.go +++ b/client/keys/export_test.go @@ -9,12 +9,11 @@ import ( "github.com/stretchr/testify/require" "github.com/Finschia/finschia-sdk/client" + "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/crypto/hd" + "github.com/Finschia/finschia-sdk/crypto/keyring" "github.com/Finschia/finschia-sdk/testutil" "github.com/Finschia/finschia-sdk/testutil/testdata" - - "github.com/Finschia/finschia-sdk/client/flags" - "github.com/Finschia/finschia-sdk/crypto/keyring" sdk "github.com/Finschia/finschia-sdk/types" ) diff --git a/client/keys/import_test.go b/client/keys/import_test.go index e454a8b9a5..2d9d9c1c34 100644 --- a/client/keys/import_test.go +++ b/client/keys/import_test.go @@ -94,7 +94,7 @@ Ax9IQsSq+jOWkPRDJQ69a5/uUm4XliPim/CbYDVoXO6D3fts5IEXcUTmIa60ynC/ keyfile := filepath.Join(kbHome, "key.asc") - require.NoError(t, os.WriteFile(keyfile, []byte(armoredKey), 0o644)) + require.NoError(t, os.WriteFile(keyfile, []byte(armoredKey), 0o600)) defer func() { _ = os.RemoveAll(kbHome) diff --git a/client/keys/list_test.go b/client/keys/list_test.go index ebaf4ca2f9..9f7184602e 100644 --- a/client/keys/list_test.go +++ b/client/keys/list_test.go @@ -5,7 +5,6 @@ import ( "fmt" "testing" - "github.com/spf13/cobra" "github.com/stretchr/testify/require" "github.com/Finschia/finschia-sdk/client" @@ -39,11 +38,6 @@ func Test_runListCmd(t *testing.T) { kb.Delete("something") // nolint:errcheck }) - type args struct { - cmd *cobra.Command - args []string - } - testData := []struct { name string kbDir string @@ -53,7 +47,6 @@ func Test_runListCmd(t *testing.T) { {"keybase: w/key", kbHome2, false}, } for _, tt := range testData { - tt := tt t.Run(tt.name, func(t *testing.T) { cmd.SetArgs([]string{ fmt.Sprintf("--%s=%s", flags.FlagHome, tt.kbDir), diff --git a/client/keys/parse_test.go b/client/keys/parse_test.go index 5f8fd6022b..fe8c26d099 100644 --- a/client/keys/parse_test.go +++ b/client/keys/parse_test.go @@ -25,7 +25,6 @@ func TestParseKey(t *testing.T) { {"hex", []string{hexstr}, false}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { require.Equal(t, tt.wantErr, doParseKey(ParseKeyStringCommand(), config, tt.args) != nil) }) diff --git a/client/keys/show.go b/client/keys/show.go index 3543f36373..0bb93b16eb 100644 --- a/client/keys/show.go +++ b/client/keys/show.go @@ -62,7 +62,7 @@ func runShowCmd(cmd *cobra.Command, args []string) (err error) { if len(args) == 1 { info, err = fetchKey(clientCtx.Keyring, args[0]) if err != nil { - return fmt.Errorf("%s is not a valid name or address: %v", args[0], err) + return fmt.Errorf("%s is not a valid name or address: %w", args[0], err) } if info.GetType() == keyring.TypeMulti { info, err = keyring.NewMultiInfo(info.GetName(), info.GetPubKey()) @@ -75,7 +75,7 @@ func runShowCmd(cmd *cobra.Command, args []string) (err error) { for i, keyref := range args { info, err := fetchKey(clientCtx.Keyring, keyref) if err != nil { - return fmt.Errorf("%s is not a valid name or address: %v", keyref, err) + return fmt.Errorf("%s is not a valid name or address: %w", keyref, err) } pks[i] = info.GetPubKey() diff --git a/client/keys/show_test.go b/client/keys/show_test.go index ff73324b39..05d945bdda 100644 --- a/client/keys/show_test.go +++ b/client/keys/show_test.go @@ -64,8 +64,10 @@ func Test_runShowCmd(t *testing.T) { fakeKeyName2 := "runShowCmd_Key2" t.Cleanup(func() { - kb.Delete("runShowCmd_Key1") - kb.Delete("runShowCmd_Key2") + err := kb.Delete("runShowCmd_Key1") + require.NoError(t, err) + err = kb.Delete("runShowCmd_Key2") + require.NoError(t, err) }) path := hd.NewFundraiserParams(1, sdk.CoinType, 0).String() @@ -176,7 +178,6 @@ func Test_validateMultisigThreshold(t *testing.T) { {"1-2", args{2, 1}, true}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { if err := validateMultisigThreshold(tt.args.k, tt.args.nKeys); (err != nil) != tt.wantErr { t.Errorf("validateMultisigThreshold() error = %v, wantErr %v", err, tt.wantErr) @@ -202,7 +203,6 @@ func Test_getBechKeyOut(t *testing.T) { {"cons", args{sdk.PrefixConsensus}, keyring.MkConsKeyOutput, false}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { got, err := getBechKeyOut(tt.args.bechPrefix) if tt.wantErr { diff --git a/client/keys/utils_test.go b/client/keys/utils_test.go index fa9571ada9..3197107af9 100644 --- a/client/keys/utils_test.go +++ b/client/keys/utils_test.go @@ -24,7 +24,8 @@ func Test_printInfos(t *testing.T) { kb, err := keyring.New(types.KeyringServiceName(), keyring.BackendTest, kbHome, mockIn) require.NoError(t, err) - kb.NewAccount("something", testdata.TestMnemonic, "", "", hd.Secp256k1) + _, err = kb.NewAccount("something", testdata.TestMnemonic, "", "", hd.Secp256k1) + require.NoError(t, err) clientCtx := client.Context{}.WithKeyring(kb) require.NoError(t, err) diff --git a/client/pruning/main.go b/client/pruning/main.go index 4971c6db18..c2b6233e91 100644 --- a/client/pruning/main.go +++ b/client/pruning/main.go @@ -5,12 +5,11 @@ import ( "os" "path/filepath" + "github.com/Finschia/ostracon/libs/log" "github.com/spf13/cobra" "github.com/spf13/viper" dbm "github.com/tendermint/tm-db" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/server" servertypes "github.com/Finschia/finschia-sdk/server/types" diff --git a/client/query.go b/client/query.go index e56b41ec1d..43866cfef6 100644 --- a/client/query.go +++ b/client/query.go @@ -5,13 +5,12 @@ import ( "fmt" "strings" - "github.com/pkg/errors" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - ostbytes "github.com/Finschia/ostracon/libs/bytes" rpcclient "github.com/Finschia/ostracon/rpc/client" + "github.com/pkg/errors" abci "github.com/tendermint/tendermint/abci/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "github.com/Finschia/finschia-sdk/store/rootmulti" sdk "github.com/Finschia/finschia-sdk/types" diff --git a/client/rpc/status.go b/client/rpc/status.go index 7a89ed8d62..5c771b4058 100644 --- a/client/rpc/status.go +++ b/client/rpc/status.go @@ -3,11 +3,10 @@ package rpc import ( "context" - "github.com/spf13/cobra" - "github.com/Finschia/ostracon/libs/bytes" "github.com/Finschia/ostracon/p2p" ctypes "github.com/Finschia/ostracon/rpc/core/types" + "github.com/spf13/cobra" "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" diff --git a/client/test_helpers.go b/client/test_helpers.go index 65eeb35e5c..322785416d 100644 --- a/client/test_helpers.go +++ b/client/test_helpers.go @@ -74,7 +74,7 @@ func (t TestAccountRetriever) EnsureExists(_ Context, addr sdk.AccAddress) error } // GetAccountNumberSequence implements AccountRetriever.GetAccountNumberSequence -func (t TestAccountRetriever) GetAccountNumberSequence(_ Context, addr sdk.AccAddress) (accNum uint64, accSeq uint64, err error) { +func (t TestAccountRetriever) GetAccountNumberSequence(_ Context, addr sdk.AccAddress) (accNum, accSeq uint64, err error) { acc, ok := t.Accounts[addr.String()] if !ok { return 0, 0, fmt.Errorf("account %s not found", addr) diff --git a/client/tx/legacy_test.go b/client/tx/legacy_test.go index 038ff852b1..333fb8c193 100644 --- a/client/tx/legacy_test.go +++ b/client/tx/legacy_test.go @@ -41,6 +41,7 @@ var ( ) func buildTestTx(t *testing.T, builder client.TxBuilder) { + t.Helper() builder.SetMemo(memo) builder.SetGasLimit(gas) builder.SetFeeAmount(fee) diff --git a/client/tx/tx.go b/client/tx/tx.go index 2789957427..b6adae5289 100644 --- a/client/tx/tx.go +++ b/client/tx/tx.go @@ -119,7 +119,7 @@ func BroadcastTx(clientCtx client.Context, txf Factory, msgs ...sdk.Msg) error { ok, err := input.GetConfirmation("confirm transaction before signing and broadcasting", buf, os.Stderr) if err != nil || !ok { - _, _ = fmt.Fprintf(os.Stderr, "%s\n", "cancelled transaction") + _, _ = fmt.Fprintf(os.Stderr, "%s\n", "canceled transaction") return err } } diff --git a/client/tx/tx_test.go b/client/tx/tx_test.go index b9eb969055..cabeab29f2 100644 --- a/client/tx/tx_test.go +++ b/client/tx/tx_test.go @@ -71,23 +71,22 @@ func TestCalculateGas(t *testing.T) { } for _, tc := range testCases { - stc := tc txCfg := NewTestTxConfig() txf := tx.Factory{}. WithChainID("test-chain"). WithTxConfig(txCfg).WithSignMode(txCfg.SignModeHandler().DefaultMode()) - t.Run(stc.name, func(t *testing.T) { + t.Run(tc.name, func(t *testing.T) { mockClientCtx := mockContext{ gasUsed: tc.args.mockGasUsed, wantErr: tc.args.mockWantErr, } - simRes, gotAdjusted, err := tx.CalculateGas(mockClientCtx, txf.WithGasAdjustment(stc.args.adjustment)) - if stc.expPass { + simRes, gotAdjusted, err := tx.CalculateGas(mockClientCtx, txf.WithGasAdjustment(tc.args.adjustment)) + if tc.expPass { require.NoError(t, err) - require.Equal(t, simRes.GasInfo.GasUsed, stc.wantEstimate) - require.Equal(t, gotAdjusted, stc.wantAdjusted) + require.Equal(t, simRes.GasInfo.GasUsed, tc.wantEstimate) + require.Equal(t, gotAdjusted, tc.wantAdjusted) require.NotNil(t, simRes.Result) } else { require.Error(t, err) diff --git a/client/utils.go b/client/utils.go index 6ae575acef..91e227f35c 100644 --- a/client/utils.go +++ b/client/utils.go @@ -57,7 +57,7 @@ func ReadPageRequest(flagSet *pflag.FlagSet) (*query.PageRequest, error) { return NewPageRequest(pageKey, offset, limit, page, countTotal, reverse) } -func NewPageRequest(pageKey string, offset, limit, page uint64, countTotal bool, reverse bool) (*query.PageRequest, error) { +func NewPageRequest(pageKey string, offset, limit, page uint64, countTotal, reverse bool) (*query.PageRequest, error) { if page > 1 && offset > 0 { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "page and offset cannot be used together") } diff --git a/client/utils_test.go b/client/utils_test.go index c54c785c50..a0381f787d 100644 --- a/client/utils_test.go +++ b/client/utils_test.go @@ -70,7 +70,6 @@ func TestPaginate(t *testing.T) { } for i, tc := range testCases { - i, tc := i, tc t.Run(tc.name, func(t *testing.T) { start, end := client.Paginate(tc.numObjs, tc.page, tc.limit, tc.defLimit) require.Equal(t, tc.expectedStart, start, "invalid result; test case #%d", i) @@ -80,7 +79,6 @@ func TestPaginate(t *testing.T) { } func TestReadPageRequest(t *testing.T) { - testCases := []struct { name string pageKey string @@ -121,10 +119,15 @@ func TestReadPageRequest(t *testing.T) { flagSet.Bool(flags.FlagCountTotal, false, "count total") err := flagSet.Set(flags.FlagPageKey, tc.pageKey) + require.NoError(t, err) err = flagSet.Set(flags.FlagOffset, strconv.Itoa(tc.offset)) + require.NoError(t, err) err = flagSet.Set(flags.FlagLimit, strconv.Itoa(tc.limit)) + require.NoError(t, err) err = flagSet.Set(flags.FlagPage, strconv.Itoa(tc.page)) + require.NoError(t, err) err = flagSet.Set(flags.FlagCountTotal, strconv.FormatBool(tc.countTotal)) + require.NoError(t, err) pr, err := client.ReadPageRequest(flagSet) if tc.ok { diff --git a/codec/amino_codec_test.go b/codec/amino_codec_test.go index bfd9107f8f..7ecc75ce51 100644 --- a/codec/amino_codec_test.go +++ b/codec/amino_codec_test.go @@ -74,8 +74,6 @@ func TestAminoCodecMarshalJSONIndent(t *testing.T) { } for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { cdc := codec.NewAminoCodec(createTestCodec()) bz, err := cdc.MarshalJSONIndent(tc.input, "", " ") @@ -126,13 +124,13 @@ func TestAminoCodecFullDecodeAndEncode(t *testing.T) { err := legacyCdc.UnmarshalJSON([]byte(txSigned), &tx) require.NoError(t, err) - // Marshalling/unmarshalling the tx should work. + // Marshaling/unmarshalling the tx should work. marshaledTx, err := legacyCdc.MarshalJSON(tx) require.NoError(t, err) require.Equal(t, string(marshaledTx), txSigned) // The test logic written below is not included in cosmos-sdk - // Marshalling/unmarshalling the tx wrapped in a struct should work. + // Marshaling/unmarshalling the tx wrapped in a struct should work. txRequest := &cli.BroadcastReq{ Mode: "block", Tx: tx, diff --git a/codec/any_test.go b/codec/any_test.go index 6fc4f1e428..4c4b2f9411 100644 --- a/codec/any_test.go +++ b/codec/any_test.go @@ -6,7 +6,6 @@ import ( "github.com/stretchr/testify/require" "github.com/Finschia/finschia-sdk/codec" - "github.com/Finschia/finschia-sdk/codec/types" codectypes "github.com/Finschia/finschia-sdk/codec/types" "github.com/Finschia/finschia-sdk/crypto/keys/ed25519" cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" @@ -14,8 +13,8 @@ import ( "github.com/Finschia/finschia-sdk/testutil/testdata" ) -func NewTestInterfaceRegistry() types.InterfaceRegistry { - registry := types.NewInterfaceRegistry() +func NewTestInterfaceRegistry() codectypes.InterfaceRegistry { + registry := codectypes.NewInterfaceRegistry() registry.RegisterInterface("Animal", (*testdata.Animal)(nil)) registry.RegisterImplementations( (*testdata.Animal)(nil), @@ -26,7 +25,7 @@ func NewTestInterfaceRegistry() types.InterfaceRegistry { } func TestMarshalAny(t *testing.T) { - registry := types.NewInterfaceRegistry() + registry := codectypes.NewInterfaceRegistry() cdc := codec.NewProtoCodec(registry) @@ -53,7 +52,6 @@ func TestMarshalAny(t *testing.T) { require.Equal(t, kitty, animal) // nil should fail - registry = NewTestInterfaceRegistry() err = cdc.UnmarshalInterface(bz, nil) require.Error(t, err) } diff --git a/codec/codec_common_test.go b/codec/codec_common_test.go index 689a6f5adc..ec3eefb424 100644 --- a/codec/codec_common_test.go +++ b/codec/codec_common_test.go @@ -28,7 +28,8 @@ func testInterfaceMarshaling(require *require.Assertions, cdc interfaceMarshaler var animal testdata.Animal if isAminoBin { require.PanicsWithValue("Unmarshal expects a pointer", func() { - cdc.unmarshal(bz, animal) + err = cdc.unmarshal(bz, animal) + require.Error(err) }) } else { err = cdc.unmarshal(bz, animal) @@ -88,6 +89,7 @@ func testMarshalingTestCase(require *require.Assertions, tc testCase, m mustMars } func testMarshaling(t *testing.T, cdc codec.Codec) { + t.Helper() any, err := types.NewAnyWithValue(&testdata.Dog{Name: "rufus"}) require.NoError(t, err) @@ -117,7 +119,6 @@ func testMarshaling(t *testing.T, cdc codec.Codec) { } for _, tc := range testCases { - tc := tc m1 := mustMarshaler{cdc.Marshal, cdc.MustMarshal, cdc.Unmarshal, cdc.MustUnmarshal} m2 := mustMarshaler{cdc.MarshalLengthPrefixed, cdc.MustMarshalLengthPrefixed, cdc.UnmarshalLengthPrefixed, cdc.MustUnmarshalLengthPrefixed} m3 := mustMarshaler{ diff --git a/codec/proto_codec.go b/codec/proto_codec.go index c07b4f3f4e..c458536b0e 100644 --- a/codec/proto_codec.go +++ b/codec/proto_codec.go @@ -181,7 +181,7 @@ func (pc *ProtoCodec) MustUnmarshalJSON(bz []byte, ptr gogoproto.Message) { } } -// MarshalInterface is a convenience function for proto marshalling interfaces. It packs +// MarshalInterface is a convenience function for proto marshaling interfaces. It packs // the provided value, which must be an interface, in an Any and then marshals it to bytes. // NOTE: to marshal a concrete type, you should use Marshal instead func (pc *ProtoCodec) MarshalInterface(i gogoproto.Message) ([]byte, error) { @@ -215,7 +215,7 @@ func (pc *ProtoCodec) UnmarshalInterface(bz []byte, ptr interface{}) error { return pc.UnpackAny(any, ptr) } -// MarshalInterfaceJSON is a convenience function for proto marshalling interfaces. It +// MarshalInterfaceJSON is a convenience function for proto marshaling interfaces. It // packs the provided value in an Any and then marshals it to bytes. // NOTE: to marshal a concrete type, you should use MarshalJSON instead func (pc *ProtoCodec) MarshalInterfaceJSON(x gogoproto.Message) ([]byte, error) { diff --git a/codec/proto_codec_test.go b/codec/proto_codec_test.go index 8e653b0d1a..ba26ddfc3e 100644 --- a/codec/proto_codec_test.go +++ b/codec/proto_codec_test.go @@ -58,8 +58,6 @@ func TestProtoCodecUnmarshalLengthPrefixedChecks(t *testing.T) { } for _, falseSize := range falseSizes { - falseSize := falseSize - t.Run(fmt.Sprintf("ByMarshaling falseSize=%d", falseSize), func(t *testing.T) { lpm := &lyingProtoMarshaler{ ProtoMarshaler: &testdata.Cat{Lives: 9, Moniker: "glowing"}, diff --git a/codec/types/compat.go b/codec/types/compat.go index 1de7828491..f202c9893b 100644 --- a/codec/types/compat.go +++ b/codec/types/compat.go @@ -7,7 +7,6 @@ import ( "github.com/gogo/protobuf/jsonpb" "github.com/gogo/protobuf/proto" - amino "github.com/tendermint/go-amino" ) diff --git a/codec/types/interface_registry.go b/codec/types/interface_registry.go index 5d7e72e890..34397030cc 100644 --- a/codec/types/interface_registry.go +++ b/codec/types/interface_registry.go @@ -5,7 +5,6 @@ import ( "reflect" "github.com/gogo/protobuf/jsonpb" - "github.com/gogo/protobuf/proto" ) diff --git a/codec/unknownproto/benchmarks_test.go b/codec/unknownproto/benchmarks_test.go index d968c92f1e..ef733b6011 100644 --- a/codec/unknownproto/benchmarks_test.go +++ b/codec/unknownproto/benchmarks_test.go @@ -51,6 +51,7 @@ func BenchmarkRejectUnknownFields_parallel(b *testing.B) { } func benchmarkRejectUnknownFields(b *testing.B, parallel bool) { + b.Helper() b.ReportAllocs() if !parallel { @@ -89,6 +90,7 @@ func BenchmarkProtoUnmarshal_parallel(b *testing.B) { } func benchmarkProtoUnmarshal(b *testing.B, parallel bool) { + b.Helper() b.ReportAllocs() if !parallel { diff --git a/codec/unknownproto/unit_helpers_test.go b/codec/unknownproto/unit_helpers_test.go index 9c408a6d1f..b156422489 100644 --- a/codec/unknownproto/unit_helpers_test.go +++ b/codec/unknownproto/unit_helpers_test.go @@ -22,7 +22,6 @@ func TestWireTypeToString(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(fmt.Sprintf("wireType=%d", tt.typ), func(t *testing.T) { if g, w := wireTypeToString(tt.typ), tt.want; g != w { t.Fatalf("Mismatch:\nGot: %q\nWant: %q\n", g, w) diff --git a/codec/unknownproto/unknown_fields_test.go b/codec/unknownproto/unknown_fields_test.go index 44c490f101..8f9a9af7f7 100644 --- a/codec/unknownproto/unknown_fields_test.go +++ b/codec/unknownproto/unknown_fields_test.go @@ -4,9 +4,8 @@ import ( "reflect" "testing" - "github.com/stretchr/testify/require" - "github.com/gogo/protobuf/proto" + "github.com/stretchr/testify/require" "github.com/Finschia/finschia-sdk/codec/types" "github.com/Finschia/finschia-sdk/testutil/testdata" @@ -224,7 +223,6 @@ func TestRejectUnknownFieldsRepeated(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { protoBlob, err := proto.Marshal(tt.in) if err != nil { @@ -281,7 +279,6 @@ func TestRejectUnknownFields_allowUnknownNonCriticals(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { blob, err := proto.Marshal(tt.in) if err != nil { @@ -484,7 +481,6 @@ func TestRejectUnknownFieldsNested(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { protoBlob, err := proto.Marshal(tt.in) if err != nil { @@ -635,7 +631,6 @@ func TestRejectUnknownFieldsFlat(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { blob, err := proto.Marshal(tt.in) if err != nil { @@ -656,11 +651,11 @@ func TestRejectUnknownFieldsFlat(t *testing.T) { func TestPackedEncoding(t *testing.T) { data := testdata.TestRepeatedUints{Nums: []uint64{12, 13}} - marshalled, err := data.Marshal() + marshaled, err := data.Marshal() require.NoError(t, err) unmarshalled := &testdata.TestRepeatedUints{} - _, err = RejectUnknownFields(marshalled, unmarshalled, false, DefaultAnyResolver{}) + _, err = RejectUnknownFields(marshaled, unmarshalled, false, DefaultAnyResolver{}) require.NoError(t, err) } diff --git a/codec/yaml_test.go b/codec/yaml_test.go index ded11ec43d..35fecfc3f0 100644 --- a/codec/yaml_test.go +++ b/codec/yaml_test.go @@ -3,10 +3,9 @@ package codec_test import ( "testing" - "github.com/Finschia/finschia-sdk/codec" - "github.com/stretchr/testify/require" + "github.com/Finschia/finschia-sdk/codec" "github.com/Finschia/finschia-sdk/codec/types" "github.com/Finschia/finschia-sdk/testutil/testdata" ) diff --git a/crypto/armor.go b/crypto/armor.go index 9520da54c6..9a7c6c825e 100644 --- a/crypto/armor.go +++ b/crypto/armor.go @@ -86,7 +86,7 @@ func UnarmorInfoBytes(armorStr string) ([]byte, error) { func UnarmorPubKeyBytes(armorStr string) (bz []byte, algo string, err error) { bz, header, err := unarmorBytes(armorStr, blockTypePubKey) if err != nil { - return nil, "", fmt.Errorf("couldn't unarmor bytes: %v", err) + return nil, "", fmt.Errorf("couldn't unarmor bytes: %w", err) } switch header[headerVersion] { @@ -124,7 +124,7 @@ func unarmorBytes(armorStr, blockType string) (bz []byte, header map[string]stri // encrypt/decrypt with armor // Encrypt and armor the private key. -func EncryptArmorPrivKey(privKey cryptotypes.PrivKey, passphrase string, algo string) string { +func EncryptArmorPrivKey(privKey cryptotypes.PrivKey, passphrase, algo string) string { saltBytes, encBytes := encryptPrivKey(privKey, passphrase) header := map[string]string{ "kdf": "bcrypt", @@ -143,7 +143,7 @@ func EncryptArmorPrivKey(privKey cryptotypes.PrivKey, passphrase string, algo st // encrypt the given privKey with the passphrase using a randomly // generated salt and the xsalsa20 cipher. returns the salt and the // encrypted priv key. -func encryptPrivKey(privKey cryptotypes.PrivKey, passphrase string) (saltBytes []byte, encBytes []byte) { +func encryptPrivKey(privKey cryptotypes.PrivKey, passphrase string) (saltBytes, encBytes []byte) { saltBytes = crypto.CRandBytes(16) key, err := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), BcryptSecurityParameter) if err != nil { @@ -157,7 +157,7 @@ func encryptPrivKey(privKey cryptotypes.PrivKey, passphrase string) (saltBytes [ } // UnarmorDecryptPrivKey returns the privkey byte slice, a string of the algo type, and an error -func UnarmorDecryptPrivKey(armorStr string, passphrase string) (privKey cryptotypes.PrivKey, algo string, err error) { +func UnarmorDecryptPrivKey(armorStr, passphrase string) (privKey cryptotypes.PrivKey, algo string, err error) { blockType, header, encBytes, err := armor.DecodeArmor(armorStr) if err != nil { return privKey, "", err @@ -189,7 +189,7 @@ func UnarmorDecryptPrivKey(armorStr string, passphrase string) (privKey cryptoty return privKey, header[headerType], err } -func decryptPrivKey(saltBytes []byte, encBytes []byte, passphrase string) (privKey cryptotypes.PrivKey, err error) { +func decryptPrivKey(saltBytes, encBytes []byte, passphrase string) (privKey cryptotypes.PrivKey, err error) { key, err := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), BcryptSecurityParameter) if err != nil { return privKey, sdkerrors.Wrap(err, "error generating bcrypt key from passphrase") diff --git a/crypto/armor_test.go b/crypto/armor_test.go index acb7493b46..70313df065 100644 --- a/crypto/armor_test.go +++ b/crypto/armor_test.go @@ -46,7 +46,7 @@ func TestArmorUnarmorPrivKey(t *testing.T) { require.Contains(t, err.Error(), "unrecognized armor type") // armor key manually - encryptPrivKeyFn := func(privKey cryptotypes.PrivKey, passphrase string) (saltBytes []byte, encBytes []byte) { + encryptPrivKeyFn := func(privKey cryptotypes.PrivKey, passphrase string) (saltBytes, encBytes []byte) { saltBytes = ostcrypto.CRandBytes(16) key, err := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), crypto.BcryptSecurityParameter) require.NoError(t, err) diff --git a/crypto/codec/oc.go b/crypto/codec/oc.go index 3087c8dfba..a27ac71e18 100644 --- a/crypto/codec/oc.go +++ b/crypto/codec/oc.go @@ -1,10 +1,9 @@ package codec import ( - tmprotocrypto "github.com/tendermint/tendermint/proto/tendermint/crypto" - occrypto "github.com/Finschia/ostracon/crypto" "github.com/Finschia/ostracon/crypto/encoding" + tmprotocrypto "github.com/tendermint/tendermint/proto/tendermint/crypto" "github.com/Finschia/finschia-sdk/crypto/keys/ed25519" "github.com/Finschia/finschia-sdk/crypto/keys/secp256k1" diff --git a/crypto/hd/algo.go b/crypto/hd/algo.go index bda4361cba..a5c5d56d73 100644 --- a/crypto/hd/algo.go +++ b/crypto/hd/algo.go @@ -26,12 +26,12 @@ const ( var Secp256k1 = secp256k1Algo{} type ( - DeriveFn func(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error) + DeriveFn func(mnemonic, bip39Passphrase, hdPath string) ([]byte, error) GenerateFn func(bz []byte) types.PrivKey ) type WalletGenerator interface { - Derive(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error) + Derive(mnemonic, bip39Passphrase, hdPath string) ([]byte, error) Generate(bz []byte) types.PrivKey } @@ -43,7 +43,7 @@ func (s secp256k1Algo) Name() PubKeyType { // Derive derives and returns the secp256k1 private key for the given seed and HD path. func (s secp256k1Algo) Derive() DeriveFn { - return func(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error) { + return func(mnemonic, bip39Passphrase, hdPath string) ([]byte, error) { seed, err := bip39.NewSeedWithErrorChecking(mnemonic, bip39Passphrase) if err != nil { return nil, err diff --git a/crypto/hd/fundraiser_test.go b/crypto/hd/fundraiser_test.go index 06fbb79368..419056814a 100644 --- a/crypto/hd/fundraiser_test.go +++ b/crypto/hd/fundraiser_test.go @@ -7,11 +7,9 @@ import ( "os" "testing" - "github.com/stretchr/testify/require" - - bip39 "github.com/cosmos/go-bip39" - "github.com/Finschia/ostracon/crypto" + "github.com/cosmos/go-bip39" + "github.com/stretchr/testify/require" "github.com/Finschia/finschia-sdk/crypto/hd" "github.com/Finschia/finschia-sdk/crypto/keys/secp256k1" @@ -31,6 +29,7 @@ func TestFullFundraiserPath(t *testing.T) { } func initFundraiserTestVectors(t *testing.T) []addrData { + t.Helper() // NOTE: atom fundraiser address // var hdPath string = "m/44'/118'/0'/0/0" var hdToAddrTable []addrData @@ -77,7 +76,7 @@ func TestFundraiserCompatibility(t *testing.T) { require.Equal(t, seedB, seed) require.Equal(t, master[:], masterB, fmt.Sprintf("Expected masters to match for %d", i)) - require.Equal(t, priv[:], privB, "Expected priv keys to match") + require.Equal(t, priv, privB, "Expected priv keys to match") pubBFixed := make([]byte, secp256k1.PubKeySize) copy(pubBFixed, pubB) require.Equal(t, pub, &secp256k1.PubKey{Key: pubBFixed}, fmt.Sprintf("Expected pub keys to match for %d", i)) diff --git a/crypto/hd/hdpath.go b/crypto/hd/hdpath.go index a4683a97c6..4fb308b2af 100644 --- a/crypto/hd/hdpath.go +++ b/crypto/hd/hdpath.go @@ -168,7 +168,7 @@ func (p BIP44Params) String() string { } // ComputeMastersFromSeed returns the master secret key's, and chain code. -func ComputeMastersFromSeed(seed []byte) (secret [32]byte, chainCode [32]byte) { +func ComputeMastersFromSeed(seed []byte) (secret, chainCode [32]byte) { curveIdentifier := []byte("Bitcoin seed") secret, chainCode = i64(curveIdentifier, seed) @@ -228,7 +228,7 @@ func DerivePrivateKeyForPath(privKeyBytes, chainCode [32]byte, path string) ([]b // It returns the new private key and new chain code. // For more information on hardened keys see: // - https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki -func derivePrivateKey(privKeyBytes [32]byte, chainCode [32]byte, index uint32, harden bool) ([32]byte, [32]byte) { +func derivePrivateKey(privKeyBytes, chainCode [32]byte, index uint32, harden bool) ([32]byte, [32]byte) { var data []byte if harden { @@ -256,7 +256,7 @@ func derivePrivateKey(privKeyBytes [32]byte, chainCode [32]byte, index uint32, h } // modular big endian addition -func addScalars(a []byte, b []byte) [32]byte { +func addScalars(a, b []byte) [32]byte { aInt := new(big.Int).SetBytes(a) bInt := new(big.Int).SetBytes(b) sInt := new(big.Int).Add(aInt, bInt) @@ -275,7 +275,7 @@ func uint32ToBytes(i uint32) []byte { } // i64 returns the two halfs of the SHA512 HMAC of key and data. -func i64(key []byte, data []byte) (il [32]byte, ir [32]byte) { +func i64(key, data []byte) (il, ir [32]byte) { mac := hmac.New(sha512.New, key) // sha512 does not err _, _ = mac.Write(data) diff --git a/crypto/hd/hdpath_test.go b/crypto/hd/hdpath_test.go index 882835e50c..4fcc46220c 100644 --- a/crypto/hd/hdpath_test.go +++ b/crypto/hd/hdpath_test.go @@ -5,11 +5,11 @@ import ( "fmt" "testing" + "github.com/cosmos/go-bip39" + "github.com/stretchr/testify/require" + "github.com/Finschia/finschia-sdk/crypto/hd" "github.com/Finschia/finschia-sdk/types" - - bip39 "github.com/cosmos/go-bip39" - "github.com/stretchr/testify/require" ) var defaultBIP39Passphrase = "" @@ -107,9 +107,7 @@ func TestCreateHDPath(t *testing.T) { {"m/44'/114'/1'/1/0", args{114, 1, 1}, hd.BIP44Params{Purpose: 44, CoinType: 114, Account: 1, AddressIndex: 1}}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { - tt := tt require.Equal(t, tt.want, *hd.CreateHDPath(tt.args.coinType, tt.args.account, tt.args.index)) }) } @@ -170,7 +168,6 @@ func TestDeriveHDPathRange(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.path, func(t *testing.T) { master, ch := hd.ComputeMastersFromSeed(seed) _, err := hd.DerivePrivateKeyForPath(master, ch, tt.path) @@ -185,7 +182,7 @@ func TestDeriveHDPathRange(t *testing.T) { } } -func ExampleStringifyPathParams() { +func StringifyPathParamsExample() { path := hd.NewParams(44, 0, 0, false, 0) fmt.Println(path.String()) path = hd.NewParams(44, 33, 7, true, 9) @@ -195,7 +192,7 @@ func ExampleStringifyPathParams() { // m/44'/33'/7'/1/9 } -func ExampleSomeBIP32TestVecs() { +func SomeBIP32TestVecsExample() { seed := mnemonicToSeed("barrel original fuel morning among eternal " + "filter ball stove pluck matrix mechanic") master, ch := hd.ComputeMastersFromSeed(seed) @@ -206,34 +203,34 @@ func ExampleSomeBIP32TestVecs() { if err != nil { fmt.Println("INVALID") } else { - fmt.Println(hex.EncodeToString(priv[:])) + fmt.Println(hex.EncodeToString(priv)) } // bitcoin priv, err = hd.DerivePrivateKeyForPath(master, ch, "44'/0'/0'/0/0") if err != nil { fmt.Println("INVALID") } else { - fmt.Println(hex.EncodeToString(priv[:])) + fmt.Println(hex.EncodeToString(priv)) } // ether priv, err = hd.DerivePrivateKeyForPath(master, ch, "44'/60'/0'/0/0") if err != nil { fmt.Println("INVALID") } else { - fmt.Println(hex.EncodeToString(priv[:])) + fmt.Println(hex.EncodeToString(priv)) } // INVALID priv, err = hd.DerivePrivateKeyForPath(master, ch, "X/0'/0'/0/0") if err != nil { fmt.Println("INVALID") } else { - fmt.Println(hex.EncodeToString(priv[:])) + fmt.Println(hex.EncodeToString(priv)) } priv, err = hd.DerivePrivateKeyForPath(master, ch, "-44/0'/0'/0/0") if err != nil { fmt.Println("INVALID") } else { - fmt.Println(hex.EncodeToString(priv[:])) + fmt.Println(hex.EncodeToString(priv)) } fmt.Println() @@ -245,13 +242,13 @@ func ExampleSomeBIP32TestVecs() { "gorilla ranch hour rival razor call lunar mention taste vacant woman sister") master, ch = hd.ComputeMastersFromSeed(seed) priv, _ = hd.DerivePrivateKeyForPath(master, ch, "44'/1'/1'/0/4") - fmt.Println(hex.EncodeToString(priv[:])) + fmt.Println(hex.EncodeToString(priv)) seed = mnemonicToSeed("idea naive region square margin day captain habit " + "gun second farm pact pulse someone armed") master, ch = hd.ComputeMastersFromSeed(seed) priv, _ = hd.DerivePrivateKeyForPath(master, ch, "44'/0'/0'/0/420") - fmt.Println(hex.EncodeToString(priv[:])) + fmt.Println(hex.EncodeToString(priv)) fmt.Println() fmt.Println("BIP 32 example") @@ -261,7 +258,7 @@ func ExampleSomeBIP32TestVecs() { seed = mnemonicToSeed("monitor flock loyal sick object grunt duty ride develop assault harsh history") master, ch = hd.ComputeMastersFromSeed(seed) priv, _ = hd.DerivePrivateKeyForPath(master, ch, "0/7") - fmt.Println(hex.EncodeToString(priv[:])) + fmt.Println(hex.EncodeToString(priv)) // Output: keys from fundraiser test-vector (link, bitcoin, ether) // @@ -297,9 +294,8 @@ func TestDerivePrivateKeyForPathDoNotCrash(t *testing.T) { } for _, path := range paths { - path := path t.Run(path, func(t *testing.T) { - hd.DerivePrivateKeyForPath([32]byte{}, [32]byte{}, path) + _, _ = hd.DerivePrivateKeyForPath([32]byte{}, [32]byte{}, path) }) } } diff --git a/crypto/keyring/keyring.go b/crypto/keyring/keyring.go index a38f57ba8a..3c6f95e569 100644 --- a/crypto/keyring/keyring.go +++ b/crypto/keyring/keyring.go @@ -112,7 +112,7 @@ type Importer interface { ImportPrivKey(uid, armor, passphrase string) error // ImportPubKey imports ASCII armored public keys. - ImportPubKey(uid string, armor string) error + ImportPubKey(uid, armor string) error } // LegacyInfoImporter is implemented by key stores that support import of Info types. @@ -307,7 +307,7 @@ func (ks keystore) ImportPrivKey(uid, armor, passphrase string) error { return nil } -func (ks keystore) ImportPubKey(uid string, armor string) error { +func (ks keystore) ImportPubKey(uid, armor string) error { if _, err := ks.Key(uid); err == nil { return fmt.Errorf("cannot overwrite key: %s", uid) } @@ -463,7 +463,7 @@ func (ks keystore) KeyByAddress(address sdk.Address) (Info, error) { } func wrapKeyNotFound(err error, msg string) error { - if err == keyring.ErrKeyNotFound { + if errors.Is(err, keyring.ErrKeyNotFound) { return sdkerrors.Wrap(sdkerrors.ErrKeyNotFound, msg) } return err @@ -554,7 +554,7 @@ func (ks keystore) NewMnemonic(uid string, language Language, hdPath, bip39Passp return info, mnemonic, nil } -func (ks keystore) NewAccount(name string, mnemonic string, bip39Passphrase string, hdPath string, algo SignatureAlgo) (Info, error) { +func (ks keystore) NewAccount(name, mnemonic, bip39Passphrase, hdPath string, algo SignatureAlgo) (Info, error) { if !ks.isSupportedSigningAlgo(algo) { return nil, ErrUnsupportedSigningAlgo } @@ -691,7 +691,7 @@ func newFileBackendKeyringConfig(name, dir string, buf io.Reader) keyring.Config func newRealPrompt(dir string, buf io.Reader) func(string) (string, error) { return func(prompt string) (string, error) { - keyhashStored := false + var keyhashStored bool keyhashFilePath := filepath.Join(dir, "keyhash") var keyhash []byte @@ -702,7 +702,7 @@ func newRealPrompt(dir string, buf io.Reader) func(string) (string, error) { case err == nil: keyhash, err = os.ReadFile(keyhashFilePath) if err != nil { - return "", fmt.Errorf("failed to read %s: %v", keyhashFilePath, err) + return "", fmt.Errorf("failed to read %s: %w", keyhashFilePath, err) } keyhashStored = true @@ -711,7 +711,7 @@ func newRealPrompt(dir string, buf io.Reader) func(string) (string, error) { keyhashStored = false default: - return "", fmt.Errorf("failed to open %s: %v", keyhashFilePath, err) + return "", fmt.Errorf("failed to open %s: %w", keyhashFilePath, err) } failureCounter := 0 @@ -820,13 +820,13 @@ func (ks keystore) writeInfo(info Info) error { func (ks keystore) existsInDb(info Info) (bool, error) { if _, err := ks.db.Get(addrHexKeyAsString(info.GetAddress())); err == nil { return true, nil // address lookup succeeds - info exists - } else if err != keyring.ErrKeyNotFound { + } else if !errors.Is(err, keyring.ErrKeyNotFound) { return false, err // received unexpected error - returns error } if _, err := ks.db.Get(infoKey(info.GetName())); err == nil { return true, nil // uid lookup succeeds - info exists - } else if err != keyring.ErrKeyNotFound { + } else if !errors.Is(err, keyring.ErrKeyNotFound) { return false, err // received unexpected error - returns } diff --git a/crypto/keyring/keyring_test.go b/crypto/keyring/keyring_test.go index 9e6a013b9f..4c89215b19 100644 --- a/crypto/keyring/keyring_test.go +++ b/crypto/keyring/keyring_test.go @@ -7,7 +7,7 @@ import ( "testing" "github.com/99designs/keyring" - bip39 "github.com/cosmos/go-bip39" + "github.com/cosmos/go-bip39" "github.com/stretchr/testify/require" "github.com/Finschia/finschia-sdk/crypto" @@ -1153,7 +1153,8 @@ func TestBackendConfigConstructors(t *testing.T) { require.Equal(t, "keyring-test", backend.PassPrefix) } -func requireEqualInfo(t *testing.T, key Info, mnemonic Info) { +func requireEqualInfo(t *testing.T, key, mnemonic Info) { + t.Helper() require.Equal(t, key.GetName(), mnemonic.GetName()) require.Equal(t, key.GetAddress(), mnemonic.GetAddress()) require.Equal(t, key.GetPubKey(), mnemonic.GetPubKey()) diff --git a/crypto/keyring/signing_algorithms_test.go b/crypto/keyring/signing_algorithms_test.go index 7259e45ce8..e4c549d65a 100644 --- a/crypto/keyring/signing_algorithms_test.go +++ b/crypto/keyring/signing_algorithms_test.go @@ -35,7 +35,6 @@ func TestNewSigningAlgoByString(t *testing.T) { list := SigningAlgoList{hd.Secp256k1} for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { algorithm, err := NewSigningAlgoFromString(tt.algoStr, list) if tt.isSupported { diff --git a/crypto/keyring/types.go b/crypto/keyring/types.go index 8eb93d01c3..9bcd2fbf36 100644 --- a/crypto/keyring/types.go +++ b/crypto/keyring/types.go @@ -65,7 +65,7 @@ func (kt KeyType) String() string { type ( // DeriveKeyFunc defines the function to derive a new key from a seed and hd path - DeriveKeyFunc func(mnemonic string, bip39Passphrase, hdPath string, algo hd.PubKeyType) ([]byte, error) + DeriveKeyFunc func(mnemonic, bip39Passphrase, hdPath string, algo hd.PubKeyType) ([]byte, error) // PrivKeyGenFunc defines the function to convert derived key bytes to a tendermint private key PrivKeyGenFunc func(bz []byte, algo hd.PubKeyType) (cryptotypes.PrivKey, error) ) diff --git a/crypto/keyring/types_test.go b/crypto/keyring/types_test.go index 1396ffd0f3..e1b666e23a 100644 --- a/crypto/keyring/types_test.go +++ b/crypto/keyring/types_test.go @@ -17,7 +17,7 @@ func Test_writeReadLedgerInfo(t *testing.T) { hexPK := "035AD6810A47F073553FF30D2FCC7E0D3B1C0B74B61A1AAA2582344037151E143A" bz, err := hex.DecodeString(hexPK) require.NoError(t, err) - copy(tmpKey[:], bz) + copy(tmpKey, bz) lInfo := newLedgerInfo("some_name", &secp256k1.PubKey{Key: tmpKey}, *hd.NewFundraiserParams(5, sdk.CoinType, 1), hd.Secp256k1Type) require.Equal(t, TypeLedger, lInfo.GetType()) diff --git a/crypto/keys/ed25519/ed25519.go b/crypto/keys/ed25519/ed25519.go index 1ebc5e9579..fcfbb1fece 100644 --- a/crypto/keys/ed25519/ed25519.go +++ b/crypto/keys/ed25519/ed25519.go @@ -92,12 +92,12 @@ func (privKey *PrivKey) Type() string { return keyType } -// MarshalAmino overrides Amino binary marshalling. +// MarshalAmino overrides Amino binary marshaling. func (privKey PrivKey) MarshalAmino() ([]byte, error) { return privKey.Key, nil } -// UnmarshalAmino overrides Amino binary marshalling. +// UnmarshalAmino overrides Amino binary marshaling. func (privKey *PrivKey) UnmarshalAmino(bz []byte) error { if len(bz) != PrivKeySize { return fmt.Errorf("invalid privkey size") @@ -107,14 +107,14 @@ func (privKey *PrivKey) UnmarshalAmino(bz []byte) error { return nil } -// MarshalAminoJSON overrides Amino JSON marshalling. +// MarshalAminoJSON overrides Amino JSON marshaling. func (privKey PrivKey) MarshalAminoJSON() ([]byte, error) { // When we marshal to Amino JSON, we don't marshal the "key" field itself, // just its contents (i.e. the key bytes). return privKey.MarshalAmino() } -// UnmarshalAminoJSON overrides Amino JSON marshalling. +// UnmarshalAminoJSON overrides Amino JSON marshaling. func (privKey *PrivKey) UnmarshalAminoJSON(bz []byte) error { return privKey.UnmarshalAmino(bz) } @@ -174,7 +174,7 @@ func (pubKey *PubKey) Bytes() []byte { return pubKey.Key } -func (pubKey *PubKey) VerifySignature(msg []byte, sig []byte) bool { +func (pubKey *PubKey) VerifySignature(msg, sig []byte) bool { // make sure we use the same algorithm to sign if len(sig) != SignatureSize { return false @@ -201,12 +201,12 @@ func (pubKey *PubKey) Equals(other cryptotypes.PubKey) bool { return subtle.ConstantTimeCompare(pubKey.Bytes(), other.Bytes()) == 1 } -// MarshalAmino overrides Amino binary marshalling. +// MarshalAmino overrides Amino binary marshaling. func (pubKey PubKey) MarshalAmino() ([]byte, error) { return pubKey.Key, nil } -// UnmarshalAmino overrides Amino binary marshalling. +// UnmarshalAmino overrides Amino binary marshaling. func (pubKey *PubKey) UnmarshalAmino(bz []byte) error { if len(bz) != PubKeySize { return errors.Wrap(errors.ErrInvalidPubKey, "invalid pubkey size") @@ -216,14 +216,14 @@ func (pubKey *PubKey) UnmarshalAmino(bz []byte) error { return nil } -// MarshalAminoJSON overrides Amino JSON marshalling. +// MarshalAminoJSON overrides Amino JSON marshaling. func (pubKey PubKey) MarshalAminoJSON() ([]byte, error) { // When we marshal to Amino JSON, we don't marshal the "key" field itself, // just its contents (i.e. the key bytes). return pubKey.MarshalAmino() } -// UnmarshalAminoJSON overrides Amino JSON marshalling. +// UnmarshalAminoJSON overrides Amino JSON marshaling. func (pubKey *PubKey) UnmarshalAminoJSON(bz []byte) error { return pubKey.UnmarshalAmino(bz) } diff --git a/crypto/keys/ed25519/ed25519_test.go b/crypto/keys/ed25519/ed25519_test.go index 3552247231..72162c838c 100644 --- a/crypto/keys/ed25519/ed25519_test.go +++ b/crypto/keys/ed25519/ed25519_test.go @@ -13,7 +13,7 @@ import ( "github.com/Finschia/finschia-sdk/codec" "github.com/Finschia/finschia-sdk/codec/types" cryptocodec "github.com/Finschia/finschia-sdk/crypto/codec" - ed25519 "github.com/Finschia/finschia-sdk/crypto/keys/ed25519" + "github.com/Finschia/finschia-sdk/crypto/keys/ed25519" "github.com/Finschia/finschia-sdk/crypto/keys/secp256k1" cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" ) @@ -31,7 +31,7 @@ func TestSignAndValidateEd25519(t *testing.T) { // ---- // Test cross packages verification - stdPrivKey := stded25519.PrivateKey(privKey.Key) + stdPrivKey := privKey.Key stdPubKey := stdPrivKey.Public().(stded25519.PublicKey) assert.Equal(t, stdPubKey, pubKey.(*ed25519.PubKey).Key) diff --git a/crypto/keys/internal/ecdsa/privkey.go b/crypto/keys/internal/ecdsa/privkey.go index 2aeedb1c4d..1d642ab9a4 100644 --- a/crypto/keys/internal/ecdsa/privkey.go +++ b/crypto/keys/internal/ecdsa/privkey.go @@ -39,7 +39,7 @@ func NormalizeS(sigS *big.Int) *big.Int { // signatureRaw will serialize signature to R || S. // R, S are padded to 32 bytes respectively. // code roughly copied from secp256k1_nocgo.go -func signatureRaw(r *big.Int, s *big.Int) []byte { +func signatureRaw(r, s *big.Int) []byte { rBytes := r.Bytes() sBytes := s.Bytes() sigBytes := make([]byte, 64) diff --git a/crypto/keys/internal/ecdsa/privkey_internal_test.go b/crypto/keys/internal/ecdsa/privkey_internal_test.go index 185ecd72cb..15452b8f4e 100644 --- a/crypto/keys/internal/ecdsa/privkey_internal_test.go +++ b/crypto/keys/internal/ecdsa/privkey_internal_test.go @@ -8,7 +8,6 @@ import ( "testing" "github.com/Finschia/ostracon/crypto" - "github.com/stretchr/testify/suite" ) @@ -40,10 +39,11 @@ func (suite *SKSuite) TestMarshal() { const size = 32 buffer := make([]byte, size) - suite.sk.MarshalTo(buffer) + _, err := suite.sk.MarshalTo(buffer) + require.NoError(err) sk := new(PrivKey) - err := sk.Unmarshal(buffer, secp256r1, size) + err = sk.Unmarshal(buffer, secp256r1, size) require.NoError(err) require.True(sk.Equal(&suite.sk.PrivateKey)) } @@ -92,7 +92,7 @@ func (suite *SKSuite) TestSign() { // check whether msg can be verified with same key, and high_s // value using "regular" ecdsa signature - hash := sha256.Sum256([]byte(msg)) + hash := sha256.Sum256(msg) require.True(ecdsa.Verify(&suite.pk.PublicKey, hash[:], r, high_s)) // Mutate the message diff --git a/crypto/keys/internal/ecdsa/pubkey.go b/crypto/keys/internal/ecdsa/pubkey.go index 97a32271bc..bb65bebc19 100644 --- a/crypto/keys/internal/ecdsa/pubkey.go +++ b/crypto/keys/internal/ecdsa/pubkey.go @@ -59,7 +59,7 @@ func (pk *PubKey) Bytes() []byte { // where the s integer component of the signature is in the // 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 { +func (pk *PubKey) VerifySignature(msg, sig []byte) bool { // check length for raw signature // which is two 32-byte padded big.Ints // concatenated diff --git a/crypto/keys/multisig/codec.go b/crypto/keys/multisig/codec.go index b3e4497fb3..1cca0551e1 100644 --- a/crypto/keys/multisig/codec.go +++ b/crypto/keys/multisig/codec.go @@ -15,7 +15,6 @@ const ( PubKeyAminoRoute = "tendermint/PubKeyMultisigThreshold" ) -// nolint // Deprecated: Amino is being deprecated in the SDK. But even if you need to // use Amino for some reason, please use `codec/legacy.Cdc` instead. var AminoCdc = codec.NewLegacyAmino() diff --git a/crypto/keys/multisig/multisig.go b/crypto/keys/multisig/multisig.go index 1e11aa01a9..c2ab34be95 100644 --- a/crypto/keys/multisig/multisig.go +++ b/crypto/keys/multisig/multisig.go @@ -100,7 +100,7 @@ func (m *LegacyAminoPubKey) VerifyMultisignature(getSignBytes multisigtypes.GetS // VerifySignature implements cryptotypes.PubKey VerifySignature method, // it panics because it can't handle MultiSignatureData // cf. https://github.com/cosmos/cosmos-sdk/issues/7109#issuecomment-686329936 -func (m *LegacyAminoPubKey) VerifySignature(msg []byte, sig []byte) bool { +func (m *LegacyAminoPubKey) VerifySignature(msg, sig []byte) bool { panic("not implemented") } diff --git a/crypto/keys/multisig/multisig_test.go b/crypto/keys/multisig/multisig_test.go index 2c2c81230e..9f9714d47c 100644 --- a/crypto/keys/multisig/multisig_test.go +++ b/crypto/keys/multisig/multisig_test.go @@ -175,7 +175,8 @@ func TestVerifyMultisignature(t *testing.T) { sig = multisig.NewMultisig(5) require.Error(pk.VerifyMultisignature(signBytesFn, sig)) - multisig.AddSignatureFromPubKey(sig, sigs[0], pubKeys[0], pubKeys) + err := multisig.AddSignatureFromPubKey(sig, sigs[0], pubKeys[0], pubKeys) + require.NoError(err) // Add second signature manually sig.Signatures = append(sig.Signatures, sigs[0]) }, @@ -213,8 +214,10 @@ func TestVerifyMultisignature(t *testing.T) { _, sigs := generatePubKeysAndSignatures(2, msg) pk = kmultisig.NewLegacyAminoPubKey(2, pubKeys) sig = multisig.NewMultisig(2) - multisig.AddSignatureFromPubKey(sig, sigs[0], pubKeys[0], pubKeys) - multisig.AddSignatureFromPubKey(sig, sigs[1], pubKeys[1], pubKeys) + err := multisig.AddSignatureFromPubKey(sig, sigs[0], pubKeys[0], pubKeys) + require.NoError(err) + err = multisig.AddSignatureFromPubKey(sig, sigs[1], pubKeys[1], pubKeys) + require.NoError(err) }, false, }, @@ -267,7 +270,7 @@ func TestMultiSigMigration(t *testing.T) { require.NoError(t, multisig.AddSignatureFromPubKey(multisignature, sigs[0], pkSet[0], pkSet)) // create a StdSignature for msg, and convert it to sigV2 - sig := legacytx.StdSignature{PubKey: pkSet[1], Signature: sigs[1].(*signing.SingleSignatureData).Signature} + sig := legacytx.StdSignature{PubKey: pkSet[1], Signature: sigs[1].(*signing.SingleSignatureData).Signature} //nolint:staticcheck // this will be removed when proto is ready sigV2, err := legacytx.StdSignatureToSignatureV2(cdc, sig) require.NoError(t, multisig.AddSignatureV2(multisignature, sigV2, pkSet)) diff --git a/crypto/keys/secp256k1/secp256k1.go b/crypto/keys/secp256k1/secp256k1.go index f5d42a07d4..3d72272802 100644 --- a/crypto/keys/secp256k1/secp256k1.go +++ b/crypto/keys/secp256k1/secp256k1.go @@ -8,11 +8,10 @@ import ( "io" "math/big" + "github.com/Finschia/ostracon/crypto" secp256k1 "github.com/btcsuite/btcd/btcec" "golang.org/x/crypto/ripemd160" //nolint: staticcheck // necessary for Bitcoin address format - "github.com/Finschia/ostracon/crypto" - "github.com/Finschia/finschia-sdk/codec" cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" "github.com/Finschia/finschia-sdk/types/errors" @@ -53,12 +52,12 @@ func (privKey *PrivKey) Type() string { return keyType } -// MarshalAmino overrides Amino binary marshalling. +// MarshalAmino overrides Amino binary marshaling. func (privKey PrivKey) MarshalAmino() ([]byte, error) { return privKey.Key, nil } -// UnmarshalAmino overrides Amino binary marshalling. +// UnmarshalAmino overrides Amino binary marshaling. func (privKey *PrivKey) UnmarshalAmino(bz []byte) error { if len(bz) != PrivKeySize { return fmt.Errorf("invalid privkey size") @@ -68,14 +67,14 @@ func (privKey *PrivKey) UnmarshalAmino(bz []byte) error { return nil } -// MarshalAminoJSON overrides Amino JSON marshalling. +// MarshalAminoJSON overrides Amino JSON marshaling. func (privKey PrivKey) MarshalAminoJSON() ([]byte, error) { // When we marshal to Amino JSON, we don't marshal the "key" field itself, // just its contents (i.e. the key bytes). return privKey.MarshalAmino() } -// UnmarshalAminoJSON overrides Amino JSON marshalling. +// UnmarshalAminoJSON overrides Amino JSON marshaling. func (privKey *PrivKey) UnmarshalAminoJSON(bz []byte) error { return privKey.UnmarshalAmino(bz) } @@ -179,12 +178,12 @@ func (pubKey *PubKey) Equals(other cryptotypes.PubKey) bool { return pubKey.Type() == other.Type() && bytes.Equal(pubKey.Bytes(), other.Bytes()) } -// MarshalAmino overrides Amino binary marshalling. +// MarshalAmino overrides Amino binary marshaling. func (pubKey PubKey) MarshalAmino() ([]byte, error) { return pubKey.Key, nil } -// UnmarshalAmino overrides Amino binary marshalling. +// UnmarshalAmino overrides Amino binary marshaling. func (pubKey *PubKey) UnmarshalAmino(bz []byte) error { if len(bz) != PubKeySize { return errors.Wrap(errors.ErrInvalidPubKey, "invalid pubkey size") @@ -194,14 +193,14 @@ func (pubKey *PubKey) UnmarshalAmino(bz []byte) error { return nil } -// MarshalAminoJSON overrides Amino JSON marshalling. +// MarshalAminoJSON overrides Amino JSON marshaling. func (pubKey PubKey) MarshalAminoJSON() ([]byte, error) { // When we marshal to Amino JSON, we don't marshal the "key" field itself, // just its contents (i.e. the key bytes). return pubKey.MarshalAmino() } -// UnmarshalAminoJSON overrides Amino JSON marshalling. +// UnmarshalAminoJSON overrides Amino JSON marshaling. func (pubKey *PubKey) UnmarshalAminoJSON(bz []byte) error { return pubKey.UnmarshalAmino(bz) } diff --git a/crypto/keys/secp256k1/secp256k1_internal_test.go b/crypto/keys/secp256k1/secp256k1_internal_test.go index 7cbe5949f7..53ca3daf47 100644 --- a/crypto/keys/secp256k1/secp256k1_internal_test.go +++ b/crypto/keys/secp256k1/secp256k1_internal_test.go @@ -27,7 +27,6 @@ func Test_genPrivKey(t *testing.T) { {"valid because 0 < 1 < N", validOne, false}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { if tt.shouldPanic { require.Panics(t, func() { @@ -36,7 +35,7 @@ func Test_genPrivKey(t *testing.T) { return } got := genPrivKey(bytes.NewReader(tt.notSoRand)) - fe := new(big.Int).SetBytes(got[:]) + fe := new(big.Int).SetBytes(got) require.True(t, fe.Cmp(btcSecp256k1.S256().N) < 0) require.True(t, fe.Sign() > 0) }) diff --git a/crypto/keys/secp256k1/secp256k1_nocgo.go b/crypto/keys/secp256k1/secp256k1_nocgo.go index 767c25074e..4aee3e7cca 100644 --- a/crypto/keys/secp256k1/secp256k1_nocgo.go +++ b/crypto/keys/secp256k1/secp256k1_nocgo.go @@ -6,9 +6,8 @@ package secp256k1 import ( "math/big" - secp256k1 "github.com/btcsuite/btcd/btcec" - "github.com/Finschia/ostracon/crypto" + secp256k1 "github.com/btcsuite/btcd/btcec" ) // used to reject malleable signatures @@ -31,7 +30,7 @@ func (privKey *PrivKey) Sign(msg []byte) ([]byte, error) { // VerifyBytes verifies a signature of the form R || S. // It rejects signatures which are not in lower-S form. -func (pubKey *PubKey) VerifySignature(msg []byte, sigStr []byte) bool { +func (pubKey *PubKey) VerifySignature(msg, sigStr []byte) bool { if len(sigStr) != 64 { return false } diff --git a/crypto/keys/secp256k1/secp256k1_test.go b/crypto/keys/secp256k1/secp256k1_test.go index 7e593d77ba..a19b410af5 100644 --- a/crypto/keys/secp256k1/secp256k1_test.go +++ b/crypto/keys/secp256k1/secp256k1_test.go @@ -7,14 +7,13 @@ import ( "math/big" "testing" + "github.com/Finschia/ostracon/crypto" + ostsecp256k1 "github.com/Finschia/ostracon/crypto/secp256k1" btcSecp256k1 "github.com/btcsuite/btcd/btcec" "github.com/cosmos/btcutil/base58" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/Finschia/ostracon/crypto" - ostsecp256k1 "github.com/Finschia/ostracon/crypto/secp256k1" - "github.com/Finschia/finschia-sdk/codec" "github.com/Finschia/finschia-sdk/crypto/keys/ed25519" "github.com/Finschia/finschia-sdk/crypto/keys/secp256k1" @@ -127,12 +126,11 @@ func TestGenPrivKeyFromSecret(t *testing.T) { {"another seed used in cosmos tests #3", []byte("")}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { gotPrivKey := secp256k1.GenPrivKeyFromSecret(tt.secret) require.NotNil(t, gotPrivKey) // interpret as a big.Int and make sure it is a valid field element: - fe := new(big.Int).SetBytes(gotPrivKey.Key[:]) + fe := new(big.Int).SetBytes(gotPrivKey.Key) require.True(t, fe.Cmp(N) < 0) require.True(t, fe.Sign() > 0) }) diff --git a/crypto/keys/secp256r1/privkey_internal_test.go b/crypto/keys/secp256r1/privkey_internal_test.go index 227baa6afb..0559e50b3a 100644 --- a/crypto/keys/secp256r1/privkey_internal_test.go +++ b/crypto/keys/secp256r1/privkey_internal_test.go @@ -3,13 +3,13 @@ package secp256r1 import ( "testing" + "github.com/Finschia/ostracon/crypto" "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" "github.com/Finschia/finschia-sdk/codec" "github.com/Finschia/finschia-sdk/codec/types" cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" - "github.com/Finschia/ostracon/crypto" ) var _ cryptotypes.PrivKey = &PrivKey{} @@ -51,7 +51,7 @@ func (suite *SKSuite) TestBytes() { func (suite *SKSuite) TestMarshalProto() { require := suite.Require() - /**** test structure marshalling ****/ + /**** test structure marshaling ****/ var sk PrivKey bz, err := proto.Marshal(suite.sk) @@ -59,7 +59,7 @@ func (suite *SKSuite) TestMarshalProto() { require.NoError(proto.Unmarshal(bz, &sk)) require.True(sk.Equals(suite.sk)) - /**** test structure marshalling with codec ****/ + /**** test structure marshaling with codec ****/ sk = PrivKey{} registry := types.NewInterfaceRegistry() diff --git a/crypto/keys/secp256r1/pubkey.go b/crypto/keys/secp256r1/pubkey.go index 452d4e99d6..164c1ef587 100644 --- a/crypto/keys/secp256r1/pubkey.go +++ b/crypto/keys/secp256r1/pubkey.go @@ -41,7 +41,7 @@ func (m *PubKey) Type() string { } // VerifySignature implements SDK PubKey interface. -func (m *PubKey) VerifySignature(msg []byte, sig []byte) bool { +func (m *PubKey) VerifySignature(msg, sig []byte) bool { return m.Key.VerifySignature(msg, sig) } diff --git a/crypto/keys/secp256r1/pubkey_internal_test.go b/crypto/keys/secp256r1/pubkey_internal_test.go index 7af700e5a5..91c855f8ce 100644 --- a/crypto/keys/secp256r1/pubkey_internal_test.go +++ b/crypto/keys/secp256r1/pubkey_internal_test.go @@ -3,7 +3,7 @@ package secp256r1 import ( "testing" - proto "github.com/gogo/protobuf/proto" + "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" "github.com/Finschia/finschia-sdk/codec" @@ -62,13 +62,13 @@ func (suite *PKSuite) TestEquals() { require.False(suite.pk.Equals(pkOther)) require.True(pkOther.Equals(pkOther2)) require.True(pkOther2.Equals(pkOther)) - require.True(pkOther.Equals(pkOther), "Equals must be reflexive") + require.True(pkOther.Equals(pkOther), "Equals must be reflexive") //nolint:gocritic // false positive } func (suite *PKSuite) TestMarshalProto() { require := suite.Require() - /**** test structure marshalling ****/ + /**** test structure marshaling ****/ var pk PubKey bz, err := proto.Marshal(suite.pk) @@ -76,7 +76,7 @@ func (suite *PKSuite) TestMarshalProto() { require.NoError(proto.Unmarshal(bz, &pk)) require.True(pk.Equals(suite.pk)) - /**** test structure marshalling with codec ****/ + /**** test structure marshaling with codec ****/ pk = PubKey{} registry := types.NewInterfaceRegistry() @@ -100,7 +100,7 @@ func (suite *PKSuite) TestMarshalProto() { require.Len(bz2, bufSize) require.Equal(bz, bz2[(bufSize-pk.Size()):]) - /**** test interface marshalling ****/ + /**** test interface marshaling ****/ bz, err = cdc.MarshalInterface(suite.pk) require.NoError(err) var pkI cryptotypes.PubKey @@ -111,7 +111,7 @@ func (suite *PKSuite) TestMarshalProto() { require.NoError(cdc.UnmarshalInterface(bz, &pkI)) require.True(pkI.Equals(suite.pk)) - cdc.UnmarshalInterface(bz, nil) + err = cdc.UnmarshalInterface(bz, nil) require.Error(err, "nil should fail") } diff --git a/crypto/ledger/encode_test.go b/crypto/ledger/encode_test.go index 75e2afd055..8d8749cb84 100644 --- a/crypto/ledger/encode_test.go +++ b/crypto/ledger/encode_test.go @@ -9,11 +9,8 @@ import ( cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" ) -type byter interface { - Bytes() []byte -} - -func checkAminoJSON(t *testing.T, src interface{}, dst interface{}, isNil bool) { +func checkAminoJSON(t *testing.T, src, dst interface{}, isNil bool) { + t.Helper() // Marshal to JSON bytes. js, err := cdc.MarshalJSON(src) require.Nil(t, err, "%+v", err) @@ -30,17 +27,17 @@ func checkAminoJSON(t *testing.T, src interface{}, dst interface{}, isNil bool) // nolint: govet func ExamplePrintRegisteredTypes() { - cdc.PrintTypes(os.Stdout) - //| Type | Name | Prefix | Length | Notes | - //| ---- | ---- | ------ | ----- | ------ | - //| PrivKeyLedgerSecp256k1 | tendermint/PrivKeyLedgerSecp256k1 | 0x10CAB393 | variable | | - //| PubKey | tendermint/PubKeySr25519 | 0x0DFB1005 | variable | | - //| PubKey | tendermint/PubKeyEd25519 | 0x1624DE64 | variable | | - //| PubKey | tendermint/PubKeySecp256k1 | 0xEB5AE987 | variable | | - //| LegacyAminoPubKey | tendermint/PubKeyMultisigThreshold | 0x22C1F7E2 | variable | | - //| PrivKey | tendermint/PrivKeySr25519 | 0x2F82D78B | variable | | - //| PrivKey | tendermint/PrivKeyEd25519 | 0xA3288910 | variable | | - //| PrivKey | tendermint/PrivKeySecp256k1 | 0xE1B0F79B | variable | | + _ = cdc.PrintTypes(os.Stdout) + // | Type | Name | Prefix | Length | Notes | + // | ---- | ---- | ------ | ----- | ------ | + // | PrivKeyLedgerSecp256k1 | tendermint/PrivKeyLedgerSecp256k1 | 0x10CAB393 | variable | | + // | PubKey | tendermint/PubKeySr25519 | 0x0DFB1005 | variable | | + // | PubKey | tendermint/PubKeyEd25519 | 0x1624DE64 | variable | | + // | PubKey | tendermint/PubKeySecp256k1 | 0xEB5AE987 | variable | | + // | LegacyAminoPubKey | tendermint/PubKeyMultisigThreshold | 0x22C1F7E2 | variable | | + // | PrivKey | tendermint/PrivKeySr25519 | 0x2F82D78B | variable | | + // | PrivKey | tendermint/PrivKeyEd25519 | 0xA3288910 | variable | | + // | PrivKey | tendermint/PrivKeySecp256k1 | 0xE1B0F79B | variable | | } func TestNilEncodings(t *testing.T) { diff --git a/crypto/ledger/ledger_mock.go b/crypto/ledger/ledger_mock.go index f1127e3475..11446e21f3 100644 --- a/crypto/ledger/ledger_mock.go +++ b/crypto/ledger/ledger_mock.go @@ -6,14 +6,12 @@ package ledger import ( "fmt" + "github.com/Finschia/ostracon/crypto" "github.com/btcsuite/btcd/btcec" - "github.com/pkg/errors" - "github.com/cosmos/go-bip39" + "github.com/pkg/errors" secp256k1 "github.com/tendermint/btcd/btcec" - "github.com/Finschia/ostracon/crypto" - "github.com/Finschia/finschia-sdk/crypto/hd" csecp256k1 "github.com/Finschia/finschia-sdk/crypto/keys/secp256k1" "github.com/Finschia/finschia-sdk/testutil/testdata" @@ -58,7 +56,7 @@ func (mock LedgerSECP256K1Mock) GetPublicKeySECP256K1(derivationPath []uint32) ( return nil, err } - _, pubkeyObject := secp256k1.PrivKeyFromBytes(secp256k1.S256(), derivedPriv[:]) + _, pubkeyObject := secp256k1.PrivKeyFromBytes(secp256k1.S256(), derivedPriv) return pubkeyObject.SerializeUncompressed(), nil } @@ -72,9 +70,9 @@ func (mock LedgerSECP256K1Mock) GetAddressPubKeySECP256K1(derivationPath []uint3 } // re-serialize in the 33-byte compressed format - cmp, err := btcec.ParsePubKey(pk[:], btcec.S256()) + cmp, err := btcec.ParsePubKey(pk, btcec.S256()) if err != nil { - return nil, "", fmt.Errorf("error parsing public key: %v", err) + return nil, "", fmt.Errorf("error parsing public key: %w", err) } compressedPublicKey := make([]byte, csecp256k1.PubKeySize) @@ -99,7 +97,7 @@ func (mock LedgerSECP256K1Mock) SignSECP256K1(derivationPath []uint32, message [ return nil, err } - priv, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), derivedPriv[:]) + priv, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), derivedPriv) sig, err := priv.Sign(crypto.Sha256(message)) if err != nil { diff --git a/crypto/ledger/ledger_secp256k1.go b/crypto/ledger/ledger_secp256k1.go index d93bd24a4b..4c0c5251ac 100644 --- a/crypto/ledger/ledger_secp256k1.go +++ b/crypto/ledger/ledger_secp256k1.go @@ -6,7 +6,6 @@ import ( "github.com/btcsuite/btcd/btcec" "github.com/pkg/errors" - tmbtcec "github.com/tendermint/btcd/btcec" "github.com/Finschia/finschia-sdk/crypto/hd" @@ -239,13 +238,13 @@ func sign(device SECP256K1, pkl PrivKeyLedgerSecp256k1, msg []byte) ([]byte, err func getPubKeyUnsafe(device SECP256K1, path hd.BIP44Params) (types.PubKey, error) { publicKey, err := device.GetPublicKeySECP256K1(path.DerivationPath()) if err != nil { - return nil, fmt.Errorf("please open Cosmos app on the Ledger device - error: %v", err) + return nil, fmt.Errorf("please open Cosmos app on the Ledger device - error: %w", err) } // re-serialize in the 33-byte compressed format cmp, err := btcec.ParsePubKey(publicKey, btcec.S256()) if err != nil { - return nil, fmt.Errorf("error parsing public key: %v", err) + return nil, fmt.Errorf("error parsing public key: %w", err) } compressedPublicKey := make([]byte, secp256k1.PubKeySize) @@ -269,7 +268,7 @@ func getPubKeyAddrSafe(device SECP256K1, path hd.BIP44Params, hrp string) (types // re-serialize in the 33-byte compressed format cmp, err := btcec.ParsePubKey(publicKey, btcec.S256()) if err != nil { - return nil, "", fmt.Errorf("error parsing public key: %v", err) + return nil, "", fmt.Errorf("error parsing public key: %w", err) } compressedPublicKey := make([]byte, secp256k1.PubKeySize) diff --git a/crypto/ledger/ledger_test.go b/crypto/ledger/ledger_test.go index 1d2d342db0..3c4c0535e7 100644 --- a/crypto/ledger/ledger_test.go +++ b/crypto/ledger/ledger_test.go @@ -29,6 +29,7 @@ func TestPublicKeyUnsafe(t *testing.T) { } func checkDefaultPubKey(t *testing.T, priv types.LedgerPrivKey) { + t.Helper() require.NotNil(t, priv) expectedPkStr := "PubKeySecp256k1{02BCD96CAB102304AC10E90C5A0F29358E3A4A6FB1217B83E5DB657918EA28BEC1}" require.Equal(t, "eb5ae9872102bcd96cab102304ac10e90c5a0f29358e3a4a6fb1217b83e5db657918ea28bec1", diff --git a/crypto/types/compact_bit_array_test.go b/crypto/types/compact_bit_array_test.go index c809dfd1fc..6fd0dda555 100644 --- a/crypto/types/compact_bit_array_test.go +++ b/crypto/types/compact_bit_array_test.go @@ -7,10 +7,9 @@ import ( "math/rand" "testing" + ostrand "github.com/Finschia/ostracon/libs/rand" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - ostrand "github.com/Finschia/ostracon/libs/rand" ) func randCompactBitArray(bits int) (*CompactBitArray, []byte) { @@ -58,7 +57,6 @@ func TestBitArrayEqual(t *testing.T) { {name: "different should not be equal", b1: big1, b2: big2, eq: false}, } for _, tc := range cases { - tc := tc t.Run(tc.name, func(t *testing.T) { eq := tc.b1.Equal(tc.b2) require.Equal(t, tc.eq, eq) @@ -102,7 +100,6 @@ func TestJSONMarshalUnmarshal(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.bA.String(), func(t *testing.T) { bz, err := json.Marshal(tc.bA) require.NoError(t, err) @@ -162,7 +159,6 @@ func TestCompactMarshalUnmarshal(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.bA.String(), func(t *testing.T) { bz := tc.bA.CompactMarshal() @@ -208,8 +204,6 @@ func TestCompactBitArrayNumOfTrueBitsBefore(t *testing.T) { {`"______________xx"`, []int{14, 15}, []int{0, 1}}, } for tcIndex, tc := range testCases { - tc := tc - tcIndex := tcIndex t.Run(tc.marshalledBA, func(t *testing.T) { var bA *CompactBitArray err := json.Unmarshal([]byte(tc.marshalledBA), &bA) @@ -282,7 +276,6 @@ func TestNewCompactBitArrayCrashWithLimits(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(fmt.Sprintf("%d", tt.in), func(t *testing.T) { got := NewCompactBitArray(tt.in) if g := got != nil; g != tt.mustPass { diff --git a/crypto/types/types.go b/crypto/types/types.go index 09746f5a2f..a51cc6a253 100644 --- a/crypto/types/types.go +++ b/crypto/types/types.go @@ -11,7 +11,7 @@ type PubKey interface { Address() Address Bytes() []byte - VerifySignature(msg []byte, sig []byte) bool + VerifySignature(msg, sig []byte) bool Equals(PubKey) bool Type() string } diff --git a/server/api/server.go b/server/api/server.go index 9bce7ff2cc..60235da90c 100644 --- a/server/api/server.go +++ b/server/api/server.go @@ -9,22 +9,20 @@ import ( "sync" "time" + "github.com/Finschia/ostracon/libs/log" + tmrpcserver "github.com/Finschia/ostracon/rpc/jsonrpc/server" "github.com/gogo/gateway" "github.com/gorilla/handlers" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/Finschia/ostracon/libs/log" - tmrpcserver "github.com/Finschia/ostracon/rpc/jsonrpc/server" - "github.com/Finschia/finschia-sdk/client" + // unnamed import of statik for swagger UI support + _ "github.com/Finschia/finschia-sdk/client/docs/statik" "github.com/Finschia/finschia-sdk/codec/legacy" "github.com/Finschia/finschia-sdk/server/config" "github.com/Finschia/finschia-sdk/telemetry" grpctypes "github.com/Finschia/finschia-sdk/types/grpc" - - // unnamed import of statik for swagger UI support - _ "github.com/Finschia/finschia-sdk/client/docs/statik" ) // Server defines the server's API interface. @@ -59,7 +57,7 @@ func CustomGRPCHeaderMatcher(key string) (string, bool) { func New(clientCtx client.Context, logger log.Logger) *Server { // The default JSON marshaller used by the gRPC-Gateway is unable to marshal non-nullable non-scalar fields. - // Using the gogo/gateway package with the gRPC-Gateway WithMarshaler option fixes the scalar field marshalling issue. + // Using the gogo/gateway package with the gRPC-Gateway WithMarshaler option fixes the scalar field marshaling issue. marshalerOption := &gateway.JSONPb{ EmitDefaults: true, Indent: " ", @@ -76,7 +74,7 @@ func New(clientCtx client.Context, logger log.Logger) *Server { runtime.WithMarshalerOption(runtime.MIMEWildcard, marshalerOption), // This is necessary to get error details properly - // marshalled in unary requests. + // marshaled in unary requests. runtime.WithProtoErrorHandler(runtime.DefaultHTTPProtoErrorHandler), // Custom header matcher for mapping request headers to diff --git a/server/config/config.go b/server/config/config.go index 3663d99c91..45de73247d 100644 --- a/server/config/config.go +++ b/server/config/config.go @@ -8,7 +8,6 @@ import ( "github.com/Finschia/finschia-sdk/store/cache" "github.com/Finschia/finschia-sdk/store/iavl" - storetypes "github.com/Finschia/finschia-sdk/store/types" "github.com/Finschia/finschia-sdk/telemetry" sdk "github.com/Finschia/finschia-sdk/types" diff --git a/server/config/toml.go b/server/config/toml.go index f5e44deae7..9e3e38f720 100644 --- a/server/config/toml.go +++ b/server/config/toml.go @@ -236,5 +236,5 @@ func WriteConfigFile(configFilePath string, config interface{}) { panic(err) } - ostos.MustWriteFile(configFilePath, buffer.Bytes(), 0644) + ostos.MustWriteFile(configFilePath, buffer.Bytes(), 0o644) } diff --git a/server/export.go b/server/export.go index 6d39e482d7..a681c4d771 100644 --- a/server/export.go +++ b/server/export.go @@ -69,7 +69,7 @@ func ExportCmd(appExporter types.AppExporter, defaultNodeHome string) *cobra.Com exported, err := appExporter(serverCtx.Logger, db, traceWriter, height, forZeroHeight, jailAllowedAddrs, serverCtx.Viper) if err != nil { - return fmt.Errorf("error exporting state: %v", err) + return fmt.Errorf("error exporting state: %w", err) } doc, err := octypes.GenesisDocFromFile(serverCtx.Config.GenesisFile()) diff --git a/server/export_test.go b/server/export_test.go index db08cc37c3..f4a08b10ab 100644 --- a/server/export_test.go +++ b/server/export_test.go @@ -10,15 +10,14 @@ import ( "path" "testing" - "github.com/spf13/cobra" - "github.com/stretchr/testify/require" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" ostjson "github.com/Finschia/ostracon/libs/json" "github.com/Finschia/ostracon/libs/log" octypes "github.com/Finschia/ostracon/types" + "github.com/spf13/cobra" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/client" @@ -123,6 +122,7 @@ func TestExportCmd_Height(t *testing.T) { } func setupApp(t *testing.T, tempDir string) (*simapp.SimApp, context.Context, *octypes.GenesisDoc, *cobra.Command) { + t.Helper() if err := createConfigFolder(tempDir); err != nil { t.Fatalf("error creating config folder: %s", err) } diff --git a/server/grpc/gogoreflection/serverreflection.go b/server/grpc/gogoreflection/serverreflection.go index 7576ba5f63..1937870ca0 100644 --- a/server/grpc/gogoreflection/serverreflection.go +++ b/server/grpc/gogoreflection/serverreflection.go @@ -39,6 +39,7 @@ package gogoreflection // import "google.golang.org/grpc/reflection" import ( "bytes" "compress/gzip" + "errors" "fmt" "io" "log" @@ -46,7 +47,6 @@ import ( "sort" "sync" - //nolint: staticcheck "github.com/golang/protobuf/proto" dpb "github.com/golang/protobuf/protoc-gen-go/descriptor" "google.golang.org/grpc" @@ -202,12 +202,12 @@ func (s *serverReflectionServer) fileDescForType(st reflect.Type) (*dpb.FileDesc func decodeFileDesc(enc []byte) (*dpb.FileDescriptorProto, error) { raw, err := decompress(enc) if err != nil { - return nil, fmt.Errorf("failed to decompress enc: %v", err) + return nil, fmt.Errorf("failed to decompress enc: %w", err) } fd := new(dpb.FileDescriptorProto) if err := proto.Unmarshal(raw, fd); err != nil { - return nil, fmt.Errorf("bad descriptor: %v", err) + return nil, fmt.Errorf("bad descriptor: %w", err) } return fd, nil } @@ -216,11 +216,11 @@ func decodeFileDesc(enc []byte) (*dpb.FileDescriptorProto, error) { func decompress(b []byte) ([]byte, error) { r, err := gzip.NewReader(bytes.NewReader(b)) if err != nil { - return nil, fmt.Errorf("bad gzipped descriptor: %v", err) + return nil, fmt.Errorf("bad gzipped descriptor: %w", err) } out, err := io.ReadAll(r) if err != nil { - return nil, fmt.Errorf("bad gzipped descriptor: %v", err) + return nil, fmt.Errorf("bad gzipped descriptor: %w", err) } return out, nil } @@ -290,8 +290,8 @@ func fileDescWithDependencies(fd *dpb.FileDescriptorProto, sentFileDescriptors m } // fileDescEncodingByFilename finds the file descriptor for given filename, -// finds all of its previously unsent transitive dependencies, does marshalling -// on them, and returns the marshalled result. +// finds all of its previously unsent transitive dependencies, does marshaling +// on them, and returns the marshaled result. func (s *serverReflectionServer) fileDescEncodingByFilename(name string, sentFileDescriptors map[string]bool) ([][]byte, error) { enc := getFileDescriptor(name) if enc == nil { @@ -324,7 +324,7 @@ func parseMetadata(meta interface{}) ([]byte, bool) { // fileDescEncodingContainingSymbol finds the file descriptor containing the // given symbol, finds all of its previously unsent transitive dependencies, -// does marshalling on them, and returns the marshalled result. The given symbol +// does marshaling on them, and returns the marshaled result. The given symbol // can be a type, a service or a method. func (s *serverReflectionServer) fileDescEncodingContainingSymbol(name string, sentFileDescriptors map[string]bool) ([][]byte, error) { _, symbols := s.getSymbols() @@ -349,7 +349,7 @@ func (s *serverReflectionServer) fileDescEncodingContainingSymbol(name string, s // fileDescEncodingContainingExtension finds the file descriptor containing // given extension, finds all of its previously unsent transitive dependencies, -// does marshalling on them, and returns the marshalled result. +// does marshaling on them, and returns the marshaled result. func (s *serverReflectionServer) fileDescEncodingContainingExtension(typeName string, extNum int32, sentFileDescriptors map[string]bool) ([][]byte, error) { st, err := typeForName(typeName) if err != nil { @@ -380,7 +380,7 @@ func (s *serverReflectionServer) ServerReflectionInfo(stream rpb.ServerReflectio sentFileDescriptors := make(map[string]bool) for { in, err := stream.Recv() - if err == io.EOF { + if errors.Is(err, io.EOF) { return nil } if err != nil { diff --git a/server/mock/app_test.go b/server/mock/app_test.go index fc5e27dfdd..372cddf79d 100644 --- a/server/mock/app_test.go +++ b/server/mock/app_test.go @@ -3,12 +3,11 @@ package mock import ( "testing" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/ostracon/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/ostracon/types" ) // TestInitApp makes sure we can initialize this thing without an error diff --git a/server/mock/store_test.go b/server/mock/store_test.go index 3eac8deb9c..8266f2dcc5 100644 --- a/server/mock/store_test.go +++ b/server/mock/store_test.go @@ -4,7 +4,6 @@ import ( "testing" "github.com/stretchr/testify/require" - dbm "github.com/tendermint/tm-db" sdk "github.com/Finschia/finschia-sdk/types" @@ -36,7 +35,7 @@ func TestStore(t *testing.T) { func TestMultiStore(t *testing.T) { store := multiStore{} - require.Panics(t, func() { store.Snapshot(1, nil) }, "Snapshot should panic") - require.Panics(t, func() { store.Restore(1, 1, nil) }, "Restore should panic") + require.Panics(t, func() { store.Snapshot(1, nil) }, "Snapshot should panic") //nolint:errcheck + require.Panics(t, func() { store.Restore(1, 1, nil) }, "Restore should panic") //nolint:errcheck require.Panics(t, func() { store.SetIAVLDisableFastNode(false) }, "SetIAVLDisableFastNode should panic") } diff --git a/server/mock/tx.go b/server/mock/tx.go index 6e9d595fb4..271dd942a3 100644 --- a/server/mock/tx.go +++ b/server/mock/tx.go @@ -1,4 +1,3 @@ -// nolint package mock import ( diff --git a/server/oc_cmds.go b/server/oc_cmds.go index 8c7bd591bf..f7c40c327f 100644 --- a/server/oc_cmds.go +++ b/server/oc_cmds.go @@ -5,9 +5,6 @@ package server import ( "fmt" - "github.com/spf13/cobra" - yaml "gopkg.in/yaml.v2" - cfg "github.com/Finschia/ostracon/config" osjson "github.com/Finschia/ostracon/libs/json" ostos "github.com/Finschia/ostracon/libs/os" @@ -16,6 +13,8 @@ import ( pvm "github.com/Finschia/ostracon/privval" "github.com/Finschia/ostracon/types" ostversion "github.com/Finschia/ostracon/version" + "github.com/spf13/cobra" + yaml "gopkg.in/yaml.v2" sdk "github.com/Finschia/finschia-sdk/types" ) @@ -95,7 +94,7 @@ func loadChainID(config *cfg.Config) (string, error) { return "", err } defer func() { - var _ = stateDB.Close() + _ = stateDB.Close() }() genesisDocProvider := node.DefaultGenesisDocProviderFunc(config) _, genDoc, err := node.LoadStateFromDBOrGenesisDocProvider(stateDB, genesisDocProvider) diff --git a/server/oc_cmds_test.go b/server/oc_cmds_test.go index 5d05eb7ab2..871972ccac 100644 --- a/server/oc_cmds_test.go +++ b/server/oc_cmds_test.go @@ -3,13 +3,11 @@ package server import ( "bytes" "context" + "errors" "fmt" - "io/ioutil" "os" "testing" - "github.com/stretchr/testify/require" - cfg "github.com/Finschia/ostracon/config" "github.com/Finschia/ostracon/crypto" tmjson "github.com/Finschia/ostracon/libs/json" @@ -20,11 +18,10 @@ import ( "github.com/Finschia/ostracon/privval" "github.com/Finschia/ostracon/types" tmtime "github.com/Finschia/ostracon/types/time" + "github.com/stretchr/testify/require" ) -var ( - logger = log.NewOCLogger(log.NewSyncWriter(os.Stdout)) -) +var logger = log.NewOCLogger(log.NewSyncWriter(os.Stdout)) func TestShowValidator(t *testing.T) { testCommon := newPrecedenceCommon(t) @@ -32,13 +29,17 @@ func TestShowValidator(t *testing.T) { serverCtx := &Context{} ctx := context.WithValue(context.Background(), ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != cancelledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCancelledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } // ostracon init & create the server config file - initFilesWithConfig(serverCtx.Config) - output := captureStdout(t, func() { ShowValidatorCmd().ExecuteContext(ctx) }) + err := initFilesWithConfig(serverCtx.Config) + require.NoError(t, err) + output := captureStdout(t, func() { + err := ShowValidatorCmd().ExecuteContext(ctx) + require.NoError(t, err) + }) // output must match the locally stored priv_validator key privKey := loadFilePVKey(t, serverCtx.Config.PrivValidatorKeyFile()) @@ -53,13 +54,14 @@ func TestShowValidatorWithKMS(t *testing.T) { serverCtx := &Context{} ctx := context.WithValue(context.Background(), ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != cancelledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCancelledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } // ostracon init & create the server config file serverCtx.Config.PrivValidatorRemoteAddresses = append(serverCtx.Config.PrivValidatorRemoteAddresses, "127.0.0.1") - initFilesWithConfig(serverCtx.Config) + err := initFilesWithConfig(serverCtx.Config) + require.NoError(t, err) chainID, err := loadChainID(serverCtx.Config) require.NoError(t, err) @@ -73,7 +75,10 @@ func TestShowValidatorWithKMS(t *testing.T) { privval.WithMockKMS(t, t.TempDir(), chainID, func(addr string, privKey crypto.PrivKey) { serverCtx.Config.PrivValidatorListenAddr = addr require.NoFileExists(t, serverCtx.Config.PrivValidatorKeyFile()) - output := captureStdout(t, func() { ShowValidatorCmd().ExecuteContext(ctx) }) + output := captureStdout(t, func() { + err := ShowValidatorCmd().ExecuteContext(ctx) + require.NoError(t, err) + }) require.NoError(t, err) // output must contains the KMS public key @@ -90,12 +95,13 @@ func TestShowValidatorWithInefficientKMSAddress(t *testing.T) { serverCtx := &Context{} ctx := context.WithValue(context.Background(), ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != cancelledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCancelledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } // ostracon init & create the server config file - initFilesWithConfig(serverCtx.Config) + err := initFilesWithConfig(serverCtx.Config) + require.NoError(t, err) // remove config file if tmos.FileExists(serverCtx.Config.PrivValidatorKeyFile()) { @@ -104,7 +110,7 @@ func TestShowValidatorWithInefficientKMSAddress(t *testing.T) { } serverCtx.Config.PrivValidatorListenAddr = "127.0.0.1:inefficient" - err := ShowValidatorCmd().ExecuteContext(ctx) + err = ShowValidatorCmd().ExecuteContext(ctx) require.Error(t, err) } @@ -112,7 +118,7 @@ func TestLoadChainID(t *testing.T) { expected := "c57861" config := cfg.ResetTestRootWithChainID("TestLoadChainID", expected) defer func() { - var _ = os.RemoveAll(config.RootDir) + _ = os.RemoveAll(config.RootDir) }() require.FileExists(t, config.GenesisFile()) @@ -129,7 +135,7 @@ func TestLoadChainIDWithoutStateDB(t *testing.T) { expected := "c34091" config := cfg.ResetTestRootWithChainID("TestLoadChainID", expected) defer func() { - var _ = os.RemoveAll(config.RootDir) + _ = os.RemoveAll(config.RootDir) }() config.DBBackend = "goleveldb" @@ -197,8 +203,9 @@ func initFilesWithConfig(config *cfg.Config) error { } func loadFilePVKey(t *testing.T, file string) privval.FilePVKey { + t.Helper() // output must match the locally stored priv_validator key - keyJSONBytes, err := ioutil.ReadFile(file) + keyJSONBytes, err := os.ReadFile(file) require.NoError(t, err) privKey := privval.FilePVKey{} err = tmjson.Unmarshal(keyJSONBytes, &privKey) diff --git a/server/pruning_test.go b/server/pruning_test.go index 9c462379ad..adf098face 100644 --- a/server/pruning_test.go +++ b/server/pruning_test.go @@ -54,8 +54,6 @@ func TestGetPruningOptionsFromFlags(t *testing.T) { } for _, tt := range tests { - tt := tt - t.Run(tt.name, func(j *testing.T) { viper.Reset() viper.SetDefault(FlagPruning, types.PruningOptionDefault) diff --git a/server/rollback.go b/server/rollback.go index 0d144d21a0..b673c5ad29 100644 --- a/server/rollback.go +++ b/server/rollback.go @@ -3,9 +3,8 @@ package server import ( "fmt" - "github.com/spf13/cobra" - ostcmd "github.com/Finschia/ostracon/cmd/ostracon/commands" + "github.com/spf13/cobra" "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/server/types" diff --git a/server/start.go b/server/start.go index ce0530949e..6457756413 100644 --- a/server/start.go +++ b/server/start.go @@ -11,12 +11,6 @@ import ( "runtime/pprof" "strings" - "github.com/hashicorp/go-metrics" - "github.com/spf13/cobra" - "golang.org/x/sync/errgroup" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" - "github.com/Finschia/ostracon/abci/server" ostcmd "github.com/Finschia/ostracon/cmd/ostracon/commands" tmcfg "github.com/Finschia/ostracon/config" @@ -28,6 +22,11 @@ import ( rpchttp "github.com/Finschia/ostracon/rpc/client/http" "github.com/Finschia/ostracon/rpc/client/local" tmtypes "github.com/Finschia/ostracon/types" + "github.com/hashicorp/go-metrics" + "github.com/spf13/cobra" + "golang.org/x/sync/errgroup" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" @@ -214,7 +213,7 @@ is performed. Note, when enabled, gRPC will also be automatically enabled. func startStandAlone(svrCtx *Context, svrCfg serverconfig.Config, clientCtx client.Context, app types.Application, tmetrics *telemetry.Metrics) error { svr, err := server.NewServer(svrCtx.Viper.GetString(flagAddress), svrCtx.Viper.GetString(flagTransport), app) if err != nil { - return fmt.Errorf("error creating listener: %v", err) + return fmt.Errorf("error creating listener: %w", err) } svr.SetLogger(svrCtx.Logger.With("module", "abci-server")) diff --git a/server/start_test.go b/server/start_test.go index 2cd2fe012b..234e47362d 100644 --- a/server/start_test.go +++ b/server/start_test.go @@ -1,10 +1,11 @@ package server import ( - "github.com/Finschia/ostracon/config" - "github.com/stretchr/testify/assert" "os" "testing" + + "github.com/Finschia/ostracon/config" + "github.com/stretchr/testify/assert" ) func TestGenPvFileOnlyWhenKmsAddressEmptyGenerateFiles(t *testing.T) { diff --git a/server/types/app.go b/server/types/app.go index 21a1a8d589..5b93ec7dd7 100644 --- a/server/types/app.go +++ b/server/types/app.go @@ -4,14 +4,13 @@ import ( "encoding/json" "io" - "github.com/gogo/protobuf/grpc" - "github.com/spf13/cobra" - dbm "github.com/tendermint/tm-db" - ocabci "github.com/Finschia/ostracon/abci/types" "github.com/Finschia/ostracon/libs/log" octypes "github.com/Finschia/ostracon/types" + "github.com/gogo/protobuf/grpc" + "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" + dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/server/api" diff --git a/server/util.go b/server/util.go index 74c163335e..9e3f718596 100644 --- a/server/util.go +++ b/server/util.go @@ -67,7 +67,9 @@ func NewContext(v *viper.Viper, config *tmcfg.Config, logger tmlog.Logger) *Cont func bindFlags(basename string, cmd *cobra.Command, v *viper.Viper) (err error) { defer func() { - recover() + if r := recover(); r != nil { + err = fmt.Errorf("bindFlags failed: %v", r) + } }() cmd.Flags().VisitAll(func(f *pflag.Flag) { @@ -93,7 +95,7 @@ func bindFlags(basename string, cmd *cobra.Command, v *viper.Viper) (err error) } }) - return + return err } // InterceptConfigsPreRunHandler performs a pre-run function for the root daemon @@ -210,7 +212,7 @@ func interceptConfigs(rootViper *viper.Viper, customAppTemplate string, customCo tmcfg.EnsureRoot(rootDir) if err = conf.ValidateBasic(); err != nil { - return nil, fmt.Errorf("error in config file: %v", err) + return nil, fmt.Errorf("error in config file: %w", err) } conf.RPC.PprofListenAddress = "localhost:6060" diff --git a/server/util_test.go b/server/util_test.go index 7899c7947f..a94e66e963 100644 --- a/server/util_test.go +++ b/server/util_test.go @@ -15,7 +15,7 @@ import ( "github.com/Finschia/finschia-sdk/client/flags" ) -var cancelledInPreRun = errors.New("Cancelled in prerun") +var errCancelledInPreRun = errors.New("canceled in prerun") // Used in each test to run the function under test via Cobra // but to always halt the command @@ -25,7 +25,7 @@ func preRunETestImpl(cmd *cobra.Command, args []string) error { return err } - return cancelledInPreRun + return errCancelledInPreRun } func TestInterceptConfigsPreRunHandlerCreatesConfigFilesWhenMissing(t *testing.T) { @@ -39,7 +39,7 @@ func TestInterceptConfigsPreRunHandlerCreatesConfigFilesWhenMissing(t *testing.T serverCtx := &Context{} ctx := context.WithValue(context.Background(), ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != cancelledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCancelledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -116,7 +116,7 @@ func TestInterceptConfigsPreRunHandlerReadsConfigToml(t *testing.T) { serverCtx := &Context{} ctx := context.WithValue(context.Background(), ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != cancelledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCancelledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -153,7 +153,7 @@ func TestInterceptConfigsPreRunHandlerReadsAppToml(t *testing.T) { serverCtx := &Context{} ctx := context.WithValue(context.Background(), ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != cancelledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCancelledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -181,7 +181,7 @@ func TestInterceptConfigsPreRunHandlerReadsFlags(t *testing.T) { serverCtx := &Context{} ctx := context.WithValue(context.Background(), ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != cancelledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCancelledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -206,17 +206,13 @@ func TestInterceptConfigsPreRunHandlerReadsEnvVars(t *testing.T) { basename = strings.ReplaceAll(basename, ".", "_") // This is added by ostracon envVarName := fmt.Sprintf("%s_RPC_LADDR", strings.ToUpper(basename)) - os.Setenv(envVarName, testAddr) - t.Cleanup(func() { - os.Unsetenv(envVarName) - }) - + t.Setenv(envVarName, testAddr) cmd.PreRunE = preRunETestImpl serverCtx := &Context{} ctx := context.WithValue(context.Background(), ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != cancelledInPreRun { + if err := cmd.ExecuteContext(ctx); !errors.Is(err, errCancelledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -245,6 +241,7 @@ type precedenceCommon struct { } func newPrecedenceCommon(t *testing.T) precedenceCommon { + t.Helper() retval := precedenceCommon{} // Determine the env. var. name based off the executable name @@ -285,7 +282,8 @@ func newPrecedenceCommon(t *testing.T) precedenceCommon { return retval } -func (v precedenceCommon) setAll(t *testing.T, setFlag *string, setEnvVar *string, setConfigFile *string) { +func (v precedenceCommon) setAll(t *testing.T, setFlag, setEnvVar, setConfigFile *string) { + t.Helper() if setFlag != nil { if err := v.cmd.Flags().Set(v.flagName, *setFlag); err != nil { t.Fatalf("Failed setting flag %q", v.flagName) @@ -320,7 +318,7 @@ func TestInterceptConfigsPreRunHandlerPrecedenceFlag(t *testing.T) { serverCtx := &Context{} ctx := context.WithValue(context.Background(), ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != cancelledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCancelledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -336,7 +334,7 @@ func TestInterceptConfigsPreRunHandlerPrecedenceEnvVar(t *testing.T) { serverCtx := &Context{} ctx := context.WithValue(context.Background(), ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != cancelledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCancelledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -352,7 +350,7 @@ func TestInterceptConfigsPreRunHandlerPrecedenceConfigFile(t *testing.T) { serverCtx := &Context{} ctx := context.WithValue(context.Background(), ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != cancelledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCancelledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } @@ -368,11 +366,11 @@ func TestInterceptConfigsPreRunHandlerPrecedenceConfigDefault(t *testing.T) { serverCtx := &Context{} ctx := context.WithValue(context.Background(), ServerContextKey, serverCtx) - if err := testCommon.cmd.ExecuteContext(ctx); err != cancelledInPreRun { + if err := testCommon.cmd.ExecuteContext(ctx); !errors.Is(err, errCancelledInPreRun) { t.Fatalf("function failed with [%T] %v", err, err) } - if "tcp://127.0.0.1:26657" != serverCtx.Config.RPC.ListenAddress { + if serverCtx.Config.RPC.ListenAddress != "tcp://127.0.0.1:26657" { t.Error("RPCListenAddress is not using default") } } diff --git a/simapp/app.go b/simapp/app.go index 1d74d4d9b1..6e52ec9c1a 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -7,6 +7,9 @@ import ( "os" "path/filepath" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/ostracon/libs/log" + ostos "github.com/Finschia/ostracon/libs/os" "github.com/gorilla/mux" "github.com/rakyll/statik/fs" "github.com/spf13/cast" @@ -14,12 +17,10 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/ostracon/libs/log" - ostos "github.com/Finschia/ostracon/libs/os" - "github.com/Finschia/finschia-sdk/baseapp" "github.com/Finschia/finschia-sdk/client" + // unnamed import of statik for swagger UI support + _ "github.com/Finschia/finschia-sdk/client/docs/statik" nodeservice "github.com/Finschia/finschia-sdk/client/grpc/node" "github.com/Finschia/finschia-sdk/client/grpc/ocservice" "github.com/Finschia/finschia-sdk/client/grpc/tmservice" @@ -109,9 +110,6 @@ import ( upgradeclient "github.com/Finschia/finschia-sdk/x/upgrade/client" upgradekeeper "github.com/Finschia/finschia-sdk/x/upgrade/keeper" upgradetypes "github.com/Finschia/finschia-sdk/x/upgrade/types" - - // unnamed import of statik for swagger UI support - _ "github.com/Finschia/finschia-sdk/client/docs/statik" ) const appName = "SimApp" diff --git a/simapp/app_test.go b/simapp/app_test.go index ff096d9439..05c728db37 100644 --- a/simapp/app_test.go +++ b/simapp/app_test.go @@ -5,15 +5,13 @@ import ( "os" "testing" + "github.com/Finschia/ostracon/libs/log" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/baseapp" "github.com/Finschia/finschia-sdk/tests/mocks" sdk "github.com/Finschia/finschia-sdk/types" diff --git a/simapp/export.go b/simapp/export.go index 606f9f866c..353f6393a7 100644 --- a/simapp/export.go +++ b/simapp/export.go @@ -47,7 +47,7 @@ func (app *SimApp) ExportAppStateAndValidators( // prepare for fresh start at zero height // NOTE zero height genesis is a temporary feature which will be deprecated // -// in favour of export at a block height +// in favor of export at a block height func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) { applyAllowedAddrs := false diff --git a/simapp/genesis_account_test.go b/simapp/genesis_account_test.go index 94c12000dd..570dd92fad 100644 --- a/simapp/genesis_account_test.go +++ b/simapp/genesis_account_test.go @@ -4,13 +4,13 @@ import ( "testing" "time" + "github.com/Finschia/ostracon/crypto" + "github.com/stretchr/testify/require" + "github.com/Finschia/finschia-sdk/crypto/keys/secp256k1" "github.com/Finschia/finschia-sdk/simapp" sdk "github.com/Finschia/finschia-sdk/types" authtypes "github.com/Finschia/finschia-sdk/x/auth/types" - - "github.com/Finschia/ostracon/crypto" - "github.com/stretchr/testify/require" ) func TestSimGenesisAccountValidate(t *testing.T) { @@ -80,7 +80,6 @@ func TestSimGenesisAccountValidate(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { require.Equal(t, tc.wantErr, tc.sga.Validate() != nil) }) diff --git a/simapp/sim_bench_test.go b/simapp/sim_bench_test.go index 7f8451637f..f4666c8876 100644 --- a/simapp/sim_bench_test.go +++ b/simapp/sim_bench_test.go @@ -117,7 +117,6 @@ func BenchmarkInvariants(b *testing.B) { // NOTE: We use the crisis keeper as it has all the invariants registered with // their respective metadata which makes it useful for testing/benchmarking. for _, cr := range app.CrisisKeeper.Routes() { - cr := cr b.Run(fmt.Sprintf("%s/%s", cr.ModuleName, cr.Route), func(b *testing.B) { if res, stop := cr.Invar(ctx); stop { b.Fatalf( diff --git a/simapp/sim_test.go b/simapp/sim_test.go index a809a7c590..033514077f 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -7,13 +7,12 @@ import ( "os" "testing" + "github.com/Finschia/ostracon/libs/log" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/baseapp" "github.com/Finschia/finschia-sdk/simapp/helpers" "github.com/Finschia/finschia-sdk/store" diff --git a/simapp/simd/cmd/genaccounts_test.go b/simapp/simd/cmd/genaccounts_test.go index 0501939e3f..283f11e8e7 100644 --- a/simapp/simd/cmd/genaccounts_test.go +++ b/simapp/simd/cmd/genaccounts_test.go @@ -5,11 +5,10 @@ import ( "fmt" "testing" + "github.com/Finschia/ostracon/libs/log" "github.com/spf13/viper" "github.com/stretchr/testify/require" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/crypto/hd" @@ -66,7 +65,6 @@ func TestAddGenesisAccountCmd(t *testing.T) { } for _, tc := range tests { - tc := tc t.Run(tc.name, func(t *testing.T) { home := t.TempDir() logger := log.NewNopLogger() diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 89133376a7..2f60d37ee2 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -6,12 +6,11 @@ import ( "os" "path/filepath" + ostcli "github.com/Finschia/ostracon/libs/cli" + "github.com/Finschia/ostracon/libs/log" "github.com/spf13/cast" "github.com/spf13/cobra" "github.com/spf13/viper" - - ostcli "github.com/Finschia/ostracon/libs/cli" - "github.com/Finschia/ostracon/libs/log" dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/baseapp" diff --git a/simapp/simd/cmd/root_test.go b/simapp/simd/cmd/root_test.go index 8ac22f33d3..2838935637 100644 --- a/simapp/simd/cmd/root_test.go +++ b/simapp/simd/cmd/root_test.go @@ -5,12 +5,11 @@ import ( "os" "testing" - "github.com/stretchr/testify/require" - dbm "github.com/tendermint/tm-db" - "github.com/Finschia/ostracon/libs/log" octypes "github.com/Finschia/ostracon/types" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" + dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/server" @@ -76,7 +75,6 @@ func TestAppExport(t *testing.T) { } for _, tc := range tests { - tc := tc t.Run(tc.name, func(t *testing.T) { exported, err := a.appExport(logger, db, nil, tc.height, false, []string{}, ctx.Viper) if tc.expectErr { @@ -87,5 +85,4 @@ func TestAppExport(t *testing.T) { require.NotNil(t, exported) }) } - } diff --git a/simapp/simd/cmd/testnet.go b/simapp/simd/cmd/testnet.go index e33bc993ca..4b1952684a 100644 --- a/simapp/simd/cmd/testnet.go +++ b/simapp/simd/cmd/testnet.go @@ -10,13 +10,12 @@ import ( "os" "path/filepath" - "github.com/spf13/cobra" - ostconfig "github.com/Finschia/ostracon/config" ostos "github.com/Finschia/ostracon/libs/os" ostrand "github.com/Finschia/ostracon/libs/rand" "github.com/Finschia/ostracon/types" osttime "github.com/Finschia/ostracon/types/time" + "github.com/spf13/cobra" "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" @@ -384,16 +383,16 @@ func calculateIP(ip string, i int) (string, error) { return ipv4.String(), nil } -func writeFile(name string, dir string, contents []byte) error { +func writeFile(name, dir string, contents []byte) error { writePath := filepath.Join(dir) //nolint:gocritic file := filepath.Join(writePath, name) - err := ostos.EnsureDir(writePath, 0755) + err := ostos.EnsureDir(writePath, 0o755) if err != nil { return err } - err = ostos.WriteFile(file, contents, 0644) + err = ostos.WriteFile(file, contents, 0o644) if err != nil { return err } diff --git a/simapp/simd/cmd/testnet_test.go b/simapp/simd/cmd/testnet_test.go index ced64412ab..c889e328ef 100644 --- a/simapp/simd/cmd/testnet_test.go +++ b/simapp/simd/cmd/testnet_test.go @@ -5,11 +5,10 @@ import ( "fmt" "testing" + "github.com/Finschia/ostracon/libs/log" "github.com/spf13/viper" "github.com/stretchr/testify/require" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/server" diff --git a/simapp/simd/main.go b/simapp/simd/main.go index 6220cc701f..2dfddc3292 100644 --- a/simapp/simd/main.go +++ b/simapp/simd/main.go @@ -1,6 +1,7 @@ package main import ( + "errors" "os" "github.com/Finschia/finschia-sdk/server" @@ -13,10 +14,10 @@ func main() { rootCmd, _ := cmd.NewRootCmd() if err := svrcmd.Execute(rootCmd, simapp.DefaultNodeHome); err != nil { - switch e := err.(type) { - case server.ErrorCode: + var e server.ErrorCode + switch { + case errors.As(err, &e): os.Exit(e.Code) - default: os.Exit(1) } diff --git a/simapp/test_access.go b/simapp/test_access.go index 5ad87a817e..a073759b21 100644 --- a/simapp/test_access.go +++ b/simapp/test_access.go @@ -5,10 +5,8 @@ import ( "github.com/Finschia/finschia-sdk/baseapp" "github.com/Finschia/finschia-sdk/client" - - "github.com/Finschia/finschia-sdk/simapp/params" - "github.com/Finschia/finschia-sdk/codec" + "github.com/Finschia/finschia-sdk/simapp/params" bankkeeper "github.com/Finschia/finschia-sdk/x/bank/keeper" stakingkeeper "github.com/Finschia/finschia-sdk/x/staking/keeper" ) @@ -18,8 +16,9 @@ type TestSupport struct { app *SimApp } -func NewTestSupport(t testing.TB, app *SimApp) *TestSupport { - return &TestSupport{t: t, app: app} +func NewTestSupport(tb testing.TB, app *SimApp) *TestSupport { + tb.Helper() + return &TestSupport{t: tb, app: app} } func (s TestSupport) AppCodec() codec.Codec { diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 947322b64a..7666491def 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -13,15 +13,14 @@ import ( "testing" "time" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/ostracon/libs/log" + octypes "github.com/Finschia/ostracon/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/ostracon/libs/log" - octypes "github.com/Finschia/ostracon/types" - bam "github.com/Finschia/finschia-sdk/baseapp" "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/crypto/keys/ed25519" @@ -98,7 +97,7 @@ func Setup(isCheckTx bool) *SimApp { // that also act as delegators. For simplicity, each validator is bonded with a delegation // of one consensus engine unit (10^6) in the default token of the simapp from first genesis // account. A Nop logger is set in SimApp. -//func SetupWithGenesisValSet(t *testing.T, valSet *octypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *SimApp { +// func SetupWithGenesisValSet(t *testing.T, valSet *octypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *SimApp { // app, genesisState := setup(true, 5) // // set genesis accounts // authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) @@ -347,7 +346,7 @@ func ConvertAddrsToValAddrs(addrs []sdk.AccAddress) []sdk.ValAddress { return valAddrs } -func TestAddr(addr string, bech string) (sdk.AccAddress, error) { +func TestAddr(addr, bech string) (sdk.AccAddress, error) { res, err := sdk.AccAddressFromHex(addr) if err != nil { return nil, err @@ -370,6 +369,7 @@ func TestAddr(addr string, bech string) (sdk.AccAddress, error) { // CheckBalance checks the balance of an account. func CheckBalance(t *testing.T, app *SimApp, addr sdk.AccAddress, balances sdk.Coins) { + t.Helper() ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{}) require.True(t, balances.Equal(app.BankKeeper.GetAllBalances(ctxCheck, addr))) } @@ -382,6 +382,7 @@ 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) { + t.Helper() tx, err := helpers.GenSignedMockTx( rand.New(rand.NewSource(time.Now().UnixNano())), txCfg, @@ -435,6 +436,7 @@ func SignAndDeliver( 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) { + t.Helper() tx, err := helpers.GenTx( txCfg, msgs, @@ -468,7 +470,7 @@ func SignAndDeliver( // GenSequenceOfTxs generates a set of signed transactions of messages, such // that they differ only by having the sequence numbers incremented between // every transaction. -func GenSequenceOfTxs(txGen client.TxConfig, msgs []sdk.Msg, accNums []uint64, initSeqNums []uint64, numToGenerate int, priv ...cryptotypes.PrivKey) ([]sdk.Tx, error) { +func GenSequenceOfTxs(txGen client.TxConfig, msgs []sdk.Msg, accNums, initSeqNums []uint64, numToGenerate int, priv ...cryptotypes.PrivKey) ([]sdk.Tx, error) { txs := make([]sdk.Tx, numToGenerate) var err error for i := 0; i < numToGenerate; i++ { diff --git a/simapp/utils_test.go b/simapp/utils_test.go index c63716dfa1..f1e3f32cfa 100644 --- a/simapp/utils_test.go +++ b/simapp/utils_test.go @@ -69,7 +69,6 @@ func TestGetSimulationLog(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.store, func(t *testing.T) { require.Equal(t, tt.expectedLog, GetSimulationLog(tt.store, decoders, tt.kvPairs, tt.kvPairs), tt.store) }) diff --git a/snapshots/chunk.go b/snapshots/chunk.go index 7e1239ec8c..f9b1692b0f 100644 --- a/snapshots/chunk.go +++ b/snapshots/chunk.go @@ -1,6 +1,7 @@ package snapshots import ( + "errors" "io" sdkerrors "github.com/Finschia/finschia-sdk/types/errors" @@ -144,7 +145,7 @@ func (r *ChunkReader) Read(p []byte) (int, error) { } } n, err := r.reader.Read(p) - if err == io.EOF { + if errors.Is(err, io.EOF) { err = r.reader.Close() r.reader = nil if err != nil { diff --git a/snapshots/helpers_test.go b/snapshots/helpers_test.go index 21965edd80..84983f73b6 100644 --- a/snapshots/helpers_test.go +++ b/snapshots/helpers_test.go @@ -13,7 +13,6 @@ import ( protoio "github.com/gogo/protobuf/io" "github.com/stretchr/testify/require" - dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/snapshots" @@ -62,7 +61,8 @@ func readChunks(chunks <-chan io.ReadCloser) [][]byte { } // snapshotItems serialize a array of bytes as SnapshotItem_ExtensionPayload, and return the chunks. -func snapshotItems(items [][]byte) [][]byte { +func snapshotItems(t *testing.T, items [][]byte) [][]byte { + t.Helper() // copy the same parameters from the code snapshotChunkSize := uint64(10e6) snapshotBufferSize := int(snapshotChunkSize) @@ -74,12 +74,17 @@ func snapshotItems(items [][]byte) [][]byte { zWriter, _ := zlib.NewWriterLevel(bufWriter, 7) protoWriter := protoio.NewDelimitedWriter(zWriter) for _, item := range items { - snapshottypes.WriteExtensionItem(protoWriter, item) + err := snapshottypes.WriteExtensionItem(protoWriter, item) + require.NoError(t, err) } - protoWriter.Close() - zWriter.Close() - bufWriter.Flush() - chunkWriter.Close() + err := protoWriter.Close() + require.NoError(t, err) + err = zWriter.Close() + require.NoError(t, err) + err = bufWriter.Flush() + require.NoError(t, err) + err = chunkWriter.Close() + require.NoError(t, err) }() var chunks [][]byte @@ -111,7 +116,7 @@ func (m *mockSnapshotter) Restore( for { item := &snapshottypes.SnapshotItem{} err := protoReader.ReadMsg(item) - if err == io.EOF { + if errors.Is(err, io.EOF) { break } else if err != nil { return snapshottypes.SnapshotItem{}, sdkerrors.Wrap(err, "invalid protobuf message") @@ -146,6 +151,7 @@ func (m *mockSnapshotter) SupportedFormats() []uint32 { // setupBusyManager creates a manager with an empty store that is busy creating a snapshot at height 1. // The snapshot will complete when the returned closer is called. func setupBusyManager(t *testing.T) *snapshots.Manager { + t.Helper() // os.MkdirTemp() is used instead of testing.T.TempDir() // see https://github.com/cosmos/cosmos-sdk/pull/8475 for // this change's rationale. diff --git a/snapshots/manager.go b/snapshots/manager.go index 9798f12d84..ffc2e2e90d 100644 --- a/snapshots/manager.go +++ b/snapshots/manager.go @@ -209,7 +209,7 @@ func (m *Manager) List() ([]*types.Snapshot, error) { // LoadChunk loads a chunk into a byte slice, mirroring ABCI LoadChunk. It can be called // concurrently with other operations. If the chunk does not exist, nil is returned. -func (m *Manager) LoadChunk(height uint64, format uint32, chunk uint32) ([]byte, error) { +func (m *Manager) LoadChunk(height uint64, format, chunk uint32) ([]byte, error) { reader, err := m.store.LoadChunk(height, format, chunk) if err != nil { return nil, err diff --git a/snapshots/manager_test.go b/snapshots/manager_test.go index 8fd1be5e81..de88e1c2fb 100644 --- a/snapshots/manager_test.go +++ b/snapshots/manager_test.go @@ -61,7 +61,7 @@ func TestManager_Take(t *testing.T) { snapshotter := &mockSnapshotter{ items: items, } - expectChunks := snapshotItems(items) + expectChunks := snapshotItems(t, items) manager := snapshots.NewManager(store, snapshotter) // nil manager should return error @@ -125,7 +125,7 @@ func TestManager_Restore(t *testing.T) { {7, 8, 9}, } - chunks := snapshotItems(expectItems) + chunks := snapshotItems(t, expectItems) // Restore errors on invalid format err := manager.Restore(types.Snapshot{ diff --git a/snapshots/store.go b/snapshots/store.go index 26c5654e7b..f41c8280d0 100644 --- a/snapshots/store.go +++ b/snapshots/store.go @@ -164,7 +164,7 @@ func (s *Store) Load(height uint64, format uint32) (*types.Snapshot, <-chan io.R // LoadChunk loads a chunk from disk, or returns nil if it does not exist. The caller must call // Close() on it when done. -func (s *Store) LoadChunk(height uint64, format uint32, chunk uint32) (io.ReadCloser, error) { +func (s *Store) LoadChunk(height uint64, format, chunk uint32) (io.ReadCloser, error) { path := s.pathChunk(height, format, chunk) file, err := os.Open(path) if os.IsNotExist(err) { @@ -174,7 +174,7 @@ func (s *Store) LoadChunk(height uint64, format uint32, chunk uint32) (io.ReadCl } // loadChunkFile loads a chunk from disk, and errors if it does not exist. -func (s *Store) loadChunkFile(height uint64, format uint32, chunk uint32) (io.ReadCloser, error) { +func (s *Store) loadChunkFile(height uint64, format, chunk uint32) (io.ReadCloser, error) { path := s.pathChunk(height, format, chunk) return os.Open(path) } @@ -259,7 +259,7 @@ func (s *Store) Save( snapshotHasher := sha256.New() chunkHasher := sha256.New() for chunkBody := range chunks { - defer chunkBody.Close() //nolint: staticcheck + defer chunkBody.Close() dir := s.pathSnapshot(height, format) err = os.MkdirAll(dir, 0o755) if err != nil { @@ -270,7 +270,7 @@ func (s *Store) Save( if err != nil { return nil, sdkerrors.Wrapf(err, "failed to create snapshot chunk file %q", path) } - defer file.Close() //nolint: staticcheck + defer file.Close() chunkHasher.Reset() _, err = io.Copy(io.MultiWriter(file, chunkHasher, snapshotHasher), chunkBody) @@ -314,7 +314,7 @@ func (s *Store) pathSnapshot(height uint64, format uint32) string { } // pathChunk generates a snapshot chunk path. -func (s *Store) pathChunk(height uint64, format uint32, chunk uint32) string { +func (s *Store) pathChunk(height uint64, format, chunk uint32) string { return filepath.Join(s.pathSnapshot(height, format), strconv.FormatUint(uint64(chunk), 10)) } diff --git a/snapshots/store_test.go b/snapshots/store_test.go index 26600e1f02..6bb8063209 100644 --- a/snapshots/store_test.go +++ b/snapshots/store_test.go @@ -11,7 +11,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/snapshots" @@ -20,6 +19,7 @@ import ( ) func setupStore(t *testing.T) *snapshots.Store { + t.Helper() // os.MkdirTemp() is used instead of testing.T.TempDir() // see https://github.com/cosmos/cosmos-sdk/pull/8475 for // this change's rationale. @@ -89,7 +89,10 @@ func TestStore_Delete(t *testing.T) { // Deleting a snapshot being saved should error ch := make(chan io.ReadCloser) - go store.Save(9, 1, ch) + go func() { + _, err := store.Save(9, 1, ch) + require.NoError(t, err) + }() time.Sleep(10 * time.Millisecond) err = store.Delete(9, 1) @@ -334,7 +337,10 @@ func TestStore_Save(t *testing.T) { // Saving a snapshot should error if a snapshot is already in progress for the same height, // regardless of format. However, a different height should succeed. ch = make(chan io.ReadCloser) - go store.Save(7, 1, ch) + go func() { + _, err := store.Save(7, 1, ch) + require.NoError(t, err) + }() time.Sleep(10 * time.Millisecond) _, err = store.Save(7, 2, makeChunks(nil)) require.Error(t, err) diff --git a/store/cache/cache.go b/store/cache/cache.go index c9ead2df0b..330da7bbb4 100644 --- a/store/cache/cache.go +++ b/store/cache/cache.go @@ -51,7 +51,8 @@ type ( ) func NewCommitKVStoreCache(store types.CommitKVStore, prefix []byte, cache *fastcache.Cache, - metrics *Metrics) *CommitKVStoreCache { + metrics *Metrics, +) *CommitKVStoreCache { return &CommitKVStoreCache{ CommitKVStore: store, prefix: prefix, diff --git a/store/cache/cache_test.go b/store/cache/cache_test.go index 550a145c83..6db144c082 100644 --- a/store/cache/cache_test.go +++ b/store/cache/cache_test.go @@ -4,9 +4,8 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/require" - "github.com/cosmos/iavl" + "github.com/stretchr/testify/require" dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/store/cache" diff --git a/store/cache/metrics.go b/store/cache/metrics.go index a857e35abd..2d931f418b 100644 --- a/store/cache/metrics.go +++ b/store/cache/metrics.go @@ -78,7 +78,5 @@ func PrometheusMetricsProvider(namespace string, labelsAndValues ...string) func // NopMetricsProvider returns NopMetrics for each store func NopMetricsProvider() func() *Metrics { - return func() *Metrics { - return NopMetrics() - } + return NopMetrics } diff --git a/store/cachekv/bench_helper_test.go b/store/cachekv/bench_helper_test.go index fe5be27fab..be7fec4b3a 100644 --- a/store/cachekv/bench_helper_test.go +++ b/store/cachekv/bench_helper_test.go @@ -34,7 +34,7 @@ func generateSequentialKeys(startKey []byte, numKeys int) [][]byte { } // Generate many random, unsorted keys -func generateRandomKeys(keySize int, numKeys int) [][]byte { +func generateRandomKeys(keySize, numKeys int) [][]byte { toReturn := make([][]byte, 0, numKeys) for i := 0; i < numKeys; i++ { newKey := randSlice(keySize) diff --git a/store/cachekv/search_test.go b/store/cachekv/search_test.go index 41321c076e..aedc066903 100644 --- a/store/cachekv/search_test.go +++ b/store/cachekv/search_test.go @@ -60,7 +60,6 @@ func TestFindStartIndex(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { body := tt.sortedL got := findStartIndex(body, tt.query) @@ -129,7 +128,6 @@ func TestFindEndIndex(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { body := tt.sortedL got := findEndIndex(body, tt.query) diff --git a/store/cachekv/store.go b/store/cachekv/store.go index 0b8203c670..aacc6cff1d 100644 --- a/store/cachekv/store.go +++ b/store/cachekv/store.go @@ -7,9 +7,8 @@ import ( "sync" "time" - dbm "github.com/tendermint/tm-db" - "github.com/Finschia/ostracon/libs/math" + dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/internal/conv" "github.com/Finschia/finschia-sdk/store/listenkv" @@ -74,7 +73,7 @@ func (store *Store) Get(key []byte) (value []byte) { } // Set implements types.KVStore. -func (store *Store) Set(key []byte, value []byte) { +func (store *Store) Set(key, value []byte) { store.mtx.Lock() defer store.mtx.Unlock() @@ -368,7 +367,10 @@ func (store *Store) clearUnsortedCacheSubset(unsorted []*kv.Pair, sortState sort // deleted element, tracked by store.deleted // setting arbitrary value // TODO: Don't ignore this error. - store.sortedCache.Set(item.Key, []byte{}) + err := store.sortedCache.Set(item.Key, []byte{}) + if err != nil { + panic(err) + } continue } err := store.sortedCache.Set(item.Key, item.Value) @@ -395,7 +397,7 @@ func (store *Store) deleteKeysFromUnsortedCache(unsorted []*kv.Pair) { // etc // Only entrypoint to mutate store.cache. -func (store *Store) setCacheValue(key, value []byte, deleted bool, dirty bool) { +func (store *Store) setCacheValue(key, value []byte, deleted, dirty bool) { types.AssertValidKey(key) keyStr := conv.UnsafeBytesToStr(key) diff --git a/store/cachekv/store_bench_test.go b/store/cachekv/store_bench_test.go index 52273138dd..dc4d4c86bf 100644 --- a/store/cachekv/store_bench_test.go +++ b/store/cachekv/store_bench_test.go @@ -15,6 +15,7 @@ const defaultValueSizeBz = 1 << 12 // This benchmark measures the time of iterator.Next() when the parent store is blank func benchmarkBlankParentIteratorNext(b *testing.B, keysize int) { + b.Helper() mem := dbadapter.Store{DB: dbm.NewMemDB()} kvstore := cachekv.NewStore(mem) // Use a singleton for value, to not waste time computing it @@ -43,6 +44,7 @@ func benchmarkBlankParentIteratorNext(b *testing.B, keysize int) { // Benchmark setting New keys to a store, where the new keys are in sequence. func benchmarkBlankParentAppend(b *testing.B, keysize int) { + b.Helper() mem := dbadapter.Store{DB: dbm.NewMemDB()} kvstore := cachekv.NewStore(mem) @@ -65,6 +67,7 @@ func benchmarkBlankParentAppend(b *testing.B, keysize int) { // Benchmark setting New keys to a store, where the new keys are random. // the speed of this function does not depend on the values in the parent store func benchmarkRandomSet(b *testing.B, keysize int) { + b.Helper() mem := dbadapter.Store{DB: dbm.NewMemDB()} kvstore := cachekv.NewStore(mem) @@ -93,6 +96,7 @@ func benchmarkRandomSet(b *testing.B, keysize int) { // We essentially are benchmarking the cacheKV iterator creation & iteration times // with the number of entries deleted in the parent. func benchmarkIteratorOnParentWithManyDeletes(b *testing.B, numDeletes int) { + b.Helper() mem := dbadapter.Store{DB: dbm.NewMemDB()} // Use a singleton for value, to not waste time computing it diff --git a/store/cachekv/store_test.go b/store/cachekv/store_test.go index 3925968a3d..3f08512653 100644 --- a/store/cachekv/store_test.go +++ b/store/cachekv/store_test.go @@ -4,9 +4,8 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/require" - ostrand "github.com/Finschia/ostracon/libs/rand" + "github.com/stretchr/testify/require" dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/store/cachekv" @@ -326,6 +325,7 @@ func randInt(n int) int { // useful for replaying a error case if we find one func doOp(t *testing.T, st types.CacheKVStore, truth dbm.DB, op int, args ...int) { + t.Helper() switch op { case opSet: k := args[0] @@ -351,6 +351,7 @@ func doOp(t *testing.T, st types.CacheKVStore, truth dbm.DB, op int, args ...int } func doRandomOp(t *testing.T, st types.CacheKVStore, truth dbm.DB, maxKey int) { + t.Helper() r := randInt(totalOps) switch r { case opSet: @@ -380,6 +381,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) { + t.Helper() itr := st.Iterator(nil, nil) i := 0 for ; itr.Valid(); itr.Next() { @@ -392,6 +394,7 @@ func assertIterateDomain(t *testing.T, st types.KVStore, expectedN int) { } func assertIterateDomainCheck(t *testing.T, st types.KVStore, mem dbm.DB, r []keyRange) { + t.Helper() // iterate over each and check they match the other itr := st.Iterator(nil, nil) itr2, err := mem.Iterator(nil, nil) // ground truth @@ -423,6 +426,7 @@ func assertIterateDomainCheck(t *testing.T, st types.KVStore, mem dbm.DB, r []ke } func assertIterateDomainCompare(t *testing.T, st types.KVStore, mem dbm.DB) { + t.Helper() // iterate over each and check they match the other itr := st.Iterator(nil, nil) itr2, err := mem.Iterator(nil, nil) // ground truth @@ -432,6 +436,7 @@ func assertIterateDomainCompare(t *testing.T, st types.KVStore, mem dbm.DB) { } func checkIterators(t *testing.T, itr, itr2 types.Iterator) { + t.Helper() for ; itr.Valid(); itr.Next() { require.True(t, itr2.Valid()) k, v := itr.Key(), itr.Value() @@ -447,6 +452,7 @@ func checkIterators(t *testing.T, itr, itr2 types.Iterator) { //-------------------------------------------------------- func setRange(t *testing.T, st types.KVStore, mem dbm.DB, start, end int) { + t.Helper() for i := start; i < end; i++ { st.Set(keyFmt(i), valFmt(i)) err := mem.Set(keyFmt(i), valFmt(i)) @@ -455,6 +461,7 @@ func setRange(t *testing.T, st types.KVStore, mem dbm.DB, start, end int) { } func deleteRange(t *testing.T, st types.KVStore, mem dbm.DB, start, end int) { + t.Helper() for i := start; i < end; i++ { st.Delete(keyFmt(i)) err := mem.Delete(keyFmt(i)) diff --git a/store/dbadapter/store_test.go b/store/dbadapter/store_test.go index 40bd9da92c..ff4e9e224c 100644 --- a/store/dbadapter/store_test.go +++ b/store/dbadapter/store_test.go @@ -5,11 +5,10 @@ import ( "errors" "testing" - "github.com/Finschia/finschia-sdk/store/cachekv" - "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" + "github.com/Finschia/finschia-sdk/store/cachekv" "github.com/Finschia/finschia-sdk/store/dbadapter" "github.com/Finschia/finschia-sdk/store/types" "github.com/Finschia/finschia-sdk/tests/mocks" diff --git a/store/gaskv/store.go b/store/gaskv/store.go index fd5dbf4a75..8157612e68 100644 --- a/store/gaskv/store.go +++ b/store/gaskv/store.go @@ -46,7 +46,7 @@ func (gs *Store) Get(key []byte) (value []byte) { } // Implements KVStore. -func (gs *Store) Set(key []byte, value []byte) { +func (gs *Store) Set(key, value []byte) { types.AssertValidKey(key) types.AssertValidValue(value) gs.gasMeter.ConsumeGas(gs.gasConfig.WriteCostFlat, types.GasWriteCostFlatDesc) @@ -130,7 +130,7 @@ func newGasIterator(gasMeter types.GasMeter, gasConfig types.GasConfig, parent t } // Implements Iterator. -func (gi *gasIterator) Domain() (start []byte, end []byte) { +func (gi *gasIterator) Domain() (start, end []byte) { return gi.parent.Domain() } diff --git a/store/gaskv/store_test.go b/store/gaskv/store_test.go index 0b36f0a055..4760430f68 100644 --- a/store/gaskv/store_test.go +++ b/store/gaskv/store_test.go @@ -5,7 +5,6 @@ import ( "testing" "github.com/stretchr/testify/require" - dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/store/dbadapter" diff --git a/store/iavl/store.go b/store/iavl/store.go index ba07406bb5..2e21a88eaa 100644 --- a/store/iavl/store.go +++ b/store/iavl/store.go @@ -6,14 +6,13 @@ import ( "io" "time" + "github.com/Finschia/ostracon/libs/log" ics23 "github.com/confio/ics23/go" "github.com/cosmos/iavl" abci "github.com/tendermint/tendermint/abci/types" tmcrypto "github.com/tendermint/tendermint/proto/tendermint/crypto" dbm "github.com/tendermint/tm-db" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/store/cachekv" "github.com/Finschia/finschia-sdk/store/listenkv" "github.com/Finschia/finschia-sdk/store/tracekv" @@ -200,7 +199,10 @@ func (st *Store) CacheWrapWithListeners(storeKey types.StoreKey, listeners []typ func (st *Store) Set(key, value []byte) { types.AssertValidKey(key) types.AssertValidValue(value) - st.tree.Set(key, value) + _, err := st.tree.Set(key, value) + if err != nil { + panic(err) + } } // Implements types.KVStore. @@ -226,7 +228,10 @@ func (st *Store) Has(key []byte) (exists bool) { // Implements types.KVStore. func (st *Store) Delete(key []byte) { defer telemetry.MeasureSince(time.Now(), "store", "iavl", "delete") - st.tree.Remove(key) + _, _, err := st.tree.Remove(key) + if err != nil { + panic(err) + } } // DeleteVersions deletes a series of versions from the MutableTree. An error diff --git a/store/iavl/store_test.go b/store/iavl/store_test.go index 133889fd4b..5d3448a9ba 100644 --- a/store/iavl/store_test.go +++ b/store/iavl/store_test.go @@ -5,12 +5,11 @@ import ( "fmt" "testing" + "github.com/Finschia/ostracon/libs/log" "github.com/cosmos/iavl" "github.com/stretchr/testify/require" - dbm "github.com/tendermint/tm-db" - - "github.com/Finschia/ostracon/libs/log" abci "github.com/tendermint/tendermint/abci/types" + dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/store/cachekv" "github.com/Finschia/finschia-sdk/store/types" @@ -34,17 +33,24 @@ func randBytes(numBytes int) []byte { // make a tree with data from above and save it func newAlohaTree(t *testing.T, db dbm.DB) (*iavl.MutableTree, types.CommitID) { + t.Helper() tree, err := iavl.NewMutableTree(db, cacheSize, false) require.NoError(t, err) for k, v := range treeData { - tree.Set([]byte(k), []byte(v)) + _, err := tree.Set([]byte(k), []byte(v)) + if err != nil { + panic(err) + } } for i := 0; i < nMoreData; i++ { key := randBytes(12) value := randBytes(50) - tree.Set(key, value) + _, err := tree.Set(key, value) + if err != nil { + panic(err) + } } hash, ver, err := tree.SaveVersion() @@ -117,13 +123,14 @@ func TestLoadStore(t *testing.T) { func TestGetImmutable(t *testing.T) { db := dbm.NewMemDB() - tree, cID := newAlohaTree(t, db) + tree, _ := newAlohaTree(t, db) store := UnsafeNewStore(tree) updated, err := tree.Set([]byte("hello"), []byte("adios")) + require.NoError(t, err) require.True(t, updated) hash, ver, err := tree.SaveVersion() - cID = types.CommitID{Version: ver, Hash: hash} + cID := types.CommitID{Version: ver, Hash: hash} require.Nil(t, err) _, err = store.GetImmutable(cID.Version + 1) @@ -292,7 +299,8 @@ func TestIAVLReverseIterator(t *testing.T) { iavlStore.Set([]byte{0x00, 0x02}, []byte("0 2")) iavlStore.Set([]byte{0x01}, []byte("1")) - testReverseIterator := func(t *testing.T, start []byte, end []byte, expected []string) { + testReverseIterator := func(t *testing.T, start, end []byte, expected []string) { + t.Helper() iter := iavlStore.ReverseIterator(start, end) var i int for i = 0; iter.Valid(); iter.Next() { @@ -476,7 +484,6 @@ func TestIAVLGetAllVersions(t *testing.T) { require.True(t, iavlStore.VersionExists(int64(ver)), "Missing version %d with latest version %d. Should be storing all versions", ver, i) - } nextVersion(iavlStore) @@ -595,7 +602,8 @@ func BenchmarkIAVLIteratorNext(b *testing.B) { for i := 0; i < treeSize; i++ { key := randBytes(4) value := randBytes(50) - tree.Set(key, value) + _, err := tree.Set(key, value) + require.NoError(b, err) } iavlStore := UnsafeNewStore(tree) @@ -648,8 +656,6 @@ func TestSetInitialVersion(t *testing.T) { } for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { db := dbm.NewMemDB() store := tc.storeFn(db) diff --git a/store/iavl/tree_test.go b/store/iavl/tree_test.go index 02d19a97bf..055746b476 100644 --- a/store/iavl/tree_test.go +++ b/store/iavl/tree_test.go @@ -12,10 +12,10 @@ func TestImmutableTreePanics(t *testing.T) { t.Parallel() immTree := iavl.NewImmutableTree(dbm.NewMemDB(), 100, false) it := &immutableTree{immTree} - require.Panics(t, func() { it.Set([]byte{}, []byte{}) }) - require.Panics(t, func() { it.Remove([]byte{}) }) - require.Panics(t, func() { it.SaveVersion() }) // nolint:errcheck - require.Panics(t, func() { it.DeleteVersion(int64(1)) }) // nolint:errcheck + require.Panics(t, func() { it.Set([]byte{}, []byte{}) }) //nolint:errcheck + require.Panics(t, func() { it.Remove([]byte{}) }) //nolint:errcheck + require.Panics(t, func() { it.SaveVersion() }) //nolint:errcheck + require.Panics(t, func() { it.DeleteVersion(int64(1)) }) //nolint:errcheck val, proof, err := it.GetVersionedWithProof(nil, 1) require.Error(t, err) diff --git a/store/internal/maps/maps.go b/store/internal/maps/maps.go index bef70d55fb..c48abc9824 100644 --- a/store/internal/maps/maps.go +++ b/store/internal/maps/maps.go @@ -3,10 +3,9 @@ package maps import ( "encoding/binary" - tmcrypto "github.com/tendermint/tendermint/proto/tendermint/crypto" - "github.com/Finschia/ostracon/crypto/merkle" "github.com/Finschia/ostracon/crypto/tmhash" + tmcrypto "github.com/tendermint/tendermint/proto/tendermint/crypto" "github.com/Finschia/finschia-sdk/types/kv" ) diff --git a/store/internal/proofs/helpers.go b/store/internal/proofs/helpers.go index 24c0fe13fd..efe8033592 100644 --- a/store/internal/proofs/helpers.go +++ b/store/internal/proofs/helpers.go @@ -3,9 +3,8 @@ package proofs import ( "sort" - tmcrypto "github.com/tendermint/tendermint/proto/tendermint/crypto" - "github.com/Finschia/ostracon/libs/rand" + tmcrypto "github.com/tendermint/tendermint/proto/tendermint/crypto" sdkmaps "github.com/Finschia/finschia-sdk/store/internal/maps" ) diff --git a/store/listenkv/store.go b/store/listenkv/store.go index 692a90b717..3e8fc215fc 100644 --- a/store/listenkv/store.go +++ b/store/listenkv/store.go @@ -32,7 +32,7 @@ func (s *Store) Get(key []byte) []byte { // Set implements the KVStore interface. It traces a write operation and // delegates the Set call to the parent KVStore. -func (s *Store) Set(key []byte, value []byte) { +func (s *Store) Set(key, value []byte) { types.AssertValidKey(key) s.parent.Set(key, value) s.onWrite(false, key, value) @@ -87,7 +87,7 @@ func newTraceIterator(parent types.Iterator, listeners []types.WriteListener) ty } // Domain implements the Iterator interface. -func (li *listenIterator) Domain() (start []byte, end []byte) { +func (li *listenIterator) Domain() (start, end []byte) { return li.parent.Domain() } @@ -150,6 +150,9 @@ func (s *Store) CacheWrapWithListeners(_ types.StoreKey, _ []types.WriteListener // onWrite writes a KVStore operation to all of the WriteListeners func (s *Store) onWrite(delete bool, key, value []byte) { for _, l := range s.listeners { - l.OnWrite(s.parentStoreKey, key, value, delete) + err := l.OnWrite(s.parentStoreKey, key, value, delete) + if err != nil { + panic(err) + } } } diff --git a/store/listenkv/store_test.go b/store/listenkv/store_test.go index d661b69eea..3ba6e03f8c 100644 --- a/store/listenkv/store_test.go +++ b/store/listenkv/store_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/stretchr/testify/require" - dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/codec" @@ -123,8 +122,8 @@ func TestListenKVStoreSet(t *testing.T) { buf.Reset() store.Set(tc.key, tc.value) storeKVPair := new(types.StoreKVPair) - testMarshaller.UnmarshalLengthPrefixed(buf.Bytes(), storeKVPair) - + err := testMarshaller.UnmarshalLengthPrefixed(buf.Bytes(), storeKVPair) + require.NoError(t, err) require.Equal(t, tc.expectedOut, storeKVPair) } @@ -157,8 +156,8 @@ func TestListenKVStoreDelete(t *testing.T) { buf.Reset() store.Delete(tc.key) storeKVPair := new(types.StoreKVPair) - testMarshaller.UnmarshalLengthPrefixed(buf.Bytes(), storeKVPair) - + err := testMarshaller.UnmarshalLengthPrefixed(buf.Bytes(), storeKVPair) + require.NoError(t, err) require.Equal(t, tc.expectedOut, storeKVPair) } } diff --git a/store/mem/mem_test.go b/store/mem/mem_test.go index 74a0bc49b5..782552cc41 100644 --- a/store/mem/mem_test.go +++ b/store/mem/mem_test.go @@ -3,10 +3,9 @@ package mem_test import ( "testing" - "github.com/Finschia/finschia-sdk/store/cachekv" - "github.com/stretchr/testify/require" + "github.com/Finschia/finschia-sdk/store/cachekv" "github.com/Finschia/finschia-sdk/store/mem" "github.com/Finschia/finschia-sdk/store/types" ) diff --git a/store/prefix/store.go b/store/prefix/store.go index 7c9471fe1f..eec9ff75ae 100644 --- a/store/prefix/store.go +++ b/store/prefix/store.go @@ -28,7 +28,7 @@ func NewStore(parent types.KVStore, prefix []byte) Store { } } -func cloneAppend(bz []byte, tail []byte) (res []byte) { +func cloneAppend(bz, tail []byte) (res []byte) { res = make([]byte, len(bz)+len(tail)) copy(res, bz) copy(res[len(bz):], tail) @@ -199,7 +199,7 @@ func (pi *prefixIterator) Error() error { } // copied from github.com/tendermint/tendermint/libs/db/prefix_db.go -func stripPrefix(key []byte, prefix []byte) []byte { +func stripPrefix(key, prefix []byte) []byte { if len(key) < len(prefix) || !bytes.Equal(key[:len(prefix)], prefix) { panic("should not happen") } diff --git a/store/prefix/store_test.go b/store/prefix/store_test.go index 6e16f0ad9b..f447b8c110 100644 --- a/store/prefix/store_test.go +++ b/store/prefix/store_test.go @@ -4,12 +4,11 @@ import ( "crypto/rand" "testing" - "github.com/stretchr/testify/require" - liavl "github.com/cosmos/iavl" - "github.com/Finschia/finschia-sdk/store/cachekv" + "github.com/stretchr/testify/require" dbm "github.com/tendermint/tm-db" + "github.com/Finschia/finschia-sdk/store/cachekv" "github.com/Finschia/finschia-sdk/store/dbadapter" "github.com/Finschia/finschia-sdk/store/gaskv" "github.com/Finschia/finschia-sdk/store/iavl" @@ -30,6 +29,7 @@ type kvpair struct { } func genRandomKVPairs(t *testing.T) []kvpair { + t.Helper() kvps := make([]kvpair, 20) for i := 0; i < 20; i++ { @@ -45,6 +45,7 @@ func genRandomKVPairs(t *testing.T) []kvpair { } func setRandomKVPairs(t *testing.T, store types.KVStore) []kvpair { + t.Helper() kvps := genRandomKVPairs(t) for _, kvp := range kvps { store.Set(kvp.key, kvp.value) @@ -53,6 +54,7 @@ func setRandomKVPairs(t *testing.T, store types.KVStore) []kvpair { } func testPrefixStore(t *testing.T, baseStore types.KVStore, prefix []byte) { + t.Helper() prefixStore := NewStore(baseStore, prefix) prefixPrefixStore := NewStore(prefixStore, []byte("prefix")) @@ -253,34 +255,40 @@ func mockStoreWithStuff() types.KVStore { return store } -func checkValue(t *testing.T, store types.KVStore, key []byte, expected []byte) { +func checkValue(t *testing.T, store types.KVStore, key, expected []byte) { + t.Helper() bz := store.Get(key) require.Equal(t, expected, bz) } func checkValid(t *testing.T, itr types.Iterator, expected bool) { + t.Helper() valid := itr.Valid() require.Equal(t, expected, valid) } func checkNext(t *testing.T, itr types.Iterator, expected bool) { + t.Helper() itr.Next() valid := itr.Valid() require.Equal(t, expected, valid) } func checkDomain(t *testing.T, itr types.Iterator, start, end []byte) { + t.Helper() ds, de := itr.Domain() require.Equal(t, start, ds) require.Equal(t, end, de) } func checkItem(t *testing.T, itr types.Iterator, key, value []byte) { + t.Helper() require.Exactly(t, key, itr.Key()) require.Exactly(t, value, itr.Value()) } func checkInvalid(t *testing.T, itr types.Iterator) { + t.Helper() checkValid(t, itr, false) checkKeyPanics(t, itr) checkValuePanics(t, itr) @@ -288,14 +296,17 @@ func checkInvalid(t *testing.T, itr types.Iterator) { } func checkKeyPanics(t *testing.T, itr types.Iterator) { + t.Helper() require.Panics(t, func() { itr.Key() }) } func checkValuePanics(t *testing.T, itr types.Iterator) { + t.Helper() require.Panics(t, func() { itr.Value() }) } func checkNextPanics(t *testing.T, itr types.Iterator) { + t.Helper() require.Panics(t, func() { itr.Next() }) } diff --git a/store/rootmulti/proof_test.go b/store/rootmulti/proof_test.go index 9a24139477..bf25277c32 100644 --- a/store/rootmulti/proof_test.go +++ b/store/rootmulti/proof_test.go @@ -3,11 +3,10 @@ package rootmulti import ( "testing" - "github.com/stretchr/testify/require" - dbm "github.com/tendermint/tm-db" - "github.com/Finschia/ostracon/libs/log" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" + dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/store/iavl" "github.com/Finschia/finschia-sdk/store/types" diff --git a/store/rootmulti/rollback_test.go b/store/rootmulti/rollback_test.go index 4b1d4fb7a6..c380241aa0 100644 --- a/store/rootmulti/rollback_test.go +++ b/store/rootmulti/rollback_test.go @@ -5,14 +5,13 @@ import ( "fmt" "testing" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/ostracon/libs/log" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/simapp" ) diff --git a/store/rootmulti/snapshot_test.go b/store/rootmulti/snapshot_test.go index 49fe681df5..bf0150e876 100644 --- a/store/rootmulti/snapshot_test.go +++ b/store/rootmulti/snapshot_test.go @@ -13,13 +13,13 @@ import ( "github.com/Finschia/ostracon/libs/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/snapshots" snapshottypes "github.com/Finschia/finschia-sdk/snapshots/types" "github.com/Finschia/finschia-sdk/store/iavl" "github.com/Finschia/finschia-sdk/store/rootmulti" "github.com/Finschia/finschia-sdk/store/types" - dbm "github.com/tendermint/tm-db" ) func newMultiStoreWithGeneratedData(db dbm.DB, stores uint8, storeKeys uint64) *rootmulti.Store { @@ -32,7 +32,10 @@ func newMultiStoreWithGeneratedData(db dbm.DB, stores uint8, storeKeys uint64) * multiStore.MountStoreWithDB(key, types.StoreTypeIAVL, nil) keys = append(keys, key) } - multiStore.LoadLatestVersion() + err := multiStore.LoadLatestVersion() + if err != nil { + panic(err) + } for _, key := range keys { store := multiStore.GetCommitKVStore(key).(*iavl.Store) @@ -49,7 +52,10 @@ func newMultiStoreWithGeneratedData(db dbm.DB, stores uint8, storeKeys uint64) * } multiStore.Commit() - multiStore.LoadLatestVersion() + err = multiStore.LoadLatestVersion() + if err != nil { + panic(err) + } return multiStore } @@ -60,7 +66,10 @@ func newMultiStoreWithMixedMounts(db dbm.DB) *rootmulti.Store { store.MountStoreWithDB(types.NewKVStoreKey("iavl2"), types.StoreTypeIAVL, nil) store.MountStoreWithDB(types.NewKVStoreKey("iavl3"), types.StoreTypeIAVL, nil) store.MountStoreWithDB(types.NewTransientStoreKey("trans1"), types.StoreTypeTransient, nil) - store.LoadLatestVersion() + err := store.LoadLatestVersion() + if err != nil { + panic(err) + } return store } @@ -92,6 +101,7 @@ func newMultiStoreWithMixedMountsAndBasicData(db dbm.DB) *rootmulti.Store { } func assertStoresEqual(t *testing.T, expect, actual types.CommitKVStore, msgAndArgs ...interface{}) { + t.Helper() assert.Equal(t, expect.LastCommitID(), actual.LastCommitID()) expectIter := expect.Iterator(nil, nil) expectMap := map[string][]byte{} @@ -132,7 +142,6 @@ func TestMultistoreSnapshot_Checksum(t *testing.T) { }}, } for _, tc := range testcases { - tc := tc t.Run(fmt.Sprintf("Format %v", tc.format), func(t *testing.T) { ch := make(chan io.ReadCloser) go func() { @@ -167,7 +176,6 @@ func TestMultistoreSnapshot_Errors(t *testing.T) { "unknown height": {9, nil}, } for name, tc := range testcases { - tc := tc t.Run(name, func(t *testing.T) { err := store.Snapshot(tc.height, nil) require.Error(t, err) @@ -224,6 +232,7 @@ func TestMultistoreSnapshotRestore(t *testing.T) { } func benchmarkMultistoreSnapshot(b *testing.B, stores uint8, storeKeys uint64) { + b.Helper() b.Skip("Noisy with slow setup time, please see https://github.com/cosmos/cosmos-sdk/issues/8855.") b.ReportAllocs() @@ -259,6 +268,7 @@ func benchmarkMultistoreSnapshot(b *testing.B, stores uint8, storeKeys uint64) { } func benchmarkMultistoreSnapshotRestore(b *testing.B, stores uint8, storeKeys uint64) { + b.Helper() b.Skip("Noisy with slow setup time, please see https://github.com/cosmos/cosmos-sdk/issues/8855.") b.ReportAllocs() diff --git a/store/rootmulti/store.go b/store/rootmulti/store.go index fe3e1d20c9..004ba88b8a 100644 --- a/store/rootmulti/store.go +++ b/store/rootmulti/store.go @@ -9,6 +9,7 @@ import ( "strings" "sync" + "github.com/Finschia/ostracon/libs/log" iavltree "github.com/cosmos/iavl" protoio "github.com/gogo/protobuf/io" gogotypes "github.com/gogo/protobuf/types" @@ -17,8 +18,6 @@ import ( "github.com/tendermint/tendermint/proto/tendermint/crypto" dbm "github.com/tendermint/tm-db" - "github.com/Finschia/ostracon/libs/log" - snapshottypes "github.com/Finschia/finschia-sdk/snapshots/types" "github.com/Finschia/finschia-sdk/store/cachemulti" "github.com/Finschia/finschia-sdk/store/dbadapter" @@ -311,7 +310,7 @@ func deleteKVStore(kv types.KVStore) { } // we simulate move by a copy and delete -func moveKVStoreData(oldDB types.KVStore, newDB types.KVStore) { +func moveKVStoreData(oldDB, newDB types.KVStore) { // we read from one and write to another itr := oldDB.Iterator(nil, nil) for itr.Valid() { @@ -470,7 +469,7 @@ func (rs *Store) PruneStores(clearStorePruningHeihgts bool, pruningHeights []int store = rs.GetCommitKVStore(key) if err := store.(*iavl.Store).DeleteVersions(pruningHeights...); err != nil { - if errCause := errors.Cause(err); errCause != nil && errCause != iavltree.ErrVersionDoesNotExist { + if errCause := errors.Cause(err); errCause != nil && !errors.Is(errCause, iavltree.ErrVersionDoesNotExist) { panic(err) } } @@ -670,7 +669,7 @@ func (rs *Store) SetInitialVersion(version int64) error { // parsePath expects a format like /[/] // Must start with /, subpath may be empty // Returns error if it doesn't start with / -func parsePath(path string) (storeName string, subpath string, err error) { +func parsePath(path string) (storeName, subpath string, err error) { if !strings.HasPrefix(path, "/") { return storeName, subpath, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid path: %s", path) } @@ -745,7 +744,7 @@ func (rs *Store) Snapshot(height uint64, protoWriter protoio.Writer) error { for { node, err := exporter.Next() - if err == iavltree.ExportDone { + if errors.Is(err, iavltree.ExportDone) { break } else if err != nil { return err @@ -784,7 +783,7 @@ loop: for { snapshotItem = snapshottypes.SnapshotItem{} err := protoReader.ReadMsg(&snapshotItem) - if err == io.EOF { + if errors.Is(err, io.EOF) { break } else if err != nil { return snapshottypes.SnapshotItem{}, sdkerrors.Wrap(err, "invalid protobuf message") @@ -1055,7 +1054,10 @@ func setCommitInfo(batch dbm.Batch, version int64, cInfo *types.CommitInfo) { } cInfoKey := fmt.Sprintf(commitInfoKeyFmt, version) - batch.Set([]byte(cInfoKey), bz) + err = batch.Set([]byte(cInfoKey), bz) + if err != nil { + panic(err) + } } func setLatestVersion(batch dbm.Batch, version int64) { @@ -1064,7 +1066,10 @@ func setLatestVersion(batch dbm.Batch, version int64) { panic(err) } - batch.Set([]byte(latestVersionKey), bz) + err = batch.Set([]byte(latestVersionKey), bz) + if err != nil { + panic(err) + } } func setPruningHeights(batch dbm.Batch, pruneHeights []int64) { @@ -1075,7 +1080,10 @@ func setPruningHeights(batch dbm.Batch, pruneHeights []int64) { bz = append(bz, buf...) } - batch.Set([]byte(pruneHeightsKey), bz) + err := batch.Set([]byte(pruneHeightsKey), bz) + if err != nil { + panic(err) + } } func getPruningHeights(db dbm.DB) ([]int64, error) { diff --git a/store/rootmulti/store_test.go b/store/rootmulti/store_test.go index 0d457402b0..1848c5c9d9 100644 --- a/store/rootmulti/store_test.go +++ b/store/rootmulti/store_test.go @@ -2,18 +2,14 @@ package rootmulti import ( "bytes" - "encoding/binary" "fmt" - "math/rand" "testing" "time" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - dbm "github.com/tendermint/tm-db" - "github.com/Finschia/ostracon/libs/log" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" + dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/codec" codecTypes "github.com/Finschia/finschia-sdk/codec/types" @@ -484,7 +480,7 @@ func TestMultiStoreQuery(t *testing.T) { require.Equal(t, 3, len(qres.ProofOps.Ops)) // 3 mounted stores // Test proofs second latest height - query.Height = query.Height - 1 + query.Height-- qres = multi.Query(query) require.EqualValues(t, 0, qres.Code) require.NotNil(t, qres.ProofOps) @@ -510,8 +506,6 @@ func TestMultiStore_Pruning(t *testing.T) { } for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { db := dbm.NewMemDB() ms := newMultiStoreWithMounts(db, tc.po) @@ -577,32 +571,14 @@ func TestMultiStore_PruningRestart(t *testing.T) { } } -func assertStoresEqual(t *testing.T, expect, actual types.CommitKVStore, msgAndArgs ...interface{}) { - assert.Equal(t, expect.LastCommitID(), actual.LastCommitID()) - expectIter := expect.Iterator(nil, nil) - expectMap := map[string][]byte{} - for ; expectIter.Valid(); expectIter.Next() { - expectMap[string(expectIter.Key())] = expectIter.Value() - } - require.NoError(t, expectIter.Error()) - - actualIter := expect.Iterator(nil, nil) - actualMap := map[string][]byte{} - for ; actualIter.Valid(); actualIter.Next() { - actualMap[string(actualIter.Key())] = actualIter.Value() - } - require.NoError(t, actualIter.Error()) - - assert.Equal(t, expectMap, actualMap, msgAndArgs...) -} - func TestSetInitialVersion(t *testing.T) { db := dbm.NewMemDB() multi := newMultiStoreWithMounts(db, types.PruneNothing) require.NoError(t, multi.LoadLatestVersion()) - multi.SetInitialVersion(5) + err := multi.SetInitialVersion(5) + require.NoError(t, err) require.Equal(t, int64(5), multi.initialVersion) multi.Commit() @@ -648,7 +624,8 @@ func TestGetListenWrappedKVStore(t *testing.T) { buf := new(bytes.Buffer) var db dbm.DB = dbm.NewMemDB() ms := newMultiStoreWithMounts(db, types.PruneNothing) - ms.LoadLatestVersion() + err := ms.LoadLatestVersion() + require.NoError(t, err) mockListeners := []types.WriteListener{types.NewStoreKVPairWriteListener(buf, testMarshaller)} ms.AddListeners(testStoreKey1, mockListeners) ms.AddListeners(testStoreKey2, mockListeners) @@ -690,6 +667,7 @@ func TestGetListenWrappedKVStore(t *testing.T) { StoreKey: testStoreKey2.Name(), Delete: false, }) + require.NoError(t, err) kvPairSet2Bytes := buf.Bytes() buf.Reset() require.Equal(t, expectedOutputKVPairSet2, kvPairSet2Bytes) @@ -701,6 +679,7 @@ func TestGetListenWrappedKVStore(t *testing.T) { StoreKey: testStoreKey2.Name(), Delete: true, }) + require.NoError(t, err) kvPairDelete2Bytes := buf.Bytes() buf.Reset() require.Equal(t, expectedOutputKVPairDelete2, kvPairDelete2Bytes) @@ -803,48 +782,6 @@ func newMultiStoreWithMounts(db dbm.DB, pruningOpts types.PruningOptions) *Store return store } -func newMultiStoreWithMixedMounts(db dbm.DB) *Store { - store := NewStore(db, log.NewNopLogger()) - store.MountStoreWithDB(types.NewKVStoreKey("iavl1"), types.StoreTypeIAVL, nil) - store.MountStoreWithDB(types.NewKVStoreKey("iavl2"), types.StoreTypeIAVL, nil) - store.MountStoreWithDB(types.NewKVStoreKey("iavl3"), types.StoreTypeIAVL, nil) - store.LoadLatestVersion() - - return store -} - -func newMultiStoreWithGeneratedData(db dbm.DB, stores uint8, storeKeys uint64) *Store { - multiStore := NewStore(db, log.NewNopLogger()) - r := rand.New(rand.NewSource(49872768940)) // Fixed seed for deterministic tests - - keys := []*types.KVStoreKey{} - for i := uint8(0); i < stores; i++ { - key := types.NewKVStoreKey(fmt.Sprintf("store%v", i)) - multiStore.MountStoreWithDB(key, types.StoreTypeIAVL, nil) - keys = append(keys, key) - } - multiStore.LoadLatestVersion() - - for _, key := range keys { - store := multiStore.stores[key].(*iavl.Store) - for i := uint64(0); i < storeKeys; i++ { - k := make([]byte, 8) - v := make([]byte, 1024) - binary.BigEndian.PutUint64(k, i) - _, err := r.Read(v) - if err != nil { - panic(err) - } - store.Set(k, v) - } - } - - multiStore.Commit() - multiStore.LoadLatestVersion() - - return multiStore -} - func newMultiStoreWithModifiedMounts(db dbm.DB, pruningOpts types.PruningOptions) (*Store, *types.StoreUpgrades) { store := NewStore(db, log.NewNopLogger()) store.pruningOpts = pruningOpts @@ -867,26 +804,27 @@ func newMultiStoreWithModifiedMounts(db dbm.DB, pruningOpts types.PruningOptions } func checkStore(t *testing.T, store *Store, expect, got types.CommitID) { + t.Helper() require.Equal(t, expect, got) require.Equal(t, expect, store.LastCommitID()) } -func checkContains(t testing.TB, info []types.StoreInfo, wanted []string) { - t.Helper() +func checkContains(tb testing.TB, info []types.StoreInfo, wanted []string) { + tb.Helper() for _, want := range wanted { - checkHas(t, info, want) + checkHas(tb, info, want) } } -func checkHas(t testing.TB, info []types.StoreInfo, want string) { - t.Helper() +func checkHas(tb testing.TB, info []types.StoreInfo, want string) { + tb.Helper() for _, i := range info { if i.Name == want { return } } - t.Fatalf("storeInfo doesn't contain %s", want) + tb.Fatalf("storeInfo doesn't contain %s", want) } func getExpectedCommitID(store *Store, ver int64) types.CommitID { diff --git a/store/streaming/constructor.go b/store/streaming/constructor.go index c6da2099b0..fcec93f2a1 100644 --- a/store/streaming/constructor.go +++ b/store/streaming/constructor.go @@ -103,7 +103,7 @@ func LoadStreamingServices(bApp *baseapp.BaseApp, appOpts serverTypes.AppOptions if err != nil { // close any services we may have already spun up before hitting the error on this one for _, activeStreamer := range activeStreamers { - activeStreamer.Close() + _ = activeStreamer.Close() } return nil, nil, err } @@ -112,14 +112,17 @@ func LoadStreamingServices(bApp *baseapp.BaseApp, appOpts serverTypes.AppOptions if err != nil { // close any services we may have already spun up before hitting the error on this one for _, activeStreamer := range activeStreamers { - activeStreamer.Close() + _ = activeStreamer.Close() } return nil, nil, err } // register the streaming service with the BaseApp bApp.SetStreamingService(streamingService) // kick off the background streaming service loop - streamingService.Stream(wg) + err = streamingService.Stream(wg) + if err != nil { + return nil, nil, err + } // add to the list of active streamers activeStreamers = append(activeStreamers, streamingService) } diff --git a/store/streaming/file/service.go b/store/streaming/file/service.go index 98d8fed761..9cc5d20dcc 100644 --- a/store/streaming/file/service.go +++ b/store/streaming/file/service.go @@ -8,9 +8,8 @@ import ( "path/filepath" "sync" - abci "github.com/tendermint/tendermint/abci/types" - ocabci "github.com/Finschia/ostracon/abci/types" + abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/baseapp" "github.com/Finschia/finschia-sdk/codec" @@ -26,7 +25,7 @@ type StreamingService struct { srcChan <-chan []byte // the channel that all the WriteListeners write their data out to filePrefix string // optional prefix for each of the generated files writeDir string // directory to write files into - codec codec.BinaryCodec // marshaller used for re-marshalling the ABCI messages to write them out to the destination files + codec codec.BinaryCodec // marshaller used for re-marshaling the ABCI messages to write them out to the destination files stateCache [][]byte // cache the protobuf binary encoded StoreKVPairs in the order they are received stateCacheLock *sync.Mutex // mutex for the state cache currentBlockNumber int64 // the current block number diff --git a/store/streaming/file/service_test.go b/store/streaming/file/service_test.go index d08d4d6c93..3b250f88c0 100644 --- a/store/streaming/file/service_test.go +++ b/store/streaming/file/service_test.go @@ -8,12 +8,11 @@ import ( "sync" "testing" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/finschia-sdk/codec" codecTypes "github.com/Finschia/finschia-sdk/codec/types" "github.com/Finschia/finschia-sdk/store/types" @@ -107,13 +106,13 @@ var ( ) func TestIntermediateWriter(t *testing.T) { - outChan := make(chan []byte, 0) + outChan := make(chan []byte) iw := NewIntermediateWriter(outChan) require.IsType(t, &IntermediateWriter{}, iw) testBytes := []byte{1, 2, 3, 4, 5} var length int var err error - waitChan := make(chan struct{}, 0) + waitChan := make(chan struct{}) go func() { length, err = iw.Write(testBytes) waitChan <- struct{}{} @@ -129,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) @@ -143,25 +142,31 @@ func TestFileStreamingService(t *testing.T) { testListener1 = testStreamingService.listeners[mockStoreKey1][0] testListener2 = testStreamingService.listeners[mockStoreKey2][0] wg := new(sync.WaitGroup) - testStreamingService.Stream(wg) + err = testStreamingService.Stream(wg) + require.NoError(t, err) testListenBeginBlock(t) testListenDeliverTx1(t) testListenDeliverTx2(t) testListenEndBlock(t) - testStreamingService.Close() + err = testStreamingService.Close() + require.NoError(t, err) wg.Wait() } func testListenBeginBlock(t *testing.T) { + t.Helper() expectedBeginBlockReqBytes, err := testMarshaller.Marshal(&testBeginBlockReq) require.Nil(t, err) expectedBeginBlockResBytes, err := testMarshaller.Marshal(&testBeginBlockRes) require.Nil(t, err) // write state changes - testListener1.OnWrite(mockStoreKey1, mockKey1, mockValue1, false) - testListener2.OnWrite(mockStoreKey2, mockKey2, mockValue2, false) - testListener1.OnWrite(mockStoreKey1, mockKey3, mockValue3, false) + err = testListener1.OnWrite(mockStoreKey1, mockKey1, mockValue1, false) + require.NoError(t, err) + err = testListener2.OnWrite(mockStoreKey2, mockKey2, mockValue2, false) + require.NoError(t, err) + err = testListener1.OnWrite(mockStoreKey1, mockKey3, mockValue3, false) + require.NoError(t, err) // expected KV pairs expectedKVPair1, err := testMarshaller.Marshal(&types.StoreKVPair{ @@ -207,15 +212,19 @@ func testListenBeginBlock(t *testing.T) { } func testListenDeliverTx1(t *testing.T) { + t.Helper() expectedDeliverTxReq1Bytes, err := testMarshaller.Marshal(&testDeliverTxReq1) require.Nil(t, err) expectedDeliverTxRes1Bytes, err := testMarshaller.Marshal(&testDeliverTxRes1) require.Nil(t, err) // write state changes - testListener1.OnWrite(mockStoreKey1, mockKey1, mockValue1, false) - testListener2.OnWrite(mockStoreKey2, mockKey2, mockValue2, false) - testListener1.OnWrite(mockStoreKey2, mockKey3, mockValue3, false) + err = testListener1.OnWrite(mockStoreKey1, mockKey1, mockValue1, false) + require.NoError(t, err) + err = testListener2.OnWrite(mockStoreKey2, mockKey2, mockValue2, false) + require.NoError(t, err) + err = testListener1.OnWrite(mockStoreKey2, mockKey3, mockValue3, false) + require.NoError(t, err) // expected KV pairs expectedKVPair1, err := testMarshaller.Marshal(&types.StoreKVPair{ @@ -261,15 +270,19 @@ func testListenDeliverTx1(t *testing.T) { } func testListenDeliverTx2(t *testing.T) { + t.Helper() expectedDeliverTxReq2Bytes, err := testMarshaller.Marshal(&testDeliverTxReq2) require.Nil(t, err) expectedDeliverTxRes2Bytes, err := testMarshaller.Marshal(&testDeliverTxRes2) require.Nil(t, err) // write state changes - testListener1.OnWrite(mockStoreKey2, mockKey1, mockValue1, false) - testListener2.OnWrite(mockStoreKey1, mockKey2, mockValue2, false) - testListener1.OnWrite(mockStoreKey2, mockKey3, mockValue3, false) + err = testListener1.OnWrite(mockStoreKey2, mockKey1, mockValue1, false) + require.NoError(t, err) + err = testListener2.OnWrite(mockStoreKey1, mockKey2, mockValue2, false) + require.NoError(t, err) + err = testListener1.OnWrite(mockStoreKey2, mockKey3, mockValue3, false) + require.NoError(t, err) // expected KV pairs expectedKVPair1, err := testMarshaller.Marshal(&types.StoreKVPair{ @@ -315,15 +328,19 @@ func testListenDeliverTx2(t *testing.T) { } func testListenEndBlock(t *testing.T) { + t.Helper() expectedEndBlockReqBytes, err := testMarshaller.Marshal(&testEndBlockReq) require.Nil(t, err) expectedEndBlockResBytes, err := testMarshaller.Marshal(&testEndBlockRes) require.Nil(t, err) // write state changes - testListener1.OnWrite(mockStoreKey1, mockKey1, mockValue1, false) - testListener2.OnWrite(mockStoreKey1, mockKey2, mockValue2, false) - testListener1.OnWrite(mockStoreKey2, mockKey3, mockValue3, false) + err = testListener1.OnWrite(mockStoreKey1, mockKey1, mockValue1, false) + require.NoError(t, err) + err = testListener2.OnWrite(mockStoreKey1, mockKey2, mockValue2, false) + require.NoError(t, err) + err = testListener1.OnWrite(mockStoreKey2, mockKey3, mockValue3, false) + require.NoError(t, err) // expected KV pairs expectedKVPair1, err := testMarshaller.Marshal(&types.StoreKVPair{ diff --git a/store/tracekv/store.go b/store/tracekv/store.go index bf5ffe32dc..1883ed32ad 100644 --- a/store/tracekv/store.go +++ b/store/tracekv/store.go @@ -59,7 +59,7 @@ func (tkv *Store) Get(key []byte) []byte { // Set implements the KVStore interface. It traces a write operation and // delegates the Set call to the parent KVStore. -func (tkv *Store) Set(key []byte, value []byte) { +func (tkv *Store) Set(key, value []byte) { types.AssertValidKey(key) writeOperation(tkv.writer, writeOp, tkv.context, key, value) tkv.parent.Set(key, value) @@ -115,7 +115,7 @@ func newTraceIterator(w io.Writer, parent types.Iterator, tc types.TraceContext) } // Domain implements the Iterator interface. -func (ti *traceIterator) Domain() (start []byte, end []byte) { +func (ti *traceIterator) Domain() (start, end []byte) { return ti.parent.Domain() } @@ -200,5 +200,8 @@ func writeOperation(w io.Writer, op operation, tc types.TraceContext, key, value panic(errors.Wrap(err, "failed to write trace operation")) } - io.WriteString(w, "\n") + _, err = io.WriteString(w, "\n") + if err != nil { + panic(err) + } } diff --git a/store/tracekv/store_test.go b/store/tracekv/store_test.go index 4ee0fe4a5d..8eaa2c420a 100644 --- a/store/tracekv/store_test.go +++ b/store/tracekv/store_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/stretchr/testify/require" - dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/store/dbadapter" diff --git a/store/types/gas_test.go b/store/types/gas_test.go index 8a02df4cfa..80ca8adf9e 100644 --- a/store/types/gas_test.go +++ b/store/types/gas_test.go @@ -44,7 +44,6 @@ func TestGasMeter(t *testing.T) { used := uint64(0) for unum, usage := range tc.usage { - usage := usage used += usage require.NotPanics(t, func() { meter.ConsumeGas(usage, "") }, "Not exceeded limit but panicked. tc #%d, usage #%d", tcnum, unum) require.Equal(t, used, meter.GasConsumed(), "Gas consumption not match. tc #%d, usage #%d", tcnum, unum) diff --git a/store/types/iterator_test.go b/store/types/iterator_test.go index 0f6582baff..d49caf7e66 100644 --- a/store/types/iterator_test.go +++ b/store/types/iterator_test.go @@ -3,16 +3,16 @@ package types_test import ( "testing" + "github.com/Finschia/ostracon/libs/log" "github.com/stretchr/testify/require" dbm "github.com/tendermint/tm-db" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/store/iavl" "github.com/Finschia/finschia-sdk/store/types" ) func newMemTestKVStore(t *testing.T) types.KVStore { + t.Helper() db := dbm.NewMemDB() store, err := iavl.LoadStore(db, log.NewNopLogger(), types.NewKVStoreKey("test"), types.CommitID{}, false, iavl.DefaultIAVLCacheSize, false) require.NoError(t, err) @@ -83,7 +83,6 @@ func TestPaginatedIterator(t *testing.T) { reverse: true, }, } { - tc := tc t.Run(tc.desc, func(t *testing.T) { var iter types.Iterator if tc.reverse { diff --git a/store/types/listening.go b/store/types/listening.go index 7033d3723f..241943c891 100644 --- a/store/types/listening.go +++ b/store/types/listening.go @@ -11,7 +11,7 @@ type WriteListener interface { // if value is nil then it was deleted // storeKey indicates the source KVStore, to facilitate using the same WriteListener across separate KVStores // delete bool indicates if it was a delete; true: delete, false: set - OnWrite(storeKey StoreKey, key []byte, value []byte, delete bool) error + OnWrite(storeKey StoreKey, key, value []byte, delete bool) error } // StoreKVPairWriteListener is used to configure listening to a KVStore by writing out length-prefixed @@ -30,7 +30,7 @@ func NewStoreKVPairWriteListener(w io.Writer, m codec.BinaryCodec) *StoreKVPairW } // OnWrite satisfies the WriteListener interface by writing length-prefixed protobuf encoded StoreKVPairs -func (wl *StoreKVPairWriteListener) OnWrite(storeKey StoreKey, key []byte, value []byte, delete bool) error { +func (wl *StoreKVPairWriteListener) OnWrite(storeKey StoreKey, key, value []byte, delete bool) error { kvPair := new(StoreKVPair) kvPair.StoreKey = storeKey.Name() kvPair.Delete = delete diff --git a/store/types/listening_test.go b/store/types/listening_test.go index c4137941a8..079d5215c9 100644 --- a/store/types/listening_test.go +++ b/store/types/listening_test.go @@ -45,7 +45,8 @@ func TestOnWrite(t *testing.T) { StoreKey: testStoreKey.Name(), Delete: false, } - testMarshaller.UnmarshalLengthPrefixed(outputBytes, outputKVPair) + err = testMarshaller.UnmarshalLengthPrefixed(outputBytes, outputKVPair) + require.NoError(t, err) require.EqualValues(t, expectedOutputKVPair, outputKVPair) testWriter.Reset() @@ -61,6 +62,7 @@ func TestOnWrite(t *testing.T) { StoreKey: testStoreKey.Name(), Delete: true, } - testMarshaller.UnmarshalLengthPrefixed(outputBytes, outputKVPair) + err = testMarshaller.UnmarshalLengthPrefixed(outputBytes, outputKVPair) + require.NoError(t, err) require.EqualValues(t, expectedOutputKVPair, outputKVPair) } diff --git a/store/types/proof.go b/store/types/proof.go index 9323284d23..281231bc31 100644 --- a/store/types/proof.go +++ b/store/types/proof.go @@ -1,10 +1,9 @@ package types import ( - tmmerkle "github.com/tendermint/tendermint/proto/tendermint/crypto" - "github.com/Finschia/ostracon/crypto/merkle" ics23 "github.com/confio/ics23/go" + tmmerkle "github.com/tendermint/tendermint/proto/tendermint/crypto" sdkerrors "github.com/Finschia/finschia-sdk/types/errors" ) @@ -48,7 +47,7 @@ func NewSimpleMerkleCommitmentOp(key []byte, proof *ics23.CommitmentProof) Commi } // CommitmentOpDecoder takes a merkle.ProofOp and attempts to decode it into a CommitmentOp ProofOperator -// The proofOp.Data is just a marshalled CommitmentProof. The Key of the CommitmentOp is extracted +// The proofOp.Data is just a marshaled CommitmentProof. The Key of the CommitmentOp is extracted // from the unmarshalled proof. func CommitmentOpDecoder(pop tmmerkle.ProofOp) (merkle.ProofOperator, error) { var spec *ics23.ProofSpec diff --git a/store/types/store_test.go b/store/types/store_test.go index 8dac7f5394..ff9765dbe8 100644 --- a/store/types/store_test.go +++ b/store/types/store_test.go @@ -47,7 +47,6 @@ func TestStoreUpgrades(t *testing.T) { } for name, tc := range cases { - tc := tc t.Run(name, func(t *testing.T) { for _, d := range tc.expectDelete { assert.Equal(t, tc.upgrades.IsDeleted(d.key), d.delete) diff --git a/store/types/utils.go b/store/types/utils.go index cb3aec5ad6..eadde90024 100644 --- a/store/types/utils.go +++ b/store/types/utils.go @@ -18,7 +18,7 @@ func KVStoreReversePrefixIterator(kvs KVStore, prefix []byte) Iterator { // DiffKVStores compares two KVstores and returns all the key/value pairs // that differ from one another. It also skips value comparison for a set of provided prefixes. -func DiffKVStores(a KVStore, b KVStore, prefixesToSkip [][]byte) (kvAs, kvBs []kv.Pair) { +func DiffKVStores(a, b KVStore, prefixesToSkip [][]byte) (kvAs, kvBs []kv.Pair) { iterA := a.Iterator(nil, nil) defer iterA.Close() diff --git a/store/types/utils_test.go b/store/types/utils_test.go index 2cf187c183..da92c44393 100644 --- a/store/types/utils_test.go +++ b/store/types/utils_test.go @@ -4,16 +4,16 @@ import ( "bytes" "testing" + "github.com/Finschia/ostracon/libs/log" "github.com/stretchr/testify/require" dbm "github.com/tendermint/tm-db" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/store/rootmulti" "github.com/Finschia/finschia-sdk/store/types" ) func initTestStores(t *testing.T) (types.KVStore, types.KVStore) { + t.Helper() db := dbm.NewMemDB() ms := rootmulti.NewStore(db, log.NewNopLogger()) diff --git a/testutil/context.go b/testutil/context.go index 2be8045fbd..fc6b4440cb 100644 --- a/testutil/context.go +++ b/testutil/context.go @@ -1,17 +1,16 @@ package testutil import ( + "github.com/Finschia/ostracon/libs/log" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/store" sdk "github.com/Finschia/finschia-sdk/types" ) // DefaultContext creates a sdk.Context with a fresh dbm that can be used in tests. -func DefaultContext(key sdk.StoreKey, tkey sdk.StoreKey) sdk.Context { +func DefaultContext(key, tkey sdk.StoreKey) sdk.Context { db := dbm.NewMemDB() cms := store.NewCommitMultiStore(db) cms.MountStoreWithDB(key, sdk.StoreTypeIAVL, db) diff --git a/testutil/ioutil.go b/testutil/ioutil.go index 6ff54d24ec..21d57157c7 100644 --- a/testutil/ioutil.go +++ b/testutil/ioutil.go @@ -52,23 +52,23 @@ func ApplyMockIODiscardOutErr(c *cobra.Command) BufferReader { // Write the given string to a new temporary file. // Returns an open file for the test to use. -func WriteToNewTempFile(t testing.TB, s string) *os.File { - t.Helper() +func WriteToNewTempFile(tb testing.TB, s string) *os.File { + tb.Helper() - fp := TempFile(t) + fp := TempFile(tb) _, err := fp.WriteString(s) - require.Nil(t, err) + require.Nil(tb, err) return fp } // TempFile returns a writable temporary file for the test to use. -func TempFile(t testing.TB) *os.File { - t.Helper() +func TempFile(tb testing.TB) *os.File { + tb.Helper() - fp, err := os.CreateTemp(t.TempDir(), "") - require.NoError(t, err) + fp, err := os.CreateTemp(tb.TempDir(), "") + require.NoError(tb, err) return fp } diff --git a/testutil/network/network.go b/testutil/network/network.go index e59f58ab25..39a0c702e2 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -170,6 +170,7 @@ type ( // New creates a new Network for integration tests. func New(t *testing.T, cfg Config) *Network { + t.Helper() // only one caller/test can create and use a network at a time t.Log("acquiring test network lock") lock.Lock() @@ -398,6 +399,7 @@ func New(t *testing.T, cfg Config) *Network { // New creates a new Network for integration tests without init. func NewWithoutInit(t *testing.T, cfg Config, baseDir string, validators []*Validator) *Network { + t.Helper() // only one caller/test can create and use a network at a time t.Log("acquiring test network lock") lock.Lock() @@ -424,6 +426,7 @@ func NewWithoutInit(t *testing.T, cfg Config, baseDir string, validators []*Vali } func AddNewValidator(t *testing.T, network *Network, validator *Validator) { + t.Helper() t.Log("adding new validator...") require.NoError(t, startInProcess(network.Config, validator)) diff --git a/testutil/network/util.go b/testutil/network/util.go index 71dd4c0126..3f696d79c8 100644 --- a/testutil/network/util.go +++ b/testutil/network/util.go @@ -190,16 +190,16 @@ func initGenFiles(cfg Config, genAccounts []authtypes.GenesisAccount, genBalance return nil } -func writeFile(name string, dir string, contents []byte) error { +func writeFile(name, dir string, contents []byte) error { writePath := filepath.Join(dir) //nolint:gocritic file := filepath.Join(writePath, name) - err := ostos.EnsureDir(writePath, 0755) + err := ostos.EnsureDir(writePath, 0o755) if err != nil { return err } - err = ostos.WriteFile(file, contents, 0644) + err = ostos.WriteFile(file, contents, 0o644) if err != nil { return err } diff --git a/testutil/rest/rest.go b/testutil/rest/rest.go index e56ef90a20..673aae18b4 100644 --- a/testutil/rest/rest.go +++ b/testutil/rest/rest.go @@ -28,7 +28,7 @@ func GetRequest(url string) ([]byte, error) { // PostRequest defines a wrapper around an HTTP POST request with a provided URL and data. // An error is returned if the request or reading the body fails. -func PostRequest(url string, contentType string, data []byte) ([]byte, error) { +func PostRequest(url, contentType string, data []byte) ([]byte, error) { res, err := http.Post(url, contentType, bytes.NewBuffer(data)) // nolint:gosec if err != nil { return nil, fmt.Errorf("error while sending post request: %w", err) diff --git a/types/abci.go b/types/abci.go index 6cd54a411e..e4e97a882c 100644 --- a/types/abci.go +++ b/types/abci.go @@ -1,9 +1,8 @@ package types import ( - abci "github.com/tendermint/tendermint/abci/types" - ocabci "github.com/Finschia/ostracon/abci/types" + abci "github.com/tendermint/tendermint/abci/types" ) // InitChainer initializes application state at genesis diff --git a/types/address.go b/types/address.go index e5eac64563..aafb3f3ef6 100644 --- a/types/address.go +++ b/types/address.go @@ -10,7 +10,7 @@ import ( "sync" "github.com/hashicorp/golang-lru/simplelru" - yaml "gopkg.in/yaml.v2" + "gopkg.in/yaml.v2" cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" "github.com/Finschia/finschia-sdk/internal/conv" @@ -291,15 +291,20 @@ func (aa AccAddress) String() string { } // Format implements the fmt.Formatter interface. -// nolint: errcheck func (aa AccAddress) Format(s fmt.State, verb rune) { + var err error switch verb { case 's': - s.Write([]byte(aa.String())) + _, err = s.Write([]byte(aa.String())) case 'p': - s.Write([]byte(fmt.Sprintf("%p", aa))) + _, err = s.Write([]byte(fmt.Sprintf("%p", aa))) + default: - s.Write([]byte(fmt.Sprintf("%X", []byte(aa)))) + _, err = s.Write([]byte(fmt.Sprintf("%X", []byte(aa)))) + } + + if err != nil { + panic(err) } } @@ -441,15 +446,20 @@ func (va ValAddress) String() string { } // Format implements the fmt.Formatter interface. -// nolint: errcheck func (va ValAddress) Format(s fmt.State, verb rune) { + var err error + switch verb { case 's': - s.Write([]byte(va.String())) + _, err = s.Write([]byte(va.String())) case 'p': - s.Write([]byte(fmt.Sprintf("%p", va))) + _, err = s.Write([]byte(fmt.Sprintf("%p", va))) default: - s.Write([]byte(fmt.Sprintf("%X", []byte(va)))) + _, err = s.Write([]byte(fmt.Sprintf("%X", []byte(va)))) + } + + if err != nil { + panic(err) } } @@ -620,15 +630,20 @@ func MustBech32ifyAddressBytes(prefix string, bs []byte) string { } // Format implements the fmt.Formatter interface. -// nolint: errcheck func (ca ConsAddress) Format(s fmt.State, verb rune) { + var err error + switch verb { case 's': - s.Write([]byte(ca.String())) + _, err = s.Write([]byte(ca.String())) case 'p': - s.Write([]byte(fmt.Sprintf("%p", ca))) + _, err = s.Write([]byte(fmt.Sprintf("%p", ca))) default: - s.Write([]byte(fmt.Sprintf("%X", []byte(ca)))) + _, err = s.Write([]byte(fmt.Sprintf("%X", []byte(ca)))) + } + + if err != nil { + panic(err) } } diff --git a/types/address/hash.go b/types/address/hash.go index c7701135cb..278e183bf8 100644 --- a/types/address/hash.go +++ b/types/address/hash.go @@ -66,6 +66,6 @@ func Module(moduleName string, key []byte) []byte { } // Derive derives a new address from the main `address` and a derivation `key`. -func Derive(address []byte, key []byte) []byte { +func Derive(address, key []byte) []byte { return Hash(conv.UnsafeBytesToStr(address), key) } diff --git a/types/address/hash_test.go b/types/address/hash_test.go index 06fede6594..a3960fa262 100644 --- a/types/address/hash_test.go +++ b/types/address/hash_test.go @@ -56,7 +56,7 @@ func (suite *AddressSuite) TestComposed() { assert.NotEqual(ac, ac2, "NewComposed must be sensitive to type") // changing order of addresses shouldn't impact a composed address - ac2, err = Compose(typ, []Addressable{a1, addrMock{make([]byte, 300, 300)}}) + _, err = Compose(typ, []Addressable{a1, addrMock{make([]byte, 300)}}) assert.Error(err) assert.Contains(err.Error(), "should be max 255 bytes, got 300") } @@ -99,6 +99,7 @@ func (a addrMock) Address() []byte { } func (a addrMock) AddressWithLen(t *testing.T) []byte { + t.Helper() addr, err := LengthPrefix(a.Addr) assert.NoError(t, err) return addr diff --git a/types/address/store_key_test.go b/types/address/store_key_test.go index ca3b4d8ec2..6f04121baf 100644 --- a/types/address/store_key_test.go +++ b/types/address/store_key_test.go @@ -32,7 +32,6 @@ func (suite *StoreKeySuite) TestLengthPrefix() { } for _, tt := range tests { - tt := tt suite.Run(tt.name, func() { storeKey, err := address.LengthPrefix(tt.addr) if tt.expErr { diff --git a/types/address_race_test.go b/types/address_race_test.go index ee44fab39a..281f036bc6 100644 --- a/types/address_race_test.go +++ b/types/address_race_test.go @@ -6,8 +6,9 @@ import ( "testing" "time" - "github.com/Finschia/finschia-sdk/types" "github.com/stretchr/testify/require" + + "github.com/Finschia/finschia-sdk/types" ) // generates AccAddress with `prefix` and calls String method diff --git a/types/address_test.go b/types/address_test.go index 32a6af3d79..cbd09dbfa6 100644 --- a/types/address_test.go +++ b/types/address_test.go @@ -2,9 +2,10 @@ package types_test import ( "bytes" + "crypto/rand" "encoding/hex" "fmt" - "math/rand" + "math/big" "strings" "testing" @@ -16,7 +17,7 @@ import ( "github.com/Finschia/finschia-sdk/crypto/keys/secp256k1" cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" "github.com/Finschia/finschia-sdk/types" - "github.com/Finschia/finschia-sdk/types/bech32/legacybech32" + "github.com/Finschia/finschia-sdk/types/bech32/legacybech32" //nolint:staticcheck // we're using this to support the legacy way of dealing with bech32 ) type addressTestSuite struct { @@ -43,7 +44,7 @@ var invalidStrs = []string{ types.Bech32PrefixConsPub + "6789", } -func (s *addressTestSuite) testMarshal(original interface{}, res interface{}, marshal func() ([]byte, error), unmarshal func([]byte) error) { +func (s *addressTestSuite) testMarshal(original, res interface{}, marshal func() ([]byte, error), unmarshal func([]byte) error) { bz, err := marshal() s.Require().Nil(err) s.Require().Nil(unmarshal(bz)) @@ -91,7 +92,8 @@ func (s *addressTestSuite) TestRandBech32AccAddrConsistency() { pub := &ed25519.PubKey{Key: pubBz} for i := 0; i < 1000; i++ { - rand.Read(pub.Key) + _, err := rand.Read(pub.Key) + s.Require().NoError(err) acc := types.AccAddress(pub.Address()) res := types.AccAddress{} @@ -100,7 +102,7 @@ func (s *addressTestSuite) TestRandBech32AccAddrConsistency() { s.testMarshal(&acc, &res, acc.Marshal, (&res).Unmarshal) str := acc.String() - res, err := types.AccAddressFromBech32(str) + res, err = types.AccAddressFromBech32(str) s.Require().Nil(err) s.Require().Equal(acc, res) @@ -130,7 +132,8 @@ func (s *addressTestSuite) TestValAddr() { pub := &ed25519.PubKey{Key: pubBz} for i := 0; i < 20; i++ { - rand.Read(pub.Key) + _, err := rand.Read(pub.Key) + s.Require().NoError(err) acc := types.ValAddress(pub.Address()) res := types.ValAddress{} @@ -139,7 +142,7 @@ func (s *addressTestSuite) TestValAddr() { s.testMarshal(&acc, &res, acc.Marshal, (&res).Unmarshal) str := acc.String() - res, err := types.ValAddressFromBech32(str) + res, err = types.ValAddressFromBech32(str) s.Require().Nil(err) s.Require().Equal(acc, res) @@ -171,7 +174,8 @@ func (s *addressTestSuite) TestConsAddress() { pub := &ed25519.PubKey{Key: pubBz} for i := 0; i < 20; i++ { - rand.Read(pub.Key[:]) + _, err := rand.Read(pub.Key[:]) + s.Require().NoError(err) acc := types.ConsAddress(pub.Address()) res := types.ConsAddress{} @@ -180,7 +184,7 @@ func (s *addressTestSuite) TestConsAddress() { s.testMarshal(&acc, &res, acc.Marshal, (&res).Unmarshal) str := acc.String() - res, err := types.ConsAddressFromBech32(str) + res, err = types.ConsAddressFromBech32(str) s.Require().Nil(err) s.Require().Equal(acc, res) @@ -211,7 +215,11 @@ const letterBytes = "abcdefghijklmnopqrstuvwxyz" func RandString(n int) string { b := make([]byte, n) for i := range b { - b[i] = letterBytes[rand.Intn(len(letterBytes))] + nBig, err := rand.Int(rand.Reader, big.NewInt(int64(len(letterBytes)))) + if err != nil { + panic(err) + } + b[i] = letterBytes[nBig.Int64()] } return string(b) } @@ -221,7 +229,9 @@ func (s *addressTestSuite) TestConfiguredPrefix() { pub := &ed25519.PubKey{Key: pubBz} for length := 1; length < 10; length++ { for times := 1; times < 20; times++ { - rand.Read(pub.Key[:]) + _, err := rand.Read(pub.Key[:]) + s.Require().NoError(err) + // Test if randomly generated prefix of a given length works prefix := RandString(length) @@ -275,7 +285,8 @@ func (s *addressTestSuite) TestConfiguredPrefix() { func (s *addressTestSuite) TestAddressInterface() { pubBz := make([]byte, ed25519.PubKeySize) pub := &ed25519.PubKey{Key: pubBz} - rand.Read(pub.Key) + _, err := rand.Read(pub.Key) + s.Require().NoError(err) addrs := []types.Address{ types.ConsAddress(pub.Address()), @@ -381,7 +392,6 @@ func (s *addressTestSuite) TestBech32ifyAddressBytes() { {"20-byte address", args{"prefixb", addr20byte}, "prefixb1qqqsyqcyq5rqwzqfpg9scrgwpugpzysnrujsuw", false}, } for _, tt := range tests { - tt := tt s.T().Run(tt.name, func(t *testing.T) { got, err := types.Bech32ifyAddressBytes(tt.args.prefix, tt.args.bs) if (err != nil) != tt.wantErr { @@ -414,7 +424,6 @@ func (s *addressTestSuite) TestMustBech32ifyAddressBytes() { {"20-byte address", args{"prefixb", addr20byte}, "prefixb1qqqsyqcyq5rqwzqfpg9scrgwpugpzysnrujsuw", false}, } for _, tt := range tests { - tt := tt s.T().Run(tt.name, func(t *testing.T) { if tt.wantPanic { require.Panics(t, func() { types.MustBech32ifyAddressBytes(tt.args.prefix, tt.args.bs) }) @@ -437,25 +446,25 @@ func (s *addressTestSuite) TestAddressTypesEquals() { valAddr2 := types.ValAddress(addr2) // equality - s.Require().True(accAddr1.Equals(accAddr1)) - s.Require().True(consAddr1.Equals(consAddr1)) - s.Require().True(valAddr1.Equals(valAddr1)) + s.Require().True(accAddr1.Equals(accAddr1)) //nolint:gocritic // checking if these are the same + s.Require().True(consAddr1.Equals(consAddr1)) //nolint:gocritic // checking if these are the same + s.Require().True(valAddr1.Equals(valAddr1)) //nolint:gocritic // checking if these are the same // emptiness - s.Require().True(types.AccAddress{}.Equals(types.AccAddress{})) + s.Require().True(types.AccAddress{}.Equals(types.AccAddress{})) //nolint:gocritic // checking if these are the same s.Require().True(types.AccAddress{}.Equals(types.AccAddress(nil))) s.Require().True(types.AccAddress(nil).Equals(types.AccAddress{})) - s.Require().True(types.AccAddress(nil).Equals(types.AccAddress(nil))) + s.Require().True(types.AccAddress(nil).Equals(types.AccAddress(nil))) //nolint:gocritic // checking if these are the same - s.Require().True(types.ConsAddress{}.Equals(types.ConsAddress{})) + s.Require().True(types.ConsAddress{}.Equals(types.ConsAddress{})) //nolint:gocritic // checking if these are the same s.Require().True(types.ConsAddress{}.Equals(types.ConsAddress(nil))) s.Require().True(types.ConsAddress(nil).Equals(types.ConsAddress{})) - s.Require().True(types.ConsAddress(nil).Equals(types.ConsAddress(nil))) + s.Require().True(types.ConsAddress(nil).Equals(types.ConsAddress(nil))) //nolint:gocritic // checking if these are the same - s.Require().True(types.ValAddress{}.Equals(types.ValAddress{})) + s.Require().True(types.ValAddress{}.Equals(types.ValAddress{})) //nolint:gocritic // checking if these are the same s.Require().True(types.ValAddress{}.Equals(types.ValAddress(nil))) s.Require().True(types.ValAddress(nil).Equals(types.ValAddress{})) - s.Require().True(types.ValAddress(nil).Equals(types.ValAddress(nil))) + s.Require().True(types.ValAddress(nil).Equals(types.ValAddress(nil))) //nolint:gocritic // checking if these are the same s.Require().False(accAddr1.Equals(accAddr2)) s.Require().Equal(accAddr1.Equals(accAddr2), accAddr2.Equals(accAddr1)) @@ -492,7 +501,7 @@ func (s *addressTestSuite) TestMustAccAddressFromBech32() { addr := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} accBech := types.AccAddress(addr).String() res := types.MustAccAddressFromBech32(accBech) - s.Require().Equal(types.AccAddress(res).String(), accBech) + s.Require().Equal(res.String(), accBech) // Set a custom address verifier only accepts 20 byte addresses types.GetConfig().SetAddressVerifier(func(bz []byte) error { diff --git a/types/bech32/legacybech32/pk_test.go b/types/bech32/legacybech32/pk_test.go index 6f1c30bb87..3b08fcedd5 100644 --- a/types/bech32/legacybech32/pk_test.go +++ b/types/bech32/legacybech32/pk_test.go @@ -22,5 +22,4 @@ func TestBeach32ifPbKey(t *testing.T) { require.NoError(err) require.Equal("linkpub1addwnpepq27djm9tzq3sftqsayx95refxk8r5jn0kyshhql9mdjhjx829zlvzszgelc", pubKeyAddr, "Is your device using test mnemonic: %s ?", testdata.TestMnemonic) - } diff --git a/types/coin_benchmark_test.go b/types/coin_benchmark_test.go index 8c8088923e..9f86a96882 100644 --- a/types/coin_benchmark_test.go +++ b/types/coin_benchmark_test.go @@ -11,8 +11,9 @@ func coinName(suffix int) string { func BenchmarkCoinsAdditionIntersect(b *testing.B) { b.ReportAllocs() - benchmarkingFunc := func(numCoinsA int, numCoinsB int) func(b *testing.B) { + benchmarkingFunc := func(numCoinsA, numCoinsB int) func(b *testing.B) { return func(b *testing.B) { + b.Helper() b.ReportAllocs() coinsA := Coins(make([]Coin, numCoinsA)) coinsB := Coins(make([]Coin, numCoinsB)) @@ -42,8 +43,9 @@ func BenchmarkCoinsAdditionIntersect(b *testing.B) { func BenchmarkCoinsAdditionNoIntersect(b *testing.B) { b.ReportAllocs() - benchmarkingFunc := func(numCoinsA int, numCoinsB int) func(b *testing.B) { + benchmarkingFunc := func(numCoinsA, numCoinsB int) func(b *testing.B) { return func(b *testing.B) { + b.Helper() b.ReportAllocs() coinsA := Coins(make([]Coin, numCoinsA)) coinsB := Coins(make([]Coin, numCoinsB)) diff --git a/types/coin_test.go b/types/coin_test.go index 4af7a46e00..d64a51131c 100644 --- a/types/coin_test.go +++ b/types/coin_test.go @@ -135,7 +135,6 @@ func (s *coinTestSuite) TestAddCoin() { } for tcIndex, tc := range cases { - tc := tc if tc.shouldPanic { s.Require().Panics(func() { tc.inputOne.Add(tc.inputTwo) }) } else { @@ -175,7 +174,6 @@ func (s *coinTestSuite) TestSubCoin() { } for tcIndex, tc := range cases { - tc := tc if tc.shouldPanic { s.Require().Panics(func() { tc.inputOne.Sub(tc.inputTwo) }) } else { @@ -230,7 +228,6 @@ func (s *coinTestSuite) TestIsGTECoin() { } for tcIndex, tc := range cases { - tc := tc if tc.panics { s.Require().Panics(func() { tc.inputOne.IsGTE(tc.inputTwo) }) } else { @@ -256,7 +253,6 @@ func (s *coinTestSuite) TestIsLTCoin() { } for tcIndex, tc := range cases { - tc := tc if tc.panics { s.Require().Panics(func() { tc.inputOne.IsLT(tc.inputTwo) }) } else { @@ -485,7 +481,6 @@ func (s *coinTestSuite) TestSubCoins() { assert := s.Assert() for i, tc := range testCases { - tc := tc if tc.shouldPanic { assert.Panics(func() { tc.inputOne.Sub(tc.inputTwo) }) } else { @@ -1065,7 +1060,6 @@ func (s *coinTestSuite) TestCoinValidate() { } for _, tc := range testCases { - tc := tc t := s.T() t.Run(tc.name, func(t *testing.T) { err := tc.coin.Validate() diff --git a/types/context.go b/types/context.go index 2db74ffa03..5fe6681d47 100644 --- a/types/context.go +++ b/types/context.go @@ -4,13 +4,12 @@ import ( "context" "time" + ocbytes "github.com/Finschia/ostracon/libs/bytes" + "github.com/Finschia/ostracon/libs/log" "github.com/gogo/protobuf/proto" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocbytes "github.com/Finschia/ostracon/libs/bytes" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/store/gaskv" stypes "github.com/Finschia/finschia-sdk/store/types" ) diff --git a/types/context_test.go b/types/context_test.go index cc106e99bf..4530cf92eb 100644 --- a/types/context_test.go +++ b/types/context_test.go @@ -68,12 +68,6 @@ func (s *contextTestSuite) TestLogContext() { ctx.Logger().Error("error") } -type dummy int64 //nolint:unused - -func (d dummy) Clone() interface{} { - return d -} - // Testing saving/loading sdk type values to/from the context func (s *contextTestSuite) TestContextWithCustom() { var ctx types.Context @@ -197,7 +191,6 @@ func (s *contextTestSuite) TestContextHeaderClone() { } for name, tc := range cases { - tc := tc s.T().Run(name, func(t *testing.T) { ctx := types.NewContext(nil, tc.h, false, nil) s.Require().Equal(tc.h.Height, ctx.BlockHeight()) diff --git a/types/dec_coin.go b/types/dec_coin.go index 86b53f1607..9c8e6cf47d 100644 --- a/types/dec_coin.go +++ b/types/dec_coin.go @@ -630,7 +630,7 @@ func ParseDecCoin(coinStr string) (coin DecCoin, err error) { } if err := ValidateDenom(denomStr); err != nil { - return DecCoin{}, fmt.Errorf("invalid denom cannot contain upper case characters or spaces: %s", err) + return DecCoin{}, fmt.Errorf("invalid denom cannot contain upper case characters or spaces: %w", err) } return NewDecCoinFromDec(denomStr, amount), nil diff --git a/types/dec_coin_test.go b/types/dec_coin_test.go index 71673f9815..bb9addef5e 100644 --- a/types/dec_coin_test.go +++ b/types/dec_coin_test.go @@ -187,7 +187,6 @@ func (s *decCoinTestSuite) TestIsValid() { } for _, tc := range tests { - tc := tc if tc.expectPass { s.Require().True(tc.coin.IsValid(), tc.msg) } else { @@ -222,7 +221,6 @@ func (s *decCoinTestSuite) TestSubDecCoin() { decCoin := sdk.NewDecCoin("mytoken", sdk.NewInt(10)) for _, tc := range tests { - tc := tc if tc.expectPass { equal := tc.coin.Sub(decCoin) s.Require().Equal(equal, decCoin, tc.msg) @@ -258,7 +256,6 @@ func (s *decCoinTestSuite) TestSubDecCoins() { decCoins := sdk.NewDecCoinsFromCoins(sdk.NewCoin("btc", sdk.NewInt(10)), sdk.NewCoin("eth", sdk.NewInt(15)), sdk.NewCoin("mytoken", sdk.NewInt(5))) for _, tc := range tests { - tc := tc if tc.expectPass { equal := tc.coins.Sub(decCoins) s.Require().Equal(equal, decCoins, tc.msg) @@ -500,7 +497,6 @@ func (s *decCoinTestSuite) TestDecCoinsQuoDecTruncate() { } for i, tc := range testCases { - tc := tc if tc.panics { s.Require().Panics(func() { tc.coins.QuoDecTruncate(tc.input) }) } else { @@ -537,7 +533,6 @@ func (s *decCoinTestSuite) TestNewDecCoinsWithIsValid() { } for _, tc := range tests { - tc := tc if tc.expectPass { s.Require().True(tc.coin.IsValid(), tc.msg) } else { @@ -564,7 +559,6 @@ func (s *decCoinTestSuite) TestNewDecCoinsWithZeroCoins() { } for _, tc := range tests { - tc := tc s.Require().Equal(sdk.NewDecCoinsFromCoins(tc.coins...).Len(), tc.expectLength) } } @@ -596,7 +590,6 @@ func (s *decCoinTestSuite) TestDecCoins_AddDecCoinWithIsValid() { } for _, tc := range tests { - tc := tc if tc.expectPass { s.Require().True(tc.coin.IsValid(), tc.msg) } else { diff --git a/types/decimal.go b/types/decimal.go index 3ebdb5c727..c1d056e9a6 100644 --- a/types/decimal.go +++ b/types/decimal.go @@ -671,7 +671,11 @@ var nilJSON []byte func init() { empty := new(big.Int) bz, _ := empty.MarshalText() - nilJSON, _ = json.Marshal(string(bz)) + var err error + nilJSON, err = json.Marshal(string(bz)) + if err != nil { + panic(err) + } } // MarshalJSON marshals the decimal @@ -740,7 +744,7 @@ func (d *Dec) MarshalTo(data []byte) (n int, err error) { // Unmarshal implements the gogo proto custom type interface. func (d *Dec) Unmarshal(data []byte) error { if len(data) == 0 { - d = nil + d = nil //nolint: wastedassign return nil } @@ -807,5 +811,6 @@ func MaxDec(d1, d2 Dec) Dec { // intended to be used with require/assert: require.True(DecEq(...)) func DecEq(t *testing.T, exp, got Dec) (*testing.T, bool, string, string, string) { + t.Helper() return t, exp.Equal(got), "expected:\t%v\ngot:\t\t%v", exp.String(), got.String() } diff --git a/types/decimal_internal_test.go b/types/decimal_internal_test.go index f033dd4088..23805998b1 100644 --- a/types/decimal_internal_test.go +++ b/types/decimal_internal_test.go @@ -24,7 +24,7 @@ func (s *decimalInternalTestSuite) TestPrecisionMultiplier() { } func (s *decimalInternalTestSuite) TestZeroDeserializationJSON() { - var cdc = codec.NewLegacyAmino() + cdc := codec.NewLegacyAmino() d := Dec{new(big.Int)} err := cdc.UnmarshalJSON([]byte(`"0"`), &d) s.Require().Nil(err) @@ -33,7 +33,7 @@ func (s *decimalInternalTestSuite) TestZeroDeserializationJSON() { } func (s *decimalInternalTestSuite) TestSerializationGocodecJSON() { - var cdc = codec.NewLegacyAmino() + cdc := codec.NewLegacyAmino() d := MustNewDecFromStr("0.333") bz, err := cdc.MarshalJSON(d) @@ -67,7 +67,6 @@ func (s *decimalInternalTestSuite) TestDecMarshalJSON() { {"12340Int", NewDec(12340), "\"12340.000000000000000000\"", false}, } for _, tt := range tests { - tt := tt s.T().Run(tt.name, func(t *testing.T) { got, err := tt.d.MarshalJSON() if (err != nil) != tt.wantErr { @@ -75,7 +74,7 @@ func (s *decimalInternalTestSuite) TestDecMarshalJSON() { return } if !tt.wantErr { - s.Require().Equal(tt.want, string(got), "incorrect marshalled value") + s.Require().Equal(tt.want, string(got), "incorrect marshaled value") unmarshalledDec := NewDec(0) err := unmarshalledDec.UnmarshalJSON(got) s.Require().NoError(err) diff --git a/types/decimal_test.go b/types/decimal_test.go index 33c8ada40d..8c49a3c066 100644 --- a/types/decimal_test.go +++ b/types/decimal_test.go @@ -236,7 +236,6 @@ func (s *decimalTestSuite) TestArithmetic() { } for tcIndex, tc := range tests { - tc := tc resAdd := tc.d1.Add(tc.d2) resSub := tc.d1.Sub(tc.d2) resMul := tc.d1.Mul(tc.d2) @@ -606,10 +605,8 @@ func BenchmarkMarshalTo(b *testing.B) { for _, bi := range bis { if n, err := bi.in.MarshalTo(data); err != nil { b.Fatal(err) - } else { - if !bytes.Equal(data[:n], bi.want) { - b.Fatalf("Mismatch\nGot: % x\nWant: % x\n", data[:n], bi.want) - } + } else if !bytes.Equal(data[:n], bi.want) { + b.Fatalf("Mismatch\nGot: % x\nWant: % x\n", data[:n], bi.want) } } } diff --git a/types/denom_internal_test.go b/types/denom_internal_test.go index 8c957353eb..d135d0a765 100644 --- a/types/denom_internal_test.go +++ b/types/denom_internal_test.go @@ -180,6 +180,7 @@ func (s *internalDenomTestSuite) TestDecOperationOrder() { s.Require().NoError(err) s.Require().NoError(RegisterDenom("unit1", dec)) dec, err = NewDecFromStr("100000011") + s.Require().NoError(err) s.Require().NoError(RegisterDenom("unit2", dec)) coin, err := ConvertCoin(NewCoin("unit1", NewInt(100000011)), "unit2") diff --git a/types/errors/abci.go b/types/errors/abci.go index bcfb37977c..16d3662581 100644 --- a/types/errors/abci.go +++ b/types/errors/abci.go @@ -4,9 +4,8 @@ import ( "fmt" "reflect" - abci "github.com/tendermint/tendermint/abci/types" - ocabci "github.com/Finschia/ostracon/abci/types" + abci "github.com/tendermint/tendermint/abci/types" ) const ( diff --git a/types/errors/abci_test.go b/types/errors/abci_test.go index 996e9c34e5..c886e3917c 100644 --- a/types/errors/abci_test.go +++ b/types/errors/abci_test.go @@ -66,12 +66,12 @@ func (s *abciTestSuite) TestABCInfo() { }, // This is hard to test because of attached stacktrace. This // case is tested in an another test. - //"wrapped stdlib is a full message in debug mode": { + // "wrapped stdlib is a full message in debug mode": { // err: Wrap(io.EOF, "cannot read file"), // debug: true, // wantLog: "cannot read file: EOF", // wantCode: 1, - //}, + // }, "custom error": { err: customErr{}, debug: false, @@ -181,7 +181,6 @@ func (s *abciTestSuite) TestABCIInfoSerializeErr() { }, } for msg, spec := range specs { - spec := spec _, _, log := ABCIInfo(spec.src, spec.debug) s.Require().Equal(spec.exp, log, msg) } diff --git a/types/errors/errors.go b/types/errors/errors.go index 8b1a017662..13bd3ab6f8 100644 --- a/types/errors/errors.go +++ b/types/errors/errors.go @@ -15,7 +15,7 @@ const UndefinedCodespace = "undefined" var ( // errInternal should never be exposed, but we reserve this code for non-specified errors - errInternal = Register(UndefinedCodespace, 1, "internal") //nolint:deadcode,unused,varcheck + errInternal = Register(UndefinedCodespace, 1, "internal") //nolint:deadcode,varcheck // ErrTxDecode is returned if we cannot parse a transaction ErrTxDecode = Register(RootCodespace, 2, "tx parse error") @@ -61,7 +61,7 @@ var ( // ErrNoSignatures to doc ErrNoSignatures = Register(RootCodespace, 15, "no signatures supplied") - // ErrJSONMarshal defines an ABCI typed JSON marshalling error + // ErrJSONMarshal defines an ABCI typed JSON marshaling error ErrJSONMarshal = Register(RootCodespace, 16, "failed to marshal JSON bytes") // ErrJSONUnmarshal defines an ABCI typed JSON unmarshalling error diff --git a/types/events.go b/types/events.go index 3e0f5c7acb..8cb7f940bc 100644 --- a/types/events.go +++ b/types/events.go @@ -7,12 +7,11 @@ import ( "sort" "strings" - "golang.org/x/exp/maps" - "golang.org/x/exp/slices" - "github.com/gogo/protobuf/jsonpb" proto "github.com/gogo/protobuf/proto" abci "github.com/tendermint/tendermint/abci/types" + "golang.org/x/exp/maps" + "golang.org/x/exp/slices" "github.com/Finschia/finschia-sdk/codec" ) diff --git a/types/events_test.go b/types/events_test.go index 45513e6fd9..334846981e 100644 --- a/types/events_test.go +++ b/types/events_test.go @@ -247,7 +247,6 @@ func (s *eventsTestSuite) TestMarkEventsToIndex() { } for name, tc := range testCases { - tc := tc s.T().Run(name, func(_ *testing.T) { s.Require().Equal(tc.expected, sdk.MarkEventsToIndex(tc.events, tc.indexSet)) }) diff --git a/types/int.go b/types/int.go index a13e19aa0a..a79da3456f 100644 --- a/types/int.go +++ b/types/int.go @@ -14,31 +14,31 @@ func newIntegerFromString(s string) (*big.Int, bool) { return new(big.Int).SetString(s, 0) } -func equal(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) == 0 } +func equal(i, i2 *big.Int) bool { return i.Cmp(i2) == 0 } -func gt(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) == 1 } +func gt(i, i2 *big.Int) bool { return i.Cmp(i2) == 1 } -func gte(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) >= 0 } +func gte(i, i2 *big.Int) bool { return i.Cmp(i2) >= 0 } -func lt(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) == -1 } +func lt(i, i2 *big.Int) bool { return i.Cmp(i2) == -1 } -func lte(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) <= 0 } +func lte(i, i2 *big.Int) bool { return i.Cmp(i2) <= 0 } -func add(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Add(i, i2) } +func add(i, i2 *big.Int) *big.Int { return new(big.Int).Add(i, i2) } -func sub(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Sub(i, i2) } +func sub(i, i2 *big.Int) *big.Int { return new(big.Int).Sub(i, i2) } -func mul(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Mul(i, i2) } +func mul(i, i2 *big.Int) *big.Int { return new(big.Int).Mul(i, i2) } -func div(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Quo(i, i2) } +func div(i, i2 *big.Int) *big.Int { return new(big.Int).Quo(i, i2) } -func mod(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Mod(i, i2) } +func mod(i, i2 *big.Int) *big.Int { return new(big.Int).Mod(i, i2) } func neg(i *big.Int) *big.Int { return new(big.Int).Neg(i) } func abs(i *big.Int) *big.Int { return new(big.Int).Abs(i) } -func min(i *big.Int, i2 *big.Int) *big.Int { +func min(i, i2 *big.Int) *big.Int { if i.Cmp(i2) == 1 { return new(big.Int).Set(i2) } @@ -46,7 +46,7 @@ func min(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Set(i) } -func max(i *big.Int, i2 *big.Int) *big.Int { +func max(i, i2 *big.Int) *big.Int { if i.Cmp(i2) == -1 { return new(big.Int).Set(i2) } @@ -403,7 +403,7 @@ func (i *Int) MarshalTo(data []byte) (n int, err error) { // Unmarshal implements the gogo proto custom type interface. func (i *Int) Unmarshal(data []byte) error { if len(data) == 0 { - i = nil + i = nil //nolint: wastedassign return nil } @@ -434,6 +434,7 @@ func (i *Int) UnmarshalAmino(bz []byte) error { return i.Unmarshal(bz) } // intended to be used with require/assert: require.True(IntEq(...)) func IntEq(t *testing.T, exp, got Int) (*testing.T, bool, string, string, string) { + t.Helper() return t, exp.Equal(got), "expected:\t%v\ngot:\t\t%v", exp.String(), got.String() } diff --git a/types/int_test.go b/types/int_test.go index bdf7a62eca..59513f258c 100644 --- a/types/int_test.go +++ b/types/int_test.go @@ -404,7 +404,6 @@ func TestRoundTripMarshalToInt(t *testing.T) { } for _, value := range values { - value := value t.Run(fmt.Sprintf("%d", value), func(t *testing.T) { t.Parallel() diff --git a/types/module/configurator.go b/types/module/configurator.go index 102328e900..6a440b9eb5 100644 --- a/types/module/configurator.go +++ b/types/module/configurator.go @@ -46,7 +46,7 @@ type configurator struct { } // NewConfigurator returns a new Configurator instance -func NewConfigurator(cdc codec.Codec, msgServer grpc.Server, queryServer grpc.Server) Configurator { +func NewConfigurator(cdc codec.Codec, msgServer, queryServer grpc.Server) Configurator { return configurator{ cdc: cdc, msgServer: msgServer, diff --git a/types/module/module.go b/types/module/module.go index 8d932455f9..0a257e3302 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -33,10 +33,9 @@ import ( "fmt" "sort" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" - - ocabci "github.com/Finschia/ostracon/abci/types" abci "github.com/tendermint/tendermint/abci/types" "golang.org/x/exp/maps" diff --git a/types/module/module_int_test.go b/types/module/module_int_test.go index 3301a9926d..5c3a8dee64 100644 --- a/types/module/module_int_test.go +++ b/types/module/module_int_test.go @@ -15,7 +15,7 @@ type TestSuite struct { suite.Suite } -func (s TestSuite) TestAssertNoForgottenModules() { +func (s *TestSuite) TestAssertNoForgottenModules() { m := Manager{ Modules: map[string]AppModule{"a": nil, "b": nil}, } @@ -37,7 +37,7 @@ func (s TestSuite) TestAssertNoForgottenModules() { } } -func (s TestSuite) TestModuleNames() { +func (s *TestSuite) TestModuleNames() { m := Manager{ Modules: map[string]AppModule{"a": nil, "b": nil}, } @@ -46,7 +46,7 @@ func (s TestSuite) TestModuleNames() { s.Require().Equal([]string{"a", "b"}, ms) } -func (s TestSuite) TestDefaultMigrationsOrder() { +func (s *TestSuite) TestDefaultMigrationsOrder() { require := s.Require() require.Equal( []string{"auth2", "d", "z", "auth"}, diff --git a/types/module/module_test.go b/types/module/module_test.go index 5f0f54bc4e..8b0c93b435 100644 --- a/types/module/module_test.go +++ b/types/module/module_test.go @@ -5,16 +5,14 @@ import ( "errors" "testing" - "github.com/Finschia/finschia-sdk/codec/types" - ocabci "github.com/Finschia/ostracon/abci/types" "github.com/golang/mock/gomock" "github.com/spf13/cobra" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" - "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/codec" + "github.com/Finschia/finschia-sdk/codec/types" "github.com/Finschia/finschia-sdk/tests/mocks" sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/types/module" @@ -29,8 +27,6 @@ func TestBasicManager(t *testing.T) { interfaceRegistry := types.NewInterfaceRegistry() cdc := codec.NewProtoCodec(interfaceRegistry) - clientCtx := client.Context{} - clientCtx = clientCtx.WithLegacyAmino(legacyAmino) wantDefaultGenesis := map[string]json.RawMessage{"mockAppModuleBasic1": json.RawMessage(``)} mockAppModuleBasic1 := mocks.NewMockAppModuleBasic(mockCtrl) diff --git a/types/query/filtered_pagination.go b/types/query/filtered_pagination.go index f3597eef11..c061aa8d94 100644 --- a/types/query/filtered_pagination.go +++ b/types/query/filtered_pagination.go @@ -18,7 +18,7 @@ import ( func FilteredPaginate( prefixStore types.KVStore, pageRequest *PageRequest, - onResult func(key []byte, value []byte, accumulate bool) (bool, error), + onResult func(key, value []byte, accumulate bool) (bool, error), ) (*PageResponse, error) { // if the PageRequest is nil, use default PageRequest if pageRequest == nil { @@ -126,7 +126,7 @@ func FilteredPaginate( // If offset is used, the pagination uses lazy filtering i.e., searches through all the records. // The resulting slice (of type F) can be of a different type than the one being iterated through // (type T), so it's possible to do any necessary transformation inside the onResult function. -func GenericFilteredPaginate[T codec.ProtoMarshaler, F codec.ProtoMarshaler]( +func GenericFilteredPaginate[T, F codec.ProtoMarshaler]( cdc codec.BinaryCodec, prefixStore types.KVStore, pageRequest *PageRequest, diff --git a/types/query/filtered_pagination_test.go b/types/query/filtered_pagination_test.go index 232aad83a1..90df88d680 100644 --- a/types/query/filtered_pagination_test.go +++ b/types/query/filtered_pagination_test.go @@ -57,7 +57,7 @@ func (s *paginationTestSuite) TestFilteredPaginations() { s.Require().NotNil(res) s.Require().Equal(2, len(balances)) s.Require().NotNil(res.NextKey) - s.Require().Equal(string(res.NextKey), fmt.Sprintf("test2denom")) + s.Require().Equal(string(res.NextKey), "test2denom") s.Require().Equal(uint64(4), res.Total) s.T().Log("verify both key and offset can't be given") @@ -140,7 +140,7 @@ func (s *paginationTestSuite) TestReverseFilteredPaginations() { s.Require().NotNil(res) s.Require().Equal(2, len(balns)) s.Require().NotNil(res.NextKey) - s.Require().Equal(string(res.NextKey), fmt.Sprintf("test7denom")) + s.Require().Equal(string(res.NextKey), "test7denom") s.Require().Equal(uint64(10), res.Total) s.T().Log("verify both key and offset can't be given") @@ -155,7 +155,7 @@ func (s *paginationTestSuite) TestReverseFilteredPaginations() { s.Require().NotNil(res) s.Require().Equal(2, len(balns)) s.Require().NotNil(res.NextKey) - s.Require().Equal(string(res.NextKey), fmt.Sprintf("test5denom")) + s.Require().Equal(string(res.NextKey), "test5denom") s.T().Log("verify last page records, nextKey for query and reverse true") pageReq = &query.PageRequest{Key: res.NextKey, Reverse: true} @@ -198,7 +198,7 @@ func ExampleFilteredPaginate() { accountStore := prefix.NewStore(balancesStore, address.MustLengthPrefix(addr1)) var balResult sdk.Coins - pageRes, err := query.FilteredPaginate(accountStore, pageReq, func(key []byte, value []byte, accumulate bool) (bool, error) { + pageRes, err := query.FilteredPaginate(accountStore, pageReq, func(key, value []byte, accumulate bool) (bool, error) { var bal sdk.Coin err := appCodec.Unmarshal(value, &bal) if err != nil { @@ -229,7 +229,7 @@ func execFilterPaginate(store sdk.KVStore, pageReq *query.PageRequest, appCodec accountStore := prefix.NewStore(balancesStore, address.MustLengthPrefix(addr1)) var balResult sdk.Coins - res, err = query.FilteredPaginate(accountStore, pageReq, func(key []byte, value []byte, accumulate bool) (bool, error) { + res, err = query.FilteredPaginate(accountStore, pageReq, func(key, value []byte, accumulate bool) (bool, error) { var bal sdk.Coin err := appCodec.Unmarshal(value, &bal) if err != nil { diff --git a/types/query/pagination.go b/types/query/pagination.go index cf74e8bb79..720b2218e6 100644 --- a/types/query/pagination.go +++ b/types/query/pagination.go @@ -4,11 +4,10 @@ import ( "fmt" "math" + dbm "github.com/tendermint/tm-db" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - dbm "github.com/tendermint/tm-db" - "github.com/Finschia/finschia-sdk/store/types" ) @@ -53,7 +52,7 @@ func ParsePagination(pageReq *PageRequest) (page, limit int, err error) { func Paginate( prefixStore types.KVStore, pageRequest *PageRequest, - onResult func(key []byte, value []byte) error, + onResult func(key, value []byte) error, ) (*PageResponse, error) { // if the PageRequest is nil, use default PageRequest if pageRequest == nil { diff --git a/types/query/pagination_test.go b/types/query/pagination_test.go index 615af19a9e..b57d5c2859 100644 --- a/types/query/pagination_test.go +++ b/types/query/pagination_test.go @@ -155,7 +155,7 @@ func (s *paginationTestSuite) TestPagination() { s.T().Log("verify paginate with offset and key - error") pageReq = &query.PageRequest{Key: res.Pagination.NextKey, Offset: 100, Limit: defaultLimit, CountTotal: false} request = types.NewQueryAllBalancesRequest(addr1, pageReq) - res, err = queryClient.AllBalances(gocontext.Background(), request) + _, err = queryClient.AllBalances(gocontext.Background(), request) s.Require().Error(err) s.Require().Equal("rpc error: code = InvalidArgument desc = paginate: invalid request, either offset or key is expected, got both", err.Error()) @@ -279,7 +279,7 @@ func (s *paginationTestSuite) TestReversePagination() { s.T().Log("verify paginate with offset and key - error") pageReq = &query.PageRequest{Key: res1.Pagination.NextKey, Offset: 100, Limit: defaultLimit, CountTotal: false} request = types.NewQueryAllBalancesRequest(addr1, pageReq) - res, err = queryClient.AllBalances(gocontext.Background(), request) + _, err = queryClient.AllBalances(gocontext.Background(), request) s.Require().Error(err) s.Require().Equal("rpc error: code = InvalidArgument desc = paginate: invalid request, either offset or key is expected, got both", err.Error()) @@ -317,7 +317,7 @@ func ExamplePaginate() { authStore := ctx.KVStore(app.GetKey(types.StoreKey)) balancesStore := prefix.NewStore(authStore, types.BalancesPrefix) accountStore := prefix.NewStore(balancesStore, address.MustLengthPrefix(addr1)) - pageRes, err := query.Paginate(accountStore, request.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(accountStore, request.Pagination, func(key, value []byte) error { var tempRes sdk.Coin err := app.AppCodec().Unmarshal(value, &tempRes) if err != nil { @@ -342,7 +342,10 @@ func setupTest() (*simapp.SimApp, sdk.Context, codec.Codec) { db := dbm.NewMemDB() ms := store.NewCommitMultiStore(db) - ms.LoadLatestVersion() + err := ms.LoadLatestVersion() + if err != nil { + panic(err) + } return app, ctx, appCodec } diff --git a/types/result.go b/types/result.go index 11328d07d7..cf3b33c728 100644 --- a/types/result.go +++ b/types/result.go @@ -6,9 +6,8 @@ import ( "math" "strings" - "github.com/gogo/protobuf/proto" - ctypes "github.com/Finschia/ostracon/rpc/core/types" + "github.com/gogo/protobuf/proto" abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/codec" diff --git a/types/result_test.go b/types/result_test.go index fcd3872a21..2c142752cf 100644 --- a/types/result_test.go +++ b/types/result_test.go @@ -6,15 +6,14 @@ import ( "strings" "testing" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/ostracon/libs/bytes" + ctypes "github.com/Finschia/ostracon/rpc/core/types" "github.com/golang/protobuf/proto" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" abci "github.com/tendermint/tendermint/abci/types" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/ostracon/libs/bytes" - ctypes "github.com/Finschia/ostracon/rpc/core/types" - "github.com/Finschia/finschia-sdk/codec" "github.com/Finschia/finschia-sdk/testutil/testdata" sdk "github.com/Finschia/finschia-sdk/types" diff --git a/types/simulation/account_test.go b/types/simulation/account_test.go index 210a8b9c8b..fa3229ca14 100644 --- a/types/simulation/account_test.go +++ b/types/simulation/account_test.go @@ -24,7 +24,6 @@ func TestRandomAccounts(t *testing.T) { {"100-accounts", 100, 100}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { got := simulation.RandomAccounts(r, tt.n) require.Equal(t, tt.want, len(got)) @@ -65,8 +64,6 @@ func TestRandomFees(t *testing.T) { {"0 coins", sdk.NewCoins(sdk.NewInt64Coin("aaa", 10), sdk.NewInt64Coin("bbb", 5)), false, false}, } for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { got, err := simulation.RandomFees(r, sdk.Context{}, tt.spendableCoins) if (err != nil) != tt.wantErr { diff --git a/types/simulation/rand_util_test.go b/types/simulation/rand_util_test.go index d46f481fda..860bfb172f 100644 --- a/types/simulation/rand_util_test.go +++ b/types/simulation/rand_util_test.go @@ -23,7 +23,6 @@ func TestRandSubsetCoins(t *testing.T) { {"seed=99", rand.New(rand.NewSource(99)), mustParseCoins("100stake,2testtoken")}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { got := simulation.RandSubsetCoins(tt.r, tt.coins) gotStringRep := got.String() @@ -46,8 +45,6 @@ func TestRandStringOfLength(t *testing.T) { {"1_000_000-size", 1_000_000, 1_000_000}, } for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { got := simulation.RandStringOfLength(r, tt.n) require.Equal(t, tt.want, len(got)) diff --git a/types/staking.go b/types/staking.go index 2f17bb1dd8..e3e19cfaeb 100644 --- a/types/staking.go +++ b/types/staking.go @@ -22,7 +22,7 @@ const ( var DefaultPowerReduction = NewIntFromUint64(1000000) // TokensToConsensusPower - convert input tokens to potential consensus-engine power -func TokensToConsensusPower(tokens Int, powerReduction Int) int64 { +func TokensToConsensusPower(tokens, powerReduction Int) int64 { return (tokens.Quo(powerReduction)).Int64() } diff --git a/types/store.go b/types/store.go index 46b73e9701..1cd2526603 100644 --- a/types/store.go +++ b/types/store.go @@ -54,7 +54,7 @@ func KVStoreReversePrefixIteratorPaginated(kvs KVStore, prefix []byte, page, lim // DiffKVStores compares two KVstores and returns all the key/value pairs // that differ from one another. It also skips value comparison for a set of provided prefixes -func DiffKVStores(a KVStore, b KVStore, prefixesToSkip [][]byte) (kvAs, kvBs []kv.Pair) { +func DiffKVStores(a, b KVStore, prefixesToSkip [][]byte) (kvAs, kvBs []kv.Pair) { return types.DiffKVStores(a, b, prefixesToSkip) } diff --git a/types/store_test.go b/types/store_test.go index a2a25db755..b8a41fc8af 100644 --- a/types/store_test.go +++ b/types/store_test.go @@ -3,11 +3,10 @@ package types_test import ( "testing" + "github.com/Finschia/ostracon/libs/log" "github.com/stretchr/testify/suite" dbm "github.com/tendermint/tm-db" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/store/rootmulti" "github.com/Finschia/finschia-sdk/store/types" sdk "github.com/Finschia/finschia-sdk/types" @@ -64,8 +63,6 @@ func (s *storeTestSuite) TestNewTransientStoreKeys() { func (s *storeTestSuite) TestNewInfiniteGasMeter() { gm := sdk.NewInfiniteGasMeter() s.Require().NotNil(gm) - _, ok := gm.(types.GasMeter) - s.Require().True(ok) } func (s *storeTestSuite) TestStoreTypes() { diff --git a/types/tx/types.go b/types/tx/types.go index fe5c07ee68..1e9646e956 100644 --- a/types/tx/types.go +++ b/types/tx/types.go @@ -13,8 +13,10 @@ import ( const MaxGasWanted = uint64((1 << 63) - 1) // Interface implementation checks. -var _, _, _, _ codectypes.UnpackInterfacesMessage = &Tx{}, &TxBody{}, &AuthInfo{}, &SignerInfo{} -var _ sdk.Tx = &Tx{} +var ( + _, _, _, _ codectypes.UnpackInterfacesMessage = &Tx{}, &TxBody{}, &AuthInfo{}, &SignerInfo{} + _ sdk.Tx = &Tx{} +) // GetMsgs implements the GetMsgs method on sdk.Tx. func (t *Tx) GetMsgs() []sdk.Msg { diff --git a/types/uint.go b/types/uint.go index ac5f6d5e7a..4eeb3cd9ec 100644 --- a/types/uint.go +++ b/types/uint.go @@ -22,7 +22,7 @@ func (u Uint) BigInt() *big.Int { func NewUintFromBigInt(i *big.Int) Uint { u, err := checkNewUint(i) if err != nil { - panic(fmt.Errorf("overflow: %s", err)) + panic(fmt.Errorf("overflow: %w", err)) } return u } @@ -178,7 +178,7 @@ func (u *Uint) MarshalTo(data []byte) (n int, err error) { // Unmarshal implements the gogo proto custom type interface. func (u *Uint) Unmarshal(data []byte) error { if len(data) == 0 { - u = nil + u = nil //nolint: wastedassign return nil } @@ -237,7 +237,7 @@ func checkNewUint(i *big.Int) (Uint, error) { // RelativePow raises x to the power of n, where x (and the result, z) are scaled by factor b // for example, RelativePow(210, 2, 100) = 441 (2.1^2 = 4.41) -func RelativePow(x Uint, n Uint, b Uint) (z Uint) { +func RelativePow(x, n, b Uint) (z Uint) { if x.IsZero() { if n.IsZero() { z = b // 0^0 = 1 diff --git a/types/uint_test.go b/types/uint_test.go index 796dd2b428..dd46e16ae9 100644 --- a/types/uint_test.go +++ b/types/uint_test.go @@ -216,7 +216,6 @@ func (s *uintTestSuite) TestSafeSub() { } for i, tc := range testCases { - tc := tc if tc.panic { s.Require().Panics(func() { tc.x.Sub(tc.y) }) continue @@ -304,7 +303,6 @@ func TestRoundTripMarshalToUint(t *testing.T) { } for _, value := range values { - value := value t.Run(fmt.Sprintf("%d", value), func(t *testing.T) { t.Parallel() diff --git a/types/utils_test.go b/types/utils_test.go index 253db8e696..391dc4eb71 100644 --- a/types/utils_test.go +++ b/types/utils_test.go @@ -54,7 +54,6 @@ func (s *utilsTestSuite) TestSortJSON() { } for tcIndex, tc := range cases { - tc := tc got, err := sdk.SortJSON([]byte(tc.unsortedJSON)) if tc.wantErr { s.Require().NotNil(err, "tc #%d", tcIndex) @@ -79,7 +78,6 @@ func (s *utilsTestSuite) TestTimeFormatAndParse() { {"2011-01-10T23:10:05.758230235Z", "2011-01-10T23:10:05.758230235", true}, } for _, tc := range cases { - tc := tc timeFromRFC, err := time.Parse(time.RFC3339Nano, tc.RFC3339NanoStr) s.Require().Nil(err) timeFromSDKFormat, err := time.Parse(sdk.SortableTimeFormat, tc.SDKSortableTimeStr) diff --git a/x/auth/ante/ante_test.go b/x/auth/ante/ante_test.go index 2eac467676..28d7e82d86 100644 --- a/x/auth/ante/ante_test.go +++ b/x/auth/ante/ante_test.go @@ -844,7 +844,8 @@ func (suite *AnteTestSuite) TestAnteHandlerSetPubKey() { privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[1].priv}, []uint64{1}, []uint64{0} msgs = []sdk.Msg{testdata.NewTestMsg(accounts[1].acc.GetAddress())} - suite.txBuilder.SetMsgs(msgs...) + err := suite.txBuilder.SetMsgs(msgs...) + suite.Require().NoError(err) suite.txBuilder.SetFeeAmount(feeAmount) suite.txBuilder.SetGasLimit(gasLimit) @@ -904,9 +905,9 @@ func generatePubKeysAndSignatures(n int, msg []byte, _ bool) (pubkeys []cryptoty // TODO: also generate ed25519 keys as below when ed25519 keys are // actually supported, https://github.com/cosmos/cosmos-sdk/issues/4789 // for now this fails: - //if rand.Int63()%2 == 0 { + // if rand.Int63()%2 == 0 { // privkey = ed25519.GenPrivKey() - //} else { + // } else { // privkey = secp256k1.GenPrivKey() //} @@ -1100,7 +1101,7 @@ func (suite *AnteTestSuite) TestAnteHandlerReCheck() { tx, err = suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) suite.Require().NoError(err) txBytes, err := json.Marshal(tx) - suite.Require().Nil(err, "Error marshalling tx: %v", err) + suite.Require().Nil(err, "Error marshaling tx: %v", err) suite.ctx = suite.ctx.WithTxBytes(txBytes) // require that state machine param-dependent checking is still run on recheck since parameters can change between check and recheck diff --git a/x/auth/ante/basic_test.go b/x/auth/ante/basic_test.go index 995b3efe9b..5ac84f506a 100644 --- a/x/auth/ante/basic_test.go +++ b/x/auth/ante/basic_test.go @@ -198,8 +198,6 @@ func (suite *AnteTestSuite) TestTxHeightTimeoutDecorator() { } for _, tc := range testCases { - tc := tc - suite.Run(tc.name, func() { suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() diff --git a/x/auth/ante/fee_test.go b/x/auth/ante/fee_test.go index efb17da404..095ad3bab5 100644 --- a/x/auth/ante/fee_test.go +++ b/x/auth/ante/fee_test.go @@ -2,9 +2,8 @@ package ante_test import ( cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" - "github.com/Finschia/finschia-sdk/testutil/testdata" - "github.com/Finschia/finschia-sdk/simapp" + "github.com/Finschia/finschia-sdk/testutil/testdata" sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/x/auth/ante" ) diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index d168be7eec..49529ac348 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -308,11 +308,11 @@ func (svd *SigVerificationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simu if !simulate { if !genesis { sigKey := fmt.Sprintf("%d:%d", signerData.AccountNumber, signerData.Sequence) - // TODO could we use `tx.(*wrapper).getBodyBytes()` instead of `ctx.TxBytes()`? + // TODO: could we use `tx.(*wrapper).getBodyBytes()` instead of `ctx.TxBytes()`? txHash := sha256.Sum256(ctx.TxBytes()) - stored := false + var stored bool - // TODO(duong2): Does this really improve performance? + // TODO: Does this really improve performance? stored, err = svd.verifySignatureWithCache(ctx, pubKey, signerData, sig.Data, tx, sigKey, txHash[:]) if stored { diff --git a/x/auth/ante/sigverify_test.go b/x/auth/ante/sigverify_test.go index 5fc21f2457..4f8b986d2b 100644 --- a/x/auth/ante/sigverify_test.go +++ b/x/auth/ante/sigverify_test.go @@ -76,7 +76,7 @@ func (suite *AnteTestSuite) TestConsumeSignatureVerificationGas() { multisignature1 := multisig.NewMultisig(len(pkSet1)) expectedCost1 := expectedGasCostByKeys(pkSet1) for i := 0; i < len(pkSet1); i++ { - stdSig := legacytx.StdSignature{PubKey: pkSet1[i], Signature: sigSet1[i]} + stdSig := legacytx.StdSignature{PubKey: pkSet1[i], Signature: sigSet1[i]} //nolint:staticcheck // this will be removed when proto is ready sigV2, err := legacytx.StdSignatureToSignatureV2(cdc, stdSig) suite.Require().NoError(err) err = multisig.AddSignatureV2(multisignature1, sigV2, pkSet1) @@ -188,7 +188,8 @@ func (suite *AnteTestSuite) TestSigVerification() { }, Sequence: tc.accSeqs[0], } - suite.txBuilder.SetSignatures(txSigs...) + err := suite.txBuilder.SetSignatures(txSigs...) + suite.Require().NoError(err) tx = suite.txBuilder.GetTx() } diff --git a/x/auth/ante/testutil_test.go b/x/auth/ante/testutil_test.go index da57cc93f3..6b61baef97 100644 --- a/x/auth/ante/testutil_test.go +++ b/x/auth/ante/testutil_test.go @@ -17,14 +17,13 @@ import ( "github.com/Finschia/finschia-sdk/types/tx/signing" "github.com/Finschia/finschia-sdk/x/auth/ante" xauthsigning "github.com/Finschia/finschia-sdk/x/auth/signing" - "github.com/Finschia/finschia-sdk/x/auth/types" authtypes "github.com/Finschia/finschia-sdk/x/auth/types" minttypes "github.com/Finschia/finschia-sdk/x/mint/types" ) // TestAccount represents an account used in the tests in x/auth/ante. type TestAccount struct { - acc types.AccountI + acc authtypes.AccountI priv cryptotypes.PrivKey } @@ -103,7 +102,7 @@ func (suite *AnteTestSuite) CreateTestAccounts(numAccs int) []TestAccount { } // CreateTestTx is a helper function to create a tx given multiple inputs. -func (suite *AnteTestSuite) CreateTestTx(privs []cryptotypes.PrivKey, accNums []uint64, accSeqs []uint64, chainID string) (xauthsigning.Tx, error) { +func (suite *AnteTestSuite) CreateTestTx(privs []cryptotypes.PrivKey, accNums, accSeqs []uint64, chainID string) (xauthsigning.Tx, error) { // First round: we gather all the signer infos. We use the "set empty // signature" hack to do that. var sigsV2 []signing.SignatureV2 diff --git a/x/auth/client/cli/query.go b/x/auth/client/cli/query.go index 4314d1ac93..574463ce24 100644 --- a/x/auth/client/cli/query.go +++ b/x/auth/client/cli/query.go @@ -246,7 +246,7 @@ $ %s query txs --%s 'message.sender=link1...&message.action=withdraw_delegator_r cmd.Flags().Int(flags.FlagPage, query.DefaultPage, "Query a specific page of paginated results") cmd.Flags().Int(flags.FlagLimit, query.DefaultLimit, "Query number of transactions results per page returned") cmd.Flags().String(flagEvents, "", fmt.Sprintf("list of transaction events in the form of %s", eventFormat)) - cmd.MarkFlagRequired(flagEvents) + _ = cmd.MarkFlagRequired(flagEvents) return cmd } diff --git a/x/auth/client/cli/tx_sign.go b/x/auth/client/cli/tx_sign.go index c522d3d596..adf5c4bce8 100644 --- a/x/auth/client/cli/tx_sign.go +++ b/x/auth/client/cli/tx_sign.go @@ -51,7 +51,7 @@ account key. It implies --signature-only. cmd.Flags().String(flags.FlagOutputDocument, "", "The document will be written to the given file instead of STDOUT") cmd.Flags().Bool(flagSigOnly, true, "Print only the generated signature, then exit") cmd.Flags().String(flags.FlagChainID, "", "network chain ID") - cmd.MarkFlagRequired(flags.FlagFrom) + _ = cmd.MarkFlagRequired(flags.FlagFrom) flags.AddTxFlagsToCmd(cmd) return cmd @@ -208,7 +208,7 @@ be generated via the 'multisign' command. cmd.Flags().String(flags.FlagOutputDocument, "", "The document will be written to the given file instead of STDOUT") cmd.Flags().String(flags.FlagChainID, "", "The network chain ID") cmd.Flags().Bool(flagAmino, false, "Generate Amino encoded JSON suitable for submiting to the txs REST endpoint") - cmd.MarkFlagRequired(flags.FlagFrom) + _ = cmd.MarkFlagRequired(flags.FlagFrom) flags.AddTxFlagsToCmd(cmd) return cmd @@ -218,8 +218,8 @@ func preSignCmd(cmd *cobra.Command, _ []string) { // Conditionally mark the account and sequence numbers required as no RPC // query will be done. if offline, _ := cmd.Flags().GetBool(flags.FlagOffline); offline { - cmd.MarkFlagRequired(flags.FlagAccountNumber) - cmd.MarkFlagRequired(flags.FlagSequence) + _ = cmd.MarkFlagRequired(flags.FlagAccountNumber) + _ = cmd.MarkFlagRequired(flags.FlagSequence) } } diff --git a/x/auth/client/testutil/helpers.go b/x/auth/client/testutil/helpers.go index 0b130cd6f2..4d3ce1107d 100644 --- a/x/auth/client/testutil/helpers.go +++ b/x/auth/client/testutil/helpers.go @@ -56,7 +56,7 @@ func TxValidateSignaturesExec(clientCtx client.Context, filename string) (testut return clitestutil.ExecTestCLICmd(clientCtx, cli.GetValidateSignaturesCommand(), args) } -func TxMultiSignExec(clientCtx client.Context, from string, filename string, extraArgs ...string) (testutil.BufferWriter, error) { +func TxMultiSignExec(clientCtx client.Context, from, filename string, extraArgs ...string) (testutil.BufferWriter, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), fmt.Sprintf("--%s=%s", flags.FlagChainID, clientCtx.ChainID), @@ -92,7 +92,7 @@ func QueryAccountExec(clientCtx client.Context, address fmt.Stringer, extraArgs return clitestutil.ExecTestCLICmd(clientCtx, cli.GetAccountCmd(), append(args, extraArgs...)) } -func TxMultiSignBatchExec(clientCtx client.Context, filename string, from string, sigFile1 string, sigFile2 string, extraArgs ...string) (testutil.BufferWriter, error) { +func TxMultiSignBatchExec(clientCtx client.Context, filename, from, sigFile1, sigFile2 string, extraArgs ...string) (testutil.BufferWriter, error) { args := []string{ fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), filename, diff --git a/x/auth/client/testutil/suite.go b/x/auth/client/testutil/suite.go index f163eb1bdf..2db31f2ff2 100644 --- a/x/auth/client/testutil/suite.go +++ b/x/auth/client/testutil/suite.go @@ -10,11 +10,10 @@ import ( "strings" "testing" + ostcli "github.com/Finschia/ostracon/libs/cli" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - ostcli "github.com/Finschia/ostracon/libs/cli" - "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/crypto/hd" @@ -332,7 +331,6 @@ func (s *IntegrationTestSuite) TestCLIQueryTxCmdByHash() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := authcli.QueryTxCmd() clientCtx := val.ClientCtx @@ -448,7 +446,6 @@ func (s *IntegrationTestSuite) TestCLIQueryTxCmdByEvents() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := authcli.QueryTxCmd() clientCtx := val.ClientCtx @@ -527,7 +524,6 @@ func (s *IntegrationTestSuite) TestCLIQueryTxsCmdByEvents() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := authcli.QueryTxsByEventsCmd() clientCtx := val.ClientCtx @@ -1167,7 +1163,6 @@ func (s *IntegrationTestSuite) TestGetAccountCmd() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { clientCtx := val.ClientCtx @@ -1206,7 +1201,6 @@ func (s *IntegrationTestSuite) TestGetAccountsCmd() { } for name, tc := range testCases { - tc := tc s.Run(name, func() { cmd := authcli.GetAccountsCmd() clientCtx := val.ClientCtx @@ -1246,7 +1240,6 @@ func (s *IntegrationTestSuite) TestQueryModuleAccountByNameCmd() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { clientCtx := val.ClientCtx @@ -1275,7 +1268,7 @@ func (s *IntegrationTestSuite) TestQueryModuleAccountByNameCmd() { func TestGetBroadcastCommandOfflineFlag(t *testing.T) { clientCtx := client.Context{}.WithOffline(true) - clientCtx = clientCtx.WithTxConfig(simapp.MakeTestEncodingConfig().TxConfig) //nolint:staticcheck + _ = clientCtx.WithTxConfig(simapp.MakeTestEncodingConfig().TxConfig) cmd := authcli.GetBroadcastCommand() _ = testutil.ApplyMockIODiscardOutErr(cmd) @@ -1336,7 +1329,6 @@ func (s *IntegrationTestSuite) TestQueryParamsCmd() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := authcli.QueryParamsCmd() clientCtx := val.ClientCtx @@ -1429,10 +1421,11 @@ func (s *IntegrationTestSuite) TestSignWithMultiSignersAminoJSON() { // because DIRECT doesn't support multi signers via the CLI. // Since we use amino, we don't need to pre-populate signer_infos. txBuilder := val0.ClientCtx.TxConfig.NewTxBuilder() - txBuilder.SetMsgs( + err := txBuilder.SetMsgs( banktypes.NewMsgSend(val0.Address, addr1, sdk.NewCoins(val0Coin)), banktypes.NewMsgSend(val1.Address, addr1, sdk.NewCoins(val1Coin)), ) + require.NoError(err) txBuilder.SetFeeAmount(sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10)))) txBuilder.SetGasLimit(testdata.NewTestGasLimit()) // min required is 101892 require.Equal([]sdk.AccAddress{val0.Address, val1.Address}, txBuilder.GetTx().GetSigners()) diff --git a/x/auth/client/tx.go b/x/auth/client/tx.go index 9f4690f639..2f45549e45 100644 --- a/x/auth/client/tx.go +++ b/x/auth/client/tx.go @@ -52,7 +52,7 @@ func SignTx(txFactory tx.Factory, clientCtx client.Context, name string, txBuild addr := sdk.AccAddress(info.GetPubKey().Address()) if !isTxSigner(addr, txBuilder.GetTx().GetSigners()) { - return fmt.Errorf("%s: %s", sdkerrors.ErrorInvalidSigner, name) + return fmt.Errorf("%w: %s", sdkerrors.ErrorInvalidSigner, name) } if !offline { txFactory, err = populateAccountFromState(txFactory, clientCtx, addr) @@ -79,7 +79,7 @@ func SignTxWithSignerAddress(txFactory tx.Factory, clientCtx client.Context, add // check whether the address is a signer if !isTxSigner(addr, txBuilder.GetTx().GetSigners()) { - return fmt.Errorf("%s: %s", sdkerrors.ErrorInvalidSigner, name) + return fmt.Errorf("%w: %s", sdkerrors.ErrorInvalidSigner, name) } if !offline { diff --git a/x/auth/client/tx_test.go b/x/auth/client/tx_test.go index 5a4ada8a6a..2a027753cf 100644 --- a/x/auth/client/tx_test.go +++ b/x/auth/client/tx_test.go @@ -39,7 +39,7 @@ func TestParseQueryResponse(t *testing.T) { require.Equal(t, 10, int(res.GasInfo.GasUsed)) require.NotNil(t, res.Result) - res, err = authclient.ParseQueryResponse([]byte("fuzzy")) + _, err = authclient.ParseQueryResponse([]byte("fuzzy")) require.Error(t, err) } @@ -123,7 +123,6 @@ func TestBatchScanner_Scan(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { scanner, i := authclient.NewBatchScanner(clientCtx.TxConfig, strings.NewReader(tt.batch)), 0 for scanner.Scan() { @@ -137,9 +136,10 @@ func TestBatchScanner_Scan(t *testing.T) { } } -func compareEncoders(t *testing.T, expected sdk.TxEncoder, actual sdk.TxEncoder) { +func compareEncoders(t *testing.T, expected, actual sdk.TxEncoder) { + t.Helper() msgs := []sdk.Msg{testdata.NewTestMsg(addr)} - tx := legacytx.NewStdTx(msgs, legacytx.StdFee{}, []legacytx.StdSignature{}, "") + tx := legacytx.NewStdTx(msgs, legacytx.StdFee{}, []legacytx.StdSignature{}, "") //nolint:staticcheck // this will be removed when proto is ready defaultEncoderBytes, err := expected(tx) require.NoError(t, err) diff --git a/x/auth/keeper/grpc_query.go b/x/auth/keeper/grpc_query.go index 175e6edb09..0a77a0d826 100644 --- a/x/auth/keeper/grpc_query.go +++ b/x/auth/keeper/grpc_query.go @@ -3,14 +3,13 @@ package keeper import ( "context" - "github.com/Finschia/finschia-sdk/store/prefix" - "github.com/Finschia/finschia-sdk/types/query" - "google.golang.org/grpc/codes" "google.golang.org/grpc/status" codectypes "github.com/Finschia/finschia-sdk/codec/types" + "github.com/Finschia/finschia-sdk/store/prefix" sdk "github.com/Finschia/finschia-sdk/types" + "github.com/Finschia/finschia-sdk/types/query" "github.com/Finschia/finschia-sdk/x/auth/types" ) diff --git a/x/auth/keeper/grpc_query_test.go b/x/auth/keeper/grpc_query_test.go index 8614998a66..ef0968dc6d 100644 --- a/x/auth/keeper/grpc_query_test.go +++ b/x/auth/keeper/grpc_query_test.go @@ -2,6 +2,7 @@ package keeper_test import ( "fmt" + "github.com/Finschia/finschia-sdk/testutil/testdata" sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/x/auth/types" diff --git a/x/auth/keeper/querier_test.go b/x/auth/keeper/querier_test.go index cebce110e0..9ec5be1ba0 100644 --- a/x/auth/keeper/querier_test.go +++ b/x/auth/keeper/querier_test.go @@ -4,12 +4,10 @@ import ( "fmt" "testing" - "github.com/Finschia/finschia-sdk/codec" - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" + "github.com/Finschia/finschia-sdk/codec" "github.com/Finschia/finschia-sdk/testutil/testdata" keep "github.com/Finschia/finschia-sdk/x/auth/keeper" "github.com/Finschia/finschia-sdk/x/auth/types" diff --git a/x/auth/legacy/legacytx/stdtx_test.go b/x/auth/legacy/legacytx/stdtx_test.go index 9adffb6de2..5b6e39b9f0 100644 --- a/x/auth/legacy/legacytx/stdtx_test.go +++ b/x/auth/legacy/legacytx/stdtx_test.go @@ -4,16 +4,14 @@ import ( "fmt" "testing" + "github.com/Finschia/ostracon/libs/log" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/codec" cryptocodec "github.com/Finschia/finschia-sdk/crypto/codec" "github.com/Finschia/finschia-sdk/crypto/keys/ed25519" kmultisig "github.com/Finschia/finschia-sdk/crypto/keys/multisig" - "github.com/Finschia/finschia-sdk/crypto/types" cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" "github.com/Finschia/finschia-sdk/testutil/testdata" sdk "github.com/Finschia/finschia-sdk/types" @@ -31,15 +29,15 @@ func init() { RegisterLegacyAminoCodec(amino) } -// Deprecated, use fee amount and gas limit separately on TxBuilder. +// Deprecated: use fee amount and gas limit separately on TxBuilder. func NewTestStdFee() StdFee { return NewStdFee(100000, sdk.NewCoins(sdk.NewInt64Coin("atom", 150)), ) } -// Deprecated, use TxBuilder. -func NewTestTx(ctx sdk.Context, msgs []sdk.Msg, privs []cryptotypes.PrivKey, accNums []uint64, seqs []uint64, timeout uint64, fee StdFee) sdk.Tx { +// Deprecated: use TxBuilder. +func NewTestTx(ctx sdk.Context, msgs []sdk.Msg, privs []cryptotypes.PrivKey, accNums, seqs []uint64, timeout uint64, fee StdFee) sdk.Tx { sigs := make([]StdSignature, len(privs)) for i, priv := range privs { signBytes := StdSignBytes(ctx.ChainID(), accNums[i], seqs[i], timeout, fee, msgs, "") @@ -207,7 +205,7 @@ func TestSignatureV2Conversions(t *testing.T) { pubKey, pubKey2, }) dummy2 := []byte("dummySig2") - bitArray := types.NewCompactBitArray(2) + bitArray := cryptotypes.NewCompactBitArray(2) bitArray.SetIndex(0, true) bitArray.SetIndex(1, true) msigData := &signing.MultiSignatureData{ diff --git a/x/auth/legacy/v043/store_test.go b/x/auth/legacy/v043/store_test.go index 097b0f9d59..1ed227a9d7 100644 --- a/x/auth/legacy/v043/store_test.go +++ b/x/auth/legacy/v043/store_test.go @@ -537,7 +537,6 @@ func TestMigrateVestingAccounts(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { app := simapp.Setup(false) ctx := app.BaseApp.NewContext(false, tmproto.Header{ @@ -578,8 +577,8 @@ func TestMigrateVestingAccounts(t *testing.T) { } trackingCorrected( - ctx, t, + ctx, app.AccountKeeper, savedAccount.GetAddress(), expVested, @@ -589,7 +588,7 @@ 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) { +func trackingCorrected(t *testing.T, ctx sdk.Context, ak authkeeper.AccountKeeper, addr sdk.AccAddress, expDelVesting, expDelFree sdk.Coins) { t.Helper() baseAccount := ak.GetAccount(ctx, addr) vDA, ok := baseAccount.(exported.VestingAccount) @@ -646,6 +645,7 @@ func dirtyTrackingFields(ctx sdk.Context, vesting exported.VestingAccount, app * } func createValidator(t *testing.T, ctx sdk.Context, app *simapp.SimApp, powers int64) (sdk.AccAddress, sdk.ValAddress) { + t.Helper() valTokens := sdk.TokensFromConsensusPower(powers, sdk.DefaultPowerReduction) addrs := simapp.AddTestAddrsIncremental(app, ctx, 1, valTokens) valAddrs := simapp.ConvertAddrsToValAddrs(addrs) diff --git a/x/auth/module.go b/x/auth/module.go index 4b3aa9bb84..b228cd64a9 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -7,7 +7,6 @@ import ( "math/rand" "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" diff --git a/x/auth/signing/handler_map.go b/x/auth/signing/handler_map.go index 36fc4c4b07..946d9bf3af 100644 --- a/x/auth/signing/handler_map.go +++ b/x/auth/signing/handler_map.go @@ -3,9 +3,8 @@ package signing import ( "fmt" - "github.com/Finschia/finschia-sdk/types/tx/signing" - sdk "github.com/Finschia/finschia-sdk/types" + "github.com/Finschia/finschia-sdk/types/tx/signing" ) // SignModeHandlerMap is SignModeHandler that aggregates multiple SignModeHandler's into diff --git a/x/auth/signing/verify_test.go b/x/auth/signing/verify_test.go index c1cbe7ae33..2ca699c46e 100644 --- a/x/auth/signing/verify_test.go +++ b/x/auth/signing/verify_test.go @@ -42,10 +42,11 @@ func TestVerifySignature(t *testing.T) { balances := sdk.NewCoins(sdk.NewInt64Coin("atom", 200)) require.NoError(t, simapp.FundAccount(app, ctx, addr, balances)) acc, err := ante.GetSignerAcc(ctx, app.AccountKeeper, addr) + require.NoError(t, err) require.NoError(t, simapp.FundAccount(app, ctx, addr, balances)) msgs := []sdk.Msg{testdata.NewTestMsg(addr)} - fee := legacytx.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) + fee := legacytx.NewStdFee(50000, sdk.Coins{sdk.NewInt64Coin("atom", 150)}) //nolint:staticcheck // this will be removed when proto is ready signerData := signing.SignerData{ ChainID: chainId, AccountNumber: acc.GetAccountNumber(), @@ -55,12 +56,12 @@ func TestVerifySignature(t *testing.T) { signature, err := priv.Sign(signBytes) require.NoError(t, err) - stdSig := legacytx.StdSignature{PubKey: pubKey, Signature: signature} + stdSig := legacytx.StdSignature{PubKey: pubKey, Signature: signature} //nolint:staticcheck // this will be removed when proto is ready sigV2, err := legacytx.StdSignatureToSignatureV2(cdc, stdSig) require.NoError(t, err) handler := MakeTestHandlerMap() - stdTx := legacytx.NewStdTx(msgs, fee, []legacytx.StdSignature{stdSig}, memo) + stdTx := legacytx.NewStdTx(msgs, fee, []legacytx.StdSignature{stdSig}, memo) //nolint:staticcheck // this will be removed when proto is ready stdTx.TimeoutHeight = 10 err = signing.VerifySignature(pubKey, signerData, sigV2.Data, handler, stdTx) require.NoError(t, err) @@ -73,13 +74,13 @@ func TestVerifySignature(t *testing.T) { sig1, err := priv.Sign(multiSignBytes) require.NoError(t, err) - stdSig1 := legacytx.StdSignature{PubKey: pubKey, Signature: sig1} + stdSig1 := legacytx.StdSignature{PubKey: pubKey, Signature: sig1} //nolint:staticcheck // this will be removed when proto is ready sig1V2, err := legacytx.StdSignatureToSignatureV2(cdc, stdSig1) require.NoError(t, err) sig2, err := priv1.Sign(multiSignBytes) require.NoError(t, err) - stdSig2 := legacytx.StdSignature{PubKey: pubKey, Signature: sig2} + stdSig2 := legacytx.StdSignature{PubKey: pubKey, Signature: sig2} //nolint:staticcheck // this will be removed when proto is ready sig2V2, err := legacytx.StdSignatureToSignatureV2(cdc, stdSig2) require.NoError(t, err) @@ -88,7 +89,7 @@ func TestVerifySignature(t *testing.T) { err = multisig.AddSignatureFromPubKey(multisignature, sig2V2.Data, pkSet[1], pkSet) require.NoError(t, err) - stdTx = legacytx.NewStdTx(msgs, fee, []legacytx.StdSignature{stdSig1, stdSig2}, memo) + stdTx = legacytx.NewStdTx(msgs, fee, []legacytx.StdSignature{stdSig1, stdSig2}, memo) //nolint:staticcheck // this will be removed when proto is ready stdTx.TimeoutHeight = 10 err = signing.VerifySignature(multisigKey, signerData, multisignature, handler, stdTx) diff --git a/x/auth/simulation/decoder_test.go b/x/auth/simulation/decoder_test.go index d4a5bc353a..7b8bcee89c 100644 --- a/x/auth/simulation/decoder_test.go +++ b/x/auth/simulation/decoder_test.go @@ -57,7 +57,6 @@ func TestDecodeStore(t *testing.T) { } for i, tt := range tests { - i, tt := i, tt t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: diff --git a/x/auth/tx/builder_test.go b/x/auth/tx/builder_test.go index 2199b895a5..39b97c1c84 100644 --- a/x/auth/tx/builder_test.go +++ b/x/auth/tx/builder_test.go @@ -40,7 +40,7 @@ func TestTxBuilder(t *testing.T) { Sequence: accSeq, }) - var sig signing.SignatureV2 = signing.SignatureV2{ + sig := signing.SignatureV2{ PubKey: pubkey, Data: &signing.SingleSignatureData{ SignMode: signing.SignMode_SIGN_MODE_DIRECT, diff --git a/x/auth/tx/config.go b/x/auth/tx/config.go index 441806c394..872360d11b 100644 --- a/x/auth/tx/config.go +++ b/x/auth/tx/config.go @@ -3,12 +3,10 @@ package tx import ( "fmt" - signingtypes "github.com/Finschia/finschia-sdk/types/tx/signing" - - "github.com/Finschia/finschia-sdk/codec" - "github.com/Finschia/finschia-sdk/client" + "github.com/Finschia/finschia-sdk/codec" sdk "github.com/Finschia/finschia-sdk/types" + signingtypes "github.com/Finschia/finschia-sdk/types/tx/signing" "github.com/Finschia/finschia-sdk/x/auth/signing" ) diff --git a/x/auth/tx/direct.go b/x/auth/tx/direct.go index 6032555354..ef1fcfa54c 100644 --- a/x/auth/tx/direct.go +++ b/x/auth/tx/direct.go @@ -3,10 +3,9 @@ package tx import ( "fmt" - signingtypes "github.com/Finschia/finschia-sdk/types/tx/signing" - sdk "github.com/Finschia/finschia-sdk/types" types "github.com/Finschia/finschia-sdk/types/tx" + signingtypes "github.com/Finschia/finschia-sdk/types/tx/signing" "github.com/Finschia/finschia-sdk/x/auth/signing" ) diff --git a/x/auth/tx/encode_decode_test.go b/x/auth/tx/encode_decode_test.go index 9368449927..4eab9a3fed 100644 --- a/x/auth/tx/encode_decode_test.go +++ b/x/auth/tx/encode_decode_test.go @@ -101,7 +101,6 @@ func TestUnknownFields(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { bodyBz, err := tt.body.Marshal() require.NoError(t, err) @@ -171,6 +170,7 @@ func TestRejectNonADR027(t *testing.T) { require.NoError(t, err) authInfo := &testdata.TestUpdatedAuthInfo{Fee: &tx.Fee{GasLimit: 127}} // Look for "127" when debugging the bytes stream. authInfoBz, err := authInfo.Marshal() + require.NoError(t, err) txRaw := &tx.TxRaw{ BodyBytes: bodyBz, AuthInfoBytes: authInfoBz, @@ -243,7 +243,6 @@ func TestRejectNonADR027(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { _, err = decoder(tt.txBz) if tt.shouldErr { @@ -281,7 +280,6 @@ func TestVarintMinLength(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(fmt.Sprintf("test %d", tt.n), func(t *testing.T) { l1 := varintMinLength(tt.n) buf := make([]byte, binary.MaxVarintLen64) diff --git a/x/auth/tx/legacy_amino_json_test.go b/x/auth/tx/legacy_amino_json_test.go index 052cfff055..db1a84ab48 100644 --- a/x/auth/tx/legacy_amino_json_test.go +++ b/x/auth/tx/legacy_amino_json_test.go @@ -25,6 +25,7 @@ var ( ) func buildTx(t *testing.T, bldr *wrapper) { + t.Helper() bldr.SetFeeAmount(coins) bldr.SetGasLimit(gas) bldr.SetMemo(memo) @@ -70,7 +71,7 @@ func TestLegacyAminoJSONHandler_GetSignBytes(t *testing.T) { require.NoError(t, err) bldr.tx.Body.ExtensionOptions = []*cdctypes.Any{any} tx = bldr.GetTx() - signBz, err = handler.GetSignBytes(signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, signingData, tx) + _, err = handler.GetSignBytes(signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, signingData, tx) require.Error(t, err) // expect error with non-critical extension options @@ -78,7 +79,7 @@ func TestLegacyAminoJSONHandler_GetSignBytes(t *testing.T) { buildTx(t, bldr) bldr.tx.Body.NonCriticalExtensionOptions = []*cdctypes.Any{any} tx = bldr.GetTx() - signBz, err = handler.GetSignBytes(signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, signingData, tx) + _, err = handler.GetSignBytes(signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, signingData, tx) require.Error(t, err) } diff --git a/x/auth/tx/service.go b/x/auth/tx/service.go index 5c8da46de4..f67d787cb8 100644 --- a/x/auth/tx/service.go +++ b/x/auth/tx/service.go @@ -7,7 +7,7 @@ import ( "strings" gogogrpc "github.com/gogo/protobuf/grpc" - "github.com/golang/protobuf/proto" //nolint: staticcheck + "github.com/golang/protobuf/proto" "github.com/grpc-ecosystem/grpc-gateway/runtime" tmtypes "github.com/tendermint/tendermint/proto/tendermint/types" "google.golang.org/grpc/codes" diff --git a/x/auth/tx/service_test.go b/x/auth/tx/service_test.go index 904e4dc93b..0b65b2d2cd 100644 --- a/x/auth/tx/service_test.go +++ b/x/auth/tx/service_test.go @@ -112,7 +112,7 @@ func (s *IntegrationTestSuite) TearDownSuite() { s.network.Cleanup() } -func (s IntegrationTestSuite) TestSimulateTx_GRPC() { +func (s *IntegrationTestSuite) TestSimulateTx_GRPC() { val := s.network.Validators[0] txBuilder := s.mkTxBuilder() // Convert the txBuilder to a tx.Tx. @@ -135,7 +135,6 @@ func (s IntegrationTestSuite) TestSimulateTx_GRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { // Broadcast the tx via gRPC via the validator's clientCtx (which goes // through Tendermint). @@ -158,7 +157,7 @@ func (s IntegrationTestSuite) TestSimulateTx_GRPC() { } } -func (s IntegrationTestSuite) TestSimulateTx_GRPCGateway() { +func (s *IntegrationTestSuite) TestSimulateTx_GRPCGateway() { val := s.network.Validators[0] txBuilder := s.mkTxBuilder() // Convert the txBuilder to a tx.Tx. @@ -199,7 +198,7 @@ func (s IntegrationTestSuite) TestSimulateTx_GRPCGateway() { } } -func (s IntegrationTestSuite) TestGetTxEvents_GRPC() { +func (s *IntegrationTestSuite) TestGetTxEvents_GRPC() { testCases := []struct { name string req *tx.GetTxsEventRequest @@ -278,7 +277,7 @@ func (s IntegrationTestSuite) TestGetTxEvents_GRPC() { } } -func (s IntegrationTestSuite) TestGetTxEvents_GRPCGateway() { +func (s *IntegrationTestSuite) TestGetTxEvents_GRPCGateway() { val := s.network.Validators[0] testCases := []struct { name string @@ -353,7 +352,7 @@ func (s IntegrationTestSuite) TestGetTxEvents_GRPCGateway() { } } -func (s IntegrationTestSuite) TestGetTx_GRPC() { +func (s *IntegrationTestSuite) TestGetTx_GRPC() { testCases := []struct { name string req *tx.GetTxRequest @@ -381,7 +380,7 @@ func (s IntegrationTestSuite) TestGetTx_GRPC() { } } -func (s IntegrationTestSuite) TestGetTx_GRPCGateway() { +func (s *IntegrationTestSuite) TestGetTx_GRPCGateway() { val := s.network.Validators[0] testCases := []struct { name string @@ -433,7 +432,7 @@ func (s IntegrationTestSuite) TestGetTx_GRPCGateway() { } } -func (s IntegrationTestSuite) TestBroadcastTx_GRPC() { +func (s *IntegrationTestSuite) TestBroadcastTx_GRPC() { val := s.network.Validators[0] txBuilder := s.mkTxBuilder() txBytes, err := val.ClientCtx.TxConfig.TxEncoder()(txBuilder.GetTx()) @@ -457,7 +456,6 @@ func (s IntegrationTestSuite) TestBroadcastTx_GRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { // Broadcast the tx via gRPC via the validator's clientCtx (which goes // through Tendermint). @@ -474,7 +472,7 @@ func (s IntegrationTestSuite) TestBroadcastTx_GRPC() { time.Sleep(1 * time.Second) // wait for block confirm time before executing next test } -func (s IntegrationTestSuite) TestBroadcastTx_GRPCGateway() { +func (s *IntegrationTestSuite) TestBroadcastTx_GRPCGateway() { val := s.network.Validators[0] txBuilder := s.mkTxBuilder() txBytes, err := val.ClientCtx.TxConfig.TxEncoder()(txBuilder.GetTx()) @@ -535,6 +533,7 @@ func (s *IntegrationTestSuite) TestSimMultiSigTx() { s.Require().NoError(err) height, err := s.network.LatestHeight() + s.Require().NoError(err) _, err = s.network.WaitForHeight(height + 1) s.Require().NoError(err) @@ -550,8 +549,10 @@ func (s *IntegrationTestSuite) TestSimMultiSigTx() { fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), fmt.Sprintf("--gas=%d", flags.DefaultGasLimit), ) + s.Require().NoError(err) height, err = s.network.LatestHeight() + s.Require().NoError(err) _, err = s.network.WaitForHeight(height + 1) s.Require().NoError(err) @@ -592,7 +593,9 @@ func (s *IntegrationTestSuite) TestSimMultiSigTx() { // convert from protoJSON to protoBinary for sim sdkTx, err := val1.ClientCtx.TxConfig.TxJSONDecoder()(multiSigWith2Signatures.Bytes()) + s.Require().NoError(err) txBytes, err := val1.ClientCtx.TxConfig.TxEncoder()(sdkTx) + s.Require().NoError(err) // simulate tx sim := &tx.SimulateRequest{TxBytes: txBytes} @@ -603,7 +606,7 @@ func (s *IntegrationTestSuite) TestSimMultiSigTx() { s.Require().Greater(res.GasInfo.GasUsed, uint64(0)) } -func (s IntegrationTestSuite) TestGetBlockWithTxs_GRPC() { +func (s *IntegrationTestSuite) TestGetBlockWithTxs_GRPC() { testCases := []struct { name string req *tx.GetBlockWithTxsRequest @@ -641,14 +644,14 @@ func (s IntegrationTestSuite) TestGetBlockWithTxs_GRPC() { } } -func (s IntegrationTestSuite) TestGetBlockWithTxs() { +func (s *IntegrationTestSuite) TestGetBlockWithTxs() { srv := tx2.NewTxServer(client.Context{}, nil, nil) _, err := srv.GetBlockWithTxs(context.Background(), nil) s.Require().Contains(err.Error(), "request cannot be nil") } -func (s IntegrationTestSuite) TestGetBlockWithTxs_GRPCGateway() { +func (s *IntegrationTestSuite) TestGetBlockWithTxs_GRPCGateway() { val := s.network.Validators[0] testCases := []struct { name string @@ -693,7 +696,7 @@ func TestIntegrationTestSuite(t *testing.T) { suite.Run(t, new(IntegrationTestSuite)) } -func (s IntegrationTestSuite) mkTxBuilder() client.TxBuilder { +func (s *IntegrationTestSuite) mkTxBuilder() client.TxBuilder { val := s.network.Validators[0] s.Require().NoError(s.network.WaitForNextBlock()) @@ -737,7 +740,7 @@ type protoTxProvider interface { // txBuilderToProtoTx converts a txBuilder into a proto tx.Tx. // Deprecated: It's only used for testing the deprecated Simulate gRPC endpoint // using a proto Tx field. -func txBuilderToProtoTx(txBuilder client.TxBuilder) (*tx.Tx, error) { // nolint +func txBuilderToProtoTx(txBuilder client.TxBuilder) (*tx.Tx, error) { protoProvider, ok := txBuilder.(protoTxProvider) if !ok { return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "expected proto tx builder, got %T", txBuilder) diff --git a/x/auth/tx/sigs_test.go b/x/auth/tx/sigs_test.go index 5d6ba6b5a9..2c22a1e911 100644 --- a/x/auth/tx/sigs_test.go +++ b/x/auth/tx/sigs_test.go @@ -6,7 +6,6 @@ import ( "github.com/stretchr/testify/require" "github.com/Finschia/finschia-sdk/crypto/types" - "github.com/Finschia/finschia-sdk/testutil/testdata" ) diff --git a/x/auth/tx2/service_test.go b/x/auth/tx2/service_test.go index 4e9e945a79..b88d3056e6 100644 --- a/x/auth/tx2/service_test.go +++ b/x/auth/tx2/service_test.go @@ -93,7 +93,7 @@ func (s *IntegrationTestSuite) TearDownSuite() { s.network.Cleanup() } -func (s IntegrationTestSuite) TestGetBlockWithTxs_GRPC() { +func (s *IntegrationTestSuite) TestGetBlockWithTxs_GRPC() { testCases := []struct { name string req *tx2.GetBlockWithTxsRequest @@ -131,7 +131,7 @@ func (s IntegrationTestSuite) TestGetBlockWithTxs_GRPC() { } } -func (s IntegrationTestSuite) TestGetBlockWithTxs_GRPCGateway() { +func (s *IntegrationTestSuite) TestGetBlockWithTxs_GRPCGateway() { val := s.network.Validators[0] testCases := []struct { name string diff --git a/x/auth/types/account_test.go b/x/auth/types/account_test.go index a90a633051..8f4b1cc9af 100644 --- a/x/auth/types/account_test.go +++ b/x/auth/types/account_test.go @@ -104,8 +104,6 @@ func TestGenesisAccountValidate(t *testing.T) { } for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { require.Equal(t, tt.expErr, tt.acc.Validate() != nil) }) @@ -170,7 +168,6 @@ func TestValidate(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { err := tt.acc.Validate() require.Equal(t, tt.expErr, err) diff --git a/x/auth/types/common_test.go b/x/auth/types/common_test.go index b59dd5406d..536cb3902e 100644 --- a/x/auth/types/common_test.go +++ b/x/auth/types/common_test.go @@ -5,7 +5,7 @@ import ( ) var ( - app = simapp.Setup(false) - ecdc = simapp.MakeTestEncodingConfig() - appCodec, legacyAmino = ecdc.Marshaler, ecdc.Amino + app = simapp.Setup(false) + ecdc = simapp.MakeTestEncodingConfig() + appCodec, _ = ecdc.Marshaler, ecdc.Amino ) diff --git a/x/auth/types/params_test.go b/x/auth/types/params_test.go index b4bbce8ba0..aeb5c48d6a 100644 --- a/x/auth/types/params_test.go +++ b/x/auth/types/params_test.go @@ -37,7 +37,6 @@ func TestParams_Validate(t *testing.T) { types.DefaultSigVerifyCostED25519, types.DefaultSigVerifyCostSecp256k1), fmt.Errorf("invalid tx size cost per byte: 0")}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { got := tt.params.Validate() if tt.wantErr == nil { diff --git a/x/auth/types/permissions_test.go b/x/auth/types/permissions_test.go index de5c256457..78133007da 100644 --- a/x/auth/types/permissions_test.go +++ b/x/auth/types/permissions_test.go @@ -41,7 +41,6 @@ func TestValidatePermissions(t *testing.T) { } for i, tc := range cases { - i, tc := i, tc t.Run(tc.name, func(t *testing.T) { err := validatePermissions(tc.permissions...) if tc.expectPass { diff --git a/x/auth/vesting/client/testutil/suite.go b/x/auth/vesting/client/testutil/suite.go index 7f8be8d668..a486b5ee84 100644 --- a/x/auth/vesting/client/testutil/suite.go +++ b/x/auth/vesting/client/testutil/suite.go @@ -112,8 +112,6 @@ func (s *IntegrationTestSuite) TestNewMsgCreateVestingAccountCmd() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { clientCtx := val.ClientCtx diff --git a/x/auth/vesting/exported/exported.go b/x/auth/vesting/exported/exported.go index b6a6008d46..1d3f6581bd 100644 --- a/x/auth/vesting/exported/exported.go +++ b/x/auth/vesting/exported/exported.go @@ -3,9 +3,8 @@ package exported import ( "time" - "github.com/Finschia/finschia-sdk/x/auth/types" - sdk "github.com/Finschia/finschia-sdk/types" + "github.com/Finschia/finschia-sdk/x/auth/types" ) // VestingAccount defines an account type that vests coins via a vesting schedule. diff --git a/x/auth/vesting/handler_test.go b/x/auth/vesting/handler_test.go index 9bd3c2ca6b..ceaa19e6e9 100644 --- a/x/auth/vesting/handler_test.go +++ b/x/auth/vesting/handler_test.go @@ -62,8 +62,6 @@ func (suite *HandlerTestSuite) TestMsgCreateVestingAccount() { } for _, tc := range testCases { - tc := tc - suite.Run(tc.name, func() { res, err := suite.handler(ctx, tc.msg) if tc.expectErr { diff --git a/x/auth/vesting/types/expected_keepers.go b/x/auth/vesting/types/expected_keepers.go index c336d83c2f..2c5e4808ee 100644 --- a/x/auth/vesting/types/expected_keepers.go +++ b/x/auth/vesting/types/expected_keepers.go @@ -8,6 +8,6 @@ import ( // for creating vesting accounts with funds. type BankKeeper interface { IsSendEnabledCoins(ctx sdk.Context, coins ...sdk.Coin) error - SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error + SendCoins(ctx sdk.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) error BlockedAddr(addr sdk.AccAddress) bool } diff --git a/x/auth/vesting/types/test_common.go b/x/auth/vesting/types/test_common.go index afe0569a4d..ef5d1e561a 100644 --- a/x/auth/vesting/types/test_common.go +++ b/x/auth/vesting/types/test_common.go @@ -4,7 +4,6 @@ import ( "github.com/Finschia/finschia-sdk/crypto/keys/secp256k1" cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" "github.com/Finschia/finschia-sdk/testutil/testdata" - sdk "github.com/Finschia/finschia-sdk/types" ) diff --git a/x/auth/vesting/types/vesting_account_test.go b/x/auth/vesting/types/vesting_account_test.go index 0327d2cf9a..07d407698d 100644 --- a/x/auth/vesting/types/vesting_account_test.go +++ b/x/auth/vesting/types/vesting_account_test.go @@ -728,8 +728,6 @@ func TestGenesisAccountValidate(t *testing.T) { } for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { require.Equal(t, tt.expErr, tt.acc.Validate() != nil) }) diff --git a/x/authz/client/testutil/grpc.go b/x/authz/client/testutil/grpc.go index 6f2c393f5a..43cbca59cd 100644 --- a/x/authz/client/testutil/grpc.go +++ b/x/authz/client/testutil/grpc.go @@ -60,7 +60,6 @@ func (s *IntegrationTestSuite) TestQueryGrantGRPC() { }, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, _ := rest.GetRequest(tc.url) require := s.Require() @@ -71,7 +70,8 @@ func (s *IntegrationTestSuite) TestQueryGrantGRPC() { err := val.ClientCtx.Codec.UnmarshalJSON(resp, &g) require.NoError(err) require.Len(g.Grants, 1) - g.Grants[0].UnpackInterfaces(val.ClientCtx.InterfaceRegistry) + err = g.Grants[0].UnpackInterfaces(val.ClientCtx.InterfaceRegistry) + s.Require().NoError(err) auth := g.Grants[0].GetAuthorization() require.Equal(auth.MsgTypeURL(), banktypes.SendAuthorization{}.MsgTypeURL()) } @@ -145,7 +145,6 @@ func (s *IntegrationTestSuite) TestQueryGrantsGRPC() { }, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { tc.preRun() resp, _ := rest.GetRequest(tc.url) @@ -157,7 +156,6 @@ func (s *IntegrationTestSuite) TestQueryGrantsGRPC() { s.Require().NoError(err) tc.postRun(&authorizations) } - }) } } diff --git a/x/authz/client/testutil/query.go b/x/authz/client/testutil/query.go index 8581130957..a3fc4a4dbc 100644 --- a/x/authz/client/testutil/query.go +++ b/x/authz/client/testutil/query.go @@ -73,8 +73,6 @@ func (s *IntegrationTestSuite) TestQueryAuthorizations() { }, } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryGrants() clientCtx := val.ClientCtx @@ -165,8 +163,6 @@ func (s *IntegrationTestSuite) TestQueryAuthorization() { }, } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryGrants() clientCtx := val.ClientCtx diff --git a/x/authz/client/testutil/tx.go b/x/authz/client/testutil/tx.go index fdf3d150b4..831e26e6d8 100644 --- a/x/authz/client/testutil/tx.go +++ b/x/authz/client/testutil/tx.go @@ -311,7 +311,6 @@ func (s *IntegrationTestSuite) TestCLITxGrantAuthorization() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { clientCtx := val.ClientCtx out, err := ExecGrant( @@ -464,7 +463,6 @@ func (s *IntegrationTestSuite) TestCmdRevokeAuthorizations() { }, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdRevokeAuthorization() clientCtx := val.ClientCtx @@ -606,7 +604,6 @@ func (s *IntegrationTestSuite) TestNewExecGenericAuthorized() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdExecAuthorization() clientCtx := val.ClientCtx @@ -691,7 +688,6 @@ func (s *IntegrationTestSuite) TestNewExecGrantAuthorized() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdExecAuthorization() clientCtx := val.ClientCtx @@ -787,7 +783,6 @@ func (s *IntegrationTestSuite) TestExecDelegateAuthorization() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdExecAuthorization() clientCtx := val.ClientCtx @@ -864,7 +859,6 @@ func (s *IntegrationTestSuite) TestExecDelegateAuthorization() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdExecAuthorization() clientCtx := val.ClientCtx @@ -1008,7 +1002,6 @@ func (s *IntegrationTestSuite) TestExecUndelegateAuthorization() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdExecAuthorization() clientCtx := val.ClientCtx @@ -1087,7 +1080,6 @@ func (s *IntegrationTestSuite) TestExecUndelegateAuthorization() { } 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 0b904f0dcd..78a8445406 100644 --- a/x/authz/codec.go +++ b/x/authz/codec.go @@ -38,6 +38,7 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { msgservice.RegisterMsgServiceDesc(registry, MsgServiceDesc()) } + func init() { // Register all Amino interfaces and concrete types on the authz and gov Amino codec so that this can later be // used to properly serialize MsgGrant, MsgExec and MsgSubmitProposal instances diff --git a/x/authz/keeper/genesis_test.go b/x/authz/keeper/genesis_test.go index 999d7b4a39..63cf857b4d 100644 --- a/x/authz/keeper/genesis_test.go +++ b/x/authz/keeper/genesis_test.go @@ -46,7 +46,8 @@ func (suite *GenesisTestSuite) TestImportExportGenesis() { genesis := suite.keeper.ExportGenesis(suite.ctx) // Clear keeper - suite.keeper.DeleteGrant(suite.ctx, granteeAddr, granterAddr, grant.MsgTypeURL()) + err = suite.keeper.DeleteGrant(suite.ctx, granteeAddr, granterAddr, grant.MsgTypeURL()) + suite.Require().NoError(err) suite.keeper.InitGenesis(suite.ctx, genesis) newGenesis := suite.keeper.ExportGenesis(suite.ctx) diff --git a/x/authz/keeper/keeper.go b/x/authz/keeper/keeper.go index aec81fb22f..f2fb27a35d 100644 --- a/x/authz/keeper/keeper.go +++ b/x/authz/keeper/keeper.go @@ -5,9 +5,8 @@ import ( "strconv" "time" - "github.com/gogo/protobuf/proto" - "github.com/Finschia/ostracon/libs/log" + "github.com/gogo/protobuf/proto" abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/baseapp" @@ -49,7 +48,7 @@ func (k Keeper) getGrant(ctx sdk.Context, skey []byte) (grant authz.Grant, found return grant, true } -func (k Keeper) update(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, updated authz.Authorization) error { +func (k Keeper) update(ctx sdk.Context, grantee, granter sdk.AccAddress, updated authz.Authorization) error { skey := grantStoreKey(grantee, granter, updated.MsgTypeURL()) grant, found := k.getGrant(ctx, skey) if !found { @@ -58,7 +57,7 @@ func (k Keeper) update(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccA msg, ok := updated.(proto.Message) if !ok { - sdkerrors.ErrPackAny.Wrapf("cannot proto marshal %T", updated) + return sdkerrors.ErrPackAny.Wrapf("cannot proto marshal %T", updated) } any, err := codectypes.NewAnyWithValue(msg) @@ -162,7 +161,7 @@ func (k Keeper) SaveGrant(ctx sdk.Context, grantee, granter sdk.AccAddress, auth // DeleteGrant revokes any authorization for the provided message type granted to the grantee // by the granter. -func (k Keeper) DeleteGrant(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) error { +func (k Keeper) DeleteGrant(ctx sdk.Context, grantee, granter sdk.AccAddress, msgType string) error { store := ctx.KVStore(k.storeKey) skey := grantStoreKey(grantee, granter, msgType) _, found := k.getGrant(ctx, skey) @@ -178,7 +177,7 @@ func (k Keeper) DeleteGrant(ctx sdk.Context, grantee sdk.AccAddress, granter sdk } // GetAuthorizations Returns list of `Authorizations` granted to the grantee by the granter. -func (k Keeper) GetAuthorizations(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress) (authorizations []authz.Authorization) { +func (k Keeper) GetAuthorizations(ctx sdk.Context, grantee, granter sdk.AccAddress) (authorizations []authz.Authorization) { store := ctx.KVStore(k.storeKey) key := grantStoreKey(grantee, granter, "") iter := sdk.KVStorePrefixIterator(store, key) @@ -194,13 +193,13 @@ func (k Keeper) GetAuthorizations(ctx sdk.Context, grantee sdk.AccAddress, grant // GetCleanAuthorization returns an `Authorization` and it's expiration time for // (grantee, granter, message name) grant. If there is no grant `nil` is returned. // If the grant is expired, the grant is revoked, removed from the storage, and `nil` is returned. -func (k Keeper) GetCleanAuthorization(ctx sdk.Context, grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) (cap authz.Authorization, expiration time.Time) { +func (k Keeper) GetCleanAuthorization(ctx sdk.Context, grantee, granter sdk.AccAddress, msgType string) (cap authz.Authorization, expiration time.Time) { grant, found := k.getGrant(ctx, grantStoreKey(grantee, granter, msgType)) if !found { return nil, time.Time{} } if grant.Expiration.Before(ctx.BlockHeader().Time) { - k.DeleteGrant(ctx, grantee, granter, msgType) + _ = k.DeleteGrant(ctx, grantee, granter, msgType) return nil, time.Time{} } @@ -211,7 +210,7 @@ func (k Keeper) GetCleanAuthorization(ctx sdk.Context, grantee sdk.AccAddress, g // This function should be used with caution because it can involve significant IO operations. // It should not be used in query or msg services without charging additional gas. func (k Keeper) IterateGrants(ctx sdk.Context, - handler func(granterAddr sdk.AccAddress, granteeAddr sdk.AccAddress, grant authz.Grant) bool, + handler func(granterAddr, granteeAddr sdk.AccAddress, grant authz.Grant) bool, ) { store := ctx.KVStore(k.storeKey) iter := sdk.KVStorePrefixIterator(store, GrantKey) diff --git a/x/authz/keeper/keeper_test.go b/x/authz/keeper/keeper_test.go index f030852add..6b5850879e 100644 --- a/x/authz/keeper/keeper_test.go +++ b/x/authz/keeper/keeper_test.go @@ -4,11 +4,10 @@ import ( "testing" "time" + octime "github.com/Finschia/ostracon/types/time" "github.com/stretchr/testify/suite" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - octime "github.com/Finschia/ostracon/types/time" - "github.com/Finschia/finschia-sdk/baseapp" "github.com/Finschia/finschia-sdk/simapp" sdk "github.com/Finschia/finschia-sdk/types" diff --git a/x/authz/keeper/keys.go b/x/authz/keeper/keys.go index df658ed68b..d1ef3f0abd 100644 --- a/x/authz/keeper/keys.go +++ b/x/authz/keeper/keys.go @@ -20,7 +20,7 @@ const StoreKey = authz.ModuleName // Items are stored with the following key: values // // - 0x01: Grant -func grantStoreKey(grantee sdk.AccAddress, granter sdk.AccAddress, msgType string) []byte { +func grantStoreKey(grantee, granter sdk.AccAddress, msgType string) []byte { m := conv.UnsafeStrToBytes(msgType) granter = address.MustLengthPrefix(granter) grantee = address.MustLengthPrefix(grantee) diff --git a/x/authz/module/module.go b/x/authz/module/module.go index e95b6ec9aa..b26dad6adb 100644 --- a/x/authz/module/module.go +++ b/x/authz/module/module.go @@ -7,7 +7,6 @@ import ( "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" - abci "github.com/tendermint/tendermint/abci/types" sdkclient "github.com/Finschia/finschia-sdk/client" diff --git a/x/authz/msgs.go b/x/authz/msgs.go index dc450663d6..2b00a1b124 100644 --- a/x/authz/msgs.go +++ b/x/authz/msgs.go @@ -29,7 +29,7 @@ var ( // NewMsgGrant creates a new MsgGrant // //nolint:interfacer -func NewMsgGrant(granter sdk.AccAddress, grantee sdk.AccAddress, a Authorization, expiration time.Time) (*MsgGrant, error) { +func NewMsgGrant(granter, grantee sdk.AccAddress, a Authorization, expiration time.Time) (*MsgGrant, error) { m := &MsgGrant{ Granter: granter.String(), Grantee: grantee.String(), @@ -123,7 +123,7 @@ func (msg MsgGrant) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { // NewMsgRevoke creates a new MsgRevoke // //nolint:interfacer -func NewMsgRevoke(granter sdk.AccAddress, grantee sdk.AccAddress, msgTypeURL string) MsgRevoke { +func NewMsgRevoke(granter, grantee sdk.AccAddress, msgTypeURL string) MsgRevoke { return MsgRevoke{ Granter: granter.String(), Grantee: grantee.String(), diff --git a/x/authz/msgs_test.go b/x/authz/msgs_test.go index 590aabb77c..f9868556f7 100644 --- a/x/authz/msgs_test.go +++ b/x/authz/msgs_test.go @@ -115,7 +115,8 @@ func TestMsgGrantGetAuthorization(t *testing.T) { require.Equal(m.GetAuthorization(), &g) g = authz.GenericAuthorization{Msg: "some_type2"} - m.SetAuthorization(&g) + err = m.SetAuthorization(&g) + require.NoError(err) require.Equal(m.GetAuthorization(), &g) } diff --git a/x/authz/simulation/decoder_test.go b/x/authz/simulation/decoder_test.go index 20239cb545..244a9722c4 100644 --- a/x/authz/simulation/decoder_test.go +++ b/x/authz/simulation/decoder_test.go @@ -26,7 +26,7 @@ func TestDecodeStore(t *testing.T) { require.NoError(t, err) kvPairs := kv.Pairs{ Pairs: []kv.Pair{ - {Key: []byte(keeper.GrantKey), Value: grantBz}, + {Key: keeper.GrantKey, Value: grantBz}, {Key: []byte{0x99}, Value: []byte{0x99}}, }, } @@ -41,7 +41,6 @@ func TestDecodeStore(t *testing.T) { } for i, tt := range tests { - i, tt := i, tt t.Run(tt.name, func(t *testing.T) { if tt.expectErr { require.Panics(t, func() { dec(kvPairs.Pairs[i], kvPairs.Pairs[i]) }, tt.name) diff --git a/x/authz/simulation/operations.go b/x/authz/simulation/operations.go index 0817763777..7991a394ad 100644 --- a/x/authz/simulation/operations.go +++ b/x/authz/simulation/operations.go @@ -9,12 +9,10 @@ import ( "github.com/Finschia/finschia-sdk/simapp/helpers" simappparams "github.com/Finschia/finschia-sdk/simapp/params" sdk "github.com/Finschia/finschia-sdk/types" + sdkerrors "github.com/Finschia/finschia-sdk/types/errors" simtypes "github.com/Finschia/finschia-sdk/types/simulation" "github.com/Finschia/finschia-sdk/x/authz" - - sdkerrors "github.com/Finschia/finschia-sdk/types/errors" "github.com/Finschia/finschia-sdk/x/authz/keeper" - banktype "github.com/Finschia/finschia-sdk/x/bank/types" "github.com/Finschia/finschia-sdk/x/simulation" ) @@ -26,10 +24,7 @@ var ( TypeMsgExec = sdk.MsgTypeURL(&authz.MsgExec{}) ) -// nolint:gosec // Simulation operation weights constants -// -//nolint:gosec const ( OpWeightMsgGrant = "op_weight_msg_grant" OpWeightRevoke = "op_weight_msg_revoke" diff --git a/x/authz/simulation/operations_test.go b/x/authz/simulation/operations_test.go index 0d92cc64cc..7e2102ea59 100644 --- a/x/authz/simulation/operations_test.go +++ b/x/authz/simulation/operations_test.go @@ -5,11 +5,10 @@ import ( "testing" "time" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/stretchr/testify/suite" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/finschia-sdk/simapp" sdk "github.com/Finschia/finschia-sdk/types" simtypes "github.com/Finschia/finschia-sdk/types/simulation" @@ -106,7 +105,9 @@ func (suite *SimTestSuite) TestSimulateGrant() { suite.Require().NoError(err) var msg authz.MsgGrant - suite.app.LegacyAmino().UnmarshalJSON(operationMsg.Msg, &msg) + err = suite.app.LegacyAmino().UnmarshalJSON(operationMsg.Msg, &msg) + suite.Require().NoError(err) + suite.Require().True(operationMsg.OK) suite.Require().Equal(granter.Address.String(), msg.Granter) suite.Require().Equal(grantee.Address.String(), msg.Grantee) @@ -143,7 +144,8 @@ func (suite *SimTestSuite) TestSimulateRevoke() { suite.Require().NoError(err) var msg authz.MsgRevoke - suite.app.LegacyAmino().UnmarshalJSON(operationMsg.Msg, &msg) + err = suite.app.LegacyAmino().UnmarshalJSON(operationMsg.Msg, &msg) + suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal(granter.Address.String(), msg.Granter) @@ -177,8 +179,8 @@ func (suite *SimTestSuite) TestSimulateExec() { suite.Require().NoError(err) var msg authz.MsgExec - - suite.app.LegacyAmino().UnmarshalJSON(operationMsg.Msg, &msg) + err = suite.app.LegacyAmino().UnmarshalJSON(operationMsg.Msg, &msg) + suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal(grantee.Address.String(), msg.Grantee) diff --git a/x/bank/bench_test.go b/x/bank/bench_test.go index 68e0720589..5d92ee7eaf 100644 --- a/x/bank/bench_test.go +++ b/x/bank/bench_test.go @@ -3,16 +3,14 @@ package bank_test import ( "testing" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/finschia-sdk/simapp" simappparams "github.com/Finschia/finschia-sdk/simapp/params" sdk "github.com/Finschia/finschia-sdk/types" - "github.com/Finschia/finschia-sdk/x/auth/types" authtypes "github.com/Finschia/finschia-sdk/x/auth/types" stakingtypes "github.com/Finschia/finschia-sdk/x/staking/types" ) @@ -27,7 +25,7 @@ func BenchmarkOneBankSendTxPerBlock(b *testing.B) { } // construct genesis state - genAccs := []types.GenesisAccount{&acc} + genAccs := []authtypes.GenesisAccount{&acc} benchmarkApp := simapp.SetupWithGenesisAccounts(genAccs) ctx := benchmarkApp.BaseApp.NewContext(false, tmproto.Header{}) diff --git a/x/bank/client/testutil/grpc.go b/x/bank/client/testutil/grpc.go index 3d9651eff9..d3b418dc27 100644 --- a/x/bank/client/testutil/grpc.go +++ b/x/bank/client/testutil/grpc.go @@ -88,7 +88,6 @@ func (s *IntegrationTestSuite) TestTotalSupplyGRPCHandler() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Require().NoError(err) @@ -209,7 +208,6 @@ func (s *IntegrationTestSuite) TestDenomMetadataGRPCHandler() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Require().NoError(err) @@ -273,7 +271,6 @@ func (s *IntegrationTestSuite) TestBalancesGRPCHandler() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) diff --git a/x/bank/client/testutil/suite.go b/x/bank/client/testutil/suite.go index 9688f3f105..e718d96b94 100644 --- a/x/bank/client/testutil/suite.go +++ b/x/bank/client/testutil/suite.go @@ -3,11 +3,10 @@ package testutil import ( "fmt" + ostcli "github.com/Finschia/ostracon/libs/cli" "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" - ostcli "github.com/Finschia/ostracon/libs/cli" - "github.com/Finschia/finschia-sdk/client/flags" clitestutil "github.com/Finschia/finschia-sdk/testutil/cli" "github.com/Finschia/finschia-sdk/testutil/network" @@ -146,8 +145,6 @@ func (s *IntegrationTestSuite) TestGetBalancesCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetBalancesCmd() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, tc.args) @@ -226,8 +223,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryTotalSupply() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryTotalSupply() clientCtx := val.ClientCtx @@ -368,8 +363,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryDenomsMetadata() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdDenomsMetadata() clientCtx := val.ClientCtx @@ -476,8 +469,6 @@ func (s *IntegrationTestSuite) TestNewSendTxCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { clientCtx := val.ClientCtx diff --git a/x/bank/keeper/genesis.go b/x/bank/keeper/genesis.go index fe680e04ee..065bd8d37b 100644 --- a/x/bank/keeper/genesis.go +++ b/x/bank/keeper/genesis.go @@ -42,7 +42,7 @@ func (k BaseKeeper) InitGenesis(ctx sdk.Context, genState *types.GenesisState) { func (k BaseKeeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { totalSupply, _, err := k.GetPaginatedTotalSupply(ctx, &query.PageRequest{Limit: query.MaxLimit}) if err != nil { - panic(fmt.Errorf("unable to fetch total supply %v", err)) + panic(fmt.Errorf("unable to fetch total supply: %w", err)) } return types.NewGenesisState( diff --git a/x/bank/keeper/genesis_test.go b/x/bank/keeper/genesis_test.go index 4c5c6ea86b..36aee9a1a9 100644 --- a/x/bank/keeper/genesis_test.go +++ b/x/bank/keeper/genesis_test.go @@ -99,7 +99,6 @@ func (suite *IntegrationTestSuite) TestTotalSupply() { } for _, tc := range testcases { - tc := tc suite.Run(tc.name, func() { if tc.expPanic { suite.PanicsWithError(tc.expPanicMsg, func() { suite.app.BankKeeper.InitGenesis(suite.ctx, tc.genesis) }) diff --git a/x/bank/keeper/grpc_query_test.go b/x/bank/keeper/grpc_query_test.go index 6d18ddd11c..398e2ead13 100644 --- a/x/bank/keeper/grpc_query_test.go +++ b/x/bank/keeper/grpc_query_test.go @@ -84,6 +84,7 @@ func (suite *IntegrationTestSuite) TestQueryAllBalances() { } req = types.NewQueryAllBalancesRequest(addr, pageReq) res, err = queryClient.AllBalances(gocontext.Background(), req) + suite.Require().NoError(err) suite.Equal(res.Balances.Len(), 1) suite.Nil(res.Pagination.NextKey) } diff --git a/x/bank/keeper/keeper.go b/x/bank/keeper/keeper.go index 3e004a1e31..e66d63f267 100644 --- a/x/bank/keeper/keeper.go +++ b/x/bank/keeper/keeper.go @@ -72,7 +72,7 @@ func (k BaseKeeper) GetPaginatedTotalSupply(ctx sdk.Context, pagination *query.P var amount sdk.Int err := amount.Unmarshal(value) if err != nil { - return fmt.Errorf("unable to convert amount string to Int %v", err) + return fmt.Errorf("unable to convert amount string to Int: %w", err) } // `Add` omits the 0 coins addition to the `supply`. @@ -231,7 +231,7 @@ func (k BaseKeeper) GetSupply(ctx sdk.Context, denom string) sdk.Coin { var amount sdk.Int err := amount.Unmarshal(bz) if err != nil { - panic(fmt.Errorf("unable to unmarshal supply value %v", err)) + panic(fmt.Errorf("unable to unmarshal supply value: %w", err)) } return sdk.Coin{ @@ -466,7 +466,7 @@ func (k BaseKeeper) BurnCoins(ctx sdk.Context, moduleName string, amounts sdk.Co func (k BaseKeeper) setSupply(ctx sdk.Context, coin sdk.Coin) { intBytes, err := coin.Amount.Marshal() if err != nil { - panic(fmt.Errorf("unable to marshal amount value %v", err)) + panic(fmt.Errorf("unable to marshal amount value: %w", err)) } store := ctx.KVStore(k.storeKey) @@ -528,7 +528,7 @@ func (k BaseViewKeeper) IterateTotalSupply(ctx sdk.Context, cb func(sdk.Coin) bo var amount sdk.Int err := amount.Unmarshal(iterator.Value()) if err != nil { - panic(fmt.Errorf("unable to unmarshal supply value %v", err)) + panic(fmt.Errorf("unable to unmarshal supply value: %w", err)) } balance := sdk.Coin{ diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index 2c91672454..74a33782c7 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -5,12 +5,11 @@ import ( "testing" "time" + osttime "github.com/Finschia/ostracon/types/time" "github.com/stretchr/testify/suite" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - osttime "github.com/Finschia/ostracon/types/time" - "github.com/Finschia/finschia-sdk/baseapp" "github.com/Finschia/finschia-sdk/simapp" sdk "github.com/Finschia/finschia-sdk/types" @@ -192,15 +191,15 @@ func (suite *IntegrationTestSuite) TestSupply_SendCoins() { authKeeper.SetAccount(ctx, baseAcc) suite.Require().Panics(func() { - _ = keeper.SendCoinsFromModuleToModule(ctx, "", holderAcc.GetName(), initCoins) // nolint:errcheck + _ = keeper.SendCoinsFromModuleToModule(ctx, "", holderAcc.GetName(), initCoins) }) suite.Require().Panics(func() { - _ = keeper.SendCoinsFromModuleToModule(ctx, authtypes.Burner, "", initCoins) // nolint:errcheck + _ = keeper.SendCoinsFromModuleToModule(ctx, authtypes.Burner, "", initCoins) }) suite.Require().Panics(func() { - _ = keeper.SendCoinsFromModuleToAccount(ctx, "", baseAcc.GetAddress(), initCoins) // nolint:errcheck + _ = keeper.SendCoinsFromModuleToAccount(ctx, "", baseAcc.GetAddress(), initCoins) }) suite.Require().Error( @@ -288,6 +287,7 @@ func (suite *IntegrationTestSuite) TestSupply_BurnCoins() { Require(). NoError(keeper.MintCoins(ctx, authtypes.Minter, initCoins)) supplyAfterInflation, _, err := keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) + suite.Require().NoError(err) suite.Require().Panics(func() { keeper.BurnCoins(ctx, "", initCoins) }, "no module account") // nolint:errcheck suite.Require().Panics(func() { keeper.BurnCoins(ctx, authtypes.Minter, initCoins) }, "invalid permission") // nolint:errcheck @@ -313,8 +313,8 @@ func (suite *IntegrationTestSuite) TestSupply_BurnCoins() { authKeeper.SetModuleAccount(ctx, multiPermAcc) err = keeper.BurnCoins(ctx, multiPermAcc.GetName(), initCoins) - supplyAfterBurn, _, err = keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) suite.Require().NoError(err) + supplyAfterBurn, _, err = keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) suite.Require().NoError(err) suite.Require().Equal(sdk.NewCoins().String(), getCoinsByName(ctx, keeper, authKeeper, multiPermAcc.GetName()).String()) suite.Require().Equal(supplyAfterInflation.Sub(initCoins), supplyAfterBurn) @@ -1127,9 +1127,9 @@ func (suite *IntegrationTestSuite) getTestMetadata() []types.Metadata { Symbol: "ATOM", Description: "The native staking token of the Cosmos Hub.", DenomUnits: []*types.DenomUnit{ - {"uatom", uint32(0), []string{"microatom"}}, - {"matom", uint32(3), []string{"milliatom"}}, - {"atom", uint32(6), nil}, + {Denom: "uatom", Exponent: uint32(0), Aliases: []string{"microatom"}}, + {Denom: "matom", Exponent: uint32(3), Aliases: []string{"milliatom"}}, + {Denom: "atom", Exponent: uint32(6), Aliases: nil}, }, Base: "uatom", Display: "atom", @@ -1139,9 +1139,9 @@ func (suite *IntegrationTestSuite) getTestMetadata() []types.Metadata { Symbol: "TOKEN", Description: "The native staking token of the Token Hub.", DenomUnits: []*types.DenomUnit{ - {"1token", uint32(5), []string{"decitoken"}}, - {"2token", uint32(4), []string{"centitoken"}}, - {"3token", uint32(7), []string{"dekatoken"}}, + {Denom: "1token", Exponent: uint32(5), Aliases: []string{"decitoken"}}, + {Denom: "2token", Exponent: uint32(4), Aliases: []string{"centitoken"}}, + {Denom: "3token", Exponent: uint32(7), Aliases: []string{"dekatoken"}}, }, Base: "utoken", Display: "token", diff --git a/x/bank/keeper/send.go b/x/bank/keeper/send.go index 6af6cfe550..bf4d4e279f 100644 --- a/x/bank/keeper/send.go +++ b/x/bank/keeper/send.go @@ -15,7 +15,7 @@ type SendKeeper interface { ViewKeeper InputOutputCoins(ctx sdk.Context, inputs []types.Input, outputs []types.Output) error - SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error + SendCoins(ctx sdk.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) error GetParams(ctx sdk.Context) types.Params SetParams(ctx sdk.Context, params types.Params) @@ -122,7 +122,7 @@ func (k BaseSendKeeper) InputOutputCoins(ctx sdk.Context, inputs []types.Input, // SendCoins transfers amt coins from a sending account to a receiving account. // An error is returned upon failure. -func (k BaseSendKeeper) SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error { +func (k BaseSendKeeper) SendCoins(ctx sdk.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) error { err := k.subUnlockedCoins(ctx, fromAddr, amt) if err != nil { return err diff --git a/x/bank/legacy/v040/types.go b/x/bank/legacy/v040/types.go index 40384aeed9..4023f10ea0 100644 --- a/x/bank/legacy/v040/types.go +++ b/x/bank/legacy/v040/types.go @@ -1,7 +1,7 @@ package v040 import ( - "github.com/golang/protobuf/proto" //nolint:staticcheck + "github.com/golang/protobuf/proto" codectypes "github.com/Finschia/finschia-sdk/codec/types" "github.com/Finschia/finschia-sdk/x/bank/types" @@ -26,6 +26,6 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) { registry.RegisterInterface( "cosmos.bank.v1beta1.SupplyI", (*SupplyI)(nil), - &types.Supply{}, //nolint:staticcheck + &types.Supply{}, ) } diff --git a/x/bank/legacy/v043/store.go b/x/bank/legacy/v043/store.go index f4506d4287..4239b197a0 100644 --- a/x/bank/legacy/v043/store.go +++ b/x/bank/legacy/v043/store.go @@ -32,7 +32,7 @@ func migrateSupply(store sdk.KVStore, cdc codec.BinaryCodec) error { // We're sure that SupplyI is a Supply struct, there's no other // implementation. - oldSupply := oldSupplyI.(*types.Supply) //nolint:staticcheck + oldSupply := oldSupplyI.(*types.Supply) for i := range oldSupply.Total { coin := oldSupply.Total[i] coinBz, err := coin.Amount.Marshal() diff --git a/x/bank/legacy/v043/store_test.go b/x/bank/legacy/v043/store_test.go index 03efb00705..8269f4ba95 100644 --- a/x/bank/legacy/v043/store_test.go +++ b/x/bank/legacy/v043/store_test.go @@ -26,8 +26,7 @@ func TestSupplyMigration(t *testing.T) { oldFooBarCoin := sdk.NewCoin("foobar", sdk.NewInt(0)) // to ensure the zero denom coins pruned. // Old supply was stored as a single blob under the `SupplyKey`. - var oldSupply v040bank.SupplyI - oldSupply = &types.Supply{Total: sdk.Coins{oldFooCoin, oldBarCoin, oldFooBarCoin}} + oldSupply := &types.Supply{Total: sdk.Coins{oldFooCoin, oldBarCoin, oldFooBarCoin}} oldSupplyBz, err := encCfg.Marshaler.MarshalInterface(oldSupply) require.NoError(t, err) store.Set(v040bank.SupplyKey, oldSupplyBz) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 9cfe944814..e1652619df 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -16,11 +16,10 @@ import ( "github.com/Finschia/finschia-sdk/x/simulation" ) -// nolint:gosec // Simulation operation weights constants const ( - OpWeightMsgSend = "op_weight_msg_send" //nolint:gosec - OpWeightMsgMultiSend = "op_weight_msg_multisend" //nolint:gosec + OpWeightMsgSend = "op_weight_msg_send" + OpWeightMsgMultiSend = "op_weight_msg_multisend" ) // WeightedOperations returns all the operations from the module with their respective weights diff --git a/x/bank/simulation/operations_test.go b/x/bank/simulation/operations_test.go index fc67f57647..9e86b22a82 100644 --- a/x/bank/simulation/operations_test.go +++ b/x/bank/simulation/operations_test.go @@ -4,11 +4,10 @@ import ( "math/rand" "testing" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/stretchr/testify/suite" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/finschia-sdk/simapp" simappparams "github.com/Finschia/finschia-sdk/simapp/params" sdk "github.com/Finschia/finschia-sdk/types" @@ -80,7 +79,8 @@ func (suite *SimTestSuite) TestSimulateMsgSend() { suite.Require().NoError(err) var msg types.MsgSend - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal("65337742stake", msg.Amount.String()) @@ -109,7 +109,8 @@ func (suite *SimTestSuite) TestSimulateMsgMultiSend() { require.NoError(err) var msg types.MsgMultiSend - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + require.NoError(err) require.True(operationMsg.OK) require.Len(msg.Inputs, 3) @@ -147,7 +148,8 @@ func (suite *SimTestSuite) TestSimulateModuleAccountMsgSend() { suite.Require().Error(err) var msg types.MsgSend - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + suite.Require().Error(err) suite.Require().False(operationMsg.OK) suite.Require().Equal(operationMsg.Comment, "invalid transfers") @@ -177,7 +179,8 @@ func (suite *SimTestSuite) TestSimulateMsgMultiSendToModuleAccount() { suite.Require().Error(err) var msg types.MsgMultiSend - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + suite.Require().Error(err) suite.Require().False(operationMsg.OK) // sending tokens to a module account should fail suite.Require().Equal(operationMsg.Comment, "invalid transfers") diff --git a/x/bank/simulation/params.go b/x/bank/simulation/params.go index d44d30c580..fcb5b18cdc 100644 --- a/x/bank/simulation/params.go +++ b/x/bank/simulation/params.go @@ -7,10 +7,9 @@ import ( "fmt" "math/rand" - "github.com/Finschia/finschia-sdk/x/simulation" - simtypes "github.com/Finschia/finschia-sdk/types/simulation" "github.com/Finschia/finschia-sdk/x/bank/types" + "github.com/Finschia/finschia-sdk/x/simulation" ) // ParamChanges defines the parameters that can be modified by param change proposals diff --git a/x/bank/types/balance_test.go b/x/bank/types/balance_test.go index 9261395751..7080371306 100644 --- a/x/bank/types/balance_test.go +++ b/x/bank/types/balance_test.go @@ -102,7 +102,6 @@ func TestBalanceValidate(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { err := tc.balance.Validate() @@ -126,7 +125,6 @@ func TestBalance_GetAddress(t *testing.T) { {"valid address", "link1vy0ga0klndqy92ceqehfkvgmn4t94ete4mhemy", false}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { b := bank.Balance{Address: tt.Address} if tt.wantPanic { @@ -191,6 +189,7 @@ func BenchmarkSanitizeBalances1000(b *testing.B) { } func benchmarkSanitizeBalances(b *testing.B, nAddresses int) { + b.Helper() b.ReportAllocs() tokens := sdk.TokensFromConsensusPower(81, sdk.DefaultPowerReduction) coin := sdk.NewCoin("benchcoin", tokens) diff --git a/x/bank/types/genesis_test.go b/x/bank/types/genesis_test.go index d5588245b2..637306464a 100644 --- a/x/bank/types/genesis_test.go +++ b/x/bank/types/genesis_test.go @@ -143,7 +143,6 @@ func TestGenesisStateValidate(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { err := tc.genesisState.Validate() diff --git a/x/bank/types/key.go b/x/bank/types/key.go index a4c8dfa250..49a0be91cb 100644 --- a/x/bank/types/key.go +++ b/x/bank/types/key.go @@ -54,6 +54,6 @@ func CreateAccountBalancesPrefix(addr []byte) []byte { // CreatePrefixedAccountStoreKey returns the key for the given account and denomination. // This method can be used when performing an ABCI query for the balance of an account. -func CreatePrefixedAccountStoreKey(addr []byte, denom []byte) []byte { +func CreatePrefixedAccountStoreKey(addr, denom []byte) []byte { return append(CreateAccountBalancesPrefix(addr), denom...) } diff --git a/x/bank/types/key_test.go b/x/bank/types/key_test.go index 9501659767..193001f4f5 100644 --- a/x/bank/types/key_test.go +++ b/x/bank/types/key_test.go @@ -12,7 +12,7 @@ import ( "github.com/Finschia/finschia-sdk/x/bank/types" ) -func cloneAppend(bz []byte, tail []byte) (res []byte) { +func cloneAppend(bz, tail []byte) (res []byte) { res = make([]byte, len(bz)+len(tail)) copy(res, bz) copy(res[len(bz):], tail) @@ -39,7 +39,6 @@ func TestAddressFromBalancesStore(t *testing.T) { } for _, tc := range tests { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() addr, err := types.AddressFromBalancesStore(tc.key) diff --git a/x/bank/types/metadata_test.go b/x/bank/types/metadata_test.go index 1201e0473b..d895a0226d 100644 --- a/x/bank/types/metadata_test.go +++ b/x/bank/types/metadata_test.go @@ -216,7 +216,6 @@ func TestMetadataValidate(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { err := tc.metadata.Validate() @@ -258,7 +257,6 @@ func TestMarshalJSONMetaData(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { bz, err := cdc.MarshalJSON(tc.input) require.NoError(t, err) diff --git a/x/bank/types/params_test.go b/x/bank/types/params_test.go index 0962d125c1..1ca04f6474 100644 --- a/x/bank/types/params_test.go +++ b/x/bank/types/params_test.go @@ -29,7 +29,6 @@ func Test_validateSendEnabledParam(t *testing.T) { {"invalid denom send disabled", args{*NewSendEnabled("0FOO", false)}, true}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { require.Equal(t, tt.wantErr, validateSendEnabled(tt.args.i) != nil) }) diff --git a/x/bankplus/keeper/inactive.go b/x/bankplus/keeper/inactive.go index 95d1a6d7e1..63eddd8e28 100644 --- a/x/bankplus/keeper/inactive.go +++ b/x/bankplus/keeper/inactive.go @@ -14,8 +14,6 @@ func inactiveAddrKey(addr sdk.AccAddress) []byte { } // isStoredInactiveAddr checks if the address is stored or not as blocked address -// -//nolint:deadcode,unused func (keeper BaseKeeper) isStoredInactiveAddr(ctx sdk.Context, address sdk.AccAddress) bool { store := ctx.KVStore(keeper.storeKey) bz := store.Get(inactiveAddrKey(address)) diff --git a/x/bankplus/keeper/inactive_test.go b/x/bankplus/keeper/inactive_test.go index 28b2843826..0e43ee5081 100644 --- a/x/bankplus/keeper/inactive_test.go +++ b/x/bankplus/keeper/inactive_test.go @@ -1,15 +1,14 @@ package keeper import ( - "math/rand" + "crypto/rand" "testing" + "github.com/Finschia/ostracon/libs/log" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/codec" codectypes "github.com/Finschia/finschia-sdk/codec/types" "github.com/Finschia/finschia-sdk/store" @@ -22,7 +21,10 @@ import ( func genAddress() sdk.AccAddress { b := make([]byte, 20) - rand.Read(b) + _, err := rand.Read(b) + if err != nil { + panic(err) + } return b } @@ -41,6 +43,7 @@ func setupKeeper(storeKey *sdk.KVStoreKey) BaseKeeper { } func setupContext(t *testing.T, storeKey *sdk.KVStoreKey) sdk.Context { + t.Helper() db := dbm.NewMemDB() stateStore := store.NewCommitMultiStore(db) stateStore.MountStoreWithDB(storeKey, sdk.StoreTypeIAVL, db) diff --git a/x/bankplus/keeper/keeper.go b/x/bankplus/keeper/keeper.go index 7e87273b75..a00d6c716f 100644 --- a/x/bankplus/keeper/keeper.go +++ b/x/bankplus/keeper/keeper.go @@ -104,7 +104,7 @@ func (keeper BaseKeeper) isInactiveAddr(addr sdk.AccAddress) bool { // SendCoins transfers amt coins from a sending account to a receiving account. // This is wrapped bank the `SendKeeper` interface of `bank` module, // and checks if `toAddr` is a inactiveAddr managed by the module. -func (keeper BaseKeeper) SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error { +func (keeper BaseKeeper) SendCoins(ctx sdk.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) error { // if toAddr is smart contract, check the status of contract. if keeper.isInactiveAddr(toAddr) { return sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", toAddr) diff --git a/x/bankplus/keeper/keeper_test.go b/x/bankplus/keeper/keeper_test.go index 3486106a61..37f271d7c7 100644 --- a/x/bankplus/keeper/keeper_test.go +++ b/x/bankplus/keeper/keeper_test.go @@ -294,7 +294,6 @@ func (suite *IntegrationTestSuite) TestInputOutputCoins() { } for name, tc := range tcs { - tc := tc suite.T().Run(name, func(t *testing.T) { if tc.err != nil { suite.EqualError(targetKeeper(tc.deactMultiSend).InputOutputCoins(ctx, input, output), tc.err.Error()) diff --git a/x/capability/capability_test.go b/x/capability/capability_test.go index ae48072ce0..d20de33e1f 100644 --- a/x/capability/capability_test.go +++ b/x/capability/capability_test.go @@ -3,6 +3,7 @@ package capability_test import ( "testing" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/stretchr/testify/suite" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" @@ -14,7 +15,6 @@ import ( "github.com/Finschia/finschia-sdk/x/capability" "github.com/Finschia/finschia-sdk/x/capability/keeper" "github.com/Finschia/finschia-sdk/x/capability/types" - ocabci "github.com/Finschia/ostracon/abci/types" ) type CapabilityTestSuite struct { diff --git a/x/capability/genesis_test.go b/x/capability/genesis_test.go index e7685c8e73..abc82b15ba 100644 --- a/x/capability/genesis_test.go +++ b/x/capability/genesis_test.go @@ -1,10 +1,9 @@ package capability_test import ( - dbm "github.com/tendermint/tm-db" - "github.com/Finschia/ostracon/libs/log" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/simapp" sdk "github.com/Finschia/finschia-sdk/types" diff --git a/x/capability/keeper/keeper.go b/x/capability/keeper/keeper.go index 2cbb054db4..dd883f2711 100644 --- a/x/capability/keeper/keeper.go +++ b/x/capability/keeper/keeper.go @@ -204,7 +204,7 @@ func (k Keeper) InitializeCapability(ctx sdk.Context, index uint64, owners types memStore.Set(types.FwdCapabilityKey(owner.Module, cap), []byte(owner.Name)) // Set the reverse mapping between the module and capability name and the - // index in the in-memory store. Since marshalling and unmarshalling into a store + // index in the in-memory store. Since marshaling and unmarshalling into a store // will change memory address of capability, we simply store index as value here // and retrieve the in-memory pointer to the capability from our map memStore.Set(types.RevCapabilityKey(owner.Module, owner.Name), sdk.Uint64ToBigEndian(index)) @@ -252,7 +252,7 @@ func (sk ScopedKeeper) NewCapability(ctx sdk.Context, name string) (*types.Capab memStore.Set(types.FwdCapabilityKey(sk.module, cap), []byte(name)) // Set the reverse mapping between the module and capability name and the - // index in the in-memory store. Since marshalling and unmarshalling into a store + // index in the in-memory store. Since marshaling and unmarshalling into a store // will change memory address of capability, we simply store index as value here // and retrieve the in-memory pointer to the capability from our map memStore.Set(types.RevCapabilityKey(sk.module, name), sdk.Uint64ToBigEndian(index)) @@ -304,7 +304,7 @@ func (sk ScopedKeeper) ClaimCapability(ctx sdk.Context, cap *types.Capability, n memStore.Set(types.FwdCapabilityKey(sk.module, cap), []byte(name)) // Set the reverse mapping between the module and capability name and the - // index in the in-memory store. Since marshalling and unmarshalling into a store + // index in the in-memory store. Since marshaling and unmarshalling into a store // will change memory address of capability, we simply store index as value here // and retrieve the in-memory pointer to the capability from our map memStore.Set(types.RevCapabilityKey(sk.module, name), sdk.Uint64ToBigEndian(cap.GetIndex())) diff --git a/x/capability/keeper/keeper_test.go b/x/capability/keeper/keeper_test.go index 0204396ceb..71fe9e741e 100644 --- a/x/capability/keeper/keeper_test.go +++ b/x/capability/keeper/keeper_test.go @@ -145,7 +145,8 @@ func (suite *KeeperTestSuite) TestAuthenticateCapability() { suite.Require().False(sk2.AuthenticateCapability(suite.ctx, cap2, "invalid")) suite.Require().False(sk2.AuthenticateCapability(suite.ctx, cap1, "bond")) - sk2.ReleaseCapability(suite.ctx, cap2) + err = sk2.ReleaseCapability(suite.ctx, cap2) + suite.Require().NoError(err) suite.Require().False(sk2.AuthenticateCapability(suite.ctx, cap2, "bond")) badCap := types.NewCapability(100) @@ -277,7 +278,7 @@ func (suite *KeeperTestSuite) TestReleaseCapability() { suite.Require().Error(sk1.ReleaseCapability(suite.ctx, nil)) } -func (suite KeeperTestSuite) TestRevertCapability() { +func (suite *KeeperTestSuite) TestRevertCapability() { sk := suite.keeper.ScopeToModule(banktypes.ModuleName) ms := suite.ctx.MultiStore() diff --git a/x/capability/module.go b/x/capability/module.go index 07181e22c1..3be6486d7e 100644 --- a/x/capability/module.go +++ b/x/capability/module.go @@ -6,10 +6,9 @@ import ( "math/rand" "time" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" - - ocabci "github.com/Finschia/ostracon/abci/types" abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/client" diff --git a/x/capability/simulation/decoder_test.go b/x/capability/simulation/decoder_test.go index d12e8b5044..ce87e508e6 100644 --- a/x/capability/simulation/decoder_test.go +++ b/x/capability/simulation/decoder_test.go @@ -47,7 +47,6 @@ func TestDecodeStore(t *testing.T) { } for i, tt := range tests { - i, tt := i, tt t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: diff --git a/x/capability/types/genesis_test.go b/x/capability/types/genesis_test.go index 5208a2b590..41525fb827 100644 --- a/x/capability/types/genesis_test.go +++ b/x/capability/types/genesis_test.go @@ -112,7 +112,6 @@ func TestValidateGenesis(t *testing.T) { } for _, tc := range testCases { - tc := tc genState := DefaultGenesis() tc.malleate(genState) err := genState.Validate() diff --git a/x/capability/types/keys_test.go b/x/capability/types/keys_test.go index 7a4efbad56..53b0e3e5ac 100644 --- a/x/capability/types/keys_test.go +++ b/x/capability/types/keys_test.go @@ -34,7 +34,7 @@ func TestIndexFromKey(t *testing.T) { require.Equal(t, uint64(3162), types.IndexFromKey([]byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xc, 0x5a})) } -// to test the backward compatibiltiy of the new function +// to test the backward compatibility of the new function func legacyFwdCapabilityKey(module string, cap *types.Capability) []byte { return []byte(fmt.Sprintf("%s/fwd/%p", module, cap)) } diff --git a/x/collection/client/cli/tx.go b/x/collection/client/cli/tx.go index 165e6da1df..79e5a3df65 100644 --- a/x/collection/client/cli/tx.go +++ b/x/collection/client/cli/tx.go @@ -352,10 +352,10 @@ func NewTxCmdIssueFT() *cobra.Command { flags.AddTxFlagsToCmd(cmd) cmd.Flags().String(FlagName, "", "set name") - cmd.MarkFlagRequired(FlagName) + _ = cmd.MarkFlagRequired(FlagName) cmd.Flags().String(FlagMeta, "", "set meta") cmd.Flags().String(FlagTo, "", "address to send the initial supply") - cmd.MarkFlagRequired(FlagTo) + _ = cmd.MarkFlagRequired(FlagTo) cmd.Flags().Bool(FlagMintable, false, "set mintable") cmd.Flags().String(FlagSupply, DefaultSupply, "initial supply") cmd.Flags().Int32(FlagDecimals, DefaultDecimals, "set decimals") @@ -506,7 +506,7 @@ func NewTxCmdMintNFT() *cobra.Command { flags.AddTxFlagsToCmd(cmd) cmd.Flags().String(FlagName, "", "set name") cmd.Flags().String(FlagMeta, "", "set meta") - cmd.MarkFlagRequired(FlagName) + _ = cmd.MarkFlagRequired(FlagName) return cmd } diff --git a/x/collection/client/testutil/query.go b/x/collection/client/testutil/query.go index 592567c363..47b957bd25 100644 --- a/x/collection/client/testutil/query.go +++ b/x/collection/client/testutil/query.go @@ -65,8 +65,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdBalance() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdBalances() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -141,8 +139,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdFTSupply() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdFTSupply() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -217,8 +213,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdFTMinted() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdFTMinted() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -293,8 +287,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdFTBurnt() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdFTBurnt() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -368,8 +360,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdNFTSupply() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdNFTSupply() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -443,8 +433,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdNFTMinted() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdNFTMinted() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -518,8 +506,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdNFTBurnt() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdNFTBurnt() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -573,8 +559,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdContract() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdContract() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -643,8 +627,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdTokenType() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdTokenType() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -719,8 +701,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdToken() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdToken() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -793,8 +773,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdRoot() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdRoot() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -865,8 +843,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdParent() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdParent() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -941,8 +917,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdChildren() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdChildren() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -1020,8 +994,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdGranteeGrants() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdGranteeGrants() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -1082,8 +1054,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdIsOperatorFor() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdIsOperatorFor() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -1142,8 +1112,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdHoldersByOperator() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdHoldersByOperator() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) diff --git a/x/collection/client/testutil/suite.go b/x/collection/client/testutil/suite.go index 342b967f97..d19cf1c71d 100644 --- a/x/collection/client/testutil/suite.go +++ b/x/collection/client/testutil/suite.go @@ -5,6 +5,7 @@ import ( "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" + abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/crypto/hd" @@ -15,7 +16,6 @@ import ( bankcli "github.com/Finschia/finschia-sdk/x/bank/client/cli" "github.com/Finschia/finschia-sdk/x/collection" "github.com/Finschia/finschia-sdk/x/collection/client/cli" - abci "github.com/tendermint/tendermint/abci/types" ) type IntegrationTestSuite struct { @@ -135,12 +135,8 @@ func (s *IntegrationTestSuite) SetupSuite() { } func (s *IntegrationTestSuite) pickEvent(events []abci.Event, event proto.Message, fn func(event proto.Message)) { - getType := func(msg proto.Message) string { - return proto.MessageName(msg) - } - for _, e := range events { - if e.Type == getType(event) { + if e.Type == proto.MessageName(event) { msg, err := sdk.ParseTypedEvent(e) s.Require().NoError(err) diff --git a/x/collection/client/testutil/tx.go b/x/collection/client/testutil/tx.go index a0aee34cde..b7c18d0e0a 100644 --- a/x/collection/client/testutil/tx.go +++ b/x/collection/client/testutil/tx.go @@ -71,8 +71,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdSendFT() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdSendFT() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -155,8 +153,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdOperatorSendFT() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdOperatorSendFT() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -234,8 +230,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdSendNFT() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdSendNFT() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -318,8 +312,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdOperatorSendNFT() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdOperatorSendNFT() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -374,8 +366,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdCreateContract() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdCreateContract() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -441,8 +431,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdIssueFT() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdIssueFT() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -502,8 +490,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdIssueNFT() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdIssueNFT() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -575,8 +561,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdMintFT() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdMintFT() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -645,8 +629,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdMintNFT() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdMintNFT() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -711,8 +693,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdBurnFT() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdBurnFT() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -781,8 +761,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdOperatorBurnFT() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdOperatorBurnFT() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -847,8 +825,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdBurnNFT() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdBurnNFT() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -917,8 +893,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdOperatorOperatorBurnNFT() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdOperatorBurnNFT() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -994,8 +968,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdModify() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdModify() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -1065,8 +1037,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdAttach() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdAttach() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -1131,8 +1101,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdDetach() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdDetach() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -1206,8 +1174,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdOperatorAttach() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdOperatorAttach() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -1276,8 +1242,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdOperatorDetach() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdOperatorDetach() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -1336,8 +1300,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdGrantPermission() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdGrantPermission() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -1393,8 +1355,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdRevokePermission() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdRevokePermission() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -1450,8 +1410,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdAuthorizeOperator() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdAuthorizeOperator() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -1507,8 +1465,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdRevokeOperator() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdRevokeOperator() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) diff --git a/x/collection/collection_test.go b/x/collection/collection_test.go index c3c7a490a3..5edecf1a3a 100644 --- a/x/collection/collection_test.go +++ b/x/collection/collection_test.go @@ -10,8 +10,10 @@ import ( "github.com/Finschia/finschia-sdk/x/collection" ) +const TestContractID = "deadbeef" + func TestFTClass(t *testing.T) { - nextIDs := collection.DefaultNextClassIDs("deadbeef") + nextIDs := collection.DefaultNextClassIDs(TestContractID) testCases := map[string]struct { id string name string @@ -38,8 +40,7 @@ func TestFTClass(t *testing.T) { for name, tc := range testCases { t.Run(name, func(t *testing.T) { - var class collection.TokenClass - class = &collection.FTClass{ + class := &collection.FTClass{ Id: tc.id, Decimals: tc.decimals, } @@ -61,7 +62,7 @@ func TestFTClass(t *testing.T) { } func TestNFTClass(t *testing.T) { - nextIDs := collection.DefaultNextClassIDs("deadbeef") + nextIDs := collection.DefaultNextClassIDs(TestContractID) testCases := map[string]struct { name string meta string @@ -80,8 +81,7 @@ func TestNFTClass(t *testing.T) { for name, tc := range testCases { t.Run(name, func(t *testing.T) { - var class collection.TokenClass - class = &collection.NFTClass{} + class := &collection.NFTClass{} class.SetId(&nextIDs) class.SetName(tc.name) class.SetMeta(tc.meta) @@ -144,10 +144,10 @@ func TestParseCoins(t *testing.T) { ), }, "valid multiple coins": { - input: "deadbeef00000001:1,00bab10c00000000:10", + input: fmt.Sprintf("%s00000001:1,00bab10c00000000:10", TestContractID), valid: true, expected: collection.NewCoins( - collection.NewNFTCoin("deadbeef", 1), + collection.NewNFTCoin(TestContractID, 1), collection.NewFTCoin("00bab10c", sdk.NewInt(10)), ), }, @@ -173,7 +173,7 @@ func TestParseCoins(t *testing.T) { } func TestDefaultNextClassIDs(t *testing.T) { - contractID := "deadbeef" + contractID := TestContractID require.Equal(t, collection.NextClassIDs{ ContractId: contractID, Fungible: sdk.NewUint(1), diff --git a/x/collection/genesis.go b/x/collection/genesis.go index 7a80d0a2cd..028101b3f7 100644 --- a/x/collection/genesis.go +++ b/x/collection/genesis.go @@ -2,7 +2,6 @@ package collection import ( codectypes "github.com/Finschia/finschia-sdk/codec/types" - sdk "github.com/Finschia/finschia-sdk/types" sdkerrors "github.com/Finschia/finschia-sdk/types/errors" ) diff --git a/x/collection/keeper/alias.go b/x/collection/keeper/alias.go index dc18fbb3cc..f3f7827f3f 100644 --- a/x/collection/keeper/alias.go +++ b/x/collection/keeper/alias.go @@ -153,12 +153,12 @@ func (k Keeper) iterateNFTsImpl(ctx sdk.Context, prefix []byte, fn func(contract } func (k Keeper) iterateContractParents(ctx sdk.Context, contractID string, fn func(tokenID, parentID string) (stop bool)) { - k.iterateParentsImpl(ctx, parentKeyPrefixByContractID(contractID), func(_ string, tokenID, parentID string) (stop bool) { + k.iterateParentsImpl(ctx, parentKeyPrefixByContractID(contractID), func(_, tokenID, parentID string) (stop bool) { return fn(tokenID, parentID) }) } -func (k Keeper) iterateParentsImpl(ctx sdk.Context, prefix []byte, fn func(contractID string, tokenID, parentID string) (stop bool)) { +func (k Keeper) iterateParentsImpl(ctx sdk.Context, prefix []byte, fn func(contractID, tokenID, parentID string) (stop bool)) { store := ctx.KVStore(k.storeKey) iter := sdk.KVStorePrefixIterator(store, prefix) @@ -175,7 +175,7 @@ func (k Keeper) iterateParentsImpl(ctx sdk.Context, prefix []byte, fn func(contr } } -func (k Keeper) iterateChildrenImpl(ctx sdk.Context, prefix []byte, fn func(contractID string, tokenID, childID string) (stop bool)) { +func (k Keeper) iterateChildrenImpl(ctx sdk.Context, prefix []byte, fn func(contractID, tokenID, childID string) (stop bool)) { store := ctx.KVStore(k.storeKey) iter := sdk.KVStorePrefixIterator(store, prefix) @@ -188,7 +188,7 @@ func (k Keeper) iterateChildrenImpl(ctx sdk.Context, prefix []byte, fn func(cont } } -func (k Keeper) iterateStatisticsImpl(ctx sdk.Context, prefix []byte, fn func(contractID string, classID string, amount sdk.Int) (stop bool)) { +func (k Keeper) iterateStatisticsImpl(ctx sdk.Context, prefix []byte, fn func(contractID, classID string, amount sdk.Int) (stop bool)) { store := ctx.KVStore(k.storeKey) iterator := sdk.KVStorePrefixIterator(store, prefix) @@ -211,13 +211,13 @@ func (k Keeper) iterateStatisticsImpl(ctx sdk.Context, prefix []byte, fn func(co } func (k Keeper) iterateContractSupplies(ctx sdk.Context, contractID string, fn func(classID string, amount sdk.Int) (stop bool)) { - k.iterateStatisticsImpl(ctx, statisticKeyPrefixByContractID(supplyKeyPrefix, contractID), func(_ string, classID string, amount sdk.Int) (stop bool) { + k.iterateStatisticsImpl(ctx, statisticKeyPrefixByContractID(supplyKeyPrefix, contractID), func(_, classID string, amount sdk.Int) (stop bool) { return fn(classID, amount) }) } func (k Keeper) iterateContractBurnts(ctx sdk.Context, contractID string, fn func(classID string, amount sdk.Int) (stop bool)) { - k.iterateStatisticsImpl(ctx, statisticKeyPrefixByContractID(burntKeyPrefix, contractID), func(_ string, classID string, amount sdk.Int) (stop bool) { + k.iterateStatisticsImpl(ctx, statisticKeyPrefixByContractID(burntKeyPrefix, contractID), func(_, classID string, amount sdk.Int) (stop bool) { return fn(classID, amount) }) } diff --git a/x/collection/keeper/grpc_query.go b/x/collection/keeper/grpc_query.go index f2f4ea6086..71d2a1b687 100644 --- a/x/collection/keeper/grpc_query.go +++ b/x/collection/keeper/grpc_query.go @@ -3,11 +3,10 @@ package keeper import ( "context" + "github.com/gogo/protobuf/proto" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "github.com/gogo/protobuf/proto" - codectypes "github.com/Finschia/finschia-sdk/codec/types" "github.com/Finschia/finschia-sdk/store/prefix" sdk "github.com/Finschia/finschia-sdk/types" @@ -28,7 +27,7 @@ func NewQueryServer(keeper Keeper) collection.QueryServer { } } -func (s queryServer) addressFromBech32GRPC(bech32 string, context string) (sdk.AccAddress, error) { +func (s queryServer) addressFromBech32GRPC(bech32, context string) (sdk.AccAddress, error) { addr, err := sdk.AccAddressFromBech32(bech32) if err != nil { return nil, status.Error(codes.InvalidArgument, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress.Wrap(bech32), context).Error()) @@ -37,7 +36,7 @@ func (s queryServer) addressFromBech32GRPC(bech32 string, context string) (sdk.A return addr, nil } -func (s queryServer) assertTokenIsFungible(ctx sdk.Context, contractID string, classID string) error { +func (s queryServer) assertTokenIsFungible(ctx sdk.Context, contractID, classID string) error { class, err := s.keeper.GetTokenClass(ctx, contractID, classID) if err != nil { return err @@ -50,7 +49,7 @@ func (s queryServer) assertTokenIsFungible(ctx sdk.Context, contractID string, c return nil } -func (s queryServer) assertTokenTypeIsNonFungible(ctx sdk.Context, contractID string, classID string) error { +func (s queryServer) assertTokenTypeIsNonFungible(ctx sdk.Context, contractID, classID string) error { class, err := s.keeper.GetTokenClass(ctx, contractID, classID) if err != nil { return err @@ -113,7 +112,7 @@ func (s queryServer) AllBalances(c context.Context, req *collection.QueryAllBala store := ctx.KVStore(s.keeper.storeKey) balanceStore := prefix.NewStore(store, balanceKeyPrefixByAddress(req.ContractId, addr)) var balances []collection.Coin - pageRes, err := query.Paginate(balanceStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(balanceStore, req.Pagination, func(key, value []byte) error { tokenID := string(key) var balance sdk.Int @@ -362,7 +361,7 @@ func (s queryServer) TokenType(c context.Context, req *collection.QueryTokenType return &collection.QueryTokenTypeResponse{TokenType: tokenType}, nil } -func (s queryServer) getToken(ctx sdk.Context, contractID string, tokenID string) (collection.Token, error) { +func (s queryServer) getToken(ctx sdk.Context, contractID, tokenID string) (collection.Token, error) { switch { case collection.ValidateNFTID(tokenID) == nil: token, err := s.keeper.GetNFT(ctx, contractID, tokenID) @@ -519,7 +518,7 @@ func (s queryServer) Children(c context.Context, req *collection.QueryChildrenRe store := ctx.KVStore(s.keeper.storeKey) childStore := prefix.NewStore(store, childKeyPrefixByTokenID(req.ContractId, req.TokenId)) var children []collection.NFT - pageRes, err := query.Paginate(childStore, req.Pagination, func(key []byte, _ []byte) error { + pageRes, err := query.Paginate(childStore, req.Pagination, func(key, _ []byte) error { childID := string(key) child, err := s.keeper.GetNFT(ctx, req.ContractId, childID) if err != nil { @@ -554,7 +553,7 @@ func (s queryServer) GranteeGrants(c context.Context, req *collection.QueryGrant store := ctx.KVStore(s.keeper.storeKey) grantStore := prefix.NewStore(store, grantKeyPrefixByGrantee(req.ContractId, granteeAddr)) var grants []collection.Grant - pageRes, err := query.Paginate(grantStore, req.Pagination, func(key []byte, _ []byte) error { + pageRes, err := query.Paginate(grantStore, req.Pagination, func(key, _ []byte) error { permission := collection.Permission(key[0]) grants = append(grants, collection.Grant{ Grantee: req.Grantee, @@ -612,7 +611,7 @@ func (s queryServer) HoldersByOperator(c context.Context, req *collection.QueryH store := ctx.KVStore(s.keeper.storeKey) authorizationStore := prefix.NewStore(store, authorizationKeyPrefixByOperator(req.ContractId, operator)) var holders []string - pageRes, err := query.Paginate(authorizationStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(authorizationStore, req.Pagination, func(key, value []byte) error { holder := sdk.AccAddress(key) holders = append(holders, holder.String()) return nil diff --git a/x/collection/keeper/keys.go b/x/collection/keeper/keys.go index debe7a453d..5f4478b5ff 100644 --- a/x/collection/keeper/keys.go +++ b/x/collection/keeper/keys.go @@ -2,7 +2,6 @@ package keeper import ( sdk "github.com/Finschia/finschia-sdk/types" - "github.com/Finschia/finschia-sdk/x/collection" ) @@ -89,7 +88,7 @@ func splitBalanceKey(key []byte) (contractID string, address sdk.AccAddress, tok // ---------------------------------------------------------------------------- // owner -func ownerKey(contractID string, tokenID string) []byte { +func ownerKey(contractID, tokenID string) []byte { prefix := ownerKeyPrefixByContractID(contractID) key := make([]byte, len(prefix)+len(tokenID)) @@ -116,7 +115,7 @@ func ownerKeyPrefixByContractID(contractID string) []byte { // ---------------------------------------------------------------------------- // nft -func nftKey(contractID string, tokenID string) []byte { +func nftKey(contractID, tokenID string) []byte { prefix := nftKeyPrefixByContractID(contractID) key := make([]byte, len(prefix)+len(tokenID)) @@ -141,7 +140,7 @@ func nftKeyPrefixByContractID(contractID string) []byte { return key } -func splitNFTKey(key []byte) (contractID string, tokenID string) { +func splitNFTKey(key []byte) (contractID, tokenID string) { begin := len(nftKeyPrefix) + 1 end := begin + int(key[begin-1]) contractID = string(key[begin:end]) @@ -154,7 +153,7 @@ func splitNFTKey(key []byte) (contractID string, tokenID string) { // ---------------------------------------------------------------------------- // parent -func parentKey(contractID string, tokenID string) []byte { +func parentKey(contractID, tokenID string) []byte { prefix := parentKeyPrefixByContractID(contractID) key := make([]byte, len(prefix)+len(tokenID)) @@ -179,7 +178,7 @@ func parentKeyPrefixByContractID(contractID string) []byte { return key } -func splitParentKey(key []byte) (contractID string, tokenID string) { +func splitParentKey(key []byte) (contractID, tokenID string) { begin := len(parentKeyPrefix) + 1 end := begin + int(key[begin-1]) contractID = string(key[begin:end]) @@ -192,7 +191,7 @@ func splitParentKey(key []byte) (contractID string, tokenID string) { // ---------------------------------------------------------------------------- // child -func childKey(contractID string, tokenID, childID string) []byte { +func childKey(contractID, tokenID, childID string) []byte { prefix := childKeyPrefixByTokenID(contractID, tokenID) key := make([]byte, len(prefix)+len(childID)) @@ -202,7 +201,7 @@ func childKey(contractID string, tokenID, childID string) []byte { return key } -func childKeyPrefixByTokenID(contractID string, tokenID string) []byte { +func childKeyPrefixByTokenID(contractID, tokenID string) []byte { prefix := childKeyPrefixByContractID(contractID) key := make([]byte, len(prefix)+1+len(tokenID)) @@ -233,7 +232,7 @@ func childKeyPrefixByContractID(contractID string) []byte { return key } -func splitChildKey(key []byte) (contractID string, tokenID, childID string) { +func splitChildKey(key []byte) (contractID, tokenID, childID string) { begin := len(childKeyPrefix) + 1 end := begin + int(key[begin-1]) contractID = string(key[begin:end]) @@ -258,7 +257,7 @@ func contractKey(contractID string) []byte { return key } -func classKey(contractID string, classID string) []byte { +func classKey(contractID, classID string) []byte { prefix := classKeyPrefixByContractID(contractID) key := make([]byte, len(prefix)+len(classID)) @@ -283,7 +282,7 @@ func classKeyPrefixByContractID(contractID string) []byte { return key } -func nextTokenIDKey(contractID string, classID string) []byte { +func nextTokenIDKey(contractID, classID string) []byte { prefix := nextTokenIDKeyPrefixByContractID(contractID) key := make([]byte, len(prefix)+len(classID)) @@ -308,7 +307,7 @@ func nextTokenIDKeyPrefixByContractID(contractID string) []byte { return key } -func splitNextTokenIDKey(key []byte) (contractID string, classID string) { +func splitNextTokenIDKey(key []byte) (contractID, classID string) { begin := len(nextTokenIDKeyPrefix) + 1 end := begin + int(key[begin-1]) contractID = string(key[begin:end]) @@ -444,7 +443,7 @@ func splitGrantKey(key []byte) (contractID string, grantee sdk.AccAddress, permi // ---------------------------------------------------------------------------- // statistics -func statisticKey(keyPrefix []byte, contractID string, classID string) []byte { +func statisticKey(keyPrefix []byte, contractID, classID string) []byte { prefix := statisticKeyPrefixByContractID(keyPrefix, contractID) key := make([]byte, len(prefix)+len(classID)) @@ -469,7 +468,7 @@ func statisticKeyPrefixByContractID(keyPrefix []byte, contractID string) []byte return key } -func splitStatisticKey(keyPrefix, key []byte) (contractID string, classID string) { +func splitStatisticKey(keyPrefix, key []byte) (contractID, classID string) { begin := len(keyPrefix) + 1 end := begin + int(key[begin-1]) contractID = string(key[begin:end]) @@ -482,7 +481,7 @@ func splitStatisticKey(keyPrefix, key []byte) (contractID string, classID string // ---------------------------------------------------------------------------- // legacy keys -func legacyTokenKey(contractID string, tokenID string) []byte { +func legacyTokenKey(contractID, tokenID string) []byte { prefix := legacyTokenKeyPrefixByContractID(contractID) key := make([]byte, len(prefix)+len(tokenID)) @@ -507,7 +506,7 @@ func legacyTokenKeyPrefixByContractID(contractID string) []byte { return key } -func legacyTokenTypeKey(contractID string, tokenType string) []byte { +func legacyTokenTypeKey(contractID, tokenType string) []byte { prefix := legacyTokenTypeKeyPrefixByContractID(contractID) key := make([]byte, len(prefix)+len(tokenType)) diff --git a/x/collection/keeper/migrations/v2/keys.go b/x/collection/keeper/migrations/v2/keys.go index 0f5d68c89c..f7b3eb5c81 100644 --- a/x/collection/keeper/migrations/v2/keys.go +++ b/x/collection/keeper/migrations/v2/keys.go @@ -80,7 +80,7 @@ func splitBalanceKey(key []byte) (contractID string, address sdk.AccAddress, tok return } -func StatisticKey(keyPrefix []byte, contractID string, classID string) []byte { +func StatisticKey(keyPrefix []byte, contractID, classID string) []byte { prefix := statisticKeyPrefixByContractID(keyPrefix, contractID) key := make([]byte, len(prefix)+len(classID)) diff --git a/x/collection/keeper/migrations/v2/store_test.go b/x/collection/keeper/migrations/v2/store_test.go index cbd97d77c6..6367ed9244 100644 --- a/x/collection/keeper/migrations/v2/store_test.go +++ b/x/collection/keeper/migrations/v2/store_test.go @@ -10,7 +10,6 @@ import ( "github.com/Finschia/finschia-sdk/testutil" sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/x/collection" - "github.com/Finschia/finschia-sdk/x/collection/keeper/migrations/v2" ) diff --git a/x/collection/keeper/msg_server_test.go b/x/collection/keeper/msg_server_test.go index e1ce0c2b61..f2a0da715b 100644 --- a/x/collection/keeper/msg_server_test.go +++ b/x/collection/keeper/msg_server_test.go @@ -36,7 +36,8 @@ func (s *KeeperTestSuite) TestMsgSendFT() { {Key: []byte("operator"), Value: testutil.W(s.vendor.String()), Index: false}, {Key: []byte("to"), Value: testutil.W(s.customer.String()), Index: false}, }, - }}, + }, + }, }, "contract not found": { isNegativeCase: true, @@ -348,7 +349,8 @@ func (s *KeeperTestSuite) TestMsgOperatorSendNFT() { {Key: []byte("to"), Value: testutil.W(s.vendor.String()), Index: false}, }, }, - }}, + }, + }, "contract not found": { contractID: "deadbeef", operator: s.operator, @@ -580,7 +582,8 @@ func (s *KeeperTestSuite) TestMsgCreateContract() { {Key: []byte("grantee"), Value: testutil.W(s.vendor.String()), Index: false}, {Key: []byte("granter"), Value: testutil.W(""), Index: false}, {Key: []byte("permission"), Value: testutil.W(collection.Permission(collection.LegacyPermissionIssue).String()), Index: false}, - }}, + }, + }, sdk.Event{ Type: "lbm.collection.v1.EventGranted", Attributes: []abci.EventAttribute{ @@ -588,7 +591,8 @@ func (s *KeeperTestSuite) TestMsgCreateContract() { {Key: []byte("grantee"), Value: testutil.W(s.vendor.String()), Index: false}, {Key: []byte("granter"), Value: testutil.W(""), Index: false}, {Key: []byte("permission"), Value: testutil.W(collection.Permission(collection.LegacyPermissionModify).String()), Index: false}, - }}, + }, + }, sdk.Event{ Type: "lbm.collection.v1.EventGranted", Attributes: []abci.EventAttribute{ @@ -596,7 +600,8 @@ func (s *KeeperTestSuite) TestMsgCreateContract() { {Key: []byte("grantee"), Value: testutil.W(s.vendor.String()), Index: false}, {Key: []byte("granter"), Value: testutil.W(""), Index: false}, {Key: []byte("permission"), Value: testutil.W(collection.Permission(collection.LegacyPermissionMint).String()), Index: false}, - }}, + }, + }, sdk.Event{ Type: "lbm.collection.v1.EventGranted", Attributes: []abci.EventAttribute{ @@ -604,8 +609,10 @@ func (s *KeeperTestSuite) TestMsgCreateContract() { {Key: []byte("grantee"), Value: testutil.W(s.vendor.String()), Index: false}, {Key: []byte("granter"), Value: testutil.W(""), Index: false}, {Key: []byte("permission"), Value: testutil.W(collection.Permission(collection.LegacyPermissionBurn).String()), Index: false}, - }}, - }}, + }, + }, + }, + }, } for name, tc := range testCases { @@ -624,7 +631,6 @@ func (s *KeeperTestSuite) TestMsgCreateContract() { s.Require().NotNil(res) s.Require().Equal(tc.events, ctx.EventManager().Events()) - }) } } @@ -758,7 +764,8 @@ func (s *KeeperTestSuite) TestMsgIssueNFT() { {Key: []byte("name"), Value: testutil.W(""), Index: false}, {Key: []byte("operator"), Value: testutil.W(s.vendor.String()), Index: false}, {Key: []byte("token_type"), Value: testutil.W(expectedTokenType), Index: false}, - }}, + }, + }, sdk.Event{ Type: "lbm.collection.v1.EventGranted", Attributes: []abci.EventAttribute{ @@ -766,7 +773,8 @@ func (s *KeeperTestSuite) TestMsgIssueNFT() { {Key: []byte("grantee"), Value: testutil.W(s.vendor.String()), Index: false}, {Key: []byte("granter"), Value: testutil.W(""), Index: false}, {Key: []byte("permission"), Value: testutil.W(collection.Permission(collection.LegacyPermissionMint).String()), Index: false}, - }}, + }, + }, sdk.Event{ Type: "lbm.collection.v1.EventGranted", Attributes: []abci.EventAttribute{ @@ -774,7 +782,8 @@ func (s *KeeperTestSuite) TestMsgIssueNFT() { {Key: []byte("grantee"), Value: testutil.W(s.vendor.String()), Index: false}, {Key: []byte("granter"), Value: testutil.W(""), Index: false}, {Key: []byte("permission"), Value: testutil.W(collection.Permission(collection.LegacyPermissionBurn).String()), Index: false}, - }}, + }, + }, }, }, "contract not found": { @@ -805,7 +814,6 @@ func (s *KeeperTestSuite) TestMsgIssueNFT() { s.Require().NotNil(res) s.Require().Equal(tc.events, ctx.EventManager().Events()) - }) } } @@ -935,7 +943,7 @@ func (s *KeeperTestSuite) TestMsgMintFT() { } // query the values to be effected by MintFT - queryValuesEffectedByMintFT := func(ctx sdk.Context, coins collection.Coins, contractID string) (balances collection.Coins, supply []sdk.Int, minted []sdk.Int) { + queryValuesEffectedByMintFT := func(ctx sdk.Context, coins collection.Coins, contractID string) (balances collection.Coins, supply, minted []sdk.Int) { for _, am := range coins { // save balance bal, err := s.queryServer.Balance(sdk.WrapSDKContext(ctx), &collection.QueryBalanceRequest{ @@ -1044,7 +1052,8 @@ func (s *KeeperTestSuite) TestMsgMintNFT() { {Key: []byte("tokens"), Value: testutil.MustJSONMarshal(expectedTokens), Index: false}, }, }, - }}, + }, + }, "contract not found": { contractID: "deadbeef", from: s.vendor, @@ -1199,7 +1208,7 @@ func (s *KeeperTestSuite) TestMsgBurnFT() { } // query the values to be effected by BurnFT - queryValuesAffectedByBurnFT := func(ctx sdk.Context, coins collection.Coins, contractID, from string) (balances collection.Coins, supply []sdk.Int, burnt []sdk.Int) { + queryValuesAffectedByBurnFT := func(ctx sdk.Context, coins collection.Coins, contractID, from string) (balances collection.Coins, supply, burnt []sdk.Int) { for _, am := range coins { // save balance bal, err := s.queryServer.Balance(sdk.WrapSDKContext(ctx), &collection.QueryBalanceRequest{ @@ -1295,7 +1304,9 @@ func (s *KeeperTestSuite) TestMsgOperatorBurnFT() { {Key: []byte("contract_id"), Value: testutil.W(s.contractID), Index: false}, {Key: []byte("from"), Value: testutil.W(s.customer.String()), Index: false}, {Key: []byte("operator"), Value: testutil.W(s.operator.String()), Index: false}, - }}}, + }, + }, + }, }, "contract not found": { contractID: "deadbeef", @@ -1387,7 +1398,9 @@ func (s *KeeperTestSuite) TestMsgBurnNFT() { {Key: []byte("contract_id"), Value: testutil.W(s.contractID), Index: false}, {Key: []byte("from"), Value: testutil.W(s.vendor.String()), Index: false}, {Key: []byte("operator"), Value: testutil.W(s.vendor.String()), Index: false}, - }}}, + }, + }, + }, }, "contract not found": { contractID: "deadbeef", @@ -1477,7 +1490,9 @@ func (s *KeeperTestSuite) TestMsgOperatorBurnNFT() { {Key: []byte("contract_id"), Value: testutil.W(s.contractID), Index: false}, {Key: []byte("from"), Value: testutil.W(s.customer.String()), Index: false}, {Key: []byte("operator"), Value: testutil.W(s.operator.String()), Index: false}, - }}}, + }, + }, + }, }, "contract not found": { contractID: "deadbeef", @@ -1547,7 +1562,6 @@ func (s *KeeperTestSuite) TestMsgOperatorBurnNFT() { s.Require().NotNil(res) s.Require().Equal(tc.events, ctx.EventManager().Events()) - }) } } @@ -1577,7 +1591,10 @@ func (s *KeeperTestSuite) TestMsgModify() { {Key: []byte("changes"), Value: testutil.MustJSONMarshal(changes), Index: false}, {Key: []byte("contract_id"), Value: testutil.W(s.contractID), Index: false}, {Key: []byte("operator"), Value: testutil.W(s.vendor.String()), Index: false}, - }}}}, + }, + }, + }, + }, "contract not found": { contractID: "deadbeef", operator: s.vendor, @@ -1656,7 +1673,8 @@ func (s *KeeperTestSuite) TestMsgGrantPermission() { {Key: []byte("grantee"), Value: testutil.W(s.operator.String()), Index: false}, {Key: []byte("granter"), Value: testutil.W(s.vendor.String()), Index: false}, {Key: []byte("permission"), Value: testutil.W(collection.Permission(collection.LegacyPermissionModify).String()), Index: false}, - }}, + }, + }, }, }, "contract not found": { @@ -1716,7 +1734,8 @@ func (s *KeeperTestSuite) TestMsgRevokePermission() { {Key: []byte("contract_id"), Value: testutil.W(s.contractID), Index: false}, {Key: []byte("grantee"), Value: testutil.W(s.operator.String()), Index: false}, {Key: []byte("permission"), Value: testutil.W(collection.Permission(collection.LegacyPermissionMint).String()), Index: false}, - }}, + }, + }, }, }, "contract not found": { @@ -1775,7 +1794,8 @@ func (s *KeeperTestSuite) TestMsgAttach() { {Key: []byte("operator"), Value: testutil.W(s.customer.String()), Index: false}, {Key: []byte("subject"), Value: testutil.W(collection.NewNFTID(s.nftClassID, s.depthLimit+1)), Index: false}, {Key: []byte("target"), Value: testutil.W(collection.NewNFTID(s.nftClassID, 1)), Index: false}, - }}, + }, + }, }, }, "contract not found": { @@ -1838,7 +1858,8 @@ func (s *KeeperTestSuite) TestMsgDetach() { {Key: []byte("operator"), Value: testutil.W(s.customer.String()), Index: false}, {Key: []byte("previous_parent"), Value: testutil.W(issuedNfts[0]), Index: false}, {Key: []byte("subject"), Value: testutil.W(issuedNfts[1]), Index: false}, - }}, + }, + }, sdk.Event{ Type: "lbm.collection.v1.EventRootChanged", Attributes: []abci.EventAttribute{ @@ -1846,7 +1867,8 @@ func (s *KeeperTestSuite) TestMsgDetach() { {Key: []byte("from"), Value: testutil.W(issuedNfts[0]), Index: false}, {Key: []byte("to"), Value: testutil.W(issuedNfts[1]), Index: false}, {Key: []byte("token_id"), Value: testutil.W(issuedNfts[2]), Index: false}, - }}, + }, + }, sdk.Event{ Type: "lbm.collection.v1.EventRootChanged", Attributes: []abci.EventAttribute{ @@ -1854,7 +1876,8 @@ func (s *KeeperTestSuite) TestMsgDetach() { {Key: []byte("from"), Value: testutil.W(issuedNfts[0]), Index: false}, {Key: []byte("to"), Value: testutil.W(issuedNfts[1]), Index: false}, {Key: []byte("token_id"), Value: testutil.W(issuedNfts[3]), Index: false}, - }}, + }, + }, }, }, "contract not found": { @@ -1891,7 +1914,6 @@ func (s *KeeperTestSuite) TestMsgDetach() { s.Require().NotNil(res) s.Require().Equal(tc.events, ctx.EventManager().Events()) - }) } } @@ -1919,8 +1941,10 @@ func (s *KeeperTestSuite) TestMsgOperatorAttach() { {Key: []byte("operator"), Value: testutil.W(s.operator.String()), Index: false}, {Key: []byte("subject"), Value: testutil.W(collection.NewNFTID(s.nftClassID, s.depthLimit+1)), Index: false}, {Key: []byte("target"), Value: testutil.W(collection.NewNFTID(s.nftClassID, 1)), Index: false}, - }}, - }}, + }, + }, + }, + }, "contract not found": { contractID: "deadbeef", operator: s.operator, @@ -1993,7 +2017,8 @@ func (s *KeeperTestSuite) TestMsgOperatorDetach() { {Key: []byte("operator"), Value: testutil.W(s.operator.String()), Index: false}, {Key: []byte("previous_parent"), Value: testutil.W(nfts[0]), Index: false}, {Key: []byte("subject"), Value: testutil.W(nfts[1]), Index: false}, - }}, + }, + }, sdk.Event{ Type: "lbm.collection.v1.EventRootChanged", Attributes: []abci.EventAttribute{ @@ -2001,7 +2026,8 @@ func (s *KeeperTestSuite) TestMsgOperatorDetach() { {Key: []byte("from"), Value: testutil.W(nfts[0]), Index: false}, {Key: []byte("to"), Value: testutil.W(nfts[1]), Index: false}, {Key: []byte("token_id"), Value: testutil.W(nfts[2]), Index: false}, - }}, + }, + }, sdk.Event{ Type: "lbm.collection.v1.EventRootChanged", Attributes: []abci.EventAttribute{ @@ -2009,8 +2035,10 @@ func (s *KeeperTestSuite) TestMsgOperatorDetach() { {Key: []byte("from"), Value: testutil.W(nfts[0]), Index: false}, {Key: []byte("to"), Value: testutil.W(nfts[1]), Index: false}, {Key: []byte("token_id"), Value: testutil.W(nfts[3]), Index: false}, - }}, - }}, + }, + }, + }, + }, "contract not found": { contractID: "deadbeef", operator: s.operator, @@ -2049,7 +2077,6 @@ func (s *KeeperTestSuite) TestMsgOperatorDetach() { s.Require().NotNil(res) s.Require().Equal(tc.events, ctx.EventManager().Events()) - }) } } diff --git a/x/collection/keeper/nft.go b/x/collection/keeper/nft.go index f4bc5540d4..96b50bde21 100644 --- a/x/collection/keeper/nft.go +++ b/x/collection/keeper/nft.go @@ -7,7 +7,7 @@ import ( "github.com/Finschia/finschia-sdk/x/collection" ) -func legacyNFTNotFoundError(k Keeper, ctx sdk.Context, contractID string, tokenID string) error { +func legacyNFTNotFoundError(k Keeper, ctx sdk.Context, contractID, tokenID string) error { if err2 := collection.ValidateLegacyNFTID(tokenID); err2 == nil /* "==" is intentional */ { return collection.ErrTokenNotExist.Wrap(tokenID) } @@ -23,7 +23,7 @@ func legacyNFTNotFoundError(k Keeper, ctx sdk.Context, contractID string, tokenI return collection.ErrTokenNotNFT.Wrap(tokenID) } -func (k Keeper) hasNFT(ctx sdk.Context, contractID string, tokenID string) error { +func (k Keeper) hasNFT(ctx sdk.Context, contractID, tokenID string) error { store := ctx.KVStore(k.storeKey) key := nftKey(contractID, tokenID) if !store.Has(key) { @@ -32,7 +32,7 @@ func (k Keeper) hasNFT(ctx sdk.Context, contractID string, tokenID string) error return nil } -func (k Keeper) GetNFT(ctx sdk.Context, contractID string, tokenID string) (*collection.NFT, error) { +func (k Keeper) GetNFT(ctx sdk.Context, contractID, tokenID string) (*collection.NFT, error) { store := ctx.KVStore(k.storeKey) key := nftKey(contractID, tokenID) bz := store.Get(key) @@ -57,13 +57,13 @@ func (k Keeper) setNFT(ctx sdk.Context, contractID string, token collection.NFT) store.Set(key, bz) } -func (k Keeper) deleteNFT(ctx sdk.Context, contractID string, tokenID string) { +func (k Keeper) deleteNFT(ctx sdk.Context, contractID, tokenID string) { store := ctx.KVStore(k.storeKey) key := nftKey(contractID, tokenID) store.Delete(key) } -func (k Keeper) pruneNFT(ctx sdk.Context, contractID string, tokenID string) []string { +func (k Keeper) pruneNFT(ctx sdk.Context, contractID, tokenID string) []string { burnt := []string{} for _, child := range k.GetChildren(ctx, contractID, tokenID) { k.deleteChild(ctx, contractID, tokenID, child) @@ -172,7 +172,7 @@ func (k Keeper) Detach(ctx sdk.Context, contractID string, owner sdk.AccAddress, return nil } -func (k Keeper) iterateAncestors(ctx sdk.Context, contractID string, tokenID string, fn func(tokenID string) error) error { +func (k Keeper) iterateAncestors(ctx sdk.Context, contractID, tokenID string, fn func(tokenID string) error) error { var err error for id := &tokenID; err == nil; id, err = k.GetParent(ctx, contractID, *id) { if fnErr := fn(*id); fnErr != nil { @@ -183,12 +183,12 @@ func (k Keeper) iterateAncestors(ctx sdk.Context, contractID string, tokenID str return nil } -func (k Keeper) GetRootOwner(ctx sdk.Context, contractID string, tokenID string) sdk.AccAddress { +func (k Keeper) GetRootOwner(ctx sdk.Context, contractID, tokenID string) sdk.AccAddress { rootID := k.GetRoot(ctx, contractID, tokenID) return k.getOwner(ctx, contractID, rootID) } -func (k Keeper) getOwner(ctx sdk.Context, contractID string, tokenID string) sdk.AccAddress { +func (k Keeper) getOwner(ctx sdk.Context, contractID, tokenID string) sdk.AccAddress { store := ctx.KVStore(k.storeKey) key := ownerKey(contractID, tokenID) bz := store.Get(key) @@ -203,7 +203,7 @@ func (k Keeper) getOwner(ctx sdk.Context, contractID string, tokenID string) sdk return owner } -func (k Keeper) setOwner(ctx sdk.Context, contractID string, tokenID string, owner sdk.AccAddress) { +func (k Keeper) setOwner(ctx sdk.Context, contractID, tokenID string, owner sdk.AccAddress) { store := ctx.KVStore(k.storeKey) key := ownerKey(contractID, tokenID) @@ -214,13 +214,13 @@ func (k Keeper) setOwner(ctx sdk.Context, contractID string, tokenID string, own store.Set(key, bz) } -func (k Keeper) deleteOwner(ctx sdk.Context, contractID string, tokenID string) { +func (k Keeper) deleteOwner(ctx sdk.Context, contractID, tokenID string) { store := ctx.KVStore(k.storeKey) key := ownerKey(contractID, tokenID) store.Delete(key) } -func (k Keeper) GetParent(ctx sdk.Context, contractID string, tokenID string) (*string, error) { +func (k Keeper) GetParent(ctx sdk.Context, contractID, tokenID string) (*string, error) { store := ctx.KVStore(k.storeKey) key := parentKey(contractID, tokenID) bz := store.Get(key) @@ -233,7 +233,7 @@ func (k Keeper) GetParent(ctx sdk.Context, contractID string, tokenID string) (* return &parent.Value, nil } -func (k Keeper) setParent(ctx sdk.Context, contractID string, tokenID, parentID string) { +func (k Keeper) setParent(ctx sdk.Context, contractID, tokenID, parentID string) { store := ctx.KVStore(k.storeKey) key := parentKey(contractID, tokenID) @@ -242,13 +242,13 @@ func (k Keeper) setParent(ctx sdk.Context, contractID string, tokenID, parentID store.Set(key, bz) } -func (k Keeper) deleteParent(ctx sdk.Context, contractID string, tokenID string) { +func (k Keeper) deleteParent(ctx sdk.Context, contractID, tokenID string) { store := ctx.KVStore(k.storeKey) key := parentKey(contractID, tokenID) store.Delete(key) } -func (k Keeper) GetChildren(ctx sdk.Context, contractID string, tokenID string) []string { +func (k Keeper) GetChildren(ctx sdk.Context, contractID, tokenID string) []string { var children []string k.iterateChildren(ctx, contractID, tokenID, func(childID string) (stop bool) { children = append(children, childID) @@ -257,17 +257,17 @@ func (k Keeper) GetChildren(ctx sdk.Context, contractID string, tokenID string) return children } -func (k Keeper) iterateChildren(ctx sdk.Context, contractID string, tokenID string, fn func(childID string) (stop bool)) { - k.iterateChildrenImpl(ctx, childKeyPrefixByTokenID(contractID, tokenID), func(_ string, _ string, childID string) (stop bool) { +func (k Keeper) iterateChildren(ctx sdk.Context, contractID, tokenID string, fn func(childID string) (stop bool)) { + k.iterateChildrenImpl(ctx, childKeyPrefixByTokenID(contractID, tokenID), func(_, _, childID string) (stop bool) { return fn(childID) }) } -func (k Keeper) iterateDescendants(ctx sdk.Context, contractID string, tokenID string, fn func(descendantID string, depth int) (stop bool)) { +func (k Keeper) iterateDescendants(ctx sdk.Context, contractID, tokenID string, fn func(descendantID string, depth int) (stop bool)) { k.iterateDescendantsImpl(ctx, contractID, tokenID, 1, fn) } -func (k Keeper) iterateDescendantsImpl(ctx sdk.Context, contractID string, tokenID string, depth int, fn func(descendantID string, depth int) (stop bool)) { +func (k Keeper) iterateDescendantsImpl(ctx sdk.Context, contractID, tokenID string, depth int, fn func(descendantID string, depth int) (stop bool)) { k.iterateChildren(ctx, contractID, tokenID, func(childID string) (stop bool) { if stop := fn(childID, depth); stop { return true @@ -278,51 +278,54 @@ func (k Keeper) iterateDescendantsImpl(ctx sdk.Context, contractID string, token }) } -func (k Keeper) setChild(ctx sdk.Context, contractID string, tokenID, childID string) { +func (k Keeper) setChild(ctx sdk.Context, contractID, tokenID, childID string) { store := ctx.KVStore(k.storeKey) key := childKey(contractID, tokenID, childID) store.Set(key, []byte{}) } -func (k Keeper) deleteChild(ctx sdk.Context, contractID string, tokenID, childID string) { +func (k Keeper) deleteChild(ctx sdk.Context, contractID, tokenID, childID string) { store := ctx.KVStore(k.storeKey) key := childKey(contractID, tokenID, childID) store.Delete(key) } -func (k Keeper) GetRoot(ctx sdk.Context, contractID string, tokenID string) string { +func (k Keeper) GetRoot(ctx sdk.Context, contractID, tokenID string) string { id := tokenID - k.iterateAncestors(ctx, contractID, tokenID, func(tokenID string) error { + err := k.iterateAncestors(ctx, contractID, tokenID, func(tokenID string) error { id = tokenID return nil }) + if err != nil { + panic(err) + } return id } // Deprecated -func (k Keeper) setLegacyToken(ctx sdk.Context, contractID string, tokenID string) { +func (k Keeper) setLegacyToken(ctx sdk.Context, contractID, tokenID string) { store := ctx.KVStore(k.storeKey) key := legacyTokenKey(contractID, tokenID) store.Set(key, []byte{}) } // Deprecated -func (k Keeper) deleteLegacyToken(ctx sdk.Context, contractID string, tokenID string) { +func (k Keeper) deleteLegacyToken(ctx sdk.Context, contractID, tokenID string) { store := ctx.KVStore(k.storeKey) key := legacyTokenKey(contractID, tokenID) store.Delete(key) } // Deprecated -func (k Keeper) setLegacyTokenType(ctx sdk.Context, contractID string, tokenType string) { +func (k Keeper) setLegacyTokenType(ctx sdk.Context, contractID, tokenType string) { store := ctx.KVStore(k.storeKey) key := legacyTokenTypeKey(contractID, tokenType) store.Set(key, []byte{}) } // Deprecated -func (k Keeper) validateDepthAndWidth(ctx sdk.Context, contractID string, tokenID string) error { +func (k Keeper) validateDepthAndWidth(ctx sdk.Context, contractID, tokenID string) error { widths := map[int]int{0: 1} k.iterateDescendants(ctx, contractID, tokenID, func(descendantID string, depth int) (stop bool) { widths[depth]++ diff --git a/x/collection/keeper/supply.go b/x/collection/keeper/supply.go index 0a09943742..8758fce8cc 100644 --- a/x/collection/keeper/supply.go +++ b/x/collection/keeper/supply.go @@ -273,7 +273,7 @@ func (k Keeper) BurnCoins(ctx sdk.Context, contractID string, from sdk.AccAddres return burntAmount, nil } -func (k Keeper) getNextTokenID(ctx sdk.Context, contractID string, classID string) sdk.Uint { +func (k Keeper) getNextTokenID(ctx sdk.Context, contractID, classID string) sdk.Uint { store := ctx.KVStore(k.storeKey) key := nextTokenIDKey(contractID, classID) bz := store.Get(key) @@ -288,7 +288,7 @@ func (k Keeper) getNextTokenID(ctx sdk.Context, contractID string, classID strin return id } -func (k Keeper) setNextTokenID(ctx sdk.Context, contractID string, classID string, tokenID sdk.Uint) { +func (k Keeper) setNextTokenID(ctx sdk.Context, contractID, classID string, tokenID sdk.Uint) { store := ctx.KVStore(k.storeKey) key := nextTokenIDKey(contractID, classID) @@ -326,7 +326,7 @@ func (k Keeper) ModifyContract(ctx sdk.Context, contractID string, operator sdk. return nil } -func (k Keeper) ModifyTokenClass(ctx sdk.Context, contractID string, classID string, operator sdk.AccAddress, changes []collection.Attribute) error { +func (k Keeper) ModifyTokenClass(ctx sdk.Context, contractID, classID string, operator sdk.AccAddress, changes []collection.Attribute) error { class, err := k.GetTokenClass(ctx, contractID, classID) if err != nil { // legacy error split @@ -359,7 +359,7 @@ func (k Keeper) ModifyTokenClass(ctx sdk.Context, contractID string, classID str return nil } -func (k Keeper) ModifyNFT(ctx sdk.Context, contractID string, tokenID string, operator sdk.AccAddress, changes []collection.Attribute) error { +func (k Keeper) ModifyNFT(ctx sdk.Context, contractID, tokenID string, operator sdk.AccAddress, changes []collection.Attribute) error { token, err := k.GetNFT(ctx, contractID, tokenID) if err != nil { return err @@ -437,7 +437,7 @@ func (k Keeper) deleteGrant(ctx sdk.Context, contractID string, grantee sdk.AccA store.Delete(key) } -func (k Keeper) getStatistic(ctx sdk.Context, keyPrefix []byte, contractID string, classID string) sdk.Int { +func (k Keeper) getStatistic(ctx sdk.Context, keyPrefix []byte, contractID, classID string) sdk.Int { store := ctx.KVStore(k.storeKey) amount := sdk.ZeroInt() bz := store.Get(statisticKey(keyPrefix, contractID, classID)) @@ -450,7 +450,7 @@ func (k Keeper) getStatistic(ctx sdk.Context, keyPrefix []byte, contractID strin return amount } -func (k Keeper) setStatistic(ctx sdk.Context, keyPrefix []byte, contractID string, classID string, amount sdk.Int) { +func (k Keeper) setStatistic(ctx sdk.Context, keyPrefix []byte, contractID, classID string, amount sdk.Int) { store := ctx.KVStore(k.storeKey) key := statisticKey(keyPrefix, contractID, classID) if amount.IsZero() { @@ -464,26 +464,26 @@ func (k Keeper) setStatistic(ctx sdk.Context, keyPrefix []byte, contractID strin } } -func (k Keeper) GetSupply(ctx sdk.Context, contractID string, classID string) sdk.Int { +func (k Keeper) GetSupply(ctx sdk.Context, contractID, classID string) sdk.Int { return k.getStatistic(ctx, supplyKeyPrefix, contractID, classID) } -func (k Keeper) GetMinted(ctx sdk.Context, contractID string, classID string) sdk.Int { +func (k Keeper) GetMinted(ctx sdk.Context, contractID, classID string) sdk.Int { return k.getStatistic(ctx, mintedKeyPrefix, contractID, classID) } -func (k Keeper) GetBurnt(ctx sdk.Context, contractID string, classID string) sdk.Int { +func (k Keeper) GetBurnt(ctx sdk.Context, contractID, classID string) sdk.Int { return k.getStatistic(ctx, burntKeyPrefix, contractID, classID) } -func (k Keeper) setSupply(ctx sdk.Context, contractID string, classID string, amount sdk.Int) { +func (k Keeper) setSupply(ctx sdk.Context, contractID, classID string, amount sdk.Int) { k.setStatistic(ctx, supplyKeyPrefix, contractID, classID, amount) } -func (k Keeper) setMinted(ctx sdk.Context, contractID string, classID string, amount sdk.Int) { +func (k Keeper) setMinted(ctx sdk.Context, contractID, classID string, amount sdk.Int) { k.setStatistic(ctx, mintedKeyPrefix, contractID, classID, amount) } -func (k Keeper) setBurnt(ctx sdk.Context, contractID string, classID string, amount sdk.Int) { +func (k Keeper) setBurnt(ctx sdk.Context, contractID, classID string, amount sdk.Int) { k.setStatistic(ctx, burntKeyPrefix, contractID, classID, amount) } diff --git a/x/collection/keeper/supply_test.go b/x/collection/keeper/supply_test.go index 865fb7e5a8..4e9e81c714 100644 --- a/x/collection/keeper/supply_test.go +++ b/x/collection/keeper/supply_test.go @@ -135,7 +135,8 @@ func (s *KeeperTestSuite) TestMintFT() { mintedBefore := s.keeper.GetMinted(ctx, contractID, classID) burntBefore := s.keeper.GetBurnt(ctx, contractID, classID) - s.keeper.MintFT(ctx, s.contractID, s.stranger, collection.NewCoins(collection.NewFTCoin(s.ftClassID, amount))) + err := s.keeper.MintFT(ctx, s.contractID, s.stranger, collection.NewCoins(collection.NewFTCoin(s.ftClassID, amount))) + s.Require().NoError(err) balanceAfter := s.keeper.GetBalance(ctx, s.contractID, s.stranger, collection.NewFTID(s.ftClassID)) s.Require().Equal(balanceBefore.Add(amount), balanceAfter) @@ -266,7 +267,8 @@ func (s *KeeperTestSuite) TestModifyContract() { ctx, _ := s.ctx.CacheContext() call := func() { - s.keeper.ModifyContract(ctx, contractID, s.vendor, changes) + err := s.keeper.ModifyContract(ctx, contractID, s.vendor, changes) + s.Require().NoError(err) } if contractID != s.contractID { diff --git a/x/collection/module/module.go b/x/collection/module/module.go index 6c0cf64e30..d781bfbeb6 100644 --- a/x/collection/module/module.go +++ b/x/collection/module/module.go @@ -72,7 +72,7 @@ func (b AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry collection.RegisterInterfaces(registry) } -//____________________________________________________________________________ +// ____________________________________________________________________________ // AppModule implements an application module for the collection module. type AppModule struct { diff --git a/x/collection/msgs_test.go b/x/collection/msgs_test.go index e9f09eb000..3b11494ba2 100644 --- a/x/collection/msgs_test.go +++ b/x/collection/msgs_test.go @@ -97,7 +97,7 @@ func TestMsgSendFT(t *testing.T) { } if tc.panic { - require.Panics(t, func() { msg.ValidateBasic() }) + require.Panics(t, func() { msg.ValidateBasic() }) //nolint:errcheck return } @@ -1745,8 +1745,8 @@ func TestMsgOperatorDetach(t *testing.T) { func TestAminoJSON(t *testing.T) { tx := legacytx.StdTx{} - var contractId = "deadbeef" - var ftClassId = "00bab10c" + contractId := "deadbeef" + ftClassId := "00bab10c" addrs := make([]sdk.AccAddress, 3) for i := range addrs { @@ -1991,7 +1991,6 @@ func TestAminoJSON(t *testing.T) { } for name, tc := range testCase { - tc := tc t.Run(name, func(t *testing.T) { tx.Msgs = []sdk.Msg{tc.msg} require.Equal(t, collection.RouterKey, tc.msg.Route()) diff --git a/x/crisis/client/testsuite/suite.go b/x/crisis/client/testsuite/suite.go index 8ac29d8ad3..75c06177c4 100644 --- a/x/crisis/client/testsuite/suite.go +++ b/x/crisis/client/testsuite/suite.go @@ -83,8 +83,6 @@ func (s *IntegrationTestSuite) TestNewMsgVerifyInvariantTxCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewMsgVerifyInvariantTxCmd() clientCtx := val.ClientCtx diff --git a/x/crisis/handler_test.go b/x/crisis/handler_test.go index c174ce536c..dc646d5338 100644 --- a/x/crisis/handler_test.go +++ b/x/crisis/handler_test.go @@ -58,7 +58,6 @@ func TestHandleMsgVerifyInvariant(t *testing.T) { } for _, tc := range cases { - tc := tc t.Run(tc.name, func(t *testing.T) { h := crisis.NewHandler(app.CrisisKeeper) diff --git a/x/crisis/keeper/keeper_test.go b/x/crisis/keeper/keeper_test.go index 243aa1a714..0d8f7c7fd8 100644 --- a/x/crisis/keeper/keeper_test.go +++ b/x/crisis/keeper/keeper_test.go @@ -3,11 +3,10 @@ package keeper_test import ( "testing" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/finschia-sdk/simapp" sdk "github.com/Finschia/finschia-sdk/types" ) diff --git a/x/distribution/client/cli/tx_test.go b/x/distribution/client/cli/tx_test.go index 0337f75b25..695737df54 100644 --- a/x/distribution/client/cli/tx_test.go +++ b/x/distribution/client/cli/tx_test.go @@ -4,17 +4,14 @@ import ( "testing" "github.com/spf13/pflag" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/crypto/keys/secp256k1" "github.com/Finschia/finschia-sdk/simapp/params" "github.com/Finschia/finschia-sdk/testutil" "github.com/Finschia/finschia-sdk/testutil/testdata" - - "github.com/stretchr/testify/require" - - "github.com/stretchr/testify/assert" - - "github.com/Finschia/finschia-sdk/client" sdk "github.com/Finschia/finschia-sdk/types" ) diff --git a/x/distribution/client/common/common_test.go b/x/distribution/client/common/common_test.go index f81db2b6d4..168cb16fd5 100644 --- a/x/distribution/client/common/common_test.go +++ b/x/distribution/client/common/common_test.go @@ -30,7 +30,6 @@ func TestQueryDelegationRewardsAddrValidation(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { _, _, err := QueryDelegationRewards(clientCtx, tt.args.delAddr, tt.args.valAddr) require.True(t, err != nil, tt.wantErr) diff --git a/x/distribution/client/testutil/grpc.go b/x/distribution/client/testutil/grpc.go index 76fc652c15..ceaf4627a1 100644 --- a/x/distribution/client/testutil/grpc.go +++ b/x/distribution/client/testutil/grpc.go @@ -56,7 +56,6 @@ func (s *GRPCQueryTestSuite) TestQueryParamsGRPC() { } for _, tc := range testCases { - tc := tc resp, err := rest.GetRequest(tc.url) s.Run(tc.name, func() { s.Require().NoError(err) @@ -106,7 +105,6 @@ func (s *GRPCQueryTestSuite) TestQueryOutstandingRewardsGRPC() { } for _, tc := range testCases { - tc := tc resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Run(tc.name, func() { if tc.expErr { @@ -160,7 +158,6 @@ func (s *GRPCQueryTestSuite) TestQueryValidatorCommissionGRPC() { } for _, tc := range testCases { - tc := tc resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Run(tc.name, func() { if tc.expErr { @@ -218,7 +215,6 @@ func (s *GRPCQueryTestSuite) TestQuerySlashesGRPC() { } for _, tc := range testCases { - tc := tc resp, err := rest.GetRequest(tc.url) s.Run(tc.name, func() { @@ -294,7 +290,6 @@ func (s *GRPCQueryTestSuite) TestQueryDelegatorRewardsGRPC() { } for _, tc := range testCases { - tc := tc resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Run(tc.name, func() { @@ -346,7 +341,6 @@ func (s *GRPCQueryTestSuite) TestQueryDelegatorValidatorsGRPC() { } for _, tc := range testCases { - tc := tc resp, err := rest.GetRequest(tc.url) s.Run(tc.name, func() { @@ -398,7 +392,6 @@ func (s *GRPCQueryTestSuite) TestQueryWithdrawAddressGRPC() { } for _, tc := range testCases { - tc := tc resp, err := rest.GetRequest(tc.url) s.Run(tc.name, func() { @@ -443,7 +436,6 @@ func (s *GRPCQueryTestSuite) TestQueryValidatorCommunityPoolGRPC() { } for _, tc := range testCases { - tc := tc resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Run(tc.name, func() { diff --git a/x/distribution/client/testutil/suite.go b/x/distribution/client/testutil/suite.go index bfde2566d6..3d5e8d2a06 100644 --- a/x/distribution/client/testutil/suite.go +++ b/x/distribution/client/testutil/suite.go @@ -5,11 +5,10 @@ import ( "strings" "time" + ostcli "github.com/Finschia/ostracon/libs/cli" "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" - ostcli "github.com/Finschia/ostracon/libs/cli" - "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/testutil" clitestutil "github.com/Finschia/finschia-sdk/testutil/cli" @@ -87,8 +86,6 @@ withdraw_addr_enabled: true`, } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryParams() clientCtx := val.ClientCtx @@ -146,8 +143,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorOutstandingRewards() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryValidatorOutstandingRewards() clientCtx := val.ClientCtx @@ -209,8 +204,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorCommission() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryValidatorCommission() clientCtx := val.ClientCtx @@ -288,8 +281,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorSlashes() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryValidatorSlashes() clientCtx := val.ClientCtx @@ -389,8 +380,6 @@ total: } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryDelegatorRewards() clientCtx := val.ClientCtx @@ -432,8 +421,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryCommunityPool() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryCommunityPool() clientCtx := val.ClientCtx @@ -493,8 +480,6 @@ func (s *IntegrationTestSuite) TestNewWithdrawRewardsCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { clientCtx := val.ClientCtx @@ -545,8 +530,6 @@ func (s *IntegrationTestSuite) TestNewWithdrawAllRewardsCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewWithdrawAllRewardsCmd() clientCtx := val.ClientCtx @@ -600,8 +583,6 @@ func (s *IntegrationTestSuite) TestNewSetWithdrawAddrCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewSetWithdrawAddrCmd() clientCtx := val.ClientCtx @@ -655,8 +636,6 @@ func (s *IntegrationTestSuite) TestNewFundCommunityPoolCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewFundCommunityPoolCmd() clientCtx := val.ClientCtx @@ -728,8 +707,6 @@ func (s *IntegrationTestSuite) TestGetCmdSubmitProposal() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdSubmitProposal() clientCtx := val.ClientCtx diff --git a/x/distribution/keeper/allocation_test.go b/x/distribution/keeper/allocation_test.go index 62bc93f4bf..28c8e7869c 100644 --- a/x/distribution/keeper/allocation_test.go +++ b/x/distribution/keeper/allocation_test.go @@ -142,7 +142,7 @@ func TestAllocateTokensTruncation(t *testing.T) { Address: valConsPk2.Address(), Power: 10, } - abciValС := abci.Validator{ + abciValC := abci.Validator{ Address: valConsPk3.Address(), Power: 10, } @@ -177,7 +177,7 @@ func TestAllocateTokensTruncation(t *testing.T) { SignedLastBlock: true, }, { - Validator: abciValС, + Validator: abciValC, SignedLastBlock: true, }, } diff --git a/x/distribution/keeper/delegation.go b/x/distribution/keeper/delegation.go index 779f78fec0..8318c1b5d4 100644 --- a/x/distribution/keeper/delegation.go +++ b/x/distribution/keeper/delegation.go @@ -119,7 +119,7 @@ func (k Keeper) CalculateDelegationRewards(ctx sdk.Context, val stakingtypes.Val // // A small amount of this error is tolerated and corrected for, // however any greater amount should be considered a breach in expected - // behaviour. + // behavior. marginOfErr := sdk.SmallestDec().MulInt64(3) if stake.LTE(currentStake.Add(marginOfErr)) { stake = currentStake diff --git a/x/distribution/keeper/genesis.go b/x/distribution/keeper/genesis.go index 1349f28e97..02082070ea 100644 --- a/x/distribution/keeper/genesis.go +++ b/x/distribution/keeper/genesis.go @@ -101,7 +101,7 @@ func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { params := k.GetParams(ctx) dwi := make([]types.DelegatorWithdrawInfo, 0) - k.IterateDelegatorWithdrawAddrs(ctx, func(del sdk.AccAddress, addr sdk.AccAddress) (stop bool) { + k.IterateDelegatorWithdrawAddrs(ctx, func(del, addr sdk.AccAddress) (stop bool) { dwi = append(dwi, types.DelegatorWithdrawInfo{ DelegatorAddress: del.String(), WithdrawAddress: addr.String(), diff --git a/x/distribution/keeper/grpc_query.go b/x/distribution/keeper/grpc_query.go index f778a98304..f2e3ad4499 100644 --- a/x/distribution/keeper/grpc_query.go +++ b/x/distribution/keeper/grpc_query.go @@ -90,7 +90,7 @@ func (k Keeper) ValidatorSlashes(c context.Context, req *types.QueryValidatorSla } slashesStore := prefix.NewStore(store, types.GetValidatorSlashEventPrefix(valAddr)) - pageRes, err := query.FilteredPaginate(slashesStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { + pageRes, err := query.FilteredPaginate(slashesStore, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) { var result types.ValidatorSlashEvent err := k.cdc.Unmarshal(value, &result) if err != nil { diff --git a/x/distribution/keeper/keeper.go b/x/distribution/keeper/keeper.go index de54742a07..e3fd0399b1 100644 --- a/x/distribution/keeper/keeper.go +++ b/x/distribution/keeper/keeper.go @@ -60,7 +60,7 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { } // SetWithdrawAddr sets a new address that will receive the rewards upon withdrawal -func (k Keeper) SetWithdrawAddr(ctx sdk.Context, delegatorAddr sdk.AccAddress, withdrawAddr sdk.AccAddress) error { +func (k Keeper) SetWithdrawAddr(ctx sdk.Context, delegatorAddr, withdrawAddr sdk.AccAddress) error { if k.blockedAddrs[withdrawAddr.String()] { return sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive external funds", withdrawAddr) } diff --git a/x/distribution/keeper/querier_test.go b/x/distribution/keeper/querier_test.go index 7b0680db10..cf11d0d399 100644 --- a/x/distribution/keeper/querier_test.go +++ b/x/distribution/keeper/querier_test.go @@ -22,6 +22,7 @@ import ( const custom = "custom" func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier) types.Params { + t.Helper() var params types.Params bz, err := querier(ctx, []string{types.QueryParams}, abci.RequestQuery{}) @@ -32,6 +33,7 @@ func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, que } func getQueriedValidatorOutstandingRewards(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, validatorAddr sdk.ValAddress) sdk.DecCoins { + t.Helper() query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryValidatorOutstandingRewards}, "/"), Data: cdc.MustMarshalJSON(types.NewQueryValidatorOutstandingRewardsParams(validatorAddr)), @@ -46,6 +48,7 @@ func getQueriedValidatorOutstandingRewards(t *testing.T, ctx sdk.Context, cdc *c } func getQueriedValidatorCommission(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, validatorAddr sdk.ValAddress) sdk.DecCoins { + t.Helper() query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryValidatorCommission}, "/"), Data: cdc.MustMarshalJSON(types.NewQueryValidatorCommissionParams(validatorAddr)), @@ -59,7 +62,8 @@ func getQueriedValidatorCommission(t *testing.T, ctx sdk.Context, cdc *codec.Leg return validatorCommission.GetCommission() } -func getQueriedValidatorSlashes(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, validatorAddr sdk.ValAddress, startHeight uint64, endHeight uint64) (slashes []types.ValidatorSlashEvent) { +func getQueriedValidatorSlashes(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, validatorAddr sdk.ValAddress, startHeight, endHeight uint64) (slashes []types.ValidatorSlashEvent) { + t.Helper() query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryValidatorSlashes}, "/"), Data: cdc.MustMarshalJSON(types.NewQueryValidatorSlashesParams(validatorAddr, startHeight, endHeight)), @@ -73,6 +77,7 @@ func getQueriedValidatorSlashes(t *testing.T, ctx sdk.Context, cdc *codec.Legacy } func getQueriedDelegationRewards(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) (rewards sdk.DecCoins) { + t.Helper() query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryDelegationRewards}, "/"), Data: cdc.MustMarshalJSON(types.NewQueryDelegationRewardsParams(delegatorAddr, validatorAddr)), @@ -86,6 +91,7 @@ func getQueriedDelegationRewards(t *testing.T, ctx sdk.Context, cdc *codec.Legac } func getQueriedDelegatorTotalRewards(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, delegatorAddr sdk.AccAddress) (response types.QueryDelegatorTotalRewardsResponse) { + t.Helper() query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryDelegatorTotalRewards}, "/"), Data: cdc.MustMarshalJSON(types.NewQueryDelegatorParams(delegatorAddr)), @@ -99,6 +105,7 @@ func getQueriedDelegatorTotalRewards(t *testing.T, ctx sdk.Context, cdc *codec.L } func getQueriedCommunityPool(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier) (ptr []byte) { + t.Helper() query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryCommunityPool}, ""), Data: []byte{}, diff --git a/x/distribution/keeper/store.go b/x/distribution/keeper/store.go index 50387303f0..f8b82141b4 100644 --- a/x/distribution/keeper/store.go +++ b/x/distribution/keeper/store.go @@ -30,7 +30,7 @@ func (k Keeper) DeleteDelegatorWithdrawAddr(ctx sdk.Context, delAddr, withdrawAd } // iterate over delegator withdraw addrs -func (k Keeper) IterateDelegatorWithdrawAddrs(ctx sdk.Context, handler func(del sdk.AccAddress, addr sdk.AccAddress) (stop bool)) { +func (k Keeper) IterateDelegatorWithdrawAddrs(ctx sdk.Context, handler func(del, addr sdk.AccAddress) (stop bool)) { store := ctx.KVStore(k.storeKey) iter := sdk.KVStorePrefixIterator(store, types.DelegatorWithdrawAddrPrefix) defer iter.Close() @@ -330,7 +330,7 @@ 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, +func (k Keeper) IterateValidatorSlashEventsBetween(ctx sdk.Context, val sdk.ValAddress, startingHeight, endingHeight uint64, handler func(height uint64, event types.ValidatorSlashEvent) (stop bool), ) { store := ctx.KVStore(k.storeKey) diff --git a/x/distribution/keeper/validator.go b/x/distribution/keeper/validator.go index 5b68f4e0c8..362250b4f1 100644 --- a/x/distribution/keeper/validator.go +++ b/x/distribution/keeper/validator.go @@ -4,7 +4,6 @@ import ( "fmt" sdk "github.com/Finschia/finschia-sdk/types" - "github.com/Finschia/finschia-sdk/x/distribution/types" stakingtypes "github.com/Finschia/finschia-sdk/x/staking/types" ) diff --git a/x/distribution/legacy/v043/store_test.go b/x/distribution/legacy/v043/store_test.go index fff87528a9..4c8ff1d522 100644 --- a/x/distribution/legacy/v043/store_test.go +++ b/x/distribution/legacy/v043/store_test.go @@ -88,7 +88,6 @@ func TestStoreMigration(t *testing.T) { // Make sure the new keys are set and old keys are deleted. for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { if !bytes.Equal(tc.oldKey, tc.newKey) { require.Nil(t, store.Get(tc.oldKey)) diff --git a/x/distribution/module.go b/x/distribution/module.go index b2fc955f6c..fea459b3d2 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -6,9 +6,8 @@ import ( "fmt" "math/rand" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" diff --git a/x/distribution/proposal_handler_test.go b/x/distribution/proposal_handler_test.go index e7a8efc994..60859e7bd1 100644 --- a/x/distribution/proposal_handler_test.go +++ b/x/distribution/proposal_handler_test.go @@ -32,7 +32,6 @@ func TestProposalHandlerPassed(t *testing.T) { // add coins to the module account macc := app.DistrKeeper.GetDistributionAccount(ctx) - balances := app.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) require.NoError(t, simapp.FundModuleAccount(app, ctx, macc.GetName(), amount)) app.AccountKeeper.SetModuleAccount(ctx, macc) @@ -49,7 +48,7 @@ func TestProposalHandlerPassed(t *testing.T) { hdlr := distribution.NewCommunityPoolSpendProposalHandler(app.DistrKeeper) require.NoError(t, hdlr(ctx, tp)) - balances = app.BankKeeper.GetAllBalances(ctx, recipient) + balances := app.BankKeeper.GetAllBalances(ctx, recipient) require.Equal(t, balances, amount) } diff --git a/x/distribution/simulation/decoder_test.go b/x/distribution/simulation/decoder_test.go index f37bb4fab8..841aaf5f17 100644 --- a/x/distribution/simulation/decoder_test.go +++ b/x/distribution/simulation/decoder_test.go @@ -66,7 +66,6 @@ func TestDecodeDistributionStore(t *testing.T) { {"other", ""}, } for i, tt := range tests { - i, tt := i, tt t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index 58fe61fc2c..98dc0df8a9 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -15,13 +15,12 @@ import ( stakingkeeper "github.com/Finschia/finschia-sdk/x/staking/keeper" ) -// nolint:gosec // Simulation operation weights constants const ( - OpWeightMsgSetWithdrawAddress = "op_weight_msg_set_withdraw_address" //nolint:gosec - OpWeightMsgWithdrawDelegationReward = "op_weight_msg_withdraw_delegation_reward" //nolint:gosec - OpWeightMsgWithdrawValidatorCommission = "op_weight_msg_withdraw_validator_commission" //nolint:gosec - OpWeightMsgFundCommunityPool = "op_weight_msg_fund_community_pool" //nolint:gosec + OpWeightMsgSetWithdrawAddress = "op_weight_msg_set_withdraw_address" + OpWeightMsgWithdrawDelegationReward = "op_weight_msg_withdraw_delegation_reward" + OpWeightMsgWithdrawValidatorCommission = "op_weight_msg_withdraw_validator_commission" + OpWeightMsgFundCommunityPool = "op_weight_msg_fund_community_pool" ) // WeightedOperations returns all the operations from the module with their respective weights diff --git a/x/distribution/simulation/operations_test.go b/x/distribution/simulation/operations_test.go index 6b37ef7123..da4a85487d 100644 --- a/x/distribution/simulation/operations_test.go +++ b/x/distribution/simulation/operations_test.go @@ -4,17 +4,15 @@ import ( "math/rand" "testing" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/stretchr/testify/suite" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/finschia-sdk/simapp" simappparams "github.com/Finschia/finschia-sdk/simapp/params" sdk "github.com/Finschia/finschia-sdk/types" simtypes "github.com/Finschia/finschia-sdk/types/simulation" "github.com/Finschia/finschia-sdk/x/distribution/simulation" - "github.com/Finschia/finschia-sdk/x/distribution/types" distrtypes "github.com/Finschia/finschia-sdk/x/distribution/types" stakingtypes "github.com/Finschia/finschia-sdk/x/staking/types" ) @@ -38,10 +36,10 @@ func (suite *SimTestSuite) TestWeightedOperations() { opMsgRoute string opMsgName string }{ - {simappparams.DefaultWeightMsgSetWithdrawAddress, types.ModuleName, types.TypeMsgSetWithdrawAddress}, - {simappparams.DefaultWeightMsgWithdrawDelegationReward, types.ModuleName, types.TypeMsgWithdrawDelegatorReward}, - {simappparams.DefaultWeightMsgWithdrawValidatorCommission, types.ModuleName, types.TypeMsgWithdrawValidatorCommission}, - {simappparams.DefaultWeightMsgFundCommunityPool, types.ModuleName, types.TypeMsgFundCommunityPool}, + {simappparams.DefaultWeightMsgSetWithdrawAddress, distrtypes.ModuleName, distrtypes.TypeMsgSetWithdrawAddress}, + {simappparams.DefaultWeightMsgWithdrawDelegationReward, distrtypes.ModuleName, distrtypes.TypeMsgWithdrawDelegatorReward}, + {simappparams.DefaultWeightMsgWithdrawValidatorCommission, distrtypes.ModuleName, distrtypes.TypeMsgWithdrawValidatorCommission}, + {simappparams.DefaultWeightMsgFundCommunityPool, distrtypes.ModuleName, distrtypes.TypeMsgFundCommunityPool}, } for i, w := range weightesOps { @@ -71,14 +69,15 @@ func (suite *SimTestSuite) TestSimulateMsgSetWithdrawAddress() { operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) - var msg types.MsgSetWithdrawAddress - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + var msg distrtypes.MsgSetWithdrawAddress + err = distrtypes.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal("link1ghekyjucln7y67ntx7cf27m9dpuxxemnqk82wt", msg.DelegatorAddress) suite.Require().Equal("link1p8wcgrjr4pjju90xg6u9cgq55dxwq8j7fmx8x8", msg.WithdrawAddress) - suite.Require().Equal(types.TypeMsgSetWithdrawAddress, msg.Type()) - suite.Require().Equal(types.ModuleName, msg.Route()) + suite.Require().Equal(distrtypes.TypeMsgSetWithdrawAddress, msg.Type()) + suite.Require().Equal(distrtypes.ModuleName, msg.Route()) suite.Require().Len(futureOperations, 0) } @@ -112,14 +111,15 @@ func (suite *SimTestSuite) TestSimulateMsgWithdrawDelegatorReward() { operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) - var msg types.MsgWithdrawDelegatorReward - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + var msg distrtypes.MsgWithdrawDelegatorReward + err = distrtypes.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal("linkvaloper1l4s054098kk9hmr5753c6k3m2kw65h68cr83wt", msg.ValidatorAddress) suite.Require().Equal("link1d6u7zhjwmsucs678d7qn95uqajd4ucl98kjf3j", msg.DelegatorAddress) - suite.Require().Equal(types.TypeMsgWithdrawDelegatorReward, msg.Type()) - suite.Require().Equal(types.ModuleName, msg.Route()) + suite.Require().Equal(distrtypes.TypeMsgWithdrawDelegatorReward, msg.Type()) + suite.Require().Equal(distrtypes.ModuleName, msg.Route()) suite.Require().Len(futureOperations, 0) } @@ -155,10 +155,10 @@ func (suite *SimTestSuite) testSimulateMsgWithdrawValidatorCommission(tokenName sdk.NewDecCoinFromDec("stake", sdk.NewDec(1).Quo(sdk.NewDec(1))), ) - suite.app.DistrKeeper.SetValidatorOutstandingRewards(suite.ctx, validator0.GetOperator(), types.ValidatorOutstandingRewards{Rewards: valCommission}) + suite.app.DistrKeeper.SetValidatorOutstandingRewards(suite.ctx, validator0.GetOperator(), distrtypes.ValidatorOutstandingRewards{Rewards: valCommission}) // setup validator accumulated commission - suite.app.DistrKeeper.SetValidatorAccumulatedCommission(suite.ctx, validator0.GetOperator(), types.ValidatorAccumulatedCommission{Commission: valCommission}) + suite.app.DistrKeeper.SetValidatorAccumulatedCommission(suite.ctx, validator0.GetOperator(), distrtypes.ValidatorAccumulatedCommission{Commission: valCommission}) // begin a new block suite.app.BeginBlock(ocabci.RequestBeginBlock{Header: tmproto.Header{Height: suite.app.LastBlockHeight() + 1, AppHash: suite.app.LastCommitID().Hash}}) @@ -168,13 +168,14 @@ func (suite *SimTestSuite) testSimulateMsgWithdrawValidatorCommission(tokenName operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) - var msg types.MsgWithdrawValidatorCommission - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + var msg distrtypes.MsgWithdrawValidatorCommission + err = distrtypes.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal("linkvaloper1tnh2q55v8wyygtt9srz5safamzdengsn8rx882", msg.ValidatorAddress) - suite.Require().Equal(types.TypeMsgWithdrawValidatorCommission, msg.Type()) - suite.Require().Equal(types.ModuleName, msg.Route()) + suite.Require().Equal(distrtypes.TypeMsgWithdrawValidatorCommission, msg.Type()) + suite.Require().Equal(distrtypes.ModuleName, msg.Route()) suite.Require().Len(futureOperations, 0) } @@ -194,14 +195,15 @@ func (suite *SimTestSuite) TestSimulateMsgFundCommunityPool() { operationMsg, futureOperations, err := op(r, suite.app.BaseApp, suite.ctx, accounts, "") suite.Require().NoError(err) - var msg types.MsgFundCommunityPool - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + var msg distrtypes.MsgFundCommunityPool + err = distrtypes.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + suite.Require().NoError(err) suite.Require().True(operationMsg.OK) suite.Require().Equal("4896096stake", msg.Amount.String()) suite.Require().Equal("link1ghekyjucln7y67ntx7cf27m9dpuxxemnqk82wt", msg.Depositor) - suite.Require().Equal(types.TypeMsgFundCommunityPool, msg.Type()) - suite.Require().Equal(types.ModuleName, msg.Route()) + suite.Require().Equal(distrtypes.TypeMsgFundCommunityPool, msg.Type()) + suite.Require().Equal(distrtypes.ModuleName, msg.Route()) suite.Require().Len(futureOperations, 0) } diff --git a/x/distribution/simulation/params.go b/x/distribution/simulation/params.go index 89a733fd68..77414e81a1 100644 --- a/x/distribution/simulation/params.go +++ b/x/distribution/simulation/params.go @@ -6,10 +6,9 @@ import ( "fmt" "math/rand" - "github.com/Finschia/finschia-sdk/x/simulation" - simtypes "github.com/Finschia/finschia-sdk/types/simulation" "github.com/Finschia/finschia-sdk/x/distribution/types" + "github.com/Finschia/finschia-sdk/x/simulation" ) const ( diff --git a/x/distribution/types/expected_keepers.go b/x/distribution/types/expected_keepers.go index 63260649d6..339b4b9363 100644 --- a/x/distribution/types/expected_keepers.go +++ b/x/distribution/types/expected_keepers.go @@ -24,7 +24,7 @@ type BankKeeper interface { LockedCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule string, recipientModule string, amt sdk.Coins) error + SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error } @@ -46,7 +46,7 @@ type StakingKeeper interface { Validator(sdk.Context, sdk.ValAddress) stakingtypes.ValidatorI // get a particular validator by operator address ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) stakingtypes.ValidatorI // get a particular validator by consensus address - // slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction + // slash the validator and delegators of the validator, specifying offense height, offense power, and slash fraction Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) Jail(sdk.Context, sdk.ConsAddress) // jail a validator Unjail(sdk.Context, sdk.ConsAddress) // unjail a validator diff --git a/x/distribution/types/params_internal_test.go b/x/distribution/types/params_internal_test.go index 234a79fbd1..152845f00c 100644 --- a/x/distribution/types/params_internal_test.go +++ b/x/distribution/types/params_internal_test.go @@ -24,7 +24,6 @@ func Test_validateAuxFuncs(t *testing.T) { {"two dec", args{sdk.NewDec(2)}, true}, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { require.Equal(t, tt.wantErr, validateCommunityTax(tt.args.i) != nil) require.Equal(t, tt.wantErr, validateBaseProposerReward(tt.args.i) != nil) diff --git a/x/distribution/types/querier.go b/x/distribution/types/querier.go index a4f2a55d55..b1ed8796b9 100644 --- a/x/distribution/types/querier.go +++ b/x/distribution/types/querier.go @@ -49,7 +49,7 @@ type QueryValidatorSlashesParams struct { } // creates a new instance of QueryValidatorSlashesParams -func NewQueryValidatorSlashesParams(validatorAddr sdk.ValAddress, startingHeight uint64, endingHeight uint64) QueryValidatorSlashesParams { +func NewQueryValidatorSlashesParams(validatorAddr sdk.ValAddress, startingHeight, endingHeight uint64) QueryValidatorSlashesParams { return QueryValidatorSlashesParams{ ValidatorAddress: validatorAddr, StartingHeight: startingHeight, diff --git a/x/evidence/client/cli/tx.go b/x/evidence/client/cli/tx.go index 596f91f68a..82abce61f3 100644 --- a/x/evidence/client/cli/tx.go +++ b/x/evidence/client/cli/tx.go @@ -1,10 +1,10 @@ package cli import ( + "github.com/spf13/cobra" + "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/x/evidence/types" - - "github.com/spf13/cobra" ) // GetTxCmd returns a CLI command that has all the native evidence module tx diff --git a/x/evidence/client/testutil/suite.go b/x/evidence/client/testutil/suite.go index 3fdba740e9..80e2ce89b4 100644 --- a/x/evidence/client/testutil/suite.go +++ b/x/evidence/client/testutil/suite.go @@ -56,8 +56,6 @@ func (s *IntegrationTestSuite) TestGetQueryCmd() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.GetQueryCmd() clientCtx := val.ClientCtx diff --git a/x/evidence/handler_test.go b/x/evidence/handler_test.go index a1c4913b6d..4104490b24 100644 --- a/x/evidence/handler_test.go +++ b/x/evidence/handler_test.go @@ -116,7 +116,8 @@ func (suite *HandlerTestSuite) TestMsgSubmitEvidence() { msg := tc.msg.(exported.MsgSubmitEvidenceI) var resultData types.MsgSubmitEvidenceResponse - suite.app.AppCodec().Unmarshal(res.Data, &resultData) + err := suite.app.AppCodec().Unmarshal(res.Data, &resultData) + suite.Require().NoError(err) suite.Require().Equal(msg.GetEvidence().Hash().Bytes(), resultData.Hash, "invalid hash; tc #%d", i) } } diff --git a/x/evidence/keeper/grpc_query.go b/x/evidence/keeper/grpc_query.go index 4d6911eaeb..0e7651b544 100644 --- a/x/evidence/keeper/grpc_query.go +++ b/x/evidence/keeper/grpc_query.go @@ -3,16 +3,14 @@ package keeper import ( "context" + proto "github.com/gogo/protobuf/proto" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "github.com/Finschia/finschia-sdk/store/prefix" - "github.com/Finschia/finschia-sdk/types/query" - - proto "github.com/gogo/protobuf/proto" - codectypes "github.com/Finschia/finschia-sdk/codec/types" + "github.com/Finschia/finschia-sdk/store/prefix" sdk "github.com/Finschia/finschia-sdk/types" + "github.com/Finschia/finschia-sdk/types/query" "github.com/Finschia/finschia-sdk/x/evidence/types" ) @@ -61,7 +59,7 @@ func (k Keeper) AllEvidence(c context.Context, req *types.QueryAllEvidenceReques store := ctx.KVStore(k.storeKey) evidenceStore := prefix.NewStore(store, types.KeyPrefixEvidence) - pageRes, err := query.Paginate(evidenceStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(evidenceStore, req.Pagination, func(key, value []byte) error { result, err := k.UnmarshalEvidence(value) if err != nil { return err diff --git a/x/evidence/keeper/grpc_query_test.go b/x/evidence/keeper/grpc_query_test.go index 81f77c0d11..3eff6ecc77 100644 --- a/x/evidence/keeper/grpc_query_test.go +++ b/x/evidence/keeper/grpc_query_test.go @@ -3,12 +3,12 @@ package keeper_test import ( "fmt" + ostbytes "github.com/Finschia/ostracon/libs/bytes" + sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/types/query" "github.com/Finschia/finschia-sdk/x/evidence/exported" "github.com/Finschia/finschia-sdk/x/evidence/types" - - ostbytes "github.com/Finschia/ostracon/libs/bytes" ) func (suite *KeeperTestSuite) TestQueryEvidence() { diff --git a/x/evidence/keeper/infraction.go b/x/evidence/keeper/infraction.go index ec7004416c..590ff0d55d 100644 --- a/x/evidence/keeper/infraction.go +++ b/x/evidence/keeper/infraction.go @@ -4,7 +4,6 @@ import ( "fmt" sdk "github.com/Finschia/finschia-sdk/types" - "github.com/Finschia/finschia-sdk/x/evidence/types" ) diff --git a/x/evidence/keeper/querier.go b/x/evidence/keeper/querier.go index c98c101a80..8cdf31fd22 100644 --- a/x/evidence/keeper/querier.go +++ b/x/evidence/keeper/querier.go @@ -1,14 +1,14 @@ package keeper import ( + abci "github.com/tendermint/tendermint/abci/types" + "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/codec" sdk "github.com/Finschia/finschia-sdk/types" sdkerrors "github.com/Finschia/finschia-sdk/types/errors" "github.com/Finschia/finschia-sdk/x/evidence/exported" "github.com/Finschia/finschia-sdk/x/evidence/types" - - abci "github.com/tendermint/tendermint/abci/types" ) func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { diff --git a/x/evidence/keeper/querier_test.go b/x/evidence/keeper/querier_test.go index fa90d96007..e2f0022c16 100644 --- a/x/evidence/keeper/querier_test.go +++ b/x/evidence/keeper/querier_test.go @@ -3,12 +3,11 @@ package keeper_test import ( "strings" - "github.com/Finschia/finschia-sdk/simapp" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/Finschia/finschia-sdk/simapp" "github.com/Finschia/finschia-sdk/x/evidence/exported" "github.com/Finschia/finschia-sdk/x/evidence/types" - - abci "github.com/tendermint/tendermint/abci/types" ) const ( diff --git a/x/evidence/module.go b/x/evidence/module.go index 050b943d21..40ee9980e2 100644 --- a/x/evidence/module.go +++ b/x/evidence/module.go @@ -6,11 +6,9 @@ import ( "fmt" "math/rand" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - ocabci "github.com/Finschia/ostracon/abci/types" abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/client" diff --git a/x/evidence/simulation/decoder_test.go b/x/evidence/simulation/decoder_test.go index 3e18656b6c..eeca030223 100644 --- a/x/evidence/simulation/decoder_test.go +++ b/x/evidence/simulation/decoder_test.go @@ -52,7 +52,6 @@ func TestDecodeStore(t *testing.T) { } for i, tt := range tests { - i, tt := i, tt t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: diff --git a/x/evidence/types/evidence_test.go b/x/evidence/types/evidence_test.go index 696600d0ad..c7a0be8e53 100644 --- a/x/evidence/types/evidence_test.go +++ b/x/evidence/types/evidence_test.go @@ -52,7 +52,6 @@ func TestEquivocationValidateBasic(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { require.Equal(t, tc.expectErr, tc.e.ValidateBasic() != nil) }) diff --git a/x/evidence/types/msgs_test.go b/x/evidence/types/msgs_test.go index 5e86252315..bc93d11150 100644 --- a/x/evidence/types/msgs_test.go +++ b/x/evidence/types/msgs_test.go @@ -13,6 +13,7 @@ import ( ) func testMsgSubmitEvidence(t *testing.T, e exported.Evidence, s sdk.AccAddress) exported.MsgSubmitEvidenceI { + t.Helper() msg, err := types.NewMsgSubmitEvidence(s, e) require.NoError(t, err) return msg diff --git a/x/fbridge/keeper/transfer.go b/x/fbridge/keeper/transfer.go index 333fa72f23..2eabb45cb5 100644 --- a/x/fbridge/keeper/transfer.go +++ b/x/fbridge/keeper/transfer.go @@ -27,7 +27,7 @@ func (k Keeper) handleBridgeTransfer(ctx sdk.Context, sender sdk.AccAddress, amo } if err := k.bankKeeper.BurnCoins(ctx, types.ModuleName, token); err != nil { - panic(fmt.Errorf("cannot burn coins after a successful send to a module account: %s", err)) + panic(fmt.Errorf("cannot burn coins after a successful send to a module account: %w", err)) } seq := k.GetNextSequence(ctx) diff --git a/x/fbridge/types/msgs_test.go b/x/fbridge/types/msgs_test.go index 87166e0ad4..b339c7d592 100644 --- a/x/fbridge/types/msgs_test.go +++ b/x/fbridge/types/msgs_test.go @@ -137,7 +137,6 @@ func TestAminoJSON(t *testing.T) { } for name, tc := range testCase { - tc := tc t.Run(name, func(t *testing.T) { tx.Msgs = []sdk.Msg{tc.msg} require.Equal(t, fbridgetypes.RouterKey, tc.msg.Route()) diff --git a/x/feegrant/client/testutil/suite.go b/x/feegrant/client/testutil/suite.go index 839dca4f30..fe22dd46f9 100644 --- a/x/feegrant/client/testutil/suite.go +++ b/x/feegrant/client/testutil/suite.go @@ -6,11 +6,10 @@ import ( "testing" "time" + ostcli "github.com/Finschia/ostracon/libs/cli" "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" - ostcli "github.com/Finschia/ostracon/libs/cli" - "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/crypto/hd" @@ -169,8 +168,6 @@ func (s *IntegrationTestSuite) TestCmdGetFeeGrant() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryFeeGrant() out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -235,8 +232,6 @@ func (s *IntegrationTestSuite) TestCmdGetFeeGrantsByGrantee() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryFeeGrantsByGrantee() out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -291,8 +286,6 @@ func (s *IntegrationTestSuite) TestCmdGetFeeGrantsByGranter() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryFeeGrantsByGranter() out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -584,8 +577,6 @@ func (s *IntegrationTestSuite) TestNewCmdFeeGrant() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewCmdFeeGrant() out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -691,8 +682,6 @@ func (s *IntegrationTestSuite) TestNewCmdRevokeFeegrant() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewCmdRevokeFeegrant() out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -830,8 +819,6 @@ func (s *IntegrationTestSuite) TestFilteredFeeAllowance() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewCmdFeeGrant() out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -925,8 +912,6 @@ func (s *IntegrationTestSuite) TestFilteredFeeAllowance() { } for _, tc := range cases { - tc := tc - s.Run(tc.name, func() { out, err := tc.malleate() s.Require().NoError(err) diff --git a/x/feegrant/filtered_fee_test.go b/x/feegrant/filtered_fee_test.go index a5a74ea499..39d4ed1d56 100644 --- a/x/feegrant/filtered_fee_test.go +++ b/x/feegrant/filtered_fee_test.go @@ -190,8 +190,7 @@ func TestFilteredFeeValidAllow(t *testing.T) { } // invalidInterfaceAllowance does not implement proto.Message -type invalidInterfaceAllowance struct { -} +type invalidInterfaceAllowance struct{} // compilation time interface implementation check var _ feegrant.FeeAllowanceI = (*invalidInterfaceAllowance)(nil) @@ -210,8 +209,10 @@ type invalidProtoAllowance struct { } // compilation time interface implementation check -var _ feegrant.FeeAllowanceI = (*invalidProtoAllowance)(nil) -var _ proto.Message = (*invalidProtoAllowance)(nil) +var ( + _ feegrant.FeeAllowanceI = (*invalidProtoAllowance)(nil) + _ proto.Message = (*invalidProtoAllowance)(nil) +) func (i invalidProtoAllowance) Reset() { } diff --git a/x/feegrant/grant_test.go b/x/feegrant/grant_test.go index 2368c77d3d..af0f1873c9 100644 --- a/x/feegrant/grant_test.go +++ b/x/feegrant/grant_test.go @@ -73,7 +73,6 @@ func TestGrant(t *testing.T) { } for name, tc := range cases { - tc := tc t.Run(name, func(t *testing.T) { grant, err := feegrant.NewGrant(tc.granter, tc.grantee, &feegrant.BasicAllowance{ SpendLimit: tc.limit, diff --git a/x/feegrant/keeper/genesis_test.go b/x/feegrant/keeper/genesis_test.go index ea2731cb4b..9f659bf30c 100644 --- a/x/feegrant/keeper/genesis_test.go +++ b/x/feegrant/keeper/genesis_test.go @@ -100,7 +100,6 @@ func (suite *GenesisTestSuite) TestInitGenesis() { } for _, tc := range testCases { - tc := tc suite.Run(tc.name, func() { err := suite.keeper.InitGenesis(suite.ctx, &feegrant.GenesisState{Allowances: tc.feeAllowances}) suite.Require().Error(err) diff --git a/x/feegrant/keeper/grpc_query.go b/x/feegrant/keeper/grpc_query.go index 19d6531b4b..92f20631cd 100644 --- a/x/feegrant/keeper/grpc_query.go +++ b/x/feegrant/keeper/grpc_query.go @@ -76,7 +76,7 @@ func (q Keeper) Allowances(c context.Context, req *feegrant.QueryAllowancesReque store := ctx.KVStore(q.storeKey) grantsStore := prefix.NewStore(store, feegrant.FeeAllowancePrefixByGrantee(granteeAddr)) - pageRes, err := query.Paginate(grantsStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(grantsStore, req.Pagination, func(key, value []byte) error { var grant feegrant.Grant if err := q.cdc.Unmarshal(value, &grant); err != nil { @@ -110,7 +110,7 @@ func (q Keeper) AllowancesByGranter(c context.Context, req *feegrant.QueryAllowa store := ctx.KVStore(q.storeKey) prefixStore := prefix.NewStore(store, feegrant.FeeAllowanceKeyPrefix) - pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { + pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) { // ParseAddressesFromFeeAllowanceKey expects the full key including the prefix. granter, _ := feegrant.ParseAddressesFromFeeAllowanceKey(append(feegrant.FeeAllowanceKeyPrefix, key...)) if !granter.Equals(granterAddr) { diff --git a/x/feegrant/keeper/keeper.go b/x/feegrant/keeper/keeper.go index 632e192106..4db35bfdda 100644 --- a/x/feegrant/keeper/keeper.go +++ b/x/feegrant/keeper/keeper.go @@ -104,7 +104,7 @@ func (k Keeper) GetAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress) ( } // getGrant returns entire grant between both accounts -func (k Keeper) getGrant(ctx sdk.Context, granter sdk.AccAddress, grantee sdk.AccAddress) (*feegrant.Grant, error) { +func (k Keeper) getGrant(ctx sdk.Context, granter, grantee sdk.AccAddress) (*feegrant.Grant, error) { store := ctx.KVStore(k.storeKey) key := feegrant.FeeAllowanceKey(granter, grantee) bz := store.Get(key) @@ -158,7 +158,7 @@ func (k Keeper) UseGrantedFees(ctx sdk.Context, granter, grantee sdk.AccAddress, if remove { // Ignoring the `revokeFeeAllowance` error, because the user has enough grants to perform this transaction. - k.revokeAllowance(ctx, granter, grantee) + _ = k.revokeAllowance(ctx, granter, grantee) if err != nil { return err } diff --git a/x/feegrant/keeper/keeper_test.go b/x/feegrant/keeper/keeper_test.go index 459fe04e6d..b6f843a6c7 100644 --- a/x/feegrant/keeper/keeper_test.go +++ b/x/feegrant/keeper/keeper_test.go @@ -120,7 +120,6 @@ func (suite *KeeperTestSuite) TestKeeperCrud() { } for name, tc := range cases { - tc := tc suite.Run(name, func() { allow, _ := suite.keeper.GetAllowance(suite.sdkCtx, tc.granter, tc.grantee) @@ -196,7 +195,6 @@ func (suite *KeeperTestSuite) TestUseGrantedFee() { } for name, tc := range cases { - tc := tc suite.Run(name, func() { err := suite.keeper.GrantAllowance(suite.sdkCtx, suite.addrs[0], suite.addrs[1], future) suite.Require().NoError(err) @@ -247,12 +245,15 @@ func (suite *KeeperTestSuite) TestIterateGrants() { Expiration: &exp, } - suite.keeper.GrantAllowance(suite.sdkCtx, suite.addrs[0], suite.addrs[1], allowance) - suite.keeper.GrantAllowance(suite.sdkCtx, suite.addrs[2], suite.addrs[1], allowance1) + err := suite.keeper.GrantAllowance(suite.sdkCtx, suite.addrs[0], suite.addrs[1], allowance) + suite.Require().NoError(err) + err = suite.keeper.GrantAllowance(suite.sdkCtx, suite.addrs[2], suite.addrs[1], allowance1) + suite.Require().NoError(err) - suite.keeper.IterateAllFeeAllowances(suite.sdkCtx, func(grant feegrant.Grant) bool { + err = suite.keeper.IterateAllFeeAllowances(suite.sdkCtx, func(grant feegrant.Grant) bool { suite.Require().Equal(suite.addrs[1].String(), grant.Grantee) suite.Require().Contains([]string{suite.addrs[0].String(), suite.addrs[2].String()}, grant.Granter) return true }) + suite.Require().NoError(err) } diff --git a/x/feegrant/keeper/msg_server_test.go b/x/feegrant/keeper/msg_server_test.go index ab53d469c9..3c402a22e4 100644 --- a/x/feegrant/keeper/msg_server_test.go +++ b/x/feegrant/keeper/msg_server_test.go @@ -174,10 +174,12 @@ func (suite *KeeperTestSuite) TestRevokeAllowance() { }, func() { // removing fee allowance from previous tests if exists - suite.msgSrvr.RevokeAllowance(suite.ctx, &feegrant.MsgRevokeAllowance{ + _, err := suite.msgSrvr.RevokeAllowance(suite.ctx, &feegrant.MsgRevokeAllowance{ Granter: suite.addrs[0].String(), Grantee: suite.addrs[1].String(), }) + suite.Require().Error(err) + any, err := codectypes.NewAnyWithValue(&feegrant.PeriodicAllowance{ Basic: feegrant.BasicAllowance{ SpendLimit: suite.atom, diff --git a/x/feegrant/key.go b/x/feegrant/key.go index 00bfb79883..1da1e5ad05 100644 --- a/x/feegrant/key.go +++ b/x/feegrant/key.go @@ -25,7 +25,7 @@ var FeeAllowanceKeyPrefix = []byte{0x00} // FeeAllowanceKey is the canonical key to store a grant from granter to grantee // We store by grantee first to allow searching by everyone who granted to you -func FeeAllowanceKey(granter sdk.AccAddress, grantee sdk.AccAddress) []byte { +func FeeAllowanceKey(granter, grantee sdk.AccAddress) []byte { return append(FeeAllowancePrefixByGrantee(grantee), address.MustLengthPrefix(granter.Bytes())...) } diff --git a/x/feegrant/module/module.go b/x/feegrant/module/module.go index fb612cf564..47c7eedfe1 100644 --- a/x/feegrant/module/module.go +++ b/x/feegrant/module/module.go @@ -74,7 +74,7 @@ func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { func (a AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config sdkclient.TxEncodingConfig, bz json.RawMessage) error { var data feegrant.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { - sdkerrors.Wrapf(err, "failed to unmarshal %s genesis state", feegrant.ModuleName) + return sdkerrors.Wrapf(err, "failed to unmarshal %s genesis state", feegrant.ModuleName) } return feegrant.ValidateGenesis(data) diff --git a/x/feegrant/msgs.go b/x/feegrant/msgs.go index 3bc65dc99e..7bc9726ff8 100644 --- a/x/feegrant/msgs.go +++ b/x/feegrant/msgs.go @@ -100,7 +100,7 @@ func (msg MsgGrantAllowance) UnpackInterfaces(unpacker types.AnyUnpacker) error // granter and grantee // //nolint:interfacer -func NewMsgRevokeAllowance(granter sdk.AccAddress, grantee sdk.AccAddress) MsgRevokeAllowance { +func NewMsgRevokeAllowance(granter, grantee sdk.AccAddress) MsgRevokeAllowance { return MsgRevokeAllowance{Granter: granter.String(), Grantee: grantee.String()} } diff --git a/x/feegrant/simulation/decoder_test.go b/x/feegrant/simulation/decoder_test.go index c0a9c190bf..c13e75111f 100644 --- a/x/feegrant/simulation/decoder_test.go +++ b/x/feegrant/simulation/decoder_test.go @@ -35,7 +35,7 @@ func TestDecodeStore(t *testing.T) { kvPairs := kv.Pairs{ Pairs: []kv.Pair{ - {Key: []byte(feegrant.FeeAllowanceKeyPrefix), Value: grantBz}, + {Key: feegrant.FeeAllowanceKeyPrefix, Value: grantBz}, {Key: []byte{0x99}, Value: []byte{0x99}}, }, } @@ -49,7 +49,6 @@ func TestDecodeStore(t *testing.T) { } for i, tt := range tests { - i, tt := i, tt t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: diff --git a/x/feegrant/simulation/operations.go b/x/feegrant/simulation/operations.go index ae3d99b20f..6378d32df4 100644 --- a/x/feegrant/simulation/operations.go +++ b/x/feegrant/simulation/operations.go @@ -13,10 +13,7 @@ import ( "github.com/Finschia/finschia-sdk/x/simulation" ) -// nolint:gosec // Simulation operation weights constants -// -//nolint:gosec const ( OpWeightMsgGrantAllowance = "op_weight_msg_grant_fee_allowance" OpWeightMsgRevokeAllowance = "op_weight_msg_grant_revoke_allowance" @@ -118,7 +115,7 @@ func SimulateMsgRevokeAllowance(ak feegrant.AccountKeeper, bk feegrant.BankKeepe hasGrant := false var granterAddr sdk.AccAddress var granteeAddr sdk.AccAddress - k.IterateAllFeeAllowances(ctx, func(grant feegrant.Grant) bool { + err := k.IterateAllFeeAllowances(ctx, func(grant feegrant.Grant) bool { granter := sdk.MustAccAddressFromBech32(grant.Granter) grantee := sdk.MustAccAddressFromBech32(grant.Grantee) granterAddr = granter @@ -126,6 +123,9 @@ func SimulateMsgRevokeAllowance(ak feegrant.AccountKeeper, bk feegrant.BankKeepe hasGrant = true return true }) + if err != nil { + panic(err) + } if !hasGrant { return simtypes.NoOpMsg(feegrant.ModuleName, TypeMsgRevokeAllowance, "no grants"), nil, nil diff --git a/x/feegrant/simulation/operations_test.go b/x/feegrant/simulation/operations_test.go index 5abc7cfd12..684b736afc 100644 --- a/x/feegrant/simulation/operations_test.go +++ b/x/feegrant/simulation/operations_test.go @@ -5,11 +5,10 @@ import ( "testing" "time" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/stretchr/testify/suite" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/finschia-sdk/simapp" simappparams "github.com/Finschia/finschia-sdk/simapp/params" sdk "github.com/Finschia/finschia-sdk/types" @@ -112,7 +111,8 @@ func (suite *SimTestSuite) TestSimulateMsgGrantAllowance() { require.NoError(err) var msg feegrant.MsgGrantAllowance - suite.app.LegacyAmino().UnmarshalJSON(operationMsg.Msg, &msg) + err = suite.app.LegacyAmino().UnmarshalJSON(operationMsg.Msg, &msg) + require.NoError(err) require.True(operationMsg.OK) require.Equal(accounts[2].Address.String(), msg.Granter) @@ -154,7 +154,8 @@ func (suite *SimTestSuite) TestSimulateMsgRevokeAllowance() { require.NoError(err) var msg feegrant.MsgRevokeAllowance - suite.app.LegacyAmino().UnmarshalJSON(operationMsg.Msg, &msg) + err = suite.app.LegacyAmino().UnmarshalJSON(operationMsg.Msg, &msg) + require.NoError(err) require.True(operationMsg.OK) require.Equal(granter.Address.String(), msg.Granter) diff --git a/x/feegrant/types/grant_test.go b/x/feegrant/types/grant_test.go index 687fe37351..2831eb09ec 100644 --- a/x/feegrant/types/grant_test.go +++ b/x/feegrant/types/grant_test.go @@ -71,7 +71,6 @@ func TestGrant(t *testing.T) { } for name, tc := range cases { - tc := tc t.Run(name, func(t *testing.T) { grant, err := feegrant.NewGrant(tc.granter, tc.grantee, &feegrant.BasicAllowance{ SpendLimit: tc.limit, diff --git a/x/foundation/authz_test.go b/x/foundation/authz_test.go index 699ac31a97..19f1d605ad 100644 --- a/x/foundation/authz_test.go +++ b/x/foundation/authz_test.go @@ -3,9 +3,10 @@ package foundation_test import ( "testing" + "github.com/stretchr/testify/require" + sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/x/foundation" - "github.com/stretchr/testify/require" ) func TestReceiveFromTreasuryAuthorization(t *testing.T) { diff --git a/x/foundation/client/cli/tx.go b/x/foundation/client/cli/tx.go index bc4eddad12..0277873f7a 100644 --- a/x/foundation/client/cli/tx.go +++ b/x/foundation/client/cli/tx.go @@ -84,8 +84,7 @@ func parseAuthorization(codec codec.Codec, authorizationJSON string) (foundation func execFromString(execStr string) foundation.Exec { exec := foundation.Exec_EXEC_UNSPECIFIED - switch execStr { - case ExecTry: + if execStr == ExecTry { exec = foundation.Exec_EXEC_TRY } return exec diff --git a/x/foundation/client/testutil/grpc.go b/x/foundation/client/testutil/grpc.go index 3f9fedc58e..b0103983ef 100644 --- a/x/foundation/client/testutil/grpc.go +++ b/x/foundation/client/testutil/grpc.go @@ -6,7 +6,6 @@ import ( "github.com/gogo/protobuf/proto" "github.com/Finschia/finschia-sdk/testutil/rest" - sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/x/foundation" ) @@ -35,7 +34,6 @@ func (s *IntegrationTestSuite) TestGRPCParams() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) diff --git a/x/foundation/client/testutil/query.go b/x/foundation/client/testutil/query.go index 3677af29f6..403f748bf3 100644 --- a/x/foundation/client/testutil/query.go +++ b/x/foundation/client/testutil/query.go @@ -44,8 +44,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdParams() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdParams() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -86,8 +84,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdTreasury() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdTreasury() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -127,8 +123,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdFoundationInfo() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdFoundationInfo() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -184,8 +178,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdMember() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdMember() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -226,8 +218,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdMembers() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdMembers() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -276,8 +266,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdProposal() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdProposal() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -317,8 +305,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdProposals() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdProposals() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -377,8 +363,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdVote() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdVote() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -427,8 +411,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdVotes() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdVotes() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -477,8 +459,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdTallyResult() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdTallyResult() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -521,8 +501,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdCensorships() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdCensorships() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -586,8 +564,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdGrants() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdGrants() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) diff --git a/x/foundation/client/testutil/suite.go b/x/foundation/client/testutil/suite.go index 06f05de7d9..2e1e9746a9 100644 --- a/x/foundation/client/testutil/suite.go +++ b/x/foundation/client/testutil/suite.go @@ -7,13 +7,12 @@ import ( "github.com/stretchr/testify/suite" + "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/crypto/hd" "github.com/Finschia/finschia-sdk/crypto/keyring" + clitestutil "github.com/Finschia/finschia-sdk/testutil/cli" "github.com/Finschia/finschia-sdk/testutil/network" "github.com/Finschia/finschia-sdk/testutil/testdata" - - "github.com/Finschia/finschia-sdk/client/flags" - clitestutil "github.com/Finschia/finschia-sdk/testutil/cli" sdk "github.com/Finschia/finschia-sdk/types" bankcli "github.com/Finschia/finschia-sdk/x/bank/client/cli" "github.com/Finschia/finschia-sdk/x/foundation" @@ -82,12 +81,13 @@ func (s *IntegrationTestSuite) SetupSuite() { info := foundation.DefaultFoundation() info.TotalWeight = sdk.NewDecFromInt(sdk.NewInt(int64(len(foundationData.Members)))) - info.SetDecisionPolicy(&foundation.ThresholdDecisionPolicy{ + err := info.SetDecisionPolicy(&foundation.ThresholdDecisionPolicy{ Threshold: sdk.OneDec(), Windows: &foundation.DecisionPolicyWindows{ VotingPeriod: 7 * 24 * time.Hour, }, }) + s.Require().NoError(err) foundationData.Foundation = info // enable censorship diff --git a/x/foundation/client/testutil/tx.go b/x/foundation/client/testutil/tx.go index 36f7169dc6..60f50dafdd 100644 --- a/x/foundation/client/testutil/tx.go +++ b/x/foundation/client/testutil/tx.go @@ -44,8 +44,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdFundTreasury() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdFundTreasury() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -92,8 +90,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdWithdrawFromTreasury() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdWithdrawFromTreasury() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -138,8 +134,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdUpdateMembers() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdUpdateMembers() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -198,8 +192,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdUpdateDecisionPolicy() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdUpdateDecisionPolicy() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -249,8 +241,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdSubmitProposal() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdSubmitProposal() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -299,8 +289,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdWithdrawProposal() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdWithdrawProposal() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -353,8 +341,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdVote() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdVote() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -402,8 +388,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdExec() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdExec() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -449,8 +433,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdLeaveFoundation() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdLeaveFoundation() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -502,8 +484,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdGrant() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdGrant() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -549,8 +529,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdRevoke() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdRevoke() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) diff --git a/x/foundation/foundation_test.go b/x/foundation/foundation_test.go index e19805706e..903b877c21 100644 --- a/x/foundation/foundation_test.go +++ b/x/foundation/foundation_test.go @@ -4,11 +4,12 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/Finschia/finschia-sdk/crypto/keys/secp256k1" "github.com/Finschia/finschia-sdk/testutil/testdata" sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/x/foundation" - "github.com/stretchr/testify/require" ) func TestTallyResult(t *testing.T) { @@ -21,15 +22,15 @@ func TestTallyResult(t *testing.T) { require.NoError(t, err) require.Equal(t, sdk.OneDec(), result.YesCount) - result.Add(foundation.VOTE_OPTION_ABSTAIN) + err = result.Add(foundation.VOTE_OPTION_ABSTAIN) require.NoError(t, err) require.Equal(t, sdk.OneDec(), result.AbstainCount) - result.Add(foundation.VOTE_OPTION_NO) + err = result.Add(foundation.VOTE_OPTION_NO) require.NoError(t, err) require.Equal(t, sdk.OneDec(), result.NoCount) - result.Add(foundation.VOTE_OPTION_NO_WITH_VETO) + err = result.Add(foundation.VOTE_OPTION_NO_WITH_VETO) require.NoError(t, err) require.Equal(t, sdk.OneDec(), result.NoWithVetoCount) diff --git a/x/foundation/genesis_test.go b/x/foundation/genesis_test.go index afc83b0606..6da5692ffa 100644 --- a/x/foundation/genesis_test.go +++ b/x/foundation/genesis_test.go @@ -7,10 +7,9 @@ import ( "github.com/stretchr/testify/require" - "github.com/Finschia/finschia-sdk/testutil/testdata" - "github.com/Finschia/finschia-sdk/codec" codectypes "github.com/Finschia/finschia-sdk/codec/types" + "github.com/Finschia/finschia-sdk/testutil/testdata" sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/x/foundation" ) @@ -413,9 +412,9 @@ func TestValidateGenesis(t *testing.T) { err := cdc.UnmarshalJSON(tc.raw, &unmarshalled) require.NoError(t, err) - marshalled, err := cdc.MarshalJSON(&tc.data) + marshaled, err := cdc.MarshalJSON(&tc.data) require.NoError(t, err) - require.Equal(t, tc.raw, marshalled) + require.Equal(t, tc.raw, marshaled) err = foundation.ValidateGenesis(unmarshalled) if !tc.valid { diff --git a/x/foundation/keeper/internal/censorship_test.go b/x/foundation/keeper/internal/censorship_test.go index 9cd4c4bccc..42ec6990f4 100644 --- a/x/foundation/keeper/internal/censorship_test.go +++ b/x/foundation/keeper/internal/censorship_test.go @@ -68,10 +68,11 @@ func (s *KeeperTestSuite) TestGrant() { }, "not being censored": { malleate: func(ctx sdk.Context) { - s.impl.UpdateCensorship(ctx, foundation.Censorship{ + err := s.impl.UpdateCensorship(ctx, foundation.Censorship{ MsgTypeUrl: sdk.MsgTypeURL((*foundation.MsgWithdrawFromTreasury)(nil)), Authority: foundation.CensorshipAuthorityUnspecified, }) + s.Require().NoError(err) }, grantee: s.members[0], auth: &foundation.ReceiveFromTreasuryAuthorization{}, @@ -148,10 +149,11 @@ func (s *KeeperTestSuite) TestAccept() { }, "not being censored": { malleate: func(ctx sdk.Context) { - s.impl.UpdateCensorship(ctx, foundation.Censorship{ + err := s.impl.UpdateCensorship(ctx, foundation.Censorship{ MsgTypeUrl: sdk.MsgTypeURL((*foundation.MsgWithdrawFromTreasury)(nil)), Authority: foundation.CensorshipAuthorityUnspecified, }) + s.Require().NoError(err) }, grantee: s.members[0], msg: &foundation.MsgWithdrawFromTreasury{ diff --git a/x/foundation/keeper/internal/exec.go b/x/foundation/keeper/internal/exec.go index 9e91a2e145..92262fa013 100644 --- a/x/foundation/keeper/internal/exec.go +++ b/x/foundation/keeper/internal/exec.go @@ -5,7 +5,6 @@ import ( sdk "github.com/Finschia/finschia-sdk/types" sdkerrors "github.com/Finschia/finschia-sdk/types/errors" - "github.com/Finschia/finschia-sdk/x/foundation" ) diff --git a/x/foundation/keeper/internal/genesis_test.go b/x/foundation/keeper/internal/genesis_test.go index 6175580226..fb7149c93f 100644 --- a/x/foundation/keeper/internal/genesis_test.go +++ b/x/foundation/keeper/internal/genesis_test.go @@ -13,7 +13,6 @@ import ( "github.com/Finschia/finschia-sdk/testutil/testdata" sdk "github.com/Finschia/finschia-sdk/types" authtypes "github.com/Finschia/finschia-sdk/x/auth/types" - "github.com/Finschia/finschia-sdk/x/foundation" "github.com/Finschia/finschia-sdk/x/foundation/keeper/internal" ) diff --git a/x/foundation/keeper/internal/grpc_query.go b/x/foundation/keeper/internal/grpc_query.go index 89656d11ba..3b8b876bfe 100644 --- a/x/foundation/keeper/internal/grpc_query.go +++ b/x/foundation/keeper/internal/grpc_query.go @@ -3,11 +3,10 @@ package internal import ( "context" + "github.com/gogo/protobuf/proto" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "github.com/gogo/protobuf/proto" - codectypes "github.com/Finschia/finschia-sdk/codec/types" "github.com/Finschia/finschia-sdk/store/prefix" sdk "github.com/Finschia/finschia-sdk/types" @@ -87,7 +86,7 @@ func (s queryServer) Members(c context.Context, req *foundation.QueryMembersRequ ctx := sdk.UnwrapSDKContext(c) store := ctx.KVStore(s.keeper.storeKey) memberStore := prefix.NewStore(store, memberKeyPrefix) - pageRes, err := query.Paginate(memberStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(memberStore, req.Pagination, func(key, value []byte) error { var member foundation.Member s.keeper.cdc.MustUnmarshal(value, &member) members = append(members, member) @@ -123,7 +122,7 @@ func (s queryServer) Proposals(c context.Context, req *foundation.QueryProposals ctx := sdk.UnwrapSDKContext(c) store := ctx.KVStore(s.keeper.storeKey) proposalStore := prefix.NewStore(store, proposalKeyPrefix) - pageRes, err := query.Paginate(proposalStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(proposalStore, req.Pagination, func(key, value []byte) error { var proposal foundation.Proposal s.keeper.cdc.MustUnmarshal(value, &proposal) proposals = append(proposals, proposal) @@ -163,7 +162,7 @@ func (s queryServer) Votes(c context.Context, req *foundation.QueryVotesRequest) ctx := sdk.UnwrapSDKContext(c) store := ctx.KVStore(s.keeper.storeKey) voteStore := prefix.NewStore(store, append(voteKeyPrefix, Uint64ToBytes(req.ProposalId)...)) - pageRes, err := query.Paginate(voteStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(voteStore, req.Pagination, func(key, value []byte) error { var vote foundation.Vote s.keeper.cdc.MustUnmarshal(value, &vote) votes = append(votes, vote) @@ -204,7 +203,7 @@ func (s queryServer) Censorships(c context.Context, req *foundation.QueryCensors ctx := sdk.UnwrapSDKContext(c) store := ctx.KVStore(s.keeper.storeKey) censorshipStore := prefix.NewStore(store, censorshipKeyPrefix) - pageRes, err := query.Paginate(censorshipStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(censorshipStore, req.Pagination, func(key, value []byte) error { var censorship foundation.Censorship s.keeper.cdc.MustUnmarshal(value, &censorship) censorships = append(censorships, censorship) @@ -235,7 +234,7 @@ func (s queryServer) Grants(c context.Context, req *foundation.QueryGrantsReques grantStore := prefix.NewStore(store, keyPrefix) var authorizations []*codectypes.Any - _, err = query.Paginate(grantStore, req.Pagination, func(key []byte, value []byte) error { + _, err = query.Paginate(grantStore, req.Pagination, func(key, value []byte) error { var authorization foundation.Authorization if err := s.keeper.cdc.UnmarshalInterface(value, &authorization); err != nil { panic(err) @@ -265,7 +264,7 @@ func (s queryServer) Grants(c context.Context, req *foundation.QueryGrantsReques grantStore := prefix.NewStore(store, keyPrefix) var authorizations []*codectypes.Any - pageRes, err := query.Paginate(grantStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(grantStore, req.Pagination, func(key, value []byte) error { var authorization foundation.Authorization if err := s.keeper.cdc.UnmarshalInterface(value, &authorization); err != nil { panic(err) diff --git a/x/foundation/keeper/internal/keeper_test.go b/x/foundation/keeper/internal/keeper_test.go index 1b81a82a20..de255389b1 100644 --- a/x/foundation/keeper/internal/keeper_test.go +++ b/x/foundation/keeper/internal/keeper_test.go @@ -278,7 +278,6 @@ func TestNewKeeper(t *testing.T) { } for name, tc := range testCases { - tc := tc t.Run(name, func(t *testing.T) { newKeeper := func() keeper.Keeper { app := simapp.Setup(false) diff --git a/x/foundation/keeper/internal/member.go b/x/foundation/keeper/internal/member.go index a38804e6a5..726e5dc5e7 100644 --- a/x/foundation/keeper/internal/member.go +++ b/x/foundation/keeper/internal/member.go @@ -162,7 +162,7 @@ func (k Keeper) validateAuthority(authority string) error { return nil } -func (k Keeper) validateCensorshipAuthority(ctx sdk.Context, msgTypeURL string, authority string) error { +func (k Keeper) validateCensorshipAuthority(ctx sdk.Context, msgTypeURL, authority string) error { censorship, err := k.GetCensorship(ctx, msgTypeURL) if err != nil { return err diff --git a/x/foundation/keeper/internal/migrations/v2/keys.go b/x/foundation/keeper/internal/migrations/v2/keys.go index ef1e1de520..0fa7f4b0c5 100644 --- a/x/foundation/keeper/internal/migrations/v2/keys.go +++ b/x/foundation/keeper/internal/migrations/v2/keys.go @@ -1,5 +1,3 @@ package v2 -var ( - ParamsKey = []byte{0x00} -) +var ParamsKey = []byte{0x00} diff --git a/x/foundation/keeper/internal/migrations/v2/store_test.go b/x/foundation/keeper/internal/migrations/v2/store_test.go index c55cb6d631..562d20e5e2 100644 --- a/x/foundation/keeper/internal/migrations/v2/store_test.go +++ b/x/foundation/keeper/internal/migrations/v2/store_test.go @@ -9,7 +9,6 @@ import ( "github.com/Finschia/finschia-sdk/testutil" sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/x/foundation" - "github.com/Finschia/finschia-sdk/x/foundation/keeper/internal/migrations/v2" ) diff --git a/x/foundation/keeper/internal/params.go b/x/foundation/keeper/internal/params.go index 5faad0e826..f9b1b3c211 100644 --- a/x/foundation/keeper/internal/params.go +++ b/x/foundation/keeper/internal/params.go @@ -2,7 +2,6 @@ package internal import ( sdk "github.com/Finschia/finschia-sdk/types" - "github.com/Finschia/finschia-sdk/x/foundation" ) diff --git a/x/foundation/keeper/internal/proposal.go b/x/foundation/keeper/internal/proposal.go index 2003e83f07..0495f45769 100644 --- a/x/foundation/keeper/internal/proposal.go +++ b/x/foundation/keeper/internal/proposal.go @@ -180,8 +180,6 @@ func (k Keeper) UpdateTallyOfVPEndProposals(ctx sdk.Context) { }) for _, proposal := range proposals { - proposal := proposal - if proposal.Status == foundation.PROPOSAL_STATUS_ABORTED || proposal.Status == foundation.PROPOSAL_STATUS_WITHDRAWN { k.pruneProposal(ctx, proposal) continue diff --git a/x/foundation/keeper/internal/treasury_test.go b/x/foundation/keeper/internal/treasury_test.go index eed0b332b7..e2bd7d94d8 100644 --- a/x/foundation/keeper/internal/treasury_test.go +++ b/x/foundation/keeper/internal/treasury_test.go @@ -14,7 +14,8 @@ func (s *KeeperTestSuite) TestCollectFoundationTax() { // and get it back later if the test case requires collector := authtypes.NewModuleAddress(authtypes.FeeCollectorName) fees := s.bankKeeper.GetAllBalances(ctx, collector) - s.bankKeeper.SendCoinsFromModuleToAccount(ctx, authtypes.FeeCollectorName, s.stranger, fees) + err := s.bankKeeper.SendCoinsFromModuleToAccount(ctx, authtypes.FeeCollectorName, s.stranger, fees) + s.Require().NoError(err) for name, tc := range map[string]struct { fee sdk.Int @@ -45,7 +46,8 @@ func (s *KeeperTestSuite) TestCollectFoundationTax() { ctx, _ := ctx.CacheContext() // set fee - s.bankKeeper.SendCoinsFromAccountToModule(ctx, s.stranger, authtypes.FeeCollectorName, sdk.NewCoins(sdk.NewCoin(fees[0].Denom, tc.fee))) + err := s.bankKeeper.SendCoinsFromAccountToModule(ctx, s.stranger, authtypes.FeeCollectorName, sdk.NewCoins(sdk.NewCoin(fees[0].Denom, tc.fee))) + s.Require().NoError(err) // set tax ratio s.impl.SetParams(ctx, foundation.Params{ @@ -60,7 +62,7 @@ func (s *KeeperTestSuite) TestCollectFoundationTax() { // ensure the behavior does not change s.Require().Equal(tc.tax, tax) - err := s.impl.CollectFoundationTax(ctx) + err = s.impl.CollectFoundationTax(ctx) if !tc.valid { s.Require().Error(err) return diff --git a/x/foundation/module/module.go b/x/foundation/module/module.go index 9164699777..c23388d2e2 100644 --- a/x/foundation/module/module.go +++ b/x/foundation/module/module.go @@ -79,7 +79,7 @@ func (b AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry foundation.RegisterInterfaces(registry) } -//____________________________________________________________________________ +// ____________________________________________________________________________ // AppModule implements an application module for the foundation module. type AppModule struct { @@ -154,7 +154,7 @@ func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.Val return []abci.ValidatorUpdate{} } -//____________________________________________________________________________ +// ____________________________________________________________________________ // AppModuleSimulation functions diff --git a/x/foundation/msgs_test.go b/x/foundation/msgs_test.go index f4298c53fb..4480243dfc 100644 --- a/x/foundation/msgs_test.go +++ b/x/foundation/msgs_test.go @@ -2,7 +2,6 @@ package foundation_test import ( "fmt" - sdkerrors "github.com/Finschia/finschia-sdk/types/errors" "testing" "time" @@ -11,6 +10,7 @@ import ( "github.com/Finschia/finschia-sdk/crypto/keys/secp256k1" "github.com/Finschia/finschia-sdk/testutil/testdata" sdk "github.com/Finschia/finschia-sdk/types" + sdkerrors "github.com/Finschia/finschia-sdk/types/errors" "github.com/Finschia/finschia-sdk/x/auth/legacy/legacytx" "github.com/Finschia/finschia-sdk/x/foundation" ) @@ -597,7 +597,8 @@ func TestMsgGrant(t *testing.T) { Grantee: tc.grantee.String(), } if tc.authorization != nil { - msg.SetAuthorization(tc.authorization) + err := msg.SetAuthorization(tc.authorization) + require.NoError(t, err) } err := msg.ValidateBasic() @@ -712,8 +713,6 @@ func TestAminoJSON(t *testing.T) { } for name, tc := range testCases { - tc := tc - t.Run(name, func(t *testing.T) { require.Equal(t, tc.expected, string(legacytx.StdSignBytes("foo", 1, 1, 1, legacytx.StdFee{}, []sdk.Msg{tc.msg}, "memo"))) }) @@ -726,7 +725,7 @@ func TestMsgSubmitProposalAminoJSON(t *testing.T) { addrs[i] = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) } - var proposer = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) + proposer := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) testCases := map[string]struct { msg sdk.Msg @@ -777,8 +776,6 @@ func TestMsgSubmitProposalAminoJSON(t *testing.T) { } for name, tc := range testCases { - tc := tc - t.Run(name, func(t *testing.T) { proposalMsg := &foundation.MsgSubmitProposal{ Proposers: []string{proposer.String()}, @@ -823,8 +820,6 @@ func TestMsgUpdateDecisionPolicyAminoJson(t *testing.T) { } for name, tc := range testCases { - tc := tc - t.Run(name, func(t *testing.T) { policyMsg := &foundation.MsgUpdateDecisionPolicy{ Authority: authority.String(), @@ -866,8 +861,6 @@ func TestMsgGrantAminoJson(t *testing.T) { } for name, tc := range testCases { - tc := tc - t.Run(name, func(t *testing.T) { grantMsg := &foundation.MsgGrant{ Authority: operator.String(), diff --git a/x/fswap/client/testutil/grpc.go b/x/fswap/client/testutil/grpc.go index 74e81b200a..1443f03401 100644 --- a/x/fswap/client/testutil/grpc.go +++ b/x/fswap/client/testutil/grpc.go @@ -52,7 +52,6 @@ func (s *IntegrationTestSuite) TestGRPCQuerySwap() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -91,7 +90,6 @@ func (s *IntegrationTestSuite) TestGRPCQuerySwaps() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -148,7 +146,6 @@ func (s *IntegrationTestSuite) TestGRPCQuerySwapped() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequestWithHeaders(tc.url, map[string]string{ grpctypes.GRPCBlockHeightHeader: "1", @@ -206,7 +203,6 @@ func (s *IntegrationTestSuite) TestGRPCQueryTotalSwappableAmount() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequestWithHeaders(tc.url, map[string]string{ grpctypes.GRPCBlockHeightHeader: "1", diff --git a/x/fswap/client/testutil/query.go b/x/fswap/client/testutil/query.go index 4e4004f8b5..ff124613f4 100644 --- a/x/fswap/client/testutil/query.go +++ b/x/fswap/client/testutil/query.go @@ -55,8 +55,6 @@ func (s *IntegrationTestSuite) TestCmdQuerySwapped() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.CmdQuerySwapped() out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -117,8 +115,6 @@ func (s *IntegrationTestSuite) TestCmdQueryTotalSwappableAmount() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.CmdQueryTotalSwappableAmount() out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -179,8 +175,6 @@ func (s *IntegrationTestSuite) TestCmdQuerySwap() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.CmdQuerySwap() out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) @@ -227,8 +221,6 @@ func (s *IntegrationTestSuite) TestCmdQuerySwaps() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.CmdQuerySwaps() out, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) diff --git a/x/fswap/client/testutil/tx.go b/x/fswap/client/testutil/tx.go index 31fd363446..73628fa037 100644 --- a/x/fswap/client/testutil/tx.go +++ b/x/fswap/client/testutil/tx.go @@ -74,8 +74,6 @@ func (s *IntegrationTestSuite) TestCmdTxMsgSwap() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.CmdTxMsgSwap() bz, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, append(tc.args, commonArgs...)) @@ -141,8 +139,6 @@ func (s *IntegrationTestSuite) TestCmdTxMsgSwapAll() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.CmdTxMsgSwapAll() bz, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, append(tc.args, commonArgs...)) @@ -279,8 +275,6 @@ func (s *IntegrationTestSuite) TestMsgSetSwap() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.CmdMsgSetSwap() bz, err := clitestutil.ExecTestCLICmd(clientCtx, cmd, append(tc.args, commonArgs...)) diff --git a/x/fswap/types/msgs_test.go b/x/fswap/types/msgs_test.go index d6091af476..c4516e1ef0 100644 --- a/x/fswap/types/msgs_test.go +++ b/x/fswap/types/msgs_test.go @@ -77,7 +77,6 @@ func TestAminoJSON(t *testing.T) { } for name, tc := range testCase { - tc := tc t.Run(name, func(t *testing.T) { tx.Msgs = []sdk.Msg{tc.msg} require.Equal(t, fswaptypes.RouterKey, tc.msg.Route()) diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 9bfca7d23d..9c7855df61 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -214,7 +214,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 := ostos.EnsureDir(writePath, 0700); err != nil { + if err := ostos.EnsureDir(writePath, 0o700); err != nil { return "", err } diff --git a/x/genutil/client/cli/init.go b/x/genutil/client/cli/init.go index 261ab10b47..979a81db0b 100644 --- a/x/genutil/client/cli/init.go +++ b/x/genutil/client/cli/init.go @@ -7,15 +7,14 @@ import ( "os" "path/filepath" - "github.com/cosmos/go-bip39" - "github.com/pkg/errors" - "github.com/spf13/cobra" - cfg "github.com/Finschia/ostracon/config" "github.com/Finschia/ostracon/libs/cli" ostos "github.com/Finschia/ostracon/libs/os" ostrand "github.com/Finschia/ostracon/libs/rand" "github.com/Finschia/ostracon/types" + "github.com/cosmos/go-bip39" + "github.com/pkg/errors" + "github.com/spf13/cobra" "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" diff --git a/x/genutil/client/cli/init_test.go b/x/genutil/client/cli/init_test.go index 61a487ed64..6bda2f2ee6 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -16,12 +16,11 @@ import ( "github.com/spf13/viper" "github.com/stretchr/testify/require" - ed255192 "github.com/Finschia/finschia-sdk/crypto/keys/ed25519" - "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/codec" "github.com/Finschia/finschia-sdk/codec/types" cryptocodec "github.com/Finschia/finschia-sdk/crypto/codec" + ed255192 "github.com/Finschia/finschia-sdk/crypto/keys/ed25519" "github.com/Finschia/finschia-sdk/server" "github.com/Finschia/finschia-sdk/server/mock" "github.com/Finschia/finschia-sdk/testutil" @@ -54,7 +53,6 @@ func TestInitCmd(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { home := t.TempDir() logger := log.NewNopLogger() @@ -153,7 +151,8 @@ func TestEmptyState(t *testing.T) { outC := make(chan string) go func() { var buf bytes.Buffer - io.Copy(&buf, r) + _, err := io.Copy(&buf, r) + require.NoError(t, err) outC <- buf.String() }() @@ -200,6 +199,7 @@ func TestStartStandAlone(t *testing.T) { func TestInitNodeValidatorFiles(t *testing.T) { home := t.TempDir() cfg, err := genutiltest.CreateDefaultTendermintConfig(home) + require.NoError(t, err) nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(cfg) require.Nil(t, err) diff --git a/x/genutil/client/testutil/helpers.go b/x/genutil/client/testutil/helpers.go index afd035a1a0..e517ebd531 100644 --- a/x/genutil/client/testutil/helpers.go +++ b/x/genutil/client/testutil/helpers.go @@ -46,7 +46,7 @@ func CreateDefaultTendermintConfig(rootDir string) (*ostcfg.Config, error) { ostcfg.EnsureRoot(rootDir) if err := conf.ValidateBasic(); err != nil { - return nil, fmt.Errorf("error in config file: %v", err) + return nil, fmt.Errorf("error in config file: %w", err) } return conf, nil diff --git a/x/genutil/client/testutil/migrate.go b/x/genutil/client/testutil/migrate.go index 62a035ca54..9c84cf12c4 100644 --- a/x/genutil/client/testutil/migrate.go +++ b/x/genutil/client/testutil/migrate.go @@ -37,7 +37,6 @@ func (s *IntegrationTestSuite) TestMigrateGenesis() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { genesisFile := testutil.WriteToNewTempFile(s.T(), tc.genesis) jsonOutput, err := clitestutil.ExecTestCLICmd(val0.ClientCtx, cli.MigrateGenesisCmd(), []string{tc.target, genesisFile.Name()}) diff --git a/x/genutil/client/testutil/suite.go b/x/genutil/client/testutil/suite.go index 051820015d..14f668b105 100644 --- a/x/genutil/client/testutil/suite.go +++ b/x/genutil/client/testutil/suite.go @@ -96,8 +96,6 @@ func (s *IntegrationTestSuite) TestGenTxCmd() { } for _, tc := range tests { - tc := tc - dir := s.T().TempDir() genTxFile := filepath.Join(dir, "myTx") tc.args = append(tc.args, fmt.Sprintf("--%s=%s", flags.FlagOutputDocument, genTxFile)) diff --git a/x/genutil/client/testutil/validate_genesis.go b/x/genutil/client/testutil/validate_genesis.go index 32181a95db..73cedc9753 100644 --- a/x/genutil/client/testutil/validate_genesis.go +++ b/x/genutil/client/testutil/validate_genesis.go @@ -87,7 +87,6 @@ func (s *IntegrationTestSuite) TestValidateGenesis() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { genesisFile := testutil.WriteToNewTempFile(s.T(), tc.genesis) _, err := clitestutil.ExecTestCLICmd(val0.ClientCtx, cli.ValidateGenesisCmd(nil), []string{genesisFile.Name()}) diff --git a/x/genutil/collect_test.go b/x/genutil/collect_test.go index 92967dd4dc..0e4566ba24 100644 --- a/x/genutil/collect_test.go +++ b/x/genutil/collect_test.go @@ -6,9 +6,8 @@ import ( "path/filepath" "testing" - "github.com/gogo/protobuf/proto" - octypes "github.com/Finschia/ostracon/types" + "github.com/gogo/protobuf/proto" "github.com/Finschia/finschia-sdk/codec" cdctypes "github.com/Finschia/finschia-sdk/codec/types" diff --git a/x/genutil/gentx_test.go b/x/genutil/gentx_test.go index c59056e9c0..c2175f313f 100644 --- a/x/genutil/gentx_test.go +++ b/x/genutil/gentx_test.go @@ -264,14 +264,14 @@ func (suite *GenTxTestSuite) TestDeliverGenTxs() { if tc.expPass { suite.Require().NotPanics(func() { - genutil.DeliverGenTxs( + _, _ = genutil.DeliverGenTxs( suite.ctx, genTxs, suite.app.StakingKeeper, suite.app.BaseApp.DeliverTx, suite.encodingConfig.TxConfig, ) }) } else { suite.Require().Panics(func() { - genutil.DeliverGenTxs( + _, _ = genutil.DeliverGenTxs( suite.ctx, genTxs, suite.app.StakingKeeper, suite.app.BaseApp.DeliverTx, suite.encodingConfig.TxConfig, ) diff --git a/x/genutil/module.go b/x/genutil/module.go index 12ab4a9981..715e6be56d 100644 --- a/x/genutil/module.go +++ b/x/genutil/module.go @@ -6,7 +6,6 @@ import ( "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" - abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/client" diff --git a/x/genutil/utils.go b/x/genutil/utils.go index 4aadb669f7..af7313e7a0 100644 --- a/x/genutil/utils.go +++ b/x/genutil/utils.go @@ -68,12 +68,12 @@ func InitializeNodeValidatorFilesFromMnemonic(config *cfg.Config, mnemonic strin nodeID = string(nodeKey.ID()) pvKeyFile := config.PrivValidatorKeyFile() - if err := ostos.EnsureDir(filepath.Dir(pvKeyFile), 0777); err != nil { + if err := ostos.EnsureDir(filepath.Dir(pvKeyFile), 0o777); err != nil { return "", nil, err } pvStateFile := config.PrivValidatorStateFile() - if err := ostos.EnsureDir(filepath.Dir(pvStateFile), 0777); err != nil { + if err := ostos.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 2a22f1f13b..2ad25289fe 100644 --- a/x/genutil/utils_test.go +++ b/x/genutil/utils_test.go @@ -49,7 +49,6 @@ func TestInitializeNodeValidatorFilesFromMnemonic(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { _, _, err := InitializeNodeValidatorFilesFromMnemonic(cfg, tt.mnemonic) diff --git a/x/gov/abci_test.go b/x/gov/abci_test.go index 6073dcb403..ad1938dce4 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -4,17 +4,16 @@ import ( "testing" "time" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/golang/protobuf/proto" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/finschia-sdk/simapp" sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/x/gov" "github.com/Finschia/finschia-sdk/x/gov/types" "github.com/Finschia/finschia-sdk/x/staking" - "github.com/golang/protobuf/proto" ) func TestTickExpiredDepositPeriod(t *testing.T) { diff --git a/x/gov/client/cli/parse_test.go b/x/gov/client/cli/parse_test.go index 7a82848783..d1069cb884 100644 --- a/x/gov/client/cli/parse_test.go +++ b/x/gov/client/cli/parse_test.go @@ -22,17 +22,17 @@ func TestParseSubmitProposalFlags(t *testing.T) { fs := NewCmdSubmitProposal().Flags() // nonexistent json - fs.Set(FlagProposal, "fileDoesNotExist") + _ = fs.Set(FlagProposal, "fileDoesNotExist") _, err := parseSubmitProposalFlags(fs) require.Error(t, err) // invalid json - fs.Set(FlagProposal, badJSON.Name()) + _ = fs.Set(FlagProposal, badJSON.Name()) _, err = parseSubmitProposalFlags(fs) require.Error(t, err) // ok json - fs.Set(FlagProposal, okJSON.Name()) + _ = fs.Set(FlagProposal, okJSON.Name()) proposal1, err := parseSubmitProposalFlags(fs) require.Nil(t, err, "unexpected error") require.Equal(t, "Test Proposal", proposal1.Title) @@ -42,18 +42,18 @@ func TestParseSubmitProposalFlags(t *testing.T) { // flags that can't be used with --proposal for _, incompatibleFlag := range ProposalFlags { - fs.Set(incompatibleFlag, "some value") + _ = fs.Set(incompatibleFlag, "some value") _, err := parseSubmitProposalFlags(fs) require.Error(t, err) - fs.Set(incompatibleFlag, "") + _ = fs.Set(incompatibleFlag, "") } // no --proposal, only flags - fs.Set(FlagProposal, "") - fs.Set(FlagTitle, proposal1.Title) - fs.Set(FlagDescription, proposal1.Description) - fs.Set(FlagProposalType, proposal1.Type) - fs.Set(FlagDeposit, proposal1.Deposit) + _ = fs.Set(FlagProposal, "") + _ = fs.Set(FlagTitle, proposal1.Title) + _ = fs.Set(FlagDescription, proposal1.Description) + _ = fs.Set(FlagProposalType, proposal1.Type) + _ = fs.Set(FlagDeposit, proposal1.Deposit) proposal2, err := parseSubmitProposalFlags(fs) require.Nil(t, err, "unexpected error") diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index 252f7a3aa4..e789aa9e2b 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -214,7 +214,7 @@ $ %s query gov vote 1 link1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk &types.QueryProposalRequest{ProposalId: proposalID}, ) if err != nil { - return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) + return fmt.Errorf("failed to fetch proposal-id %d: %w", proposalID, err) } voterAddr, err := sdk.AccAddressFromBech32(args[1]) @@ -288,7 +288,7 @@ $ %[1]s query gov votes 1 --page=2 --limit=100 &types.QueryProposalRequest{ProposalId: proposalID}, ) if err != nil { - return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) + return fmt.Errorf("failed to fetch proposal-id %d: %w", proposalID, err) } propStatus := proposalRes.GetProposal().Status @@ -369,7 +369,7 @@ $ %s query gov deposit 1 link1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk &types.QueryProposalRequest{ProposalId: proposalID}, ) if err != nil { - return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) + return fmt.Errorf("failed to fetch proposal-id %d: %w", proposalID, err) } depositorAddr, err := sdk.AccAddressFromBech32(args[1]) @@ -442,7 +442,7 @@ $ %s query gov deposits 1 &types.QueryProposalRequest{ProposalId: proposalID}, ) if err != nil { - return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) + return fmt.Errorf("failed to fetch proposal-id %d: %w", proposalID, err) } propStatus := proposalRes.GetProposal().Status @@ -520,7 +520,7 @@ $ %s query gov tally 1 &types.QueryProposalRequest{ProposalId: proposalID}, ) if err != nil { - return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) + return fmt.Errorf("failed to fetch proposal-id %d: %w", proposalID, err) } // Query store diff --git a/x/gov/client/testutil/deposits.go b/x/gov/client/testutil/deposits.go index f98229b65e..0667018377 100644 --- a/x/gov/client/testutil/deposits.go +++ b/x/gov/client/testutil/deposits.go @@ -4,9 +4,8 @@ import ( "fmt" "time" - "github.com/stretchr/testify/suite" - ostcli "github.com/Finschia/ostracon/libs/cli" + "github.com/stretchr/testify/suite" clitestutil "github.com/Finschia/finschia-sdk/testutil/cli" "github.com/Finschia/finschia-sdk/testutil/network" diff --git a/x/gov/client/testutil/grpc.go b/x/gov/client/testutil/grpc.go index e97273afdf..e421b48126 100644 --- a/x/gov/client/testutil/grpc.go +++ b/x/gov/client/testutil/grpc.go @@ -38,7 +38,6 @@ func (s *IntegrationTestSuite) TestGetProposalGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -92,7 +91,6 @@ func (s *IntegrationTestSuite) TestGetProposalsGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Require().NoError(err) @@ -159,7 +157,6 @@ func (s *IntegrationTestSuite) TestGetProposalVoteGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -203,7 +200,6 @@ func (s *IntegrationTestSuite) TestGetProposalVotesGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -252,7 +248,6 @@ func (s *IntegrationTestSuite) TestGetProposalDepositGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -291,7 +286,6 @@ func (s *IntegrationTestSuite) TestGetProposalDepositsGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -336,7 +330,6 @@ func (s *IntegrationTestSuite) TestGetTallyGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -399,7 +392,6 @@ func (s *IntegrationTestSuite) TestGetParamsGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) diff --git a/x/gov/client/testutil/suite.go b/x/gov/client/testutil/suite.go index a42c39e9ea..a1b426a716 100644 --- a/x/gov/client/testutil/suite.go +++ b/x/gov/client/testutil/suite.go @@ -4,11 +4,10 @@ import ( "fmt" "strings" + ostcli "github.com/Finschia/ostracon/libs/cli" "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" - ostcli "github.com/Finschia/ostracon/libs/cli" - "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/testutil" clitestutil "github.com/Finschia/finschia-sdk/testutil/cli" @@ -109,8 +108,6 @@ voting_params: } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryParams() clientCtx := val.ClientCtx @@ -157,8 +154,6 @@ func (s *IntegrationTestSuite) TestCmdParam() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryParam() clientCtx := val.ClientCtx @@ -199,8 +194,6 @@ func (s *IntegrationTestSuite) TestCmdProposer() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryProposer() clientCtx := val.ClientCtx @@ -254,8 +247,6 @@ func (s *IntegrationTestSuite) TestCmdTally() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryTally() clientCtx := val.ClientCtx @@ -345,8 +336,6 @@ func (s *IntegrationTestSuite) TestNewCmdSubmitProposal() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewCmdSubmitProposal() clientCtx := val.ClientCtx @@ -393,8 +382,6 @@ func (s *IntegrationTestSuite) TestCmdGetProposal() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryProposal() clientCtx := val.ClientCtx @@ -446,8 +433,6 @@ func (s *IntegrationTestSuite) TestCmdGetProposals() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryProposals() clientCtx := val.ClientCtx @@ -492,7 +477,6 @@ func (s *IntegrationTestSuite) TestCmdQueryDeposits() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryDeposits() clientCtx := val.ClientCtx @@ -548,7 +532,6 @@ func (s *IntegrationTestSuite) TestCmdQueryDeposit() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryDeposit() clientCtx := val.ClientCtx @@ -626,7 +609,6 @@ func (s *IntegrationTestSuite) TestNewCmdDeposit() { } for _, tc := range testCases { - tc := tc var resp sdk.TxResponse s.Run(tc.name, func() { @@ -677,7 +659,6 @@ func (s *IntegrationTestSuite) TestCmdQueryVotes() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryVotes() clientCtx := val.ClientCtx @@ -752,7 +733,6 @@ func (s *IntegrationTestSuite) TestCmdQueryVote() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryVote() clientCtx := val.ClientCtx @@ -817,7 +797,6 @@ func (s *IntegrationTestSuite) TestNewCmdVote() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdVote() clientCtx := val.ClientCtx @@ -901,7 +880,6 @@ func (s *IntegrationTestSuite) TestNewCmdWeightedVote() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.NewCmdWeightedVote() clientCtx := val.ClientCtx diff --git a/x/gov/client/utils/query.go b/x/gov/client/utils/query.go index f889aaa04b..4fd07ae2e2 100644 --- a/x/gov/client/utils/query.go +++ b/x/gov/client/utils/query.go @@ -33,7 +33,7 @@ func (p Proposer) String() string { // QueryDepositsByTxQuery will query for deposits via a direct txs tags query. It // will fetch and build deposits directly from the returned txs and return a -// JSON marshalled result or any error that occurred. +// JSON marshaled result or any error that occurred. // // NOTE: SearchTxs is used to facilitate the txs query which does not currently // support configurable pagination. @@ -89,7 +89,7 @@ func QueryDepositsByTxQuery(clientCtx client.Context, params types.QueryProposal // QueryVotesByTxQuery will query for votes via a direct txs tags query. It // will fetch and build votes directly from the returned txs and return a JSON -// marshalled result or any error that occurred. +// marshaled result or any error that occurred. func QueryVotesByTxQuery(clientCtx client.Context, params types.QueryProposalVotesParams) ([]byte, error) { var ( votes []types.Vote diff --git a/x/gov/client/utils/query_test.go b/x/gov/client/utils/query_test.go index b638febf48..6a96f7e593 100644 --- a/x/gov/client/utils/query_test.go +++ b/x/gov/client/utils/query_test.go @@ -5,11 +5,10 @@ import ( "regexp" "testing" - "github.com/stretchr/testify/require" - "github.com/Finschia/ostracon/rpc/client/mock" ctypes "github.com/Finschia/ostracon/rpc/core/types" octypes "github.com/Finschia/ostracon/types" + "github.com/stretchr/testify/require" "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/simapp" @@ -161,11 +160,9 @@ func TestGetPaginatedVotes(t *testing.T) { }, }, } { - tc := tc - t.Run(tc.description, func(t *testing.T) { - marshalled := make([]octypes.Tx, len(tc.msgs)) - cli := TxSearchMock{txs: marshalled, txConfig: encCfg.TxConfig} + marshaled := make([]octypes.Tx, len(tc.msgs)) + cli := TxSearchMock{txs: marshaled, txConfig: encCfg.TxConfig} clientCtx := client.Context{}. WithLegacyAmino(encCfg.Amino). WithClient(cli). @@ -178,7 +175,7 @@ func TestGetPaginatedVotes(t *testing.T) { tx, err := clientCtx.TxConfig.TxEncoder()(txBuilder.GetTx()) require.NoError(t, err) - marshalled[i] = tx + marshaled[i] = tx } params := types.NewQueryProposalVotesParams(0, tc.page, tc.limit) diff --git a/x/gov/common_test.go b/x/gov/common_test.go index 2a7887b149..dce082f151 100644 --- a/x/gov/common_test.go +++ b/x/gov/common_test.go @@ -77,6 +77,7 @@ var pubkeys = []cryptotypes.PubKey{ } func createValidators(t *testing.T, stakingHandler sdk.Handler, ctx sdk.Context, addrs []sdk.ValAddress, powerAmt []int64) { + t.Helper() require.True(t, len(addrs) <= len(pubkeys), "Not enough pubkeys specified at top of file.") for i := 0; i < len(addrs); i++ { @@ -91,6 +92,7 @@ func createValidators(t *testing.T, stakingHandler sdk.Handler, ctx sdk.Context, } func handleAndCheck(t *testing.T, h sdk.Handler, ctx sdk.Context, msg sdk.Msg) { + t.Helper() res, err := h(ctx, msg) require.NoError(t, err) require.NotNil(t, res) diff --git a/x/gov/genesis_test.go b/x/gov/genesis_test.go index ea96276e62..4d0df2a1df 100644 --- a/x/gov/genesis_test.go +++ b/x/gov/genesis_test.go @@ -4,12 +4,11 @@ import ( "encoding/json" "testing" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" "github.com/Finschia/ostracon/libs/log" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/simapp" @@ -106,7 +105,7 @@ func TestImportExportQueues(t *testing.T) { // Run the endblocker. Check to make sure that proposal1 is removed from state, and proposal2 is finished VotingPeriod. gov.EndBlocker(ctx2, app2.GovKeeper) - proposal1, ok = app2.GovKeeper.GetProposal(ctx2, proposalID1) + _, ok = app2.GovKeeper.GetProposal(ctx2, proposalID1) require.False(t, ok) proposal2, ok = app2.GovKeeper.GetProposal(ctx2, proposalID2) diff --git a/x/gov/keeper/common_test.go b/x/gov/keeper/common_test.go index 8c9630e5bc..46fecdb749 100644 --- a/x/gov/keeper/common_test.go +++ b/x/gov/keeper/common_test.go @@ -16,6 +16,7 @@ import ( var TestProposal = types.NewTextProposal("Test", "description") func createValidators(t *testing.T, ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sdk.AccAddress, []sdk.ValAddress) { + t.Helper() addrs := simapp.AddTestAddrsIncremental(app, ctx, 5, sdk.NewInt(30000000)) valAddrs := simapp.ConvertAddrsToValAddrs(addrs) pks := simapp.CreateTestPubKeys(5) @@ -39,9 +40,12 @@ func createValidators(t *testing.T, ctx sdk.Context, app *simapp.SimApp, powers app.StakingKeeper.SetValidator(ctx, val1) app.StakingKeeper.SetValidator(ctx, val2) app.StakingKeeper.SetValidator(ctx, val3) - app.StakingKeeper.SetValidatorByConsAddr(ctx, val1) - app.StakingKeeper.SetValidatorByConsAddr(ctx, val2) - app.StakingKeeper.SetValidatorByConsAddr(ctx, val3) + err = app.StakingKeeper.SetValidatorByConsAddr(ctx, val1) + require.NoError(t, err) + err = app.StakingKeeper.SetValidatorByConsAddr(ctx, val2) + require.NoError(t, err) + err = app.StakingKeeper.SetValidatorByConsAddr(ctx, val3) + require.NoError(t, err) app.StakingKeeper.SetNewValidatorByPowerIndex(ctx, val1) app.StakingKeeper.SetNewValidatorByPowerIndex(ctx, val2) app.StakingKeeper.SetNewValidatorByPowerIndex(ctx, val3) diff --git a/x/gov/keeper/deposit_test.go b/x/gov/keeper/deposit_test.go index a92a19bdb6..df26ab6fb9 100644 --- a/x/gov/keeper/deposit_test.go +++ b/x/gov/keeper/deposit_test.go @@ -31,7 +31,7 @@ func TestDeposits(t *testing.T) { require.True(t, proposal.TotalDeposit.Equal(sdk.NewCoins())) // Check no deposits at beginning - deposit, found := app.GovKeeper.GetDeposit(ctx, proposalID, TestAddrs[1]) + _, found := app.GovKeeper.GetDeposit(ctx, proposalID, TestAddrs[1]) require.False(t, found) proposal, ok := app.GovKeeper.GetProposal(ctx, proposalID) require.True(t, ok) @@ -41,7 +41,7 @@ func TestDeposits(t *testing.T) { votingStarted, err := app.GovKeeper.AddDeposit(ctx, proposalID, TestAddrs[0], fourStake) require.NoError(t, err) require.False(t, votingStarted) - deposit, found = app.GovKeeper.GetDeposit(ctx, proposalID, TestAddrs[0]) + deposit, found := app.GovKeeper.GetDeposit(ctx, proposalID, TestAddrs[0]) require.True(t, found) require.Equal(t, fourStake, deposit.Amount) require.Equal(t, TestAddrs[0].String(), deposit.Depositor) @@ -96,7 +96,7 @@ func TestDeposits(t *testing.T) { require.True(t, found) require.Equal(t, fourStake, deposit.Amount) app.GovKeeper.RefundDeposits(ctx, proposalID) - deposit, found = app.GovKeeper.GetDeposit(ctx, proposalID, TestAddrs[1]) + _, found = app.GovKeeper.GetDeposit(ctx, proposalID, TestAddrs[1]) require.False(t, found) require.Equal(t, addr0Initial, app.BankKeeper.GetAllBalances(ctx, TestAddrs[0])) require.Equal(t, addr1Initial, app.BankKeeper.GetAllBalances(ctx, TestAddrs[1])) diff --git a/x/gov/keeper/grpc_query.go b/x/gov/keeper/grpc_query.go index ff36017f45..80a86cab85 100644 --- a/x/gov/keeper/grpc_query.go +++ b/x/gov/keeper/grpc_query.go @@ -42,7 +42,7 @@ func (q Keeper) Proposals(c context.Context, req *types.QueryProposalsRequest) ( store := ctx.KVStore(q.storeKey) proposalStore := prefix.NewStore(store, types.ProposalsKeyPrefix) - pageRes, err := query.FilteredPaginate(proposalStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { + pageRes, err := query.FilteredPaginate(proposalStore, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) { var p types.Proposal if err := q.cdc.Unmarshal(value, &p); err != nil { return false, status.Error(codes.Internal, err.Error()) @@ -136,7 +136,7 @@ func (q Keeper) Votes(c context.Context, req *types.QueryVotesRequest) (*types.Q store := ctx.KVStore(q.storeKey) votesStore := prefix.NewStore(store, types.VotesKey(req.ProposalId)) - pageRes, err := query.Paginate(votesStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(votesStore, req.Pagination, func(key, value []byte) error { var vote types.Vote if err := q.cdc.Unmarshal(value, &vote); err != nil { return err @@ -225,7 +225,7 @@ func (q Keeper) Deposits(c context.Context, req *types.QueryDepositsRequest) (*t store := ctx.KVStore(q.storeKey) depositStore := prefix.NewStore(store, types.DepositsKey(req.ProposalId)) - pageRes, err := query.Paginate(depositStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(depositStore, req.Pagination, func(key, value []byte) error { var deposit types.Deposit if err := q.cdc.Unmarshal(value, &deposit); err != nil { return err diff --git a/x/gov/keeper/querier_test.go b/x/gov/keeper/querier_test.go index cac387370a..befef0d18f 100644 --- a/x/gov/keeper/querier_test.go +++ b/x/gov/keeper/querier_test.go @@ -20,6 +20,7 @@ import ( const custom = "custom" func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier) (types.DepositParams, types.VotingParams, types.TallyParams) { + t.Helper() query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryParams, types.ParamDeposit}, "/"), Data: []byte{}, @@ -63,6 +64,7 @@ func getQueriedProposals( t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, depositor, voter sdk.AccAddress, status types.ProposalStatus, page, limit int, ) []types.Proposal { + t.Helper() query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryProposals}, "/"), Data: cdc.MustMarshalJSON(types.NewQueryProposalsParams(page, limit, status, voter, depositor)), @@ -79,6 +81,7 @@ func getQueriedProposals( } func getQueriedDeposit(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, proposalID uint64, depositor sdk.AccAddress) types.Deposit { + t.Helper() query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryDeposit}, "/"), Data: cdc.MustMarshalJSON(types.NewQueryDepositParams(proposalID, depositor)), @@ -95,6 +98,7 @@ func getQueriedDeposit(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, qu } func getQueriedDeposits(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, proposalID uint64) []types.Deposit { + t.Helper() query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryDeposits}, "/"), Data: cdc.MustMarshalJSON(types.NewQueryProposalParams(proposalID)), @@ -111,6 +115,7 @@ func getQueriedDeposits(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, q } func getQueriedVote(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, proposalID uint64, voter sdk.AccAddress) types.Vote { + t.Helper() query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryVote}, "/"), Data: cdc.MustMarshalJSON(types.NewQueryVoteParams(proposalID, voter)), @@ -129,6 +134,7 @@ func getQueriedVote(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, queri func getQueriedVotes(t *testing.T, ctx sdk.Context, cdc *codec.LegacyAmino, querier sdk.Querier, proposalID uint64, page, limit int, ) []types.Vote { + t.Helper() query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryVote}, "/"), Data: cdc.MustMarshalJSON(types.NewQueryProposalVotesParams(proposalID, page, limit)), @@ -374,7 +380,6 @@ func TestPaginatedVotesQuery(t *testing.T) { page: -1, }, } { - tc := tc t.Run(tc.description, func(t *testing.T) { votes := getQueriedVotes(t, ctx, legacyQuerierCdc, querier, proposal.ProposalId, tc.page, tc.limit) require.Equal(t, len(tc.votes), len(votes)) @@ -391,6 +396,7 @@ func TestPaginatedVotesQuery(t *testing.T) { // only 1 vote, this function checks equality of structs while skipping that // field. func checkEqualVotes(t *testing.T, vote1, vote2 types.Vote) { + t.Helper() require.Equal(t, vote1.Options, vote2.Options) require.Equal(t, vote1.Voter, vote2.Voter) require.Equal(t, vote1.ProposalId, vote2.ProposalId) diff --git a/x/gov/keeper/tally.go b/x/gov/keeper/tally.go index 6e9ab81fca..1d6e5648ba 100644 --- a/x/gov/keeper/tally.go +++ b/x/gov/keeper/tally.go @@ -10,7 +10,7 @@ import ( // Tally iterates over the votes and updates the tally of a proposal based on the voting power of the // voters -func (keeper Keeper) Tally(ctx sdk.Context, proposal types.Proposal) (passes bool, burnDeposits bool, tallyResults types.TallyResult) { +func (keeper Keeper) Tally(ctx sdk.Context, proposal types.Proposal) (passes, burnDeposits bool, tallyResults types.TallyResult) { results := make(map[types.VoteOption]sdk.Dec) results[types.OptionYes] = sdk.ZeroDec() results[types.OptionAbstain] = sdk.ZeroDec() diff --git a/x/gov/keeper/vote.go b/x/gov/keeper/vote.go index bde5b3c2ce..49da37fabe 100644 --- a/x/gov/keeper/vote.go +++ b/x/gov/keeper/vote.go @@ -78,8 +78,8 @@ func (keeper Keeper) GetVote(ctx sdk.Context, proposalID uint64, voterAddr sdk.A // SetVote sets a Vote to the gov store func (keeper Keeper) SetVote(ctx sdk.Context, vote types.Vote) { // vote.Option is a deprecated field, we don't set it in state - if vote.Option != types.OptionEmpty { //nolint - vote.Option = types.OptionEmpty //nolint + if vote.Option != types.OptionEmpty { + vote.Option = types.OptionEmpty } store := ctx.KVStore(keeper.storeKey) @@ -133,6 +133,6 @@ func (keeper Keeper) deleteVote(ctx sdk.Context, proposalID uint64, voterAddr sd // there's only 1 VoteOption. func populateLegacyOption(vote *types.Vote) { if len(vote.Options) == 1 && vote.Options[0].Weight.Equal(sdk.MustNewDecFromStr("1.0")) { - vote.Option = vote.Options[0].Option //nolint + vote.Option = vote.Options[0].Option } } diff --git a/x/gov/legacy/v043/store.go b/x/gov/legacy/v043/store.go index cd0eee77eb..4a1331320f 100644 --- a/x/gov/legacy/v043/store.go +++ b/x/gov/legacy/v043/store.go @@ -40,7 +40,7 @@ func migrateVote(oldVote types.Vote) types.Vote { return types.Vote{ ProposalId: oldVote.ProposalId, Voter: oldVote.Voter, - Options: types.NewNonSplitVoteOption(oldVote.Option), //nolint:staticcheck + Options: types.NewNonSplitVoteOption(oldVote.Option), } } diff --git a/x/gov/legacy/v043/store_test.go b/x/gov/legacy/v043/store_test.go index 6f7f0c9876..a9bbe4368c 100644 --- a/x/gov/legacy/v043/store_test.go +++ b/x/gov/legacy/v043/store_test.go @@ -80,7 +80,6 @@ func TestMigrateStore(t *testing.T) { // Make sure the new keys are set and old keys are deleted. for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { if !bytes.Equal(tc.oldKey, tc.newKey) { require.Nil(t, store.Get(tc.oldKey)) diff --git a/x/gov/module.go b/x/gov/module.go index c528281bd3..8ab13f287e 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -10,7 +10,6 @@ import ( "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" - abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/client" diff --git a/x/gov/simulation/decoder_test.go b/x/gov/simulation/decoder_test.go index 049e0f4a6f..2629b5409b 100644 --- a/x/gov/simulation/decoder_test.go +++ b/x/gov/simulation/decoder_test.go @@ -81,7 +81,6 @@ func TestDecodeStore(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { if tt.wantPanic { require.Panics(t, func() { dec(tt.kvA, tt.kvB) }, tt.name) diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index e2ffb9724b..bde953d6f2 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -18,12 +18,11 @@ import ( var initialProposalID = uint64(100000000000000) -// nolint:gosec // Simulation operation weights constants const ( - OpWeightMsgDeposit = "op_weight_msg_deposit" //nolint:gosec - OpWeightMsgVote = "op_weight_msg_vote" //nolint:gosec - OpWeightMsgVoteWeighted = "op_weight_msg_weighted_vote" //nolint:gosec + OpWeightMsgDeposit = "op_weight_msg_deposit" + OpWeightMsgVote = "op_weight_msg_vote" + OpWeightMsgVoteWeighted = "op_weight_msg_weighted_vote" ) // WeightedOperations returns all the operations from the module with their respective weights @@ -59,7 +58,6 @@ func WeightedOperations( var wProposalOps simulation.WeightedOperations for _, wContent := range wContents { - wContent := wContent // pin variable var weight int appParams.GetOrGenerate(cdc, wContent.AppParamsKey(), &weight, nil, func(_ *rand.Rand) { weight = wContent.DefaultWeight() }) diff --git a/x/gov/simulation/operations_test.go b/x/gov/simulation/operations_test.go index ba492587f7..ec4596d2db 100644 --- a/x/gov/simulation/operations_test.go +++ b/x/gov/simulation/operations_test.go @@ -265,6 +265,7 @@ func createTestApp(isCheckTx bool) (*simapp.SimApp, sdk.Context) { } func getTestingAccounts(t *testing.T, r *rand.Rand, app *simapp.SimApp, ctx sdk.Context, n int) []simtypes.Account { + t.Helper() accounts := simtypes.RandomAccounts(r, n) initAmt := app.StakingKeeper.TokensFromConsensusPower(ctx, 200) diff --git a/x/gov/types/proposal.go b/x/gov/types/proposal.go index 56dd2ecb56..2fe7840537 100644 --- a/x/gov/types/proposal.go +++ b/x/gov/types/proposal.go @@ -6,7 +6,7 @@ import ( "time" "github.com/gogo/protobuf/proto" - yaml "gopkg.in/yaml.v2" + "gopkg.in/yaml.v2" "github.com/Finschia/finschia-sdk/codec/types" sdk "github.com/Finschia/finschia-sdk/types" @@ -167,14 +167,19 @@ func (status *ProposalStatus) Unmarshal(data []byte) error { } // Format implements the fmt.Formatter interface. -// nolint: errcheck func (status ProposalStatus) Format(s fmt.State, verb rune) { + var err error + switch verb { case 's': - s.Write([]byte(status.String())) + _, err = s.Write([]byte(status.String())) default: // TODO: Do this conversion more directly - s.Write([]byte(fmt.Sprintf("%v", byte(status)))) + _, err = s.Write([]byte(fmt.Sprintf("%v", byte(status)))) + } + + if err != nil { + panic(err) } } diff --git a/x/gov/types/vote.go b/x/gov/types/vote.go index ba2c6e6972..e722bced7b 100644 --- a/x/gov/types/vote.go +++ b/x/gov/types/vote.go @@ -62,7 +62,10 @@ func NewNonSplitVoteOption(option VoteOption) WeightedVoteOptions { } func (v WeightedVoteOption) String() string { - out, _ := json.Marshal(v) + out, err := json.Marshal(v) + if err != nil { + panic(err) + } return string(out) } @@ -141,10 +144,16 @@ func (vo *VoteOption) Unmarshal(data []byte) error { // Format implements the fmt.Formatter interface. func (vo VoteOption) Format(s fmt.State, verb rune) { + var err error + switch verb { case 's': - s.Write([]byte(vo.String())) + _, err = s.Write([]byte(vo.String())) default: - s.Write([]byte(fmt.Sprintf("%v", byte(vo)))) + _, err = s.Write([]byte(fmt.Sprintf("%v", byte(vo)))) + } + + if err != nil { + panic(err) } } diff --git a/x/mint/client/testutil/grpc.go b/x/mint/client/testutil/grpc.go index eaf8188d9b..52ead8c536 100644 --- a/x/mint/client/testutil/grpc.go +++ b/x/mint/client/testutil/grpc.go @@ -3,12 +3,11 @@ package testutil import ( "fmt" + "github.com/gogo/protobuf/proto" + "github.com/Finschia/finschia-sdk/testutil" sdk "github.com/Finschia/finschia-sdk/types" grpctypes "github.com/Finschia/finschia-sdk/types/grpc" - - "github.com/gogo/protobuf/proto" - minttypes "github.com/Finschia/finschia-sdk/x/mint/types" ) @@ -54,7 +53,6 @@ func (s *IntegrationTestSuite) TestQueryGRPC() { }, } for _, tc := range testCases { - tc := tc resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Run(tc.name, func() { s.Require().NoError(err) diff --git a/x/mint/client/testutil/suite.go b/x/mint/client/testutil/suite.go index fd3d0f86fc..f123c9f12a 100644 --- a/x/mint/client/testutil/suite.go +++ b/x/mint/client/testutil/suite.go @@ -4,9 +4,8 @@ import ( "fmt" "strings" - "github.com/stretchr/testify/suite" - ostcli "github.com/Finschia/ostracon/libs/cli" + "github.com/stretchr/testify/suite" "github.com/Finschia/finschia-sdk/client/flags" clitestutil "github.com/Finschia/finschia-sdk/testutil/cli" @@ -82,8 +81,6 @@ mint_denom: stake`, } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryParams() clientCtx := val.ClientCtx @@ -116,8 +113,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryInflation() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryInflation() clientCtx := val.ClientCtx @@ -150,8 +145,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryAnnualProvisions() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryAnnualProvisions() clientCtx := val.ClientCtx diff --git a/x/mint/keeper/querier_test.go b/x/mint/keeper/querier_test.go index 8d36860426..d2d440aaa5 100644 --- a/x/mint/keeper/querier_test.go +++ b/x/mint/keeper/querier_test.go @@ -3,15 +3,13 @@ package keeper_test import ( "testing" - "github.com/Finschia/finschia-sdk/codec" - "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" + "github.com/Finschia/finschia-sdk/codec" sdk "github.com/Finschia/finschia-sdk/types" keep "github.com/Finschia/finschia-sdk/x/mint/keeper" "github.com/Finschia/finschia-sdk/x/mint/types" - - abci "github.com/tendermint/tendermint/abci/types" ) func TestNewQuerier(t *testing.T) { diff --git a/x/mint/simulation/decoder_test.go b/x/mint/simulation/decoder_test.go index 8fb33000db..790313a374 100644 --- a/x/mint/simulation/decoder_test.go +++ b/x/mint/simulation/decoder_test.go @@ -34,7 +34,6 @@ func TestDecodeStore(t *testing.T) { } for i, tt := range tests { - i, tt := i, tt t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: diff --git a/x/mint/simulation/params.go b/x/mint/simulation/params.go index 4769e15133..8912652069 100644 --- a/x/mint/simulation/params.go +++ b/x/mint/simulation/params.go @@ -6,10 +6,9 @@ import ( "fmt" "math/rand" - "github.com/Finschia/finschia-sdk/x/simulation" - simtypes "github.com/Finschia/finschia-sdk/types/simulation" "github.com/Finschia/finschia-sdk/x/mint/types" + "github.com/Finschia/finschia-sdk/x/simulation" ) const ( diff --git a/x/params/client/testutil/grpc.go b/x/params/client/testutil/grpc.go index 64cde94976..9f00b3921c 100644 --- a/x/params/client/testutil/grpc.go +++ b/x/params/client/testutil/grpc.go @@ -80,7 +80,6 @@ func (s *IntegrationTestSuite) TestQueryParamsGRPC() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Require().NoError(err) diff --git a/x/params/client/testutil/suite.go b/x/params/client/testutil/suite.go index 3d885d52d4..f891472971 100644 --- a/x/params/client/testutil/suite.go +++ b/x/params/client/testutil/suite.go @@ -66,8 +66,6 @@ value: "100"`, } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewQuerySubspaceParamsCmd() clientCtx := val.ClientCtx diff --git a/x/params/keeper/keeper_test.go b/x/params/keeper/keeper_test.go index cc9c6df606..6285d5fb1a 100644 --- a/x/params/keeper/keeper_test.go +++ b/x/params/keeper/keeper_test.go @@ -83,13 +83,11 @@ func TestKeeper(t *testing.T) { // Set params for i, kv := range kvs { - kv := kv require.NotPanics(t, func() { space.Set(ctx, []byte(kv.key), kv.param) }, "space.Set panics, tc #%d", i) } // Test space.Get for i, kv := range kvs { - i, kv := i, kv var param int64 require.NotPanics(t, func() { space.Get(ctx, []byte(kv.key), ¶m) }, "space.Get panics, tc #%d", i) require.Equal(t, kv.param, param, "stored param not equal, tc #%d", i) @@ -116,20 +114,17 @@ func TestKeeper(t *testing.T) { // Test invalid space.Get for i, kv := range kvs { - kv := kv var param bool require.Panics(t, func() { space.Get(ctx, []byte(kv.key), ¶m) }, "invalid space.Get not panics, tc #%d", i) } // Test invalid space.Set for i, kv := range kvs { - kv := kv require.Panics(t, func() { space.Set(ctx, []byte(kv.key), true) }, "invalid space.Set not panics, tc #%d", i) } // Test GetSubspace for i, kv := range kvs { - i, kv := i, kv var gparam, param int64 gspace, ok := keeper.GetSubspace("test") require.True(t, ok, "cannot retrieve subspace, tc #%d", i) @@ -165,9 +160,9 @@ func TestSubspace(t *testing.T) { {"uint16", uint16(1), uint16(0), new(uint16)}, {"uint32", uint32(1), uint32(0), new(uint32)}, {"uint64", uint64(1), uint64(0), new(uint64)}, - {"int", sdk.NewInt(1), *new(sdk.Int), new(sdk.Int)}, - {"uint", sdk.NewUint(1), *new(sdk.Uint), new(sdk.Uint)}, - {"dec", sdk.NewDec(1), *new(sdk.Dec), new(sdk.Dec)}, + {"int", sdk.NewInt(1), sdk.Int{}, new(sdk.Int)}, + {"uint", sdk.NewUint(1), sdk.Uint{}, new(sdk.Uint)}, + {"dec", sdk.NewDec(1), sdk.Dec{}, new(sdk.Dec)}, {"struct", s{1}, s{0}, new(s)}, } @@ -191,13 +186,11 @@ func TestSubspace(t *testing.T) { // Test space.Set for i, kv := range kvs { - i, kv := i, kv require.NotPanics(t, func() { space.Set(ctx, []byte(kv.key), kv.param) }, "space.Set panics, tc #%d", i) } // Test space.Get, space.GetIfExists for i, kv := range kvs { - i, kv := i, kv require.NotPanics(t, func() { space.GetIfExists(ctx, []byte("invalid"), kv.ptr) }, "space.GetIfExists panics when no value exists, tc #%d", i) require.Equal(t, kv.zero, indirect(kv.ptr), "space.GetIfExists unmarshalls when no value exists, tc #%d", i) require.Panics(t, func() { space.Get(ctx, []byte("invalid"), kv.ptr) }, "invalid space.Get not panics when no value exists, tc #%d", i) diff --git a/x/params/module.go b/x/params/module.go index 4bb919abdc..7fe2ef5ad9 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -6,7 +6,6 @@ import ( "math/rand" "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" diff --git a/x/params/proposal_handler_test.go b/x/params/proposal_handler_test.go index 81f42547e2..9162fea2f3 100644 --- a/x/params/proposal_handler_test.go +++ b/x/params/proposal_handler_test.go @@ -77,7 +77,6 @@ func (suite *HandlerTestSuite) TestProposalHandler() { } for _, tc := range testCases { - tc := tc suite.Run(tc.name, func() { err := suite.govHandler(suite.ctx, tc.proposal) if tc.expErr { diff --git a/x/params/simulation/operations.go b/x/params/simulation/operations.go index 74e3e2c1b3..5df58b64dc 100644 --- a/x/params/simulation/operations.go +++ b/x/params/simulation/operations.go @@ -9,7 +9,7 @@ import ( "github.com/Finschia/finschia-sdk/x/params/types/proposal" ) -func min(a int, b int) int { +func min(a, b int) int { if a <= b { return a } diff --git a/x/params/types/subspace.go b/x/params/types/subspace.go index 4eaa3b69bc..3e974ad3e2 100644 --- a/x/params/types/subspace.go +++ b/x/params/types/subspace.go @@ -28,7 +28,7 @@ type Subspace struct { } // NewSubspace constructs a store with namestore -func NewSubspace(cdc codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key storetypes.StoreKey, tkey storetypes.StoreKey, name string) Subspace { +func NewSubspace(cdc codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey storetypes.StoreKey, name string) Subspace { return Subspace{ cdc: cdc, legacyAmino: legacyAmino, @@ -82,7 +82,7 @@ func (s Subspace) Validate(ctx sdk.Context, key []byte, value interface{}) error } if err := attr.vfn(value); err != nil { - return fmt.Errorf("invalid parameter value: %s", err) + return fmt.Errorf("invalid parameter value: %w", err) } return nil diff --git a/x/params/types/subspace_test.go b/x/params/types/subspace_test.go index eebb9818dd..7806fd1473 100644 --- a/x/params/types/subspace_test.go +++ b/x/params/types/subspace_test.go @@ -5,12 +5,11 @@ import ( "testing" "time" + "github.com/Finschia/ostracon/libs/log" "github.com/stretchr/testify/suite" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/codec" "github.com/Finschia/finschia-sdk/simapp" "github.com/Finschia/finschia-sdk/store" @@ -50,7 +49,7 @@ func (suite *SubspaceTestSuite) TestKeyTable() { }) suite.Require().NotPanics(func() { ss := types.NewSubspace(suite.cdc, suite.amino, key, tkey, "testsubspace2") - ss = ss.WithKeyTable(paramKeyTable()) + _ = ss.WithKeyTable(paramKeyTable()) }) } @@ -185,7 +184,6 @@ func (suite *SubspaceTestSuite) TestSetParamSet() { } for _, tc := range testCases { - tc := tc suite.Run(tc.name, func() { suite.Require().Panics(func() { suite.ss.SetParamSet(suite.ctx, tc.ps) diff --git a/x/simulation/mock_ostracon.go b/x/simulation/mock_ostracon.go index 0fea9e6243..5b45e85e09 100644 --- a/x/simulation/mock_ostracon.go +++ b/x/simulation/mock_ostracon.go @@ -7,12 +7,11 @@ import ( "testing" "time" - abci "github.com/tendermint/tendermint/abci/types" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" cryptoenc "github.com/Finschia/ostracon/crypto/encoding" ostbytes "github.com/Finschia/ostracon/libs/bytes" + abci "github.com/tendermint/tendermint/abci/types" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" ) type mockValidator struct { @@ -88,6 +87,7 @@ func updateValidators( updates []abci.ValidatorUpdate, event func(route, op, evResult string), ) map[string]mockValidator { + tb.Helper() for _, update := range updates { str := fmt.Sprintf("%X", update.PubKey.GetEd25519()) diff --git a/x/simulation/operation.go b/x/simulation/operation.go index 04261a153b..433518f3dd 100644 --- a/x/simulation/operation.go +++ b/x/simulation/operation.go @@ -73,13 +73,12 @@ func NewOperationQueue() OperationQueue { } // queueOperations adds all future operations into the operation queue. -func queueOperations(queuedOps OperationQueue, queuedTimeOps []simulation.FutureOperation, futureOps []simulation.FutureOperation) { +func queueOperations(queuedOps OperationQueue, queuedTimeOps, futureOps []simulation.FutureOperation) { if futureOps == nil { return } for _, futureOp := range futureOps { - futureOp := futureOp if futureOp.BlockHeight != 0 { if val, ok := queuedOps[futureOp.BlockHeight]; ok { queuedOps[futureOp.BlockHeight] = append(val, futureOp.Op) diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index 9d15e99ff8..3477cad42b 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -59,6 +59,7 @@ func SimulateFromSeed( config simulation.Config, cdc codec.JSONCodec, ) (stopEarly bool, exportedParams Params, err error) { + tb.Helper() // in case we have to end early, don't os.Exit so that we can run cleanup code. testingMode, _, b := getTestingMode(tb) @@ -131,8 +132,8 @@ func SimulateFromSeed( logWriter := NewLogWriter(testingMode) - blockSimulator := createBlockSimulator( - testingMode, tb, w, params, eventStats.Tally, + blockSimulator := createBlockSimulator(tb, + testingMode, w, params, eventStats.Tally, ops, operationQueue, timeOperationQueue, logWriter, config) if !testingMode { @@ -167,14 +168,14 @@ func SimulateFromSeed( ctx := app.NewContext(false, header) // Run queued operations. Ignores blocksize if blocksize is too small - numQueuedOpsRan := runQueuedOperations( - operationQueue, int(header.Height), tb, r, app, ctx, accs, logWriter, + numQueuedOpsRan := runQueuedOperations(tb, + operationQueue, int(header.Height), r, app, ctx, accs, logWriter, eventStats.Tally, config.Lean, config.ChainID, ) - numQueuedTimeOpsRan := runQueuedTimeOperations( + numQueuedTimeOpsRan := runQueuedTimeOperations(tb, timeOperationQueue, int(header.Height), header.Time, - tb, r, app, ctx, accs, logWriter, eventStats.Tally, + r, app, ctx, accs, logWriter, eventStats.Tally, config.Lean, config.ChainID, ) @@ -249,11 +250,12 @@ type blockSimFn func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, // Returns a function to simulate blocks. Written like this to avoid constant // parameters being passed everytime, to minimize memory overhead. -func createBlockSimulator(testingMode bool, tb testing.TB, w io.Writer, params Params, +func createBlockSimulator(tb testing.TB, testingMode bool, w io.Writer, params Params, event func(route, op, evResult string), ops WeightedOperations, operationQueue OperationQueue, timeOperationQueue []simulation.FutureOperation, logWriter LogWriter, config simulation.Config, ) blockSimFn { + tb.Helper() lastBlockSizeState := 0 // state for [4 * uniform distribution] blocksize := 0 selectOp := ops.getSelectOpFn() @@ -316,12 +318,12 @@ Comment: %s`, } } -// nolint: errcheck -func runQueuedOperations(queueOps map[int][]simulation.Operation, - height int, tb testing.TB, r *rand.Rand, app *baseapp.BaseApp, +func runQueuedOperations(tb testing.TB, queueOps map[int][]simulation.Operation, + height int, 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) { + tb.Helper() queuedOp, ok := queueOps[height] if !ok { return 0 @@ -350,12 +352,13 @@ func runQueuedOperations(queueOps map[int][]simulation.Operation, return numOpsRan } -func runQueuedTimeOperations(queueOps []simulation.FutureOperation, - height int, currentTime time.Time, tb testing.TB, r *rand.Rand, +func runQueuedTimeOperations(tb testing.TB, queueOps []simulation.FutureOperation, + height int, currentTime time.Time, 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) { + tb.Helper() numOpsRan = 0 for len(queueOps) > 0 && currentTime.After(queueOps[0].BlockTime) { diff --git a/x/simulation/util.go b/x/simulation/util.go index c004aac2a0..91e9d3fad5 100644 --- a/x/simulation/util.go +++ b/x/simulation/util.go @@ -15,6 +15,7 @@ import ( ) func getTestingMode(tb testing.TB) (testingMode bool, t *testing.T, b *testing.B) { + tb.Helper() testingMode = false if _t, ok := tb.(*testing.T); ok { diff --git a/x/slashing/abci_test.go b/x/slashing/abci_test.go index 990bf0e2c8..4eca5c228f 100644 --- a/x/slashing/abci_test.go +++ b/x/slashing/abci_test.go @@ -4,12 +4,11 @@ import ( "testing" "time" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/finschia-sdk/simapp" sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/x/slashing" diff --git a/x/slashing/app_test.go b/x/slashing/app_test.go index 14c6aab848..8b7afe6600 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -4,11 +4,10 @@ import ( "errors" "testing" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/finschia-sdk/crypto/keys/ed25519" "github.com/Finschia/finschia-sdk/crypto/keys/secp256k1" "github.com/Finschia/finschia-sdk/simapp" @@ -28,6 +27,7 @@ var ( ) func checkValidator(t *testing.T, app *simapp.SimApp, _ sdk.AccAddress, expFound bool) stakingtypes.Validator { + t.Helper() ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{}) validator, found := app.StakingKeeper.GetValidator(ctxCheck, sdk.ValAddress(addr1)) require.Equal(t, expFound, found) @@ -35,6 +35,7 @@ func checkValidator(t *testing.T, app *simapp.SimApp, _ sdk.AccAddress, expFound } func checkValidatorSigningInfo(t *testing.T, app *simapp.SimApp, addr sdk.ConsAddress, expFound bool) types.ValidatorSigningInfo { + t.Helper() ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{}) signingInfo, found := app.SlashingKeeper.GetValidatorSigningInfo(ctxCheck, addr) require.Equal(t, expFound, found) diff --git a/x/slashing/client/testutil/grpc.go b/x/slashing/client/testutil/grpc.go index a56583e355..245b4023b8 100644 --- a/x/slashing/client/testutil/grpc.go +++ b/x/slashing/client/testutil/grpc.go @@ -83,8 +83,6 @@ func (s *IntegrationTestSuite) TestGRPCQueries() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Require().NoError(err) diff --git a/x/slashing/client/testutil/suite.go b/x/slashing/client/testutil/suite.go index c2ccdf929e..549ce52c94 100644 --- a/x/slashing/client/testutil/suite.go +++ b/x/slashing/client/testutil/suite.go @@ -85,8 +85,6 @@ tombstoned: false`, sdk.ConsAddress(val.PubKey.Address())), } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQuerySigningInfo() clientCtx := val.ClientCtx @@ -127,8 +125,6 @@ slash_fraction_downtime: "0.010000000000000000"`, } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryParams() clientCtx := val.ClientCtx @@ -162,8 +158,6 @@ func (s *IntegrationTestSuite) TestNewUnjailTxCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewUnjailTxCmd() clientCtx := val.ClientCtx diff --git a/x/slashing/genesis_test.go b/x/slashing/genesis_test.go index 7a83331fd4..d6d760a52a 100644 --- a/x/slashing/genesis_test.go +++ b/x/slashing/genesis_test.go @@ -42,15 +42,17 @@ func TestExportAndInitGenesis(t *testing.T) { require.True(t, ok) newInfo1, ok := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0])) + require.True(t, ok) require.NotEqual(t, info1, newInfo1) - // Initialise genesis with genesis state before tombstone + // Initialize genesis with genesis state before tombstone slashing.InitGenesis(ctx, app.SlashingKeeper, app.StakingKeeper, genesisState) - // Validator isTombstoned should return false as GenesisState is initialised + // Validator isTombstoned should return false as GenesisState is initialized ok = app.SlashingKeeper.IsTombstoned(ctx, sdk.ConsAddress(addrDels[0])) require.False(t, ok) newInfo1, ok = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0])) + require.True(t, ok) newInfo2, ok := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[1])) require.True(t, ok) require.Equal(t, info1, newInfo1) diff --git a/x/slashing/keeper/grpc_query.go b/x/slashing/keeper/grpc_query.go index 89ba6ad1c3..2f606932fa 100644 --- a/x/slashing/keeper/grpc_query.go +++ b/x/slashing/keeper/grpc_query.go @@ -58,7 +58,7 @@ func (k Keeper) SigningInfos(c context.Context, req *types.QuerySigningInfosRequ var signInfos []types.ValidatorSigningInfo sigInfoStore := prefix.NewStore(store, types.ValidatorSigningInfoKeyPrefix) - pageRes, err := query.Paginate(sigInfoStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(sigInfoStore, req.Pagination, func(key, value []byte) error { var info types.ValidatorSigningInfo err := k.cdc.Unmarshal(value, &info) if err != nil { diff --git a/x/slashing/keeper/hooks.go b/x/slashing/keeper/hooks.go index bf55719854..69fb7e8a78 100644 --- a/x/slashing/keeper/hooks.go +++ b/x/slashing/keeper/hooks.go @@ -68,7 +68,10 @@ func (h Hooks) AfterValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, // Implements sdk.ValidatorHooks func (h Hooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) { - h.k.AfterValidatorCreated(ctx, valAddr) + err := h.k.AfterValidatorCreated(ctx, valAddr) + if err != nil { + panic(err) + } } func (h Hooks) AfterValidatorBeginUnbonding(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) {} diff --git a/x/slashing/keeper/keeper_test.go b/x/slashing/keeper/keeper_test.go index fb77ee205e..e76e75687a 100644 --- a/x/slashing/keeper/keeper_test.go +++ b/x/slashing/keeper/keeper_test.go @@ -250,7 +250,6 @@ func TestValidatorDippingInAndOut(t *testing.T) { // another block happened ctx = ctx.WithBlockHeight(height) app.SlashingKeeper.HandleValidatorSignature(ctx, val.Address(), newPower, true) - height++ // should now be jailed & kicked staking.EndBlocker(ctx, app.StakingKeeper) @@ -299,7 +298,6 @@ func TestValidatorDippingInAndOut(t *testing.T) { // validator misses another block ctx = ctx.WithBlockHeight(height) app.SlashingKeeper.HandleValidatorSignature(ctx, val.Address(), newPower, false) - height++ // validator should now be jailed & kicked staking.EndBlocker(ctx, app.StakingKeeper) diff --git a/x/slashing/keeper/signing_info_test.go b/x/slashing/keeper/signing_info_test.go index fba161dc64..c8dd3a2c46 100644 --- a/x/slashing/keeper/signing_info_test.go +++ b/x/slashing/keeper/signing_info_test.go @@ -17,7 +17,7 @@ func TestGetSetValidatorSigningInfo(t *testing.T) { ctx := app.BaseApp.NewContext(false, tmproto.Header{}) addrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, app.StakingKeeper.TokensFromConsensusPower(ctx, 200)) - info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0])) + _, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0])) require.False(t, found) newInfo := types.NewValidatorSigningInfo( sdk.ConsAddress(addrDels[0]), @@ -28,7 +28,7 @@ func TestGetSetValidatorSigningInfo(t *testing.T) { int64(10), ) app.SlashingKeeper.SetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0]), newInfo) - info, found = app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0])) + info, found := app.SlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(addrDels[0])) require.True(t, found) require.Equal(t, info.StartHeight, int64(4)) require.Equal(t, info.IndexOffset, int64(3)) diff --git a/x/slashing/legacy/v043/store_test.go b/x/slashing/legacy/v043/store_test.go index 69df9372c1..318bc16bd5 100644 --- a/x/slashing/legacy/v043/store_test.go +++ b/x/slashing/legacy/v043/store_test.go @@ -57,7 +57,6 @@ func TestStoreMigration(t *testing.T) { // Make sure the new keys are set and old keys are deleted. for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { if !bytes.Equal(tc.oldKey, tc.newKey) { require.Nil(t, store.Get(tc.oldKey)) diff --git a/x/slashing/module.go b/x/slashing/module.go index 3e336c2f0d..771e7b1874 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -6,11 +6,9 @@ import ( "fmt" "math/rand" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - ocabci "github.com/Finschia/ostracon/abci/types" abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/client" diff --git a/x/slashing/simulation/decoder_test.go b/x/slashing/simulation/decoder_test.go index 9d5794a590..892fda56d8 100644 --- a/x/slashing/simulation/decoder_test.go +++ b/x/slashing/simulation/decoder_test.go @@ -53,7 +53,6 @@ func TestDecodeStore(t *testing.T) { {"other", "", true}, } for i, tt := range tests { - i, tt := i, tt t.Run(tt.name, func(t *testing.T) { if tt.panics { require.Panics(t, func() { dec(kvPairs.Pairs[i], kvPairs.Pairs[i]) }, tt.name) diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 28abc07ec2..0740cad518 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -16,10 +16,9 @@ import ( stakingkeeper "github.com/Finschia/finschia-sdk/x/staking/keeper" ) -// nolint: gosec // Simulation operation weights constants const ( - OpWeightMsgUnjail = "op_weight_msg_unjail" //nolint:gosec + OpWeightMsgUnjail = "op_weight_msg_unjail" ) // WeightedOperations returns all the operations from the module with their respective weights diff --git a/x/slashing/simulation/operations_test.go b/x/slashing/simulation/operations_test.go index 066f8c9e5e..f60c656cc6 100644 --- a/x/slashing/simulation/operations_test.go +++ b/x/slashing/simulation/operations_test.go @@ -5,11 +5,10 @@ import ( "testing" "time" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/finschia-sdk/simapp" simappparams "github.com/Finschia/finschia-sdk/simapp/params" sdk "github.com/Finschia/finschia-sdk/types" @@ -67,7 +66,8 @@ func TestSimulateMsgUnjail(t *testing.T) { validator0 := getTestingValidator0(t, app, ctx, accounts) // setup validator0 by consensus address - app.StakingKeeper.SetValidatorByConsAddr(ctx, validator0) + err := app.StakingKeeper.SetValidatorByConsAddr(ctx, validator0) + require.NoError(t, err) val0ConsAddress, err := validator0.GetConsAddr() require.NoError(t, err) info := types.NewValidatorSigningInfo(val0ConsAddress, int64(4), int64(3), @@ -95,7 +95,8 @@ func TestSimulateMsgUnjail(t *testing.T) { require.NoError(t, err) var msg types.MsgUnjail - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + require.NoError(t, err) require.True(t, operationMsg.OK) require.Equal(t, types.TypeMsgUnjail, msg.Type()) @@ -115,6 +116,7 @@ func createTestApp(isCheckTx bool) (*simapp.SimApp, sdk.Context) { } func getTestingAccounts(t *testing.T, r *rand.Rand, app *simapp.SimApp, ctx sdk.Context, n int) []simtypes.Account { + t.Helper() accounts := simtypes.RandomAccounts(r, n) initAmt := app.StakingKeeper.TokensFromConsensusPower(ctx, 200) @@ -131,11 +133,13 @@ func getTestingAccounts(t *testing.T, r *rand.Rand, app *simapp.SimApp, ctx sdk. } func getTestingValidator0(t *testing.T, app *simapp.SimApp, ctx sdk.Context, accounts []simtypes.Account) stakingtypes.Validator { + t.Helper() commission0 := stakingtypes.NewCommission(sdk.ZeroDec(), sdk.OneDec(), sdk.OneDec()) return getTestingValidator(t, app, ctx, accounts, commission0, 0) } func getTestingValidator(t *testing.T, app *simapp.SimApp, ctx sdk.Context, accounts []simtypes.Account, commission stakingtypes.Commission, n int) stakingtypes.Validator { + t.Helper() account := accounts[n] valPubKey := account.ConsKey.PubKey() valAddr := sdk.ValAddress(account.PubKey.Address().Bytes()) diff --git a/x/slashing/types/expected_keepers.go b/x/slashing/types/expected_keepers.go index 5abf600704..bb0149204c 100644 --- a/x/slashing/types/expected_keepers.go +++ b/x/slashing/types/expected_keepers.go @@ -41,7 +41,7 @@ type StakingKeeper interface { Validator(sdk.Context, sdk.ValAddress) stakingtypes.ValidatorI // get a particular validator by operator address ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) stakingtypes.ValidatorI // get a particular validator by consensus address - // slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction + // slash the validator and delegators of the validator, specifying offense height, offense power, and slash fraction Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) Jail(sdk.Context, sdk.ConsAddress) // jail a validator Unjail(sdk.Context, sdk.ConsAddress) // unjail a validator diff --git a/x/staking/app_test.go b/x/staking/app_test.go index c546eb6e60..1db6fb5180 100644 --- a/x/staking/app_test.go +++ b/x/staking/app_test.go @@ -3,11 +3,10 @@ package staking_test import ( "testing" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/finschia-sdk/simapp" sdk "github.com/Finschia/finschia-sdk/types" authtypes "github.com/Finschia/finschia-sdk/x/auth/types" @@ -16,6 +15,7 @@ import ( ) func checkValidator(t *testing.T, app *simapp.SimApp, addr sdk.ValAddress, expFound bool) types.Validator { + t.Helper() ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{}) validator, found := app.StakingKeeper.GetValidator(ctxCheck, addr) @@ -27,6 +27,7 @@ func checkDelegation( t *testing.T, app *simapp.SimApp, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, expFound bool, expShares sdk.Dec, ) { + t.Helper() ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{}) delegation, found := app.StakingKeeper.GetDelegation(ctxCheck, delegatorAddr, validatorAddr) if expFound { diff --git a/x/staking/bench_test.go b/x/staking/bench_test.go index fe52614b7b..abbae5357a 100644 --- a/x/staking/bench_test.go +++ b/x/staking/bench_test.go @@ -23,6 +23,7 @@ func BenchmarkValidateGenesis400Validators(b *testing.B) { } func benchmarkValidateGenesis(b *testing.B, n int) { + b.Helper() b.ReportAllocs() validators := make([]types.Validator, 0, n) diff --git a/x/staking/client/cli/query.go b/x/staking/client/cli/query.go index 3638881217..eb7c35c894 100644 --- a/x/staking/client/cli/query.go +++ b/x/staking/client/cli/query.go @@ -655,7 +655,7 @@ $ %s query staking historical-info 5 height, err := strconv.ParseInt(args[0], 10, 64) if err != nil || height < 0 { - return fmt.Errorf("height argument provided must be a non-negative-integer: %v", err) + return fmt.Errorf("height argument provided must be a non-negative-integer: %w", err) } params := &types.QueryHistoricalInfoRequest{Height: height} diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index 994adcb740..64a693de93 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -111,7 +111,7 @@ func NewEditValidatorCmd() *cobra.Command { if commissionRate != "" { rate, err := sdk.NewDecFromStr(commissionRate) if err != nil { - return fmt.Errorf("invalid new commission rate: %v", err) + return fmt.Errorf("invalid new commission rate: %w", err) } newRate = &rate diff --git a/x/staking/client/cli/tx_test.go b/x/staking/client/cli/tx_test.go index 0110d667a7..9153d126d5 100644 --- a/x/staking/client/cli/tx_test.go +++ b/x/staking/client/cli/tx_test.go @@ -38,51 +38,53 @@ func TestPrepareConfigForTxCreateValidator(t *testing.T) { expectedCfg TxCreateValidatorConfig }{ { - name: "all defaults", - fsModify: func(fs *pflag.FlagSet) { - return - }, + name: "all defaults", + fsModify: func(fs *pflag.FlagSet) {}, expectedCfg: mkTxValCfg(defaultAmount, "0.1", "0.2", "0.01", "1"), }, { name: "Custom amount", fsModify: func(fs *pflag.FlagSet) { - fs.Set(FlagAmount, "2000stake") + err := fs.Set(FlagAmount, "2000stake") + require.NoError(t, err) }, expectedCfg: mkTxValCfg("2000stake", "0.1", "0.2", "0.01", "1"), }, { name: "Custom commission rate", fsModify: func(fs *pflag.FlagSet) { - fs.Set(FlagCommissionRate, "0.54") + err := fs.Set(FlagCommissionRate, "0.54") + require.NoError(t, err) }, 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") + err := fs.Set(FlagCommissionMaxRate, "0.89") + require.NoError(t, err) }, 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") + err := fs.Set(FlagCommissionMaxChangeRate, "0.55") + require.NoError(t, err) }, expectedCfg: mkTxValCfg(defaultAmount, "0.1", "0.2", "0.55", "1"), }, { name: "Custom min self delegations", fsModify: func(fs *pflag.FlagSet) { - fs.Set(FlagMinSelfDelegation, "0.33") + err := fs.Set(FlagMinSelfDelegation, "0.33") + require.NoError(t, err) }, expectedCfg: mkTxValCfg(defaultAmount, "0.1", "0.2", "0.01", "0.33"), }, } for _, tc := range tests { - tc := tc t.Run(tc.name, func(t *testing.T) { fs, _ := CreateValidatorMsgFlagSet(ip) fs.String(flags.FlagName, "", "name of private key with which to sign the gentx") diff --git a/x/staking/client/testutil/grpc.go b/x/staking/client/testutil/grpc.go index 690443ffa7..03062377c8 100644 --- a/x/staking/client/testutil/grpc.go +++ b/x/staking/client/testutil/grpc.go @@ -43,7 +43,6 @@ func (s *IntegrationTestSuite) TestGRPCQueryValidatorsHandler() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -91,7 +90,6 @@ func (s *IntegrationTestSuite) TestGRPCQueryValidator() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -156,7 +154,6 @@ func (s *IntegrationTestSuite) TestGRPCQueryValidatorDelegations() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Require().NoError(err) @@ -200,7 +197,6 @@ func (s *IntegrationTestSuite) TestGRPCQueryValidatorUnbondingDelegations() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -279,7 +275,6 @@ func (s *IntegrationTestSuite) TestGRPCQueryDelegation() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -333,7 +328,6 @@ func (s *IntegrationTestSuite) TestGRPCQueryUnbondingDelegation() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -418,7 +412,6 @@ func (s *IntegrationTestSuite) TestGRPCQueryDelegatorDelegations() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Require().NoError(err) @@ -466,7 +459,6 @@ func (s *IntegrationTestSuite) TestGRPCQueryDelegatorUnbondingDelegations() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -528,7 +520,6 @@ func (s *IntegrationTestSuite) TestGRPCQueryRedelegations() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -577,7 +568,6 @@ func (s *IntegrationTestSuite) TestGRPCQueryDelegatorValidators() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -634,7 +624,6 @@ func (s *IntegrationTestSuite) TestGRPCQueryDelegatorValidator() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -680,7 +669,6 @@ func (s *IntegrationTestSuite) TestGRPCQueryHistoricalInfo() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { resp, err := rest.GetRequest(tc.url) s.Require().NoError(err) @@ -720,7 +708,6 @@ func (s *IntegrationTestSuite) TestGRPCQueryParams() { } for _, tc := range testCases { - tc := tc resp, err := rest.GetRequest(tc.url) s.Run(tc.name, func() { s.Require().NoError(err) @@ -758,7 +745,6 @@ func (s *IntegrationTestSuite) TestGRPCQueryPool() { } for _, tc := range testCases { - tc := tc resp, err := testutil.GetRequestWithHeaders(tc.url, tc.headers) s.Run(tc.name, func() { s.Require().NoError(err) diff --git a/x/staking/client/testutil/suite.go b/x/staking/client/testutil/suite.go index 556275a938..f6a88585f2 100644 --- a/x/staking/client/testutil/suite.go +++ b/x/staking/client/testutil/suite.go @@ -6,13 +6,12 @@ import ( "strings" "testing" + ostcli "github.com/Finschia/ostracon/libs/cli" + "github.com/Finschia/ostracon/rpc/client/http" "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" "github.com/tendermint/tendermint/proto/tendermint/crypto" - ostcli "github.com/Finschia/ostracon/libs/cli" - "github.com/Finschia/ostracon/rpc/client/http" - "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/crypto/hd" "github.com/Finschia/finschia-sdk/crypto/keyring" @@ -190,8 +189,6 @@ func (s *IntegrationTestSuite) TestNewCreateValidatorCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewCreateValidatorCmd() clientCtx := val.ClientCtx @@ -245,7 +242,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidator() { }, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryValidator() clientCtx := val.ClientCtx @@ -286,8 +282,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidators() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.GetCmdQueryValidators() clientCtx := val.ClientCtx @@ -352,7 +346,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryDelegation() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryDelegation() clientCtx := val.ClientCtx @@ -408,7 +401,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryDelegations() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryDelegations() clientCtx := val.ClientCtx @@ -464,7 +456,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorDelegations() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryDelegations() clientCtx := val.ClientCtx @@ -508,7 +499,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryUnbondingDelegations() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryUnbondingDelegations() clientCtx := val.ClientCtx @@ -567,7 +557,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryUnbondingDelegation() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryUnbondingDelegation() clientCtx := val.ClientCtx @@ -616,7 +605,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorUnbondingDelegations() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryValidatorUnbondingDelegations() clientCtx := val.ClientCtx @@ -665,7 +653,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryRedelegations() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryRedelegations() clientCtx := val.ClientCtx @@ -741,7 +728,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryRedelegation() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryRedelegation() clientCtx := val.ClientCtx @@ -793,7 +779,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryValidatorRedelegations() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryValidatorRedelegations() clientCtx := val.ClientCtx @@ -844,7 +829,6 @@ func (s *IntegrationTestSuite) TestGetCmdQueryHistoricalInfo() { } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryHistoricalInfo() clientCtx := val.ClientCtx @@ -886,7 +870,6 @@ unbonding_time: 1814400s`, }, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryParams() clientCtx := val.ClientCtx @@ -923,7 +906,6 @@ not_bonded_tokens: "0"`, cli.DefaultTokens.Mul(sdk.NewInt(2)).String()), }, } for _, tc := range testCases { - tc := tc s.Run(tc.name, func() { cmd := cli.GetCmdQueryPool() clientCtx := val.ClientCtx @@ -1030,8 +1012,6 @@ func (s *IntegrationTestSuite) TestNewEditValidatorCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewEditValidatorCmd() clientCtx := val.ClientCtx @@ -1112,8 +1092,6 @@ func (s *IntegrationTestSuite) TestNewDelegateCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewDelegateCmd() clientCtx := val.ClientCtx @@ -1198,8 +1176,6 @@ func (s *IntegrationTestSuite) TestNewRedelegateCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewRedelegateCmd() clientCtx := val.ClientCtx @@ -1265,8 +1241,6 @@ func (s *IntegrationTestSuite) TestNewUnbondCmd() { } for _, tc := range testCases { - tc := tc - s.Run(tc.name, func() { cmd := cli.NewUnbondCmd() clientCtx := val.ClientCtx @@ -1351,7 +1325,8 @@ func (s *IntegrationTestSuite) TestBlockResults() { break } - s.network.WaitForNextBlock() + err = s.network.WaitForNextBlock() + require.NoError(err) } } diff --git a/x/staking/client/testutil/test_helpers.go b/x/staking/client/testutil/test_helpers.go index 682e428b5d..333de34edd 100644 --- a/x/staking/client/testutil/test_helpers.go +++ b/x/staking/client/testutil/test_helpers.go @@ -35,8 +35,9 @@ 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, +func MsgUnbondExec(clientCtx client.Context, from, valAddress, + amount fmt.Stringer, + extraArgs ...string, ) (testutil.BufferWriter, error) { args := []string{ valAddress.String(), diff --git a/x/staking/genesis_test.go b/x/staking/genesis_test.go index c61257a448..afcf3db100 100644 --- a/x/staking/genesis_test.go +++ b/x/staking/genesis_test.go @@ -230,7 +230,6 @@ func TestValidateGenesis(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { genesisState := types.DefaultGenesisState() tt.mutate(genesisState) diff --git a/x/staking/handler_test.go b/x/staking/handler_test.go index f9d10be53e..33f8c51d7d 100644 --- a/x/staking/handler_test.go +++ b/x/staking/handler_test.go @@ -26,6 +26,7 @@ import ( ) func bootstrapHandlerGenesisTest(t *testing.T, power int64, numAddrs int, accAmount sdk.Int) (*simapp.SimApp, sdk.Context, []sdk.AccAddress, []sdk.ValAddress) { + t.Helper() _, app, ctx := getBaseSimappWithCustomKeeper() addrDels, addrVals := generateAddresses(app, ctx, numAddrs, accAmount) @@ -79,7 +80,8 @@ func TestValidatorByPowerIndex(t *testing.T) { consAddr0 := sdk.ConsAddress(PKs[0].Address()) app.StakingKeeper.Slash(ctx, consAddr0, 0, initPower, sdk.NewDecWithPrec(5, 1)) app.StakingKeeper.Jail(ctx, consAddr0) - app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + _, err = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + require.NoError(t, err) validator, found = app.StakingKeeper.GetValidator(ctx, validatorAddr) require.True(t, found) @@ -127,7 +129,8 @@ func TestDuplicatesMsgCreateValidator(t *testing.T) { tstaking := teststaking.NewHelper(t, ctx, app.StakingKeeper) valTokens := tstaking.CreateValidatorWithValPower(addr1, pk1, 10, true) - app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + _, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + require.NoError(t, err) validator := tstaking.CheckValidator(addr1, types.Bonded, false) assert.Equal(t, addr1.String(), validator.OperatorAddress) @@ -304,7 +307,8 @@ func TestIncrementsMsgDelegate(t *testing.T) { bondAmount := tstaking.CreateValidatorWithValPower(validatorAddr, PKs[0], 10, true) // apply TM updates - app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + _, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + require.NoError(t, err) validator := tstaking.CheckValidator(validatorAddr, types.Bonded, false) require.Equal(t, bondAmount, validator.DelegatorShares.RoundInt()) @@ -434,7 +438,8 @@ func TestIncrementsMsgUnbond(t *testing.T) { require.True(sdk.IntEq(t, amt1.Sub(initBond), amt2)) // apply TM updates - app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + _, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + require.NoError(t, err) validator, found := app.StakingKeeper.GetValidator(ctx, validatorAddr) require.True(t, found) @@ -752,7 +757,7 @@ func TestUnbondingFromUnbondingValidator(t *testing.T) { ctx = ctx.WithBlockTime(resData.CompletionTime.Add(time.Second * -1)) // unbond the delegator from the validator - res = tstaking.Undelegate(delegatorAddr, validatorAddr, unbondAmt, true) + _ = tstaking.Undelegate(delegatorAddr, validatorAddr, unbondAmt, true) ctx = tstaking.TurnBlockTimeDiff(app.StakingKeeper.UnbondingTime(ctx)) tstaking.Ctx = ctx @@ -888,7 +893,7 @@ func TestMultipleRedelegationAtSameTime(t *testing.T) { // move forward in time, should complete both redelegations ctx = tstaking.TurnBlockTimeDiff(1 * time.Second) - rd, found = app.StakingKeeper.GetRedelegation(ctx, selfDelAddr, valAddr, valAddr2) + _, found = app.StakingKeeper.GetRedelegation(ctx, selfDelAddr, valAddr, valAddr2) require.False(t, found) } @@ -935,7 +940,7 @@ func TestMultipleRedelegationAtUniqueTimes(t *testing.T) { // move forward in time, should complete the second redelegation ctx = tstaking.TurnBlockTimeDiff(5 * time.Second) - rd, found = app.StakingKeeper.GetRedelegation(ctx, selfDelAddr, valAddr, valAddr2) + _, found = app.StakingKeeper.GetRedelegation(ctx, selfDelAddr, valAddr, valAddr2) require.False(t, found) } @@ -975,7 +980,7 @@ func TestMultipleUnbondingDelegationAtSameTime(t *testing.T) { // move forwaubd in time, should complete both ubds ctx = tstaking.TurnBlockTimeDiff(1 * time.Second) - ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, selfDelAddr, valAddr) + _, found = app.StakingKeeper.GetUnbondingDelegation(ctx, selfDelAddr, valAddr) require.False(t, found) } @@ -1023,7 +1028,7 @@ func TestMultipleUnbondingDelegationAtUniqueTimes(t *testing.T) { // move forwaubd in time, should complete the second redelegation ctx = tstaking.TurnBlockTimeDiff(5 * time.Second) - ubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, selfDelAddr, valAddr) + _, found = app.StakingKeeper.GetUnbondingDelegation(ctx, selfDelAddr, valAddr) require.False(t, found) } @@ -1043,21 +1048,25 @@ func TestUnbondingWhenExcessValidators(t *testing.T) { // add three validators tstaking.CreateValidatorWithValPower(val1, PKs[0], 50, true) // apply TM updates - app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + _, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + require.NoError(t, err) require.Equal(t, 1, len(app.StakingKeeper.GetLastValidators(ctx))) valTokens2 := tstaking.CreateValidatorWithValPower(val2, PKs[1], 30, true) - app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + _, err = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + require.NoError(t, err) require.Equal(t, 2, len(app.StakingKeeper.GetLastValidators(ctx))) tstaking.CreateValidatorWithValPower(val3, PKs[2], 10, true) - app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + _, err = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + require.NoError(t, err) require.Equal(t, 2, len(app.StakingKeeper.GetLastValidators(ctx))) // unbond the validator-2 tstaking.Undelegate(sdk.AccAddress(val2), val2, valTokens2, true) // apply TM updates - app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + _, err = app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) + require.NoError(t, err) // because there are extra validators waiting to get in, the queued // validator (aka. validator-1) should make it into the bonded group, thus diff --git a/x/staking/keeper/common_test.go b/x/staking/keeper/common_test.go index b968255736..30cd6e0ca3 100644 --- a/x/staking/keeper/common_test.go +++ b/x/staking/keeper/common_test.go @@ -37,6 +37,7 @@ func createTestInput() (*codec.LegacyAmino, *simapp.SimApp, sdk.Context) { // intended to be used with require/assert: require.True(ValEq(...)) func ValEq(t *testing.T, exp, got types.Validator) (*testing.T, bool, string, types.Validator, types.Validator) { + t.Helper() return t, exp.MinEqual(&got), "expected:\n%v\ngot:\n%v", exp, got } diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index e87f208da2..f81fa3d399 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -205,7 +205,7 @@ func TestUnbondDelegation(t *testing.T) { validator, issuedShares := validator.AddTokensFromDel(startTokens) require.Equal(t, startTokens, issuedShares.RoundInt()) - validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) + _ = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) delegation := types.NewDelegation(delAddrs[0], valAddrs[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, delegation) @@ -328,7 +328,8 @@ func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) { app.AccountKeeper.SetModuleAccount(ctx, notBondedPool) validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) - app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + err := app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + require.NoError(t, err) require.True(t, validator.IsBonded()) selfDelegation := types.NewDelegation(sdk.AccAddress(addrVals[0].Bytes()), addrVals[0], issuedShares) @@ -349,12 +350,12 @@ func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) { require.NoError(t, simapp.FundModuleAccount(app, ctx, bondedPool.GetName(), delCoins)) app.AccountKeeper.SetModuleAccount(ctx, bondedPool) - validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) + _ = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) delegation := types.NewDelegation(addrDels[0], addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, delegation) val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) - _, err := app.StakingKeeper.Undelegate(ctx, val0AccAddr, addrVals[0], app.StakingKeeper.TokensFromConsensusPower(ctx, 6).ToDec()) + _, err = app.StakingKeeper.Undelegate(ctx, val0AccAddr, addrVals[0], app.StakingKeeper.TokensFromConsensusPower(ctx, 6).ToDec()) require.NoError(t, err) // end block @@ -377,7 +378,8 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) { // create a validator with a self-delegation validator := teststaking.NewValidator(t, addrVals[0], PKs[0]) - app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + err := app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + require.NoError(t, err) validator, issuedShares := validator.AddTokensFromDel(delTokens) require.Equal(t, delTokens, issuedShares.RoundInt()) @@ -407,7 +409,7 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) { require.NoError(t, simapp.FundModuleAccount(app, ctx, bondedPool.GetName(), delCoins)) app.AccountKeeper.SetModuleAccount(ctx, bondedPool) - validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) + _ = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) delegation := types.NewDelegation(addrDels[1], addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, delegation) @@ -423,7 +425,7 @@ func TestUndelegateFromUnbondingValidator(t *testing.T) { // unbond the all self-delegation to put validator in unbonding state val0AccAddr := sdk.AccAddress(addrVals[0]) - _, err := app.StakingKeeper.Undelegate(ctx, val0AccAddr, addrVals[0], delTokens.ToDec()) + _, err = app.StakingKeeper.Undelegate(ctx, val0AccAddr, addrVals[0], delTokens.ToDec()) require.NoError(t, err) // end block @@ -468,7 +470,8 @@ func TestUndelegateFromUnbondedValidator(t *testing.T) { // create a validator with a self-delegation validator := teststaking.NewValidator(t, addrVals[0], PKs[0]) - app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + err := app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + require.NoError(t, err) valTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10) validator, issuedShares := validator.AddTokensFromDel(valTokens) @@ -498,7 +501,7 @@ func TestUndelegateFromUnbondedValidator(t *testing.T) { ctx = ctx.WithBlockTime(time.Unix(333, 0)) // unbond the all self-delegation to put validator in unbonding state - _, err := app.StakingKeeper.Undelegate(ctx, val0AccAddr, addrVals[0], valTokens.ToDec()) + _, err = app.StakingKeeper.Undelegate(ctx, val0AccAddr, addrVals[0], valTokens.ToDec()) require.NoError(t, err) // end block @@ -549,7 +552,8 @@ func TestUnbondingAllDelegationFromValidator(t *testing.T) { // create a validator with a self-delegation validator := teststaking.NewValidator(t, addrVals[0], PKs[0]) - app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + err := app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + require.NoError(t, err) valTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10) validator, issuedShares := validator.AddTokensFromDel(valTokens) @@ -582,7 +586,7 @@ func TestUnbondingAllDelegationFromValidator(t *testing.T) { ctx = ctx.WithBlockTime(time.Unix(333, 0)) // unbond the all self-delegation to put validator in unbonding state - _, err := app.StakingKeeper.Undelegate(ctx, val0AccAddr, addrVals[0], valTokens.ToDec()) + _, err = app.StakingKeeper.Undelegate(ctx, val0AccAddr, addrVals[0], valTokens.ToDec()) require.NoError(t, err) // end block @@ -745,7 +749,7 @@ func TestRedelegationMaxEntries(t *testing.T) { valTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10) validator, issuedShares := validator.AddTokensFromDel(valTokens) require.Equal(t, valTokens, issuedShares.RoundInt()) - validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) + _ = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) val0AccAddr := sdk.AccAddress(addrVals[0].Bytes()) selfDelegation := types.NewDelegation(val0AccAddr, addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, selfDelegation) @@ -798,7 +802,8 @@ func TestRedelegateSelfDelegation(t *testing.T) { // create a validator with a self-delegation validator := teststaking.NewValidator(t, addrVals[0], PKs[0]) - app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + err := app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + require.NoError(t, err) valTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10) validator, issuedShares := validator.AddTokensFromDel(valTokens) @@ -821,12 +826,12 @@ func TestRedelegateSelfDelegation(t *testing.T) { delTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10) validator, issuedShares = validator.AddTokensFromDel(delTokens) require.Equal(t, delTokens, issuedShares.RoundInt()) - validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) + _ = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) delegation := types.NewDelegation(addrDels[0], addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, delegation) - _, err := app.StakingKeeper.BeginRedelegation(ctx, val0AccAddr, addrVals[0], addrVals[1], delTokens.ToDec()) + _, err = app.StakingKeeper.BeginRedelegation(ctx, val0AccAddr, addrVals[0], addrVals[1], delTokens.ToDec()) require.NoError(t, err) // end block @@ -854,7 +859,8 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) { // create a validator with a self-delegation validator := teststaking.NewValidator(t, addrVals[0], PKs[0]) - app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + err := app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + require.NoError(t, err) valTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10) validator, issuedShares := validator.AddTokensFromDel(valTokens) @@ -869,7 +875,7 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) { delTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10) validator, issuedShares = validator.AddTokensFromDel(delTokens) require.Equal(t, delTokens, issuedShares.RoundInt()) - validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) + _ = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) delegation := types.NewDelegation(addrDels[1], addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, delegation) @@ -877,7 +883,7 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) { validator2 := teststaking.NewValidator(t, addrVals[1], PKs[1]) validator2, issuedShares = validator2.AddTokensFromDel(valTokens) require.Equal(t, valTokens, issuedShares.RoundInt()) - validator2 = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator2, true) + _ = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator2, true) header := ctx.BlockHeader() blockHeight := int64(10) @@ -887,7 +893,7 @@ func TestRedelegateFromUnbondingValidator(t *testing.T) { ctx = ctx.WithBlockHeader(header) // unbond the all self-delegation to put validator in unbonding state - _, err := app.StakingKeeper.Undelegate(ctx, val0AccAddr, addrVals[0], delTokens.ToDec()) + _, err = app.StakingKeeper.Undelegate(ctx, val0AccAddr, addrVals[0], delTokens.ToDec()) require.NoError(t, err) // end block @@ -936,7 +942,8 @@ func TestRedelegateFromUnbondedValidator(t *testing.T) { // create a validator with a self-delegation validator := teststaking.NewValidator(t, addrVals[0], PKs[0]) - app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + err := app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + require.NoError(t, err) valTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10) validator, issuedShares := validator.AddTokensFromDel(valTokens) @@ -951,7 +958,7 @@ func TestRedelegateFromUnbondedValidator(t *testing.T) { delTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 10) validator, issuedShares = validator.AddTokensFromDel(delTokens) require.Equal(t, delTokens, issuedShares.RoundInt()) - validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) + _ = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) delegation := types.NewDelegation(addrDels[1], addrVals[0], issuedShares) app.StakingKeeper.SetDelegation(ctx, delegation) @@ -966,7 +973,7 @@ func TestRedelegateFromUnbondedValidator(t *testing.T) { ctx = ctx.WithBlockTime(time.Unix(333, 0)) // unbond the all self-delegation to put validator in unbonding state - _, err := app.StakingKeeper.Undelegate(ctx, val0AccAddr, addrVals[0], delTokens.ToDec()) + _, err = app.StakingKeeper.Undelegate(ctx, val0AccAddr, addrVals[0], delTokens.ToDec()) require.NoError(t, err) // end block diff --git a/x/staking/keeper/grpc_query.go b/x/staking/keeper/grpc_query.go index ed4fd1ba6a..55f763e210 100644 --- a/x/staking/keeper/grpc_query.go +++ b/x/staking/keeper/grpc_query.go @@ -37,7 +37,7 @@ func (k Querier) Validators(c context.Context, req *types.QueryValidatorsRequest store := ctx.KVStore(k.storeKey) valStore := prefix.NewStore(store, types.ValidatorsKey) - pageRes, err := query.FilteredPaginate(valStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { + pageRes, err := query.FilteredPaginate(valStore, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) { val, err := types.UnmarshalValidator(k.cdc, value) if err != nil { return false, err @@ -98,7 +98,7 @@ func (k Querier) ValidatorDelegations(c context.Context, req *types.QueryValidat store := ctx.KVStore(k.storeKey) valStore := prefix.NewStore(store, types.DelegationKey) - pageRes, err := query.FilteredPaginate(valStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { + pageRes, err := query.FilteredPaginate(valStore, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) { delegation, err := types.UnmarshalDelegation(k.cdc, value) if err != nil { return false, err @@ -153,7 +153,7 @@ func (k Querier) ValidatorUnbondingDelegations(c context.Context, req *types.Que srcValPrefix := types.GetUBDsByValIndexKey(valAddr) ubdStore := prefix.NewStore(store, srcValPrefix) - pageRes, err := query.Paginate(ubdStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(ubdStore, req.Pagination, func(key, value []byte) error { storeKey := types.GetUBDKeyFromValIndexKey(append(srcValPrefix, key...)) storeValue := store.Get(storeKey) @@ -269,7 +269,7 @@ func (k Querier) DelegatorDelegations(c context.Context, req *types.QueryDelegat store := ctx.KVStore(k.storeKey) delStore := prefix.NewStore(store, types.GetDelegationsKey(delAddr)) - pageRes, err := query.Paginate(delStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(delStore, req.Pagination, func(key, value []byte) error { delegation, err := types.UnmarshalDelegation(k.cdc, value) if err != nil { return err @@ -340,7 +340,7 @@ func (k Querier) DelegatorUnbondingDelegations(c context.Context, req *types.Que } unbStore := prefix.NewStore(store, types.GetUBDsKey(delAddr)) - pageRes, err := query.Paginate(unbStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(unbStore, req.Pagination, func(key, value []byte) error { unbond, err := types.UnmarshalUBD(k.cdc, value) if err != nil { return err @@ -425,7 +425,7 @@ func (k Querier) DelegatorValidators(c context.Context, req *types.QueryDelegato } delStore := prefix.NewStore(store, types.GetDelegationsKey(delAddr)) - pageRes, err := query.Paginate(delStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(delStore, req.Pagination, func(key, value []byte) error { delegation, err := types.UnmarshalDelegation(k.cdc, value) if err != nil { return err @@ -505,7 +505,7 @@ func queryRedelegationsFromSrcValidator(store sdk.KVStore, k Querier, req *types srcValPrefix := types.GetREDsFromValSrcIndexKey(valAddr) redStore := prefix.NewStore(store, srcValPrefix) - res, err = query.Paginate(redStore, req.Pagination, func(key []byte, value []byte) error { + res, err = query.Paginate(redStore, req.Pagination, func(key, value []byte) error { storeKey := types.GetREDKeyFromValSrcIndexKey(append(srcValPrefix, key...)) storeValue := store.Get(storeKey) red, err := types.UnmarshalRED(k.cdc, storeValue) @@ -526,7 +526,7 @@ func queryAllRedelegations(store sdk.KVStore, k Querier, req *types.QueryRedeleg } redStore := prefix.NewStore(store, types.GetREDsKey(delAddr)) - res, err = query.Paginate(redStore, req.Pagination, func(key []byte, value []byte) error { + res, err = query.Paginate(redStore, req.Pagination, func(key, value []byte) error { redelegation, err := types.UnmarshalRED(k.cdc, value) if err != nil { return err diff --git a/x/staking/keeper/grpc_query_test.go b/x/staking/keeper/grpc_query_test.go index 364737a3df..d5d962dc3f 100644 --- a/x/staking/keeper/grpc_query_test.go +++ b/x/staking/keeper/grpc_query_test.go @@ -786,6 +786,7 @@ func (suite *KeeperTestSuite) TestGRPCQueryValidatorUnbondingDelegations() { } func createValidators(t *testing.T, ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sdk.AccAddress, []sdk.ValAddress, []types.Validator) { + t.Helper() addrs := simapp.AddTestAddrsIncremental(app, ctx, 5, app.StakingKeeper.TokensFromConsensusPower(ctx, 300)) valAddrs := simapp.ConvertAddrsToValAddrs(addrs) pks := simapp.CreateTestPubKeys(5) @@ -804,12 +805,14 @@ func createValidators(t *testing.T, ctx sdk.Context, app *simapp.SimApp, powers app.StakingKeeper.SetValidator(ctx, val1) app.StakingKeeper.SetValidator(ctx, val2) - app.StakingKeeper.SetValidatorByConsAddr(ctx, val1) - app.StakingKeeper.SetValidatorByConsAddr(ctx, val2) + err := app.StakingKeeper.SetValidatorByConsAddr(ctx, val1) + require.NoError(t, err) + err = app.StakingKeeper.SetValidatorByConsAddr(ctx, val2) + require.NoError(t, err) app.StakingKeeper.SetNewValidatorByPowerIndex(ctx, val1) app.StakingKeeper.SetNewValidatorByPowerIndex(ctx, val2) - _, err := app.StakingKeeper.Delegate(ctx, addrs[0], app.StakingKeeper.TokensFromConsensusPower(ctx, powers[0]), types.Unbonded, val1, true) + _, err = app.StakingKeeper.Delegate(ctx, addrs[0], app.StakingKeeper.TokensFromConsensusPower(ctx, powers[0]), types.Unbonded, val1, true) require.NoError(t, err) _, err = app.StakingKeeper.Delegate(ctx, addrs[1], app.StakingKeeper.TokensFromConsensusPower(ctx, powers[1]), types.Unbonded, val2, true) require.NoError(t, err) diff --git a/x/staking/keeper/historical_info_test.go b/x/staking/keeper/historical_info_test.go index 7562c72de5..3936ed71d9 100644 --- a/x/staking/keeper/historical_info_test.go +++ b/x/staking/keeper/historical_info_test.go @@ -149,8 +149,8 @@ func TestGetAllHistoricalInfo(t *testing.T) { expHistInfos := []types.HistoricalInfo{hist1, hist2, hist3} - for i, hi := range expHistInfos { - app.StakingKeeper.SetHistoricalInfo(ctx, int64(10+i), &hi) + for i := range expHistInfos { + app.StakingKeeper.SetHistoricalInfo(ctx, int64(10+i), &expHistInfos[i]) } infos := app.StakingKeeper.GetAllHistoricalInfo(ctx) diff --git a/x/staking/keeper/querier_test.go b/x/staking/keeper/querier_test.go index c601332015..23ba473bbe 100644 --- a/x/staking/keeper/querier_test.go +++ b/x/staking/keeper/querier_test.go @@ -483,11 +483,11 @@ func TestQueryValidatorDelegations_Pagination(t *testing.T) { for _, c := range cases { // Query Delegator bonded validators queryParams := types.NewQueryDelegatorParams(addrs[0]) - bz, errRes := cdc.MarshalJSON(queryParams) + _, errRes := cdc.MarshalJSON(queryParams) require.NoError(t, errRes) // Query valAddress delegations - bz, errRes = cdc.MarshalJSON(types.NewQueryValidatorParams(valAddress, c.page, c.limit)) + bz, errRes := cdc.MarshalJSON(types.NewQueryValidatorParams(valAddress, c.page, c.limit)) require.NoError(t, errRes) query := abci.RequestQuery{ @@ -517,10 +517,10 @@ func TestQueryValidatorDelegations_Pagination(t *testing.T) { for _, c := range cases { // Query Unbonding delegations with pagination. queryParams := types.NewQueryDelegatorParams(addrs[0]) - bz, errRes := cdc.MarshalJSON(queryParams) + _, errRes := cdc.MarshalJSON(queryParams) require.NoError(t, errRes) - bz, errRes = cdc.MarshalJSON(types.NewQueryValidatorParams(valAddress, c.page, c.limit)) + bz, errRes := cdc.MarshalJSON(types.NewQueryValidatorParams(valAddress, c.page, c.limit)) require.NoError(t, errRes) query := abci.RequestQuery{ Data: bz, diff --git a/x/staking/keeper/slash.go b/x/staking/keeper/slash.go index 85918ab795..1562254574 100644 --- a/x/staking/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -28,7 +28,7 @@ import ( // // Infraction was committed at the current height or at a past height, // not at a height in the future -func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeight int64, power int64, slashFactor sdk.Dec) { +func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeight, power int64, slashFactor sdk.Dec) { logger := k.Logger(ctx) if slashFactor.IsNegative() { @@ -273,7 +273,7 @@ func (k Keeper) SlashRedelegation(ctx sdk.Context, srcValidator types.Validator, tokensToBurn, err := k.Unbond(ctx, delegatorAddress, valDstAddr, sharesToUnbond) if err != nil { - panic(fmt.Errorf("error unbonding delegator: %v", err)) + panic(fmt.Errorf("error unbonding delegator: %w", err)) } dstValidator, found := k.GetValidator(ctx, valDstAddr) diff --git a/x/staking/keeper/slash_test.go b/x/staking/keeper/slash_test.go index 88790d6136..bc92c1118d 100644 --- a/x/staking/keeper/slash_test.go +++ b/x/staking/keeper/slash_test.go @@ -17,6 +17,7 @@ import ( // bootstrapSlashTest creates 3 validators and bootstrap the app. func bootstrapSlashTest(t *testing.T, power int64) (*simapp.SimApp, sdk.Context, []sdk.AccAddress, []sdk.ValAddress) { + t.Helper() _, app, ctx := createTestInput() addrDels, addrVals := generateAddresses(app, ctx, 100) @@ -41,7 +42,8 @@ func bootstrapSlashTest(t *testing.T, power int64) (*simapp.SimApp, sdk.Context, validator := teststaking.NewValidator(t, addrVals[i], PKs[i]) validator, _ = validator.AddTokensFromDel(amt) validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) - app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + err := app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + require.NoError(t, err) } return app, ctx, addrDels, addrVals @@ -123,7 +125,7 @@ func TestSlashRedelegation(t *testing.T) { // add bonded tokens to pool for (re)delegations startCoins := sdk.NewCoins(sdk.NewInt64Coin(app.StakingKeeper.BondDenom(ctx), 15)) bondedPool := app.StakingKeeper.GetBondedPool(ctx) - balances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress()) + _ = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress()) require.NoError(t, simapp.FundModuleAccount(app, ctx, bondedPool.GetName(), startCoins)) app.AccountKeeper.SetModuleAccount(ctx, bondedPool) @@ -153,7 +155,7 @@ func TestSlashRedelegation(t *testing.T) { slashAmount = app.StakingKeeper.SlashRedelegation(ctx, validator, rd, 0, fraction) require.True(t, slashAmount.Equal(sdk.NewInt(0))) - balances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress()) + balances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress()) // test valid slash, before expiration timestamp and to which stake contributed ctx = ctx.WithBlockHeader(tmproto.Header{Time: time.Unix(0, 0)}) @@ -201,12 +203,12 @@ func TestSlashAtNegativeHeight(t *testing.T) { bondedPool := app.StakingKeeper.GetBondedPool(ctx) oldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress()) - validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) + _, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) app.StakingKeeper.Slash(ctx, consAddr, -2, 10, fraction) // read updated state - validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) + validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) // end block @@ -232,12 +234,12 @@ func TestSlashValidatorAtCurrentHeight(t *testing.T) { bondedPool := app.StakingKeeper.GetBondedPool(ctx) oldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress()) - validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) + _, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) app.StakingKeeper.Slash(ctx, consAddr, ctx.BlockHeight(), 10, fraction) // read updated state - validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) + validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) // end block @@ -272,7 +274,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { bondedPool := app.StakingKeeper.GetBondedPool(ctx) oldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress()) - validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) + _, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) app.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction) @@ -293,7 +295,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { require.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 3), diffTokens) // read updated validator - validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) + validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) // power decreased by 3 - 6 stake originally bonded at the time of infraction @@ -328,7 +330,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // slash validator again // all originally bonded stake has been slashed, so this will have no effect // on the unbonding delegation, but it will slash stake bonded since the infraction - // this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440 + // this may not be the desirable behavior, ref https://github.com/cosmos/cosmos-sdk/issues/1440 ctx = ctx.WithBlockHeight(13) app.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction) @@ -354,7 +356,7 @@ func TestSlashWithUnbondingDelegation(t *testing.T) { // slash validator again // all originally bonded stake has been slashed, so this will have no effect // on the unbonding delegation, but it will slash stake bonded since the infraction - // this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440 + // this may not be the desirable behavior, ref https://github.com/cosmos/cosmos-sdk/issues/1440 ctx = ctx.WithBlockHeight(13) app.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction) @@ -411,7 +413,7 @@ func TestSlashWithRedelegation(t *testing.T) { // slash validator ctx = ctx.WithBlockHeight(12) - validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) + _, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) require.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction) }) @@ -433,7 +435,7 @@ func TestSlashWithRedelegation(t *testing.T) { require.True(t, found) require.Len(t, rd.Entries, 1) // read updated validator - validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) + validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) // power decreased by 2 - 4 stake originally bonded at the time of infraction // was still bonded at the time of discovery and was slashed by half, 4 stake @@ -442,7 +444,7 @@ func TestSlashWithRedelegation(t *testing.T) { require.Equal(t, int64(8), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx))) // slash the validator again - validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) + _, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) require.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) }) @@ -476,7 +478,7 @@ func TestSlashWithRedelegation(t *testing.T) { // slash the validator again, by 100% ctx = ctx.WithBlockHeight(12) - validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) + _, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr) require.True(t, found) require.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) }) @@ -575,7 +577,7 @@ func TestSlashBoth(t *testing.T) { oldNotBonded := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount // slash validator ctx = ctx.WithBlockHeight(12) - validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0])) + _, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0])) require.True(t, found) consAddr0 := sdk.ConsAddress(PKs[0].Address()) app.StakingKeeper.Slash(ctx, consAddr0, 10, 10, fraction) @@ -599,7 +601,7 @@ func TestSlashBoth(t *testing.T) { require.True(t, found) require.Len(t, rdA.Entries, 1) // read updated validator - validator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0])) + validator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0])) require.True(t, found) // power not decreased, all stake was bonded since require.Equal(t, int64(10), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx))) diff --git a/x/staking/keeper/val_state_change_test.go b/x/staking/keeper/val_state_change_test.go index 734f442beb..1de382f3d6 100644 --- a/x/staking/keeper/val_state_change_test.go +++ b/x/staking/keeper/val_state_change_test.go @@ -1,11 +1,13 @@ package keeper_test import ( - "github.com/Finschia/finschia-sdk/x/staking/keeper" - "github.com/Finschia/finschia-sdk/x/staking/types" + "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "testing" + + "github.com/Finschia/finschia-sdk/x/staking/keeper" + "github.com/Finschia/finschia-sdk/x/staking/types" ) func TestUnbondingToUnbondedPanic(t *testing.T) { diff --git a/x/staking/keeper/validator_test.go b/x/staking/keeper/validator_test.go index c7c969610f..20fe6d8db3 100644 --- a/x/staking/keeper/validator_test.go +++ b/x/staking/keeper/validator_test.go @@ -18,13 +18,15 @@ import ( "github.com/Finschia/finschia-sdk/x/staking/types" ) -func newMonikerValidator(t testing.TB, operator sdk.ValAddress, pubKey cryptotypes.PubKey, moniker string) types.Validator { +func newMonikerValidator(tb testing.TB, operator sdk.ValAddress, pubKey cryptotypes.PubKey, moniker string) types.Validator { + tb.Helper() v, err := types.NewValidator(operator, pubKey, types.Description{Moniker: moniker}) - require.NoError(t, err) + require.NoError(tb, err) return v } -func bootstrapValidatorTest(t testing.TB, power int64, numAddrs int) (*simapp.SimApp, sdk.Context, []sdk.AccAddress, []sdk.ValAddress) { +func bootstrapValidatorTest(tb testing.TB, power int64, numAddrs int) (*simapp.SimApp, sdk.Context, []sdk.AccAddress, []sdk.ValAddress) { + tb.Helper() _, app, ctx := createTestInput() addrDels, addrVals := generateAddresses(app, ctx, numAddrs) @@ -36,18 +38,19 @@ func bootstrapValidatorTest(t testing.TB, power int64, numAddrs int) (*simapp.Si // set bonded pool supply app.AccountKeeper.SetModuleAccount(ctx, notBondedPool) - require.NoError(t, simapp.FundModuleAccount(app, ctx, notBondedPool.GetName(), totalSupply)) + require.NoError(tb, simapp.FundModuleAccount(app, ctx, notBondedPool.GetName(), totalSupply)) return app, ctx, addrDels, addrVals } -func initValidators(t testing.TB, power int64, numAddrs int, powers []int64) (*simapp.SimApp, sdk.Context, []sdk.AccAddress, []sdk.ValAddress, []types.Validator) { - app, ctx, addrs, valAddrs := bootstrapValidatorTest(t, power, numAddrs) +func initValidators(tb testing.TB, power int64, numAddrs int, powers []int64) (*simapp.SimApp, sdk.Context, []sdk.AccAddress, []sdk.ValAddress, []types.Validator) { + tb.Helper() + app, ctx, addrs, valAddrs := bootstrapValidatorTest(tb, power, numAddrs) pks := simapp.CreateTestPubKeys(numAddrs) vs := make([]types.Validator, len(powers)) for i, power := range powers { - vs[i] = teststaking.NewValidator(t, sdk.ValAddress(addrs[i]), pks[i]) + vs[i] = teststaking.NewValidator(tb, sdk.ValAddress(addrs[i]), pks[i]) tokens := app.StakingKeeper.TokensFromConsensusPower(ctx, power) vs[i], _ = vs[i].AddTokensFromDel(tokens) } @@ -186,7 +189,7 @@ func TestUpdateBondedValidatorsDecreaseCliff(t *testing.T) { app.StakingKeeper.DeleteValidatorByPowerIndex(ctx, nextCliffVal) shares := app.StakingKeeper.TokensFromConsensusPower(ctx, 21) nextCliffVal, _ = nextCliffVal.RemoveDelShares(shares.ToDec()) - nextCliffVal = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, nextCliffVal, true) + _ = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, nextCliffVal, true) expectedValStatus := map[int]types.BondStatus{ 9: types.Bonded, 8: types.Bonded, 7: types.Bonded, 5: types.Bonded, 4: types.Bonded, @@ -224,7 +227,8 @@ func TestSlashToZeroPowerRemoved(t *testing.T) { validator, _ = validator.AddTokensFromDel(valTokens) require.Equal(t, types.Unbonded, validator.Status) require.Equal(t, valTokens, validator.Tokens) - app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + err := app.StakingKeeper.SetValidatorByConsAddr(ctx, validator) + require.NoError(t, err) validator = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validator, true) require.Equal(t, valTokens, validator.Tokens, "\nvalidator %v\npool %v", validator, valTokens) @@ -267,7 +271,8 @@ func TestValidatorBasics(t *testing.T) { // set and retrieve a record validators[0] = keeper.TestingUpdateValidator(app.StakingKeeper, ctx, validators[0], true) - app.StakingKeeper.SetValidatorByConsAddr(ctx, validators[0]) + err := app.StakingKeeper.SetValidatorByConsAddr(ctx, validators[0]) + require.NoError(t, err) resVal, found := app.StakingKeeper.GetValidator(ctx, addrVals[0]) require.True(t, found) assert.True(ValEq(t, validators[0], resVal)) @@ -1097,6 +1102,7 @@ func TestUpdateValidatorCommission(t *testing.T) { } func applyValidatorSetUpdates(t *testing.T, ctx sdk.Context, k keeper.Keeper, expectedUpdatesLen int) []abci.ValidatorUpdate { + t.Helper() updates, err := k.ApplyAndReturnValidatorSetUpdates(ctx) require.NoError(t, err) if expectedUpdatesLen >= 0 { diff --git a/x/staking/legacy/v043/store_test.go b/x/staking/legacy/v043/store_test.go index 6bc9e36cff..bad5fba9ba 100644 --- a/x/staking/legacy/v043/store_test.go +++ b/x/staking/legacy/v043/store_test.go @@ -25,7 +25,7 @@ func TestStoreMigration(t *testing.T) { _, pk1, addr1 := testdata.KeyTestPubAddr() valAddr1 := sdk.ValAddress(addr1) val := teststaking.NewValidator(t, valAddr1, pk1) - _, pk1, addr2 := testdata.KeyTestPubAddr() + _, _, addr2 := testdata.KeyTestPubAddr() valAddr2 := sdk.ValAddress(addr2) _, _, addr3 := testdata.KeyTestPubAddr() consAddr := sdk.ConsAddress(addr3) @@ -127,7 +127,6 @@ func TestStoreMigration(t *testing.T) { // Make sure the new keys are set and old keys are deleted. for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { if !bytes.Equal(tc.oldKey, tc.newKey) { require.Nil(t, store.Get(tc.oldKey)) diff --git a/x/staking/module.go b/x/staking/module.go index fa038e479d..80d234521d 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -6,9 +6,8 @@ import ( "fmt" "math/rand" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" diff --git a/x/staking/simulation/decoder_test.go b/x/staking/simulation/decoder_test.go index 7e215029f4..bc486e7c88 100644 --- a/x/staking/simulation/decoder_test.go +++ b/x/staking/simulation/decoder_test.go @@ -7,8 +7,6 @@ import ( "github.com/stretchr/testify/require" - "github.com/Finschia/finschia-sdk/codec" - cryptocodec "github.com/Finschia/finschia-sdk/crypto/codec" "github.com/Finschia/finschia-sdk/crypto/keys/ed25519" "github.com/Finschia/finschia-sdk/simapp" sdk "github.com/Finschia/finschia-sdk/types" @@ -23,14 +21,6 @@ var ( valAddr1 = sdk.ValAddress(delPk1.Address()) ) -func makeTestCodec() (cdc *codec.LegacyAmino) { - cdc = codec.NewLegacyAmino() - sdk.RegisterLegacyAminoCodec(cdc) - cryptocodec.RegisterCrypto(cdc) - types.RegisterLegacyAminoCodec(cdc) - return -} - func TestDecodeStore(t *testing.T) { cdc := simapp.MakeTestEncodingConfig().Marshaler dec := simulation.NewDecodeStore(cdc) @@ -67,7 +57,6 @@ func TestDecodeStore(t *testing.T) { {"other", ""}, } for i, tt := range tests { - i, tt := i, tt t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 3f594edd06..e005204228 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -15,13 +15,12 @@ import ( ) // Simulation operation weights constants -// nolint:gosec const ( - OpWeightMsgCreateValidator = "op_weight_msg_create_validator" //nolint:gosec - OpWeightMsgEditValidator = "op_weight_msg_edit_validator" //nolint:gosec - OpWeightMsgDelegate = "op_weight_msg_delegate" //nolint:gosec - OpWeightMsgUndelegate = "op_weight_msg_undelegate" //nolint:gosec - OpWeightMsgBeginRedelegate = "op_weight_msg_begin_redelegate" //nolint:gosec + OpWeightMsgCreateValidator = "op_weight_msg_create_validator" + OpWeightMsgEditValidator = "op_weight_msg_edit_validator" + OpWeightMsgDelegate = "op_weight_msg_delegate" + OpWeightMsgUndelegate = "op_weight_msg_undelegate" + OpWeightMsgBeginRedelegate = "op_weight_msg_begin_redelegate" ) // WeightedOperations returns all the operations from the module with their respective weights diff --git a/x/staking/simulation/operations_test.go b/x/staking/simulation/operations_test.go index 063c665383..21267be4cb 100644 --- a/x/staking/simulation/operations_test.go +++ b/x/staking/simulation/operations_test.go @@ -5,11 +5,10 @@ import ( "testing" "time" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/finschia-sdk/simapp" simappparams "github.com/Finschia/finschia-sdk/simapp/params" sdk "github.com/Finschia/finschia-sdk/types" @@ -80,7 +79,8 @@ func TestSimulateMsgCreateValidator(t *testing.T) { require.NoError(t, err) var msg types.MsgCreateValidator - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + require.NoError(t, err) require.True(t, operationMsg.OK) require.Equal(t, "0.080000000000000000", msg.Commission.MaxChangeRate.String()) @@ -117,7 +117,8 @@ func TestSimulateMsgEditValidator(t *testing.T) { require.NoError(t, err) var msg types.MsgEditValidator - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + require.NoError(t, err) require.True(t, operationMsg.OK) require.Equal(t, "0.280623462081924936", msg.CommissionRate.String()) @@ -155,7 +156,8 @@ func TestSimulateMsgDelegate(t *testing.T) { require.NoError(t, err) var msg types.MsgDelegate - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + require.NoError(t, err) require.True(t, operationMsg.OK) require.Equal(t, "link1ghekyjucln7y67ntx7cf27m9dpuxxemnqk82wt", msg.DelegatorAddress) @@ -200,7 +202,8 @@ func TestSimulateMsgUndelegate(t *testing.T) { require.NoError(t, err) var msg types.MsgUndelegate - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + require.NoError(t, err) require.True(t, operationMsg.OK) require.Equal(t, "link1p8wcgrjr4pjju90xg6u9cgq55dxwq8j7fmx8x8", msg.DelegatorAddress) @@ -250,7 +253,8 @@ func TestSimulateMsgBeginRedelegate(t *testing.T) { require.NoError(t, err) var msg types.MsgBeginRedelegate - types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + err = types.ModuleCdc.UnmarshalJSON(operationMsg.Msg, &msg) + require.NoError(t, err) require.True(t, operationMsg.OK) require.Equal(t, "link12gwd9jchc69wck8dhstxgwz3z8qs8yv6t0s9q5", msg.DelegatorAddress) @@ -275,6 +279,7 @@ func createTestApp(isCheckTx bool) (*simapp.SimApp, sdk.Context) { } func getTestingAccounts(t *testing.T, r *rand.Rand, app *simapp.SimApp, ctx sdk.Context, n int) []simtypes.Account { + t.Helper() accounts := simtypes.RandomAccounts(r, n) initAmt := app.StakingKeeper.TokensFromConsensusPower(ctx, 200) @@ -291,16 +296,19 @@ func getTestingAccounts(t *testing.T, r *rand.Rand, app *simapp.SimApp, ctx sdk. } func getTestingValidator0(t *testing.T, app *simapp.SimApp, ctx sdk.Context, accounts []simtypes.Account) types.Validator { + t.Helper() commission0 := types.NewCommission(sdk.ZeroDec(), sdk.OneDec(), sdk.OneDec()) return getTestingValidator(t, app, ctx, accounts, commission0, 0) } func getTestingValidator1(t *testing.T, app *simapp.SimApp, ctx sdk.Context, accounts []simtypes.Account) types.Validator { + t.Helper() commission1 := types.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) return getTestingValidator(t, app, ctx, accounts, commission1, 1) } func getTestingValidator(t *testing.T, app *simapp.SimApp, ctx sdk.Context, accounts []simtypes.Account, commission types.Commission, n int) types.Validator { + t.Helper() account := accounts[n] valPubKey := account.PubKey valAddr := sdk.ValAddress(account.PubKey.Address().Bytes()) diff --git a/x/staking/teststaking/helper.go b/x/staking/teststaking/helper.go index 4c1a09806c..62132efa00 100644 --- a/x/staking/teststaking/helper.go +++ b/x/staking/teststaking/helper.go @@ -28,6 +28,7 @@ type Helper struct { // NewHelper creates staking Handler wrapper for tests func NewHelper(t *testing.T, ctx sdk.Context, k keeper.Keeper) *Helper { + t.Helper() return &Helper{t, staking.NewHandler(k), k, ctx, ZeroCommission(), sdk.DefaultBondDenom} } diff --git a/x/staking/teststaking/validator.go b/x/staking/teststaking/validator.go index 76a3d7f92b..319b232929 100644 --- a/x/staking/teststaking/validator.go +++ b/x/staking/teststaking/validator.go @@ -11,8 +11,9 @@ import ( ) // NewValidator is a testing helper method to create validators in tests -func NewValidator(t testing.TB, operator sdk.ValAddress, pubKey cryptotypes.PubKey) types.Validator { +func NewValidator(tb testing.TB, operator sdk.ValAddress, pubKey cryptotypes.PubKey) types.Validator { + tb.Helper() v, err := types.NewValidator(operator, pubKey, types.Description{}) - require.NoError(t, err) + require.NoError(tb, err) return v } diff --git a/x/staking/types/authz.go b/x/staking/types/authz.go index b037710897..aa08bbde4f 100644 --- a/x/staking/types/authz.go +++ b/x/staking/types/authz.go @@ -16,7 +16,7 @@ var ( ) // NewStakeAuthorization creates a new StakeAuthorization object. -func NewStakeAuthorization(allowed []sdk.ValAddress, denied []sdk.ValAddress, authzType AuthorizationType, amount *sdk.Coin) (*StakeAuthorization, error) { +func NewStakeAuthorization(allowed, denied []sdk.ValAddress, authzType AuthorizationType, amount *sdk.Coin) (*StakeAuthorization, error) { allowedValidators, deniedValidators, err := validateAndBech32fy(allowed, denied) if err != nil { return nil, err @@ -115,7 +115,7 @@ func (a StakeAuthorization) Accept(ctx sdk.Context, msg sdk.Msg) (authz.AcceptRe }, nil } -func validateAndBech32fy(allowed []sdk.ValAddress, denied []sdk.ValAddress) ([]string, []string, error) { +func validateAndBech32fy(allowed, denied []sdk.ValAddress) ([]string, []string, error) { if len(allowed) == 0 && len(denied) == 0 { return nil, nil, sdkerrors.ErrInvalidRequest.Wrap("both allowed & deny list cannot be empty") } diff --git a/x/staking/types/authz_test.go b/x/staking/types/authz_test.go index 1bc5094c6c..1063dce831 100644 --- a/x/staking/types/authz_test.go +++ b/x/staking/types/authz_test.go @@ -134,7 +134,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", @@ -266,7 +267,6 @@ func TestAuthzAuthorizations(t *testing.T) { } for _, tc := range testCases { - tc := tc t.Run(tc.msg, func(t *testing.T) { delAuth, err := stakingtypes.NewStakeAuthorization(tc.allowed, tc.denied, tc.msgType, tc.limit) require.NoError(t, err) diff --git a/x/staking/types/data_test.go b/x/staking/types/data_test.go index e4f4a8b046..b364658e09 100644 --- a/x/staking/types/data_test.go +++ b/x/staking/types/data_test.go @@ -14,9 +14,6 @@ var ( pk1Any *codectypes.Any pk2 = ed25519.GenPrivKey().PubKey() pk3 = ed25519.GenPrivKey().PubKey() - addr1, _ = sdk.Bech32ifyAddressBytes(sdk.Bech32PrefixAccAddr, pk1.Address().Bytes()) - addr2, _ = sdk.Bech32ifyAddressBytes(sdk.Bech32PrefixAccAddr, pk2.Address().Bytes()) - addr3, _ = sdk.Bech32ifyAddressBytes(sdk.Bech32PrefixAccAddr, pk3.Address().Bytes()) valAddr1 = sdk.ValAddress(pk1.Address()) valAddr2 = sdk.ValAddress(pk2.Address()) valAddr3 = sdk.ValAddress(pk3.Address()) diff --git a/x/staking/types/expected_keepers.go b/x/staking/types/expected_keepers.go index c6846785ca..61eb13f8e1 100644 --- a/x/staking/types/expected_keepers.go +++ b/x/staking/types/expected_keepers.go @@ -58,7 +58,7 @@ type ValidatorSet interface { TotalBondedTokens(sdk.Context) sdk.Int // total bonded tokens within the validator set StakingTokenSupply(sdk.Context) sdk.Int // total staking token supply - // slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction + // slash the validator and delegators of the validator, specifying offense height, offense power, and slash fraction Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) Jail(sdk.Context, sdk.ConsAddress) // jail a validator Unjail(sdk.Context, sdk.ConsAddress) // unjail a validator diff --git a/x/staking/types/historical_info_test.go b/x/staking/types/historical_info_test.go index 7daf103dc6..dcb29fba3a 100644 --- a/x/staking/types/historical_info_test.go +++ b/x/staking/types/historical_info_test.go @@ -20,6 +20,7 @@ var header = tmproto.Header{ } func createValidators(t *testing.T) []types.Validator { + t.Helper() return []types.Validator{ newValidator(t, valAddr1, pk1), newValidator(t, valAddr2, pk2), @@ -36,7 +37,7 @@ func TestHistoricalInfo(t *testing.T) { require.NotPanics(t, func() { value = legacy.Cdc.MustMarshal(&hi) }) - require.NotNil(t, value, "Marshalled HistoricalInfo is nil") + require.NotNil(t, value, "Marshaled HistoricalInfo is nil") recv, err := types.UnmarshalHistoricalInfo(codec.NewAminoCodec(legacy.Cdc), value) require.Nil(t, err, "Unmarshalling HistoricalInfo failed") @@ -58,9 +59,7 @@ func TestValidateBasic(t *testing.T) { // Ensure validators are not sorted for sort.IsSorted(types.Validators(validators)) { rand.Shuffle(len(validators), func(i, j int) { - it := validators[i] - validators[i] = validators[j] - validators[j] = it + validators[i], validators[j] = validators[j], validators[i] }) } hi = types.HistoricalInfo{ diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index d840c009fa..d1006a3aa3 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -9,7 +9,6 @@ import ( abci "github.com/tendermint/tendermint/abci/types" tmprotocrypto "github.com/tendermint/tendermint/proto/tendermint/crypto" - "gopkg.in/yaml.v2" "github.com/Finschia/finschia-sdk/codec" diff --git a/x/staking/types/validator_test.go b/x/staking/types/validator_test.go index 6a66f5ad54..7f0a296370 100644 --- a/x/staking/types/validator_test.go +++ b/x/staking/types/validator_test.go @@ -260,9 +260,7 @@ func TestValidatorsSortDeterminism(t *testing.T) { // Randomly shuffle validators, sort, and check it is equal to original sort for i := 0; i < 10; i++ { rand.Shuffle(10, func(i, j int) { - it := vals[i] - vals[i] = vals[j] - vals[j] = it + vals[i], vals[j] = vals[j], vals[i] }) types.Validators(vals).Sort() @@ -345,6 +343,7 @@ func mkValidator(tokens int64, shares sdk.Dec) types.Validator { // Creates a new validators and asserts the error check. func newValidator(t *testing.T, operator sdk.ValAddress, pubKey cryptotypes.PubKey) types.Validator { + t.Helper() v, err := types.NewValidator(operator, pubKey, types.Description{}) require.NoError(t, err) return v diff --git a/x/stakingplus/authz_test.go b/x/stakingplus/authz_test.go index 81e7e89c6d..498a46c8d0 100644 --- a/x/stakingplus/authz_test.go +++ b/x/stakingplus/authz_test.go @@ -12,9 +12,9 @@ import ( ) func TestAminoJson(t *testing.T) { - var authority = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - var grantee = sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) - var valAddr = sdk.ValAddress(secp256k1.GenPrivKey().PubKey().Address()) + authority := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) + grantee := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()) + valAddr := sdk.ValAddress(secp256k1.GenPrivKey().PubKey().Address()) src := &CreateValidatorAuthorization{ValidatorAddress: valAddr.String()} expected := fmt.Sprintf("{\"type\":\"lbm-sdk/MsgGrant\",\"value\":{\"authority\":\"%s\",\"authorization\":{\"type\":\"lbm-sdk/CreateValidatorAuthorization\",\"value\":{\"validator_address\":\"%s\"}},\"grantee\":\"%s\"}}", authority.String(), valAddr.String(), grantee.String()) diff --git a/x/stakingplus/keeper/msg_server.go b/x/stakingplus/keeper/msg_server.go index 929a5bbc39..03b9061076 100644 --- a/x/stakingplus/keeper/msg_server.go +++ b/x/stakingplus/keeper/msg_server.go @@ -1,13 +1,12 @@ package keeper import ( - "github.com/Finschia/finschia-sdk/types/errors" - stakingkeeper "github.com/Finschia/finschia-sdk/x/staking/keeper" - stakingtypes "github.com/Finschia/finschia-sdk/x/staking/types" - "context" sdk "github.com/Finschia/finschia-sdk/types" + "github.com/Finschia/finschia-sdk/types/errors" + stakingkeeper "github.com/Finschia/finschia-sdk/x/staking/keeper" + stakingtypes "github.com/Finschia/finschia-sdk/x/staking/types" "github.com/Finschia/finschia-sdk/x/stakingplus" ) diff --git a/x/stakingplus/module/module.go b/x/stakingplus/module/module.go index 0e4d18079c..1ec3ad55e6 100644 --- a/x/stakingplus/module/module.go +++ b/x/stakingplus/module/module.go @@ -7,17 +7,14 @@ import ( abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/codec" - "github.com/Finschia/finschia-sdk/types/module" - codectypes "github.com/Finschia/finschia-sdk/codec/types" sdk "github.com/Finschia/finschia-sdk/types" - - "github.com/Finschia/finschia-sdk/x/stakingplus" - "github.com/Finschia/finschia-sdk/x/stakingplus/keeper" - + "github.com/Finschia/finschia-sdk/types/module" "github.com/Finschia/finschia-sdk/x/staking" stakingkeeper "github.com/Finschia/finschia-sdk/x/staking/keeper" stakingtypes "github.com/Finschia/finschia-sdk/x/staking/types" + "github.com/Finschia/finschia-sdk/x/stakingplus" + "github.com/Finschia/finschia-sdk/x/stakingplus/keeper" ) var ( @@ -37,7 +34,7 @@ func (b AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry stakingplus.RegisterInterfaces(registry) } -//____________________________________________________________________________ +// ____________________________________________________________________________ // AppModule implements an application module for the stakingplus module. type AppModule struct { diff --git a/x/token/client/testutil/query.go b/x/token/client/testutil/query.go index 8f957d4a2f..f28c626923 100644 --- a/x/token/client/testutil/query.go +++ b/x/token/client/testutil/query.go @@ -62,8 +62,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdBalance() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdBalance() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -117,8 +115,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdToken() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdContract() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -192,8 +188,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdGranteeGrants() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdGranteeGrants() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -254,8 +248,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdIsOperatorFor() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdIsOperatorFor() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -314,8 +306,6 @@ func (s *IntegrationTestSuite) TestNewQueryCmdHoldersByOperator() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewQueryCmdHoldersByOperator() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) diff --git a/x/token/client/testutil/suite.go b/x/token/client/testutil/suite.go index 5da8dac7a2..07bc4b8f4a 100644 --- a/x/token/client/testutil/suite.go +++ b/x/token/client/testutil/suite.go @@ -5,7 +5,6 @@ import ( "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" - abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/client/flags" @@ -154,12 +153,8 @@ func (s *IntegrationTestSuite) authorizeOperator(contractID string, holder, oper } func (s *IntegrationTestSuite) pickEvent(events []abci.Event, event proto.Message, fn func(event proto.Message)) { - getType := func(msg proto.Message) string { - return proto.MessageName(msg) - } - for _, e := range events { - if e.Type == getType(event) { + if e.Type == proto.MessageName(event) { msg, err := sdk.ParseTypedEvent(e) s.Require().NoError(err) diff --git a/x/token/client/testutil/tx.go b/x/token/client/testutil/tx.go index e3e6746321..662606d97a 100644 --- a/x/token/client/testutil/tx.go +++ b/x/token/client/testutil/tx.go @@ -62,8 +62,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdSend() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdSend() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -136,8 +134,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdOperatorSend() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdOperatorSend() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -194,8 +190,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdAuthorizeOperator() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdAuthorizeOperator() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -252,8 +246,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdRevokeOperator() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdRevokeOperator() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -318,8 +310,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdIssue() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdIssue() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -379,8 +369,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdGrantPermission() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdGrantPermission() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -437,8 +425,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdRevokePermission() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdRevokePermission() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -498,8 +484,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdMint() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdMint() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -556,8 +540,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdBurn() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdBurn() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -617,8 +599,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdOperatorBurn() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdOperatorBurn() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) @@ -678,8 +658,6 @@ func (s *IntegrationTestSuite) TestNewTxCmdModify() { } for name, tc := range testCases { - tc := tc - s.Run(name, func() { cmd := cli.NewTxCmdModify() out, err := clitestutil.ExecTestCLICmd(val.ClientCtx, cmd, append(tc.args, commonArgs...)) diff --git a/x/token/keeper/grpc_query.go b/x/token/keeper/grpc_query.go index 9da18e4c7a..586c9e1d1f 100644 --- a/x/token/keeper/grpc_query.go +++ b/x/token/keeper/grpc_query.go @@ -27,7 +27,7 @@ func NewQueryServer(keeper Keeper) token.QueryServer { var _ token.QueryServer = queryServer{} -func (s queryServer) addressFromBech32GRPC(address string, context string) (sdk.AccAddress, error) { +func (s queryServer) addressFromBech32GRPC(address, context string) (sdk.AccAddress, error) { addr, err := sdk.AccAddressFromBech32(address) if err != nil { return nil, status.Error(codes.InvalidArgument, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress.Wrap(address), context).Error()) @@ -140,7 +140,7 @@ func (s queryServer) GranteeGrants(c context.Context, req *token.QueryGranteeGra store := ctx.KVStore(s.keeper.storeKey) grantStore := prefix.NewStore(store, grantKeyPrefixByGrantee(req.ContractId, grantee)) var grants []token.Grant - pageRes, err := query.Paginate(grantStore, req.Pagination, func(key []byte, _ []byte) error { + pageRes, err := query.Paginate(grantStore, req.Pagination, func(key, _ []byte) error { permission := token.Permission(key[0]) grants = append(grants, token.Grant{ Grantee: req.Grantee, @@ -196,7 +196,7 @@ func (s queryServer) HoldersByOperator(c context.Context, req *token.QueryHolder store := ctx.KVStore(s.keeper.storeKey) authorizationStore := prefix.NewStore(store, authorizationKeyPrefixByOperator(req.ContractId, operator)) var holders []string - pageRes, err := query.Paginate(authorizationStore, req.Pagination, func(key []byte, value []byte) error { + pageRes, err := query.Paginate(authorizationStore, req.Pagination, func(key, value []byte) error { holder := sdk.AccAddress(key) holders = append(holders, holder.String()) return nil diff --git a/x/token/keeper/msg_server_test.go b/x/token/keeper/msg_server_test.go index 6ca2caeb00..4835d17ad0 100644 --- a/x/token/keeper/msg_server_test.go +++ b/x/token/keeper/msg_server_test.go @@ -621,7 +621,8 @@ func (s *KeeperTestSuite) TestMsgRevokePermission() { {Key: []uint8("grantee"), Value: testutil.W(s.operator), Index: false}, {Key: []uint8("permission"), Value: testutil.W("PERMISSION_MINT"), Index: false}, }, - }}, + }, + }, }, "valid request - revoke BURN": { contractID: s.contractID, @@ -635,7 +636,8 @@ func (s *KeeperTestSuite) TestMsgRevokePermission() { {Key: []uint8("grantee"), Value: testutil.W(s.operator), Index: false}, {Key: []uint8("permission"), Value: testutil.W("PERMISSION_BURN"), Index: false}, }, - }}, + }, + }, }, "valid request - revoke MODIFY": { contractID: s.contractID, @@ -649,7 +651,8 @@ func (s *KeeperTestSuite) TestMsgRevokePermission() { {Key: []uint8("grantee"), Value: testutil.W(s.vendor), Index: false}, {Key: []uint8("permission"), Value: testutil.W("PERMISSION_MODIFY"), Index: false}, }, - }}, + }, + }, }, } @@ -1014,13 +1017,15 @@ func (s *KeeperTestSuite) TestMsgModify() { Owner: s.vendor.String(), Changes: []token.Attribute{{Key: token.AttributeKeyURI.String(), Value: "uri222"}}, }, - expectedEvents: []sdk.Event{{ - Type: "lbm.token.v1.EventModified", - Attributes: []abci.EventAttribute{ - {Key: []byte("changes"), Value: testutil.MustJSONMarshal([]token.Attribute{{Key: token.AttributeKeyURI.String(), Value: "uri222"}}), Index: false}, - {Key: []byte("contract_id"), Value: testutil.W(s.contractID), Index: false}, - {Key: []byte("operator"), Value: testutil.W(s.vendor), Index: false}, - }}, + expectedEvents: []sdk.Event{ + { + Type: "lbm.token.v1.EventModified", + Attributes: []abci.EventAttribute{ + {Key: []byte("changes"), Value: testutil.MustJSONMarshal([]token.Attribute{{Key: token.AttributeKeyURI.String(), Value: "uri222"}}), Index: false}, + {Key: []byte("contract_id"), Value: testutil.W(s.contractID), Index: false}, + {Key: []byte("operator"), Value: testutil.W(s.vendor), Index: false}, + }, + }, }, }, "modify(nonExistingContractId, from, 1) -> error": { diff --git a/x/token/module/module.go b/x/token/module/module.go index b2a057b0b6..2444954654 100644 --- a/x/token/module/module.go +++ b/x/token/module/module.go @@ -72,7 +72,7 @@ func (b AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry token.RegisterInterfaces(registry) } -//____________________________________________________________________________ +// ____________________________________________________________________________ // AppModule implements an application module for the token module. type AppModule struct { @@ -128,7 +128,7 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.Raw // ConsensusVersion implements AppModule/ConsensusVersion. func (AppModule) ConsensusVersion() uint64 { return 1 } -//____________________________________________________________________________ +// ____________________________________________________________________________ // AppModuleSimulation functions diff --git a/x/token/msgs_test.go b/x/token/msgs_test.go index 34e4c41212..4cee77b52b 100644 --- a/x/token/msgs_test.go +++ b/x/token/msgs_test.go @@ -888,7 +888,7 @@ func TestMsgRevokePermission(t *testing.T) { func TestAminoJSON(t *testing.T) { tx := legacytx.StdTx{} - var contractId = "deadbeef" + contractId := "deadbeef" addrs := make([]sdk.AccAddress, 3) for i := range addrs { @@ -1014,8 +1014,6 @@ func TestAminoJSON(t *testing.T) { } for name, tc := range testCases { - tc := tc - t.Run(name, func(t *testing.T) { tx.Msgs = []sdk.Msg{tc.msg} require.Equal(t, token.RouterKey, tc.msg.Route()) diff --git a/x/upgrade/abci_test.go b/x/upgrade/abci_test.go index e78ac83d80..56a7d5ba3e 100644 --- a/x/upgrade/abci_test.go +++ b/x/upgrade/abci_test.go @@ -7,12 +7,11 @@ import ( "testing" "time" - "github.com/stretchr/testify/require" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - ocabci "github.com/Finschia/ostracon/abci/types" "github.com/Finschia/ostracon/libs/log" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/simapp" @@ -29,7 +28,6 @@ import ( type TestSuite struct { module module.BeginBlockAppModule keeper keeper.Keeper - querier sdk.Querier handler govtypes.Handler ctx sdk.Context } @@ -55,7 +53,6 @@ func setupTest(height int64, skip map[int64]bool) TestSuite { s.ctx = app.BaseApp.NewContext(false, tmproto.Header{Height: height, Time: time.Now()}) s.module = upgrade.NewAppModule(s.keeper) - s.querier = s.module.LegacyQuerierHandler(app.LegacyAmino()) s.handler = upgrade.NewSoftwareUpgradeProposalHandler(s.keeper) return s } @@ -96,6 +93,7 @@ func TestCanOverwriteScheduleUpgrade(t *testing.T) { } func VerifyDoUpgrade(t *testing.T) { + t.Helper() t.Log("Verify that a panic happens at the upgrade height") newCtx := s.ctx.WithBlockHeight(s.ctx.BlockHeight() + 1).WithBlockTime(time.Now()) @@ -116,6 +114,7 @@ func VerifyDoUpgrade(t *testing.T) { } func VerifyDoUpgradeWithCtx(t *testing.T, newCtx sdk.Context, proposalName string) { + t.Helper() t.Log("Verify that a panic happens at the upgrade height") req := ocabci.RequestBeginBlock{Header: newCtx.BlockHeader()} require.Panics(t, func() { @@ -170,10 +169,11 @@ func TestHaltIfTooNew(t *testing.T) { } func VerifyCleared(t *testing.T, newCtx sdk.Context) { + t.Helper() t.Log("Verify that the upgrade plan has been cleared") - bz, err := s.querier(newCtx, []string{types.QueryCurrent}, abci.RequestQuery{}) - require.NoError(t, err) - require.Nil(t, bz) + plan, _ := s.keeper.GetUpgradePlan(newCtx) + expected := types.Plan{} + require.Equal(t, plan, expected) } func TestCanClear(t *testing.T) { @@ -222,18 +222,21 @@ func TestPlanStringer(t *testing.T) { } func VerifyNotDone(t *testing.T, newCtx sdk.Context, name string) { + t.Helper() t.Log("Verify that upgrade was not done") height := s.keeper.GetDoneHeight(newCtx, name) require.Zero(t, height) } func VerifyDone(t *testing.T, newCtx sdk.Context, name string) { + t.Helper() t.Log("Verify that the upgrade plan has been executed") height := s.keeper.GetDoneHeight(newCtx, name) require.NotZero(t, height) } func VerifySet(t *testing.T, skipUpgradeHeights map[int64]bool) { + t.Helper() t.Log("Verify if the skip upgrade has been set") for k := range skipUpgradeHeights { diff --git a/x/upgrade/client/cli/tx.go b/x/upgrade/client/cli/tx.go index 1ca4c34865..48eb8ddfc0 100644 --- a/x/upgrade/client/cli/tx.go +++ b/x/upgrade/client/cli/tx.go @@ -123,8 +123,8 @@ func NewCmdSubmitCancelUpgradeProposal() *cobra.Command { cmd.Flags().String(cli.FlagTitle, "", "title of proposal") cmd.Flags().String(cli.FlagDescription, "", "description of proposal") cmd.Flags().String(cli.FlagDeposit, "", "deposit of proposal") - cmd.MarkFlagRequired(cli.FlagTitle) - cmd.MarkFlagRequired(cli.FlagDescription) + _ = cmd.MarkFlagRequired(cli.FlagTitle) + _ = cmd.MarkFlagRequired(cli.FlagDescription) return cmd } diff --git a/x/upgrade/client/testutil/suite.go b/x/upgrade/client/testutil/suite.go index 9a189cde4e..3533b899b1 100644 --- a/x/upgrade/client/testutil/suite.go +++ b/x/upgrade/client/testutil/suite.go @@ -95,7 +95,7 @@ func (s *IntegrationTestSuite) TestModuleVersionsCLI() { } jsonVM, _ := clientCtx.Codec.MarshalJSON(&pm) expectedRes := string(jsonVM) - // append new line to match behaviour of PrintProto + // append new line to match behavior of PrintProto expectedRes += "\n" // get actual module versions list response from cli diff --git a/x/upgrade/doc.go b/x/upgrade/doc.go index 1ba1614c32..ae574f5995 100644 --- a/x/upgrade/doc.go +++ b/x/upgrade/doc.go @@ -117,7 +117,7 @@ specified here https://github.com/cosmos/cosmos-sdk/tree/v0.40.0-rc5/cosmovisor/ This will allow a properly configured cosmsod daemon to auto-download new binaries and auto-upgrade. As noted there, this is intended more for full nodes than validators. -# Cancelling Upgrades +# Canceling Upgrades There are two ways to cancel a planned upgrade - with on-chain governance or off-chain social consensus. For the first one, there is a CancelSoftwareUpgrade proposal type, which can be voted on and will diff --git a/x/upgrade/keeper/grpc_query_test.go b/x/upgrade/keeper/grpc_query_test.go index 6545c174ea..56a7087ca5 100644 --- a/x/upgrade/keeper/grpc_query_test.go +++ b/x/upgrade/keeper/grpc_query_test.go @@ -55,7 +55,8 @@ func (suite *UpgradeTestSuite) TestQueryCurrentPlan() { "with current upgrade plan", func() { plan := types.Plan{Name: "test-plan", Height: 5} - suite.app.UpgradeKeeper.ScheduleUpgrade(suite.ctx, plan) + err := suite.app.UpgradeKeeper.ScheduleUpgrade(suite.ctx, plan) + suite.Require().NoError(err) req = &types.QueryCurrentPlanRequest{} expResponse = types.QueryCurrentPlanResponse{Plan: &plan} @@ -108,7 +109,8 @@ func (suite *UpgradeTestSuite) TestAppliedCurrentPlan() { planName := "test-plan" plan := types.Plan{Name: planName, Height: expHeight} - suite.app.UpgradeKeeper.ScheduleUpgrade(suite.ctx, plan) + err := suite.app.UpgradeKeeper.ScheduleUpgrade(suite.ctx, plan) + suite.Require().NoError(err) suite.ctx = suite.ctx.WithBlockHeight(expHeight) suite.app.UpgradeKeeper.SetUpgradeHandler(planName, func(ctx sdk.Context, plan types.Plan, vm module.VersionMap) (module.VersionMap, error) { diff --git a/x/upgrade/keeper/keeper.go b/x/upgrade/keeper/keeper.go index 568b865f66..65b48ed830 100644 --- a/x/upgrade/keeper/keeper.go +++ b/x/upgrade/keeper/keeper.go @@ -168,7 +168,7 @@ func (k Keeper) getModuleVersion(ctx sdk.Context, name string) (uint64, bool) { // ScheduleUpgrade schedules an upgrade based on the specified plan. // If there is another Plan already scheduled, it will overwrite it -// (implicitly cancelling the current plan) +// (implicitly canceling the current plan) // ScheduleUpgrade will also write the upgraded client to the upgraded client path // if an upgraded client is specified in the plan func (k Keeper) ScheduleUpgrade(ctx sdk.Context, plan types.Plan) error { @@ -376,7 +376,7 @@ func (k Keeper) DumpUpgradeInfoToDisk(height int64, name string) error { // `info` should be provided and contain Plan.Info data in order to support // auto download functionality by cosmovisor and other tools using upgarde-info.json // (GetUpgradeInfoPath()) file. -func (k Keeper) DumpUpgradeInfoWithInfoToDisk(height int64, name string, info string) error { +func (k Keeper) DumpUpgradeInfoWithInfoToDisk(height int64, name, info string) error { upgradeInfoFilePath, err := k.GetUpgradeInfoPath() if err != nil { return err diff --git a/x/upgrade/keeper/keeper_test.go b/x/upgrade/keeper/keeper_test.go index fa7e909f51..56b97db97d 100644 --- a/x/upgrade/keeper/keeper_test.go +++ b/x/upgrade/keeper/keeper_test.go @@ -82,11 +82,12 @@ func (s *KeeperTestSuite) TestScheduleUpgrade() { Height: 123450000, }, setup: func() { - s.app.UpgradeKeeper.ScheduleUpgrade(s.ctx, types.Plan{ + err := s.app.UpgradeKeeper.ScheduleUpgrade(s.ctx, types.Plan{ Name: "alt-good", Info: "new text here", Height: 543210000, }) + s.Require().NoError(err) }, expPass: true, }, @@ -130,8 +131,6 @@ func (s *KeeperTestSuite) TestScheduleUpgrade() { } for _, tc := range cases { - tc := tc - s.Run(tc.name, func() { // reset suite s.SetupTest() @@ -169,7 +168,8 @@ func (s *KeeperTestSuite) TestSetUpgradedClient() { name: "success", height: 10, setup: func() { - s.app.UpgradeKeeper.SetUpgradedClient(s.ctx, 10, cs) + err := s.app.UpgradeKeeper.SetUpgradedClient(s.ctx, 10, cs) + s.Require().NoError(err) }, exists: true, }, @@ -217,7 +217,7 @@ func (s *KeeperTestSuite) TestMigrations() { vmBefore := s.app.UpgradeKeeper.GetModuleVersionMap(s.ctx) s.app.UpgradeKeeper.SetUpgradeHandler("dummy", func(_ sdk.Context, _ types.Plan, vm module.VersionMap) (module.VersionMap, error) { // simulate upgrading the bank module - vm["bank"] = vm["bank"] + 1 + vm["bank"]++ return vm, nil }) dummyPlan := types.Plan{ diff --git a/x/upgrade/keeper/querier.go b/x/upgrade/keeper/querier.go index 887433abff..17a3b2c47f 100644 --- a/x/upgrade/keeper/querier.go +++ b/x/upgrade/keeper/querier.go @@ -3,14 +3,12 @@ package keeper import ( "encoding/binary" - "github.com/Finschia/finschia-sdk/codec" - - "github.com/Finschia/finschia-sdk/x/upgrade/types" - abci "github.com/tendermint/tendermint/abci/types" + "github.com/Finschia/finschia-sdk/codec" sdk "github.com/Finschia/finschia-sdk/types" sdkerrors "github.com/Finschia/finschia-sdk/types/errors" + "github.com/Finschia/finschia-sdk/x/upgrade/types" ) // NewQuerier creates a querier for upgrade cli and REST endpoints diff --git a/x/upgrade/types/plan_test.go b/x/upgrade/types/plan_test.go index 42b7770f13..bc5bdcde5b 100644 --- a/x/upgrade/types/plan_test.go +++ b/x/upgrade/types/plan_test.go @@ -4,12 +4,11 @@ import ( "testing" "time" + "github.com/Finschia/ostracon/libs/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - "github.com/Finschia/ostracon/libs/log" - codectypes "github.com/Finschia/finschia-sdk/codec/types" sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/x/upgrade/types" @@ -45,7 +44,6 @@ func TestPlanString(t *testing.T) { } for name, tc := range cases { - tc := tc // copy to local variable for scopelint t.Run(name, func(t *testing.T) { s := tc.p.String() require.Equal(t, tc.expect, s) @@ -91,7 +89,6 @@ func TestPlanValid(t *testing.T) { } for name, tc := range cases { - tc := tc // copy to local variable for scopelint t.Run(name, func(t *testing.T) { err := tc.p.ValidateBasic() if tc.valid { @@ -140,7 +137,6 @@ func TestShouldExecute(t *testing.T) { } for name, tc := range cases { - tc := tc // copy to local variable for scopelint t.Run(name, func(t *testing.T) { ctx := sdk.NewContext(nil, tmproto.Header{Height: tc.ctxHeight, Time: tc.ctxTime}, false, log.NewNopLogger()) should := tc.p.ShouldExecute(ctx) diff --git a/x/upgrade/types/proposal_test.go b/x/upgrade/types/proposal_test.go index 6a576265c9..174a427200 100644 --- a/x/upgrade/types/proposal_test.go +++ b/x/upgrade/types/proposal_test.go @@ -49,7 +49,6 @@ func TestContentAccessors(t *testing.T) { types.RegisterLegacyAminoCodec(cdc) for name, tc := range cases { - tc := tc // copy to local variable for scopelint t.Run(name, func(t *testing.T) { assert.Equal(t, tc.title, tc.p.GetTitle()) assert.Equal(t, tc.desc, tc.p.GetDescription()) @@ -72,7 +71,6 @@ func TestContentAccessors(t *testing.T) { 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 429baf50c0..caff2532b0 100644 --- a/x/upgrade/types/storeloader_test.go +++ b/x/upgrade/types/storeloader_test.go @@ -6,13 +6,12 @@ import ( "path/filepath" "testing" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/ostracon/libs/log" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - ocabci "github.com/Finschia/ostracon/abci/types" - "github.com/Finschia/ostracon/libs/log" - "github.com/Finschia/finschia-sdk/baseapp" "github.com/Finschia/finschia-sdk/store/rootmulti" store "github.com/Finschia/finschia-sdk/store/types" @@ -30,6 +29,7 @@ func defaultLogger() log.Logger { } func initStore(t *testing.T, db dbm.DB, storeKey string, k, v []byte) { + t.Helper() rs := rootmulti.NewStore(db, log.NewNopLogger()) rs.SetPruning(store.PruneNothing) key := sdk.NewKVStoreKey(storeKey) @@ -47,6 +47,7 @@ func initStore(t *testing.T, db dbm.DB, storeKey string, k, v []byte) { } func checkStore(t *testing.T, db dbm.DB, ver int64, storeKey string, k, v []byte) { + t.Helper() rs := rootmulti.NewStore(db, log.NewNopLogger()) rs.SetPruning(store.PruneNothing) key := sdk.NewKVStoreKey(storeKey) @@ -77,7 +78,7 @@ func TestSetLoader(t *testing.T) { data, err := json.Marshal(upgradeInfo) require.NoError(t, err) - err = os.WriteFile(upgradeInfoFilePath, data, 0o644) + err = os.WriteFile(upgradeInfoFilePath, data, 0o600) require.NoError(t, err) // make sure it exists before running everything @@ -109,7 +110,6 @@ func TestSetLoader(t *testing.T) { v := []byte("value") for name, tc := range cases { - tc := tc t.Run(name, func(t *testing.T) { // prepare a db with some data db := dbm.NewMemDB()