From 888642a14dc0451ed143683047ca20c02231a995 Mon Sep 17 00:00:00 2001 From: Jayden Lee <41176085+tkxkd0159@users.noreply.github.com> Date: Wed, 19 Jun 2024 15:29:11 +0900 Subject: [PATCH] Backport #1171 --- .golangci.yml | 159 +++++++++++++++--- baseapp/abci.go | 6 +- baseapp/abci_test.go | 11 +- baseapp/baseapp.go | 3 +- baseapp/baseapp_test.go | 11 +- baseapp/block_gas_test.go | 2 +- baseapp/deliver_tx_test.go | 9 +- baseapp/grpcrouter_test.go | 3 +- baseapp/queryrouter_test.go | 1 - baseapp/reactor.go | 1 - baseapp/xxx_msg_test.go | 3 +- client/account_retriever.go | 2 +- client/broadcast_test.go | 3 +- client/cmd.go | 3 +- client/config/config_test.go | 14 +- client/context.go | 4 +- client/flags/flags.go | 4 +- client/grpc/ocservice/service.go | 5 +- client/grpc/ocservice/service_test.go | 26 +-- client/grpc/tmservice/block.go | 3 +- client/grpc/tmservice/block_test.go | 6 +- client/grpc/tmservice/service.go | 10 +- client/grpc/tmservice/service_test.go | 18 +- client/keys/add.go | 2 +- client/keys/add_ledger_test.go | 3 +- client/keys/add_test.go | 96 ++++++----- client/keys/delete.go | 4 +- client/keys/export_test.go | 5 +- client/keys/import_test.go | 2 +- client/keys/list_test.go | 6 - client/keys/parse.go | 3 +- client/keys/root.go | 3 +- client/keys/show.go | 3 +- client/keys/show_test.go | 6 +- client/keys/utils_test.go | 3 +- client/query.go | 2 +- client/rpc/validators.go | 3 +- client/test_helpers.go | 2 +- client/tx/legacy_test.go | 1 + client/tx/tx.go | 2 +- client/utils.go | 5 +- client/utils_test.go | 6 +- codec/amino.go | 3 +- codec/amino_codec_test.go | 4 +- codec/any_test.go | 8 +- codec/codec_common_test.go | 4 +- codec/proto_codec.go | 4 +- codec/types/compat.go | 1 - codec/types/interface_registry.go | 1 - codec/unknownproto/benchmarks_test.go | 2 + codec/unknownproto/unknown_fields_test.go | 7 +- codec/yaml_test.go | 3 +- crypto/armor.go | 11 +- crypto/armor_test.go | 7 +- crypto/hd/algo.go | 6 +- crypto/hd/fundraiser_test.go | 6 +- crypto/hd/hdpath.go | 8 +- crypto/hd/hdpath_test.go | 28 +-- crypto/keyring/keyring.go | 8 +- crypto/keyring/keyring_test.go | 5 +- crypto/keyring/types.go | 2 +- crypto/keyring/types_test.go | 2 +- crypto/keys/ed25519/ed25519.go | 21 +-- crypto/keys/ed25519/ed25519_test.go | 9 +- crypto/keys/internal/ecdsa/privkey.go | 2 +- .../internal/ecdsa/privkey_internal_test.go | 11 +- crypto/keys/internal/ecdsa/pubkey.go | 2 +- crypto/keys/multisig/multisig.go | 2 +- crypto/keys/multisig/multisig_test.go | 11 +- crypto/keys/secp256k1/secp256k1.go | 16 +- .../keys/secp256k1/secp256k1_internal_test.go | 4 +- crypto/keys/secp256k1/secp256k1_nocgo.go | 2 +- .../keys/secp256r1/privkey_internal_test.go | 7 +- crypto/keys/secp256r1/pubkey.go | 5 +- crypto/keys/secp256r1/pubkey_internal_test.go | 12 +- crypto/ledger/encode_test.go | 29 ++-- crypto/ledger/ledger_test.go | 1 + crypto/types/types.go | 5 +- server/api/server.go | 9 +- server/cmd/execute.go | 3 +- server/config/config.go | 1 - server/config/toml.go | 5 +- server/export.go | 5 +- server/export_test.go | 5 +- .../grpc/gogoreflection/serverreflection.go | 9 +- server/mock/app.go | 3 +- server/mock/store_test.go | 5 +- server/mock/tx.go | 1 - server/oc_cmds.go | 2 +- server/oc_cmds_test.go | 40 +++-- server/start_test.go | 6 +- server/types/app.go | 2 +- server/util.go | 10 +- server/util_test.go | 28 +-- simapp/app.go | 5 +- simapp/app_test.go | 1 - simapp/export.go | 2 +- simapp/genesis_account_test.go | 7 +- simapp/simd/cmd/root.go | 2 +- simapp/simd/cmd/root_test.go | 3 +- simapp/simd/cmd/testnet.go | 6 +- simapp/test_access.go | 9 +- simapp/test_helpers.go | 9 +- simapp/types.go | 3 +- simapp/utils.go | 3 +- snapshots/helpers_test.go | 20 ++- 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/store.go | 9 +- store/cachekv/store_bench_test.go | 4 + store/cachekv/store_test.go | 10 +- store/dbadapter/store_test.go | 3 +- store/gaskv/store.go | 4 +- store/gaskv/store_test.go | 1 - store/iavl/store.go | 10 +- store/iavl/store_test.go | 25 ++- store/iavl/tree_test.go | 8 +- 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 | 2 +- store/rootmulti/snapshot_test.go | 23 ++- store/rootmulti/store.go | 19 ++- store/rootmulti/store_test.go | 89 ++-------- store/store.go | 3 +- store/streaming/constructor.go | 9 +- store/streaming/file/service.go | 2 +- store/streaming/file/service_test.go | 52 ++++-- store/tracekv/store.go | 9 +- store/tracekv/store_test.go | 1 - store/types/iterator_test.go | 1 + store/types/listening.go | 4 +- store/types/listening_test.go | 6 +- store/types/proof.go | 4 +- store/types/store.go | 3 +- store/types/utils.go | 2 +- store/types/utils_test.go | 1 + testutil/context.go | 2 +- testutil/ioutil.go | 16 +- testutil/network/network.go | 7 + testutil/network/util.go | 6 +- testutil/rest/rest.go | 2 +- types/address.go | 41 +++-- types/address/hash.go | 2 +- types/address/hash_test.go | 3 +- types/address_race_test.go | 3 +- types/address_test.go | 55 +++--- types/bech32/legacybech32/pk_test.go | 1 - types/coin_benchmark_test.go | 6 +- types/context_test.go | 6 - types/decimal.go | 1 + types/decimal_internal_test.go | 6 +- types/decimal_test.go | 6 +- types/denom_internal_test.go | 1 + types/errors/abci_test.go | 4 +- types/errors/errors.go | 4 +- types/events.go | 5 +- types/int.go | 25 +-- types/module/configurator.go | 2 +- types/module/module.go | 1 + types/module/module_int_test.go | 6 +- types/module/module_test.go | 9 +- 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 | 2 +- types/staking.go | 2 +- types/store.go | 2 +- types/store_test.go | 2 - types/tx/types.go | 6 +- types/uint.go | 2 +- version/command.go | 3 +- version/version_test.go | 3 +- x/auth/ante/ante_test.go | 9 +- x/auth/ante/fee_test.go | 3 +- x/auth/ante/sigverify_benchmark_test.go | 3 +- x/auth/ante/sigverify_test.go | 5 +- x/auth/ante/testutil_test.go | 5 +- x/auth/client/cli/query.go | 5 +- x/auth/client/cli/tx_sign.go | 8 +- x/auth/client/testutil/helpers.go | 4 +- x/auth/client/testutil/suite.go | 3 +- x/auth/client/tx_test.go | 5 +- x/auth/keeper/grpc_query.go | 5 +- x/auth/keeper/grpc_query_test.go | 1 + x/auth/keeper/keeper.go | 3 +- x/auth/keeper/querier_test.go | 4 +- x/auth/legacy/legacytx/stdtx_test.go | 9 +- x/auth/legacy/v043/store_test.go | 5 +- x/auth/module.go | 1 - x/auth/signing/handler_map.go | 3 +- x/auth/signing/verify_test.go | 13 +- 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 | 1 + x/auth/tx/legacy_amino_json_test.go | 5 +- x/auth/tx/service.go | 2 +- x/auth/tx/service_test.go | 31 ++-- x/auth/tx/sigs_test.go | 1 - x/auth/tx2/service_test.go | 4 +- x/auth/types/account.go | 3 +- x/auth/types/common_test.go | 6 +- x/auth/vesting/exported/exported.go | 3 +- x/auth/vesting/types/expected_keepers.go | 2 +- x/auth/vesting/types/test_common.go | 1 - x/auth/vesting/types/vesting_account_test.go | 3 +- x/authz/client/testutil/grpc.go | 4 +- x/authz/codec.go | 1 + x/authz/keeper/genesis_test.go | 3 +- x/authz/keeper/grpc_query_test.go | 4 + x/authz/keeper/keeper.go | 16 +- 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 | 2 +- x/authz/simulation/operations.go | 7 +- x/authz/simulation/operations_test.go | 11 +- x/bank/bench_test.go | 3 +- x/bank/keeper/grpc_query_test.go | 1 + x/bank/keeper/keeper_test.go | 21 +-- 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/genesis_test.go | 2 + x/bank/simulation/operations.go | 5 +- x/bank/simulation/operations_test.go | 12 +- x/bank/simulation/params.go | 3 +- x/bank/types/balance_test.go | 1 + x/bank/types/key.go | 2 +- x/bank/types/key_test.go | 2 +- x/bankplus/keeper/inactive.go | 2 - x/bankplus/keeper/inactive_test.go | 8 +- x/bankplus/keeper/keeper.go | 2 +- x/capability/capability_test.go | 3 +- x/capability/genesis_test.go | 2 +- x/capability/keeper/keeper.go | 6 +- x/capability/keeper/keeper_test.go | 5 +- x/capability/module.go | 2 +- x/capability/simulation/genesis_test.go | 2 + x/capability/types/keys_test.go | 2 +- x/collection/client/cli/tx.go | 6 +- x/collection/client/testutil/query.go | 3 +- x/collection/client/testutil/suite.go | 8 +- 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 | 6 +- x/distribution/client/cli/tx_test.go | 9 +- 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/module.go | 4 +- x/distribution/proposal_handler_test.go | 3 +- x/distribution/simulation/genesis_test.go | 2 + x/distribution/simulation/operations.go | 9 +- x/distribution/simulation/operations_test.go | 49 +++--- x/distribution/simulation/params.go | 3 +- x/distribution/types/expected_keepers.go | 4 +- x/distribution/types/querier.go | 2 +- x/evidence/abci.go | 3 +- x/evidence/client/cli/tx.go | 4 +- x/evidence/exported/evidence.go | 3 +- x/evidence/genesis_test.go | 3 +- 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 | 3 +- x/evidence/types/evidence.go | 5 +- x/evidence/types/genesis_test.go | 3 +- x/evidence/types/msgs_test.go | 1 + x/feegrant/filtered_fee_test.go | 9 +- x/feegrant/keeper/grpc_query.go | 4 +- x/feegrant/keeper/keeper.go | 4 +- x/feegrant/keeper/keeper_test.go | 9 +- 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 | 2 +- x/feegrant/simulation/operations.go | 8 +- x/feegrant/simulation/operations_test.go | 6 +- x/foundation/authz_test.go | 3 +- x/foundation/client/cli/tx.go | 3 +- x/foundation/client/testutil/grpc.go | 1 - x/foundation/client/testutil/query.go | 3 +- x/foundation/client/testutil/suite.go | 8 +- x/foundation/foundation_test.go | 9 +- x/foundation/genesis_test.go | 9 +- .../keeper/internal/censorship_test.go | 6 +- x/foundation/keeper/internal/exec.go | 1 - x/foundation/keeper/internal/grpc_query.go | 15 +- 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/treasury_test.go | 8 +- x/foundation/module/module.go | 7 +- x/foundation/msgs_test.go | 7 +- x/genutil/client/cli/collect.go | 3 +- x/genutil/client/cli/gentx.go | 7 +- x/genutil/client/cli/init_test.go | 12 +- x/genutil/client/cli/migrate.go | 3 +- x/genutil/client/cli/validate_genesis.go | 3 +- x/genutil/client/testutil/helpers.go | 3 +- x/genutil/gentx_test.go | 4 +- x/genutil/module.go | 1 - x/genutil/utils.go | 7 +- x/genutil/utils_test.go | 3 +- x/gov/abci_test.go | 2 +- x/gov/client/cli/parse_test.go | 20 +-- x/gov/client/utils/query.go | 4 +- x/gov/client/utils/query_test.go | 6 +- x/gov/common_test.go | 2 + x/gov/genesis_test.go | 6 +- x/gov/keeper/common_test.go | 10 +- x/gov/keeper/deposit_test.go | 4 +- x/gov/keeper/grpc_query.go | 6 +- x/gov/keeper/querier_test.go | 7 + x/gov/keeper/tally.go | 2 +- x/gov/keeper/vote.go | 6 +- x/gov/legacy/v043/store.go | 2 +- x/gov/module.go | 1 - x/gov/simulation/genesis_test.go | 2 + x/gov/simulation/operations.go | 7 +- x/gov/simulation/operations_test.go | 4 +- x/gov/types/proposal.go | 3 +- x/mint/client/testutil/grpc.go | 5 +- x/mint/keeper/querier_test.go | 6 +- x/mint/module.go | 3 +- x/mint/simulation/genesis_test.go | 2 + x/mint/simulation/params.go | 3 +- x/params/client/testutil/suite.go | 3 +- x/params/keeper/keeper_test.go | 6 +- x/params/module.go | 1 - x/params/simulation/operations.go | 2 +- x/params/types/subspace.go | 2 +- x/params/types/subspace_test.go | 2 +- x/simulation/mock_ostracon.go | 1 + x/simulation/operation.go | 2 +- x/simulation/params.go | 3 +- x/simulation/simulate.go | 27 +-- x/simulation/util.go | 1 + x/slashing/app_test.go | 2 + x/slashing/client/testutil/suite.go | 3 +- 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/module.go | 3 +- x/slashing/simulation/genesis_test.go | 2 + x/slashing/simulation/operations.go | 3 +- x/slashing/simulation/operations_test.go | 9 +- x/slashing/types/expected_keepers.go | 2 +- x/staking/app_test.go | 2 + x/staking/bench_test.go | 1 + x/staking/client/cli/tx_test.go | 21 ++- x/staking/client/testutil/suite.go | 3 +- x/staking/client/testutil/test_helpers.go | 5 +- x/staking/genesis.go | 3 +- x/staking/handler_test.go | 30 ++-- x/staking/keeper/common_test.go | 1 + x/staking/keeper/delegation_test.go | 49 +++--- 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/msg_server.go | 2 + x/staking/keeper/querier_test.go | 8 +- x/staking/keeper/slash.go | 2 +- 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 | 2 +- x/staking/module.go | 4 +- x/staking/simulation/decoder_test.go | 10 -- x/staking/simulation/genesis_test.go | 2 + x/staking/simulation/operations.go | 11 +- x/staking/simulation/operations_test.go | 19 ++- x/staking/teststaking/helper.go | 1 + x/staking/teststaking/validator.go | 5 +- x/staking/types/authz.go | 4 +- x/staking/types/authz_test.go | 3 +- 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/msg_test.go | 2 + x/staking/types/validator.go | 1 - x/staking/types/validator_test.go | 8 +- x/stakingplus/authz_test.go | 6 +- x/stakingplus/keeper/msg_server.go | 7 +- x/stakingplus/module/module.go | 14 +- x/token/client/testutil/query.go | 3 +- x/token/client/testutil/suite.go | 7 +- 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 | 2 +- x/upgrade/abci_test.go | 18 +- 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 | 8 +- x/upgrade/keeper/keeper.go | 4 +- x/upgrade/keeper/keeper_test.go | 8 +- x/upgrade/keeper/querier.go | 6 +- x/upgrade/module.go | 3 +- x/upgrade/types/storeloader_test.go | 4 +- 435 files changed, 1797 insertions(+), 1397 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/baseapp/abci.go b/baseapp/abci.go index f347f3ef87..d351ed0210 100644 --- a/baseapp/abci.go +++ b/baseapp/abci.go @@ -23,12 +23,11 @@ import ( "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} @@ -62,7 +61,7 @@ func (app *BaseApp) InitChain(req abci.RequestInitChain) (res abci.ResponseInitC // 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..c4c047ad59 100644 --- a/baseapp/abci_test.go +++ b/baseapp/abci_test.go @@ -140,7 +140,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 +191,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 +220,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..c7a3ed6805 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -9,9 +9,9 @@ import ( "sync" "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" ocabci "github.com/Finschia/ostracon/abci/types" "github.com/Finschia/ostracon/crypto/tmhash" @@ -672,7 +672,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..2ce750c823 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -63,6 +63,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 +133,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 +165,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 +217,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..8d83d660aa 100644 --- a/baseapp/block_gas_test.go +++ b/baseapp/block_gas_test.go @@ -142,7 +142,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..78aadc971a 100644 --- a/baseapp/deliver_tx_test.go +++ b/baseapp/deliver_tx_test.go @@ -869,7 +869,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 +1284,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 +1308,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 +1340,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 +1392,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 +1653,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 +1790,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 +1808,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) diff --git a/baseapp/grpcrouter_test.go b/baseapp/grpcrouter_test.go index 0c89aa21a0..55d4f5a10f 100644 --- a/baseapp/grpcrouter_test.go +++ b/baseapp/grpcrouter_test.go @@ -5,10 +5,11 @@ import ( "os" "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/baseapp" "github.com/Finschia/finschia-sdk/codec/types" "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/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_test.go b/client/broadcast_test.go index a1e62d34e4..e0b758b611 100644 --- a/client/broadcast_test.go +++ b/client/broadcast_test.go @@ -5,12 +5,13 @@ import ( "fmt" "testing" + "github.com/stretchr/testify/require" + "github.com/Finschia/ostracon/crypto/tmhash" "github.com/Finschia/ostracon/mempool" "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/flags" sdkerrors "github.com/Finschia/finschia-sdk/types/errors" diff --git a/client/cmd.go b/client/cmd.go index b53840902d..3bd834bd3b 100644 --- a/client/cmd.go +++ b/client/cmd.go @@ -4,11 +4,12 @@ import ( "fmt" "strings" - "github.com/Finschia/ostracon/libs/cli" "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" + "github.com/Finschia/ostracon/libs/cli" + "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/config/config_test.go b/client/config/config_test.go index 46a1dadc89..d766a800f1 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") diff --git a/client/context.go b/client/context.go index 74cff41775..b48f1d359d 100644 --- a/client/context.go +++ b/client/context.go @@ -6,13 +6,13 @@ import ( "io" "os" + "github.com/gogo/protobuf/proto" + "github.com/pkg/errors" "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/Finschia/finschia-sdk/codec" codectypes "github.com/Finschia/finschia-sdk/codec/types" diff --git a/client/flags/flags.go b/client/flags/flags.go index ce79cdd2be..58bc675752 100644 --- a/client/flags/flags.go +++ b/client/flags/flags.go @@ -95,7 +95,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 +124,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/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..50c2029681 100644 --- a/client/grpc/ocservice/service_test.go +++ b/client/grpc/ocservice/service_test.go @@ -50,7 +50,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 +64,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 +76,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 +87,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 +124,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 +141,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 +158,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 +166,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 +178,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 +213,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 @@ -244,7 +244,7 @@ func (s IntegrationTestSuite) TestLatestValidatorSet_GRPC() { } } -func (s IntegrationTestSuite) TestLatestValidatorSet_GRPCGateway() { +func (s *IntegrationTestSuite) TestLatestValidatorSet_GRPCGateway() { vals := s.network.Validators testCases := []struct { name string @@ -276,7 +276,7 @@ func (s IntegrationTestSuite) TestLatestValidatorSet_GRPCGateway() { } } -func (s IntegrationTestSuite) TestValidatorSetByHeight_GRPC() { +func (s *IntegrationTestSuite) TestValidatorSetByHeight_GRPC() { vals := s.network.Validators testCases := []struct { name string @@ -305,7 +305,7 @@ func (s IntegrationTestSuite) TestValidatorSetByHeight_GRPC() { } } -func (s IntegrationTestSuite) TestValidatorSetByHeight_GRPCGateway() { +func (s *IntegrationTestSuite) TestValidatorSetByHeight_GRPCGateway() { vals := s.network.Validators testCases := []struct { name string diff --git a/client/grpc/tmservice/block.go b/client/grpc/tmservice/block.go index 0d8eac28d0..ae54290462 100644 --- a/client/grpc/tmservice/block.go +++ b/client/grpc/tmservice/block.go @@ -3,9 +3,10 @@ package tmservice import ( "context" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + ocproto "github.com/Finschia/ostracon/proto/ostracon/types" ctypes "github.com/Finschia/ostracon/rpc/core/types" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/Finschia/finschia-sdk/client" ) 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..fa67ef4568 100644 --- a/client/grpc/tmservice/service.go +++ b/client/grpc/tmservice/service.go @@ -3,12 +3,11 @@ package tmservice import ( "context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - gogogrpc "github.com/gogo/protobuf/grpc" "github.com/grpc-ecosystem/grpc-gateway/runtime" tmtypes "github.com/tendermint/tendermint/proto/tendermint/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" octypes "github.com/Finschia/ostracon/proto/ostracon/types" @@ -223,5 +222,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..ff5d1189c3 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 @@ -164,7 +164,7 @@ func (s IntegrationTestSuite) TestLatestValidatorSet_GRPC() { } } -func (s IntegrationTestSuite) TestLatestValidatorSet_GRPCGateway() { +func (s *IntegrationTestSuite) TestLatestValidatorSet_GRPCGateway() { vals := s.network.Validators testCases := []struct { name string @@ -196,7 +196,7 @@ func (s IntegrationTestSuite) TestLatestValidatorSet_GRPCGateway() { } } -func (s IntegrationTestSuite) TestValidatorSetByHeight_GRPC() { +func (s *IntegrationTestSuite) TestValidatorSetByHeight_GRPC() { vals := s.network.Validators testCases := []struct { name string @@ -225,7 +225,7 @@ func (s IntegrationTestSuite) TestValidatorSetByHeight_GRPC() { } } -func (s IntegrationTestSuite) TestValidatorSetByHeight_GRPCGateway() { +func (s *IntegrationTestSuite) TestValidatorSetByHeight_GRPCGateway() { vals := s.network.Validators testCases := []struct { name string 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..c32fdfaf40 100644 --- a/client/keys/add_ledger_test.go +++ b/client/keys/add_ledger_test.go @@ -10,9 +10,10 @@ import ( "io" "testing" - "github.com/Finschia/ostracon/libs/cli" "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" diff --git a/client/keys/add_test.go b/client/keys/add_test.go index dd0bb56298..7550bae324 100644 --- a/client/keys/add_test.go +++ b/client/keys/add_test.go @@ -83,57 +83,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 +153,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) } }) } @@ -314,7 +320,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/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..6a0d4fdf18 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 diff --git a/client/keys/parse.go b/client/keys/parse.go index 5ea2533da0..d92f6648ad 100644 --- a/client/keys/parse.go +++ b/client/keys/parse.go @@ -7,10 +7,11 @@ import ( "io" "strings" - "github.com/Finschia/ostracon/libs/cli" "github.com/spf13/cobra" yaml "gopkg.in/yaml.v2" + "github.com/Finschia/ostracon/libs/cli" + sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/types/bech32" ) diff --git a/client/keys/root.go b/client/keys/root.go index 562161e4cb..18e79cb592 100644 --- a/client/keys/root.go +++ b/client/keys/root.go @@ -1,9 +1,10 @@ package keys import ( - "github.com/Finschia/ostracon/libs/cli" "github.com/spf13/cobra" + "github.com/Finschia/ostracon/libs/cli" + "github.com/Finschia/finschia-sdk/client/flags" ) diff --git a/client/keys/show.go b/client/keys/show.go index 3543f36373..a44abb1bf0 100644 --- a/client/keys/show.go +++ b/client/keys/show.go @@ -4,9 +4,10 @@ import ( "errors" "fmt" - "github.com/Finschia/ostracon/libs/cli" "github.com/spf13/cobra" + "github.com/Finschia/ostracon/libs/cli" + "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/crypto/keyring" "github.com/Finschia/finschia-sdk/crypto/keys/multisig" diff --git a/client/keys/show_test.go b/client/keys/show_test.go index ff73324b39..56394b10bb 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() 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/query.go b/client/query.go index e56b41ec1d..08f79ebbab 100644 --- a/client/query.go +++ b/client/query.go @@ -6,12 +6,12 @@ import ( "strings" "github.com/pkg/errors" + abci "github.com/tendermint/tendermint/abci/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ostbytes "github.com/Finschia/ostracon/libs/bytes" rpcclient "github.com/Finschia/ostracon/rpc/client" - abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/store/rootmulti" sdk "github.com/Finschia/finschia-sdk/types" diff --git a/client/rpc/validators.go b/client/rpc/validators.go index 4b46de5da4..ba2262ca6b 100644 --- a/client/rpc/validators.go +++ b/client/rpc/validators.go @@ -6,9 +6,10 @@ import ( "strconv" "strings" - octypes "github.com/Finschia/ostracon/types" "github.com/spf13/cobra" + octypes "github.com/Finschia/ostracon/types" + "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" cryptocodec "github.com/Finschia/finschia-sdk/crypto/codec" 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/utils.go b/client/utils.go index 6ae575acef..e8e4261a42 100644 --- a/client/utils.go +++ b/client/utils.go @@ -1,9 +1,10 @@ package client import ( - rpchttp "github.com/Finschia/ostracon/rpc/client/http" "github.com/spf13/pflag" + rpchttp "github.com/Finschia/ostracon/rpc/client/http" + "github.com/Finschia/finschia-sdk/client/flags" sdkerrors "github.com/Finschia/finschia-sdk/types/errors" "github.com/Finschia/finschia-sdk/types/query" @@ -57,7 +58,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..840af06fff 100644 --- a/client/utils_test.go +++ b/client/utils_test.go @@ -80,7 +80,6 @@ func TestPaginate(t *testing.T) { } func TestReadPageRequest(t *testing.T) { - testCases := []struct { name string pageKey string @@ -121,10 +120,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.go b/codec/amino.go index d1b050ed8d..e320d73c06 100644 --- a/codec/amino.go +++ b/codec/amino.go @@ -7,9 +7,10 @@ import ( "fmt" "io" - octypes "github.com/Finschia/ostracon/types" amino "github.com/tendermint/go-amino" + octypes "github.com/Finschia/ostracon/types" + "github.com/Finschia/finschia-sdk/codec/types" ) diff --git a/codec/amino_codec_test.go b/codec/amino_codec_test.go index bfd9107f8f..2e305a0686 100644 --- a/codec/amino_codec_test.go +++ b/codec/amino_codec_test.go @@ -126,13 +126,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..dc08f0fb24 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) 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/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/unknown_fields_test.go b/codec/unknownproto/unknown_fields_test.go index 44c490f101..9b14c77287 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" @@ -656,11 +655,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..58aee0b504 100644 --- a/crypto/armor.go +++ b/crypto/armor.go @@ -4,10 +4,11 @@ import ( "encoding/hex" "fmt" + "github.com/tendermint/crypto/bcrypt" + "github.com/Finschia/ostracon/crypto" "github.com/Finschia/ostracon/crypto/armor" "github.com/Finschia/ostracon/crypto/xsalsa20symmetric" - "github.com/tendermint/crypto/bcrypt" "github.com/Finschia/finschia-sdk/codec/legacy" cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" @@ -124,7 +125,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 +144,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 +158,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 +190,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..4808226967 100644 --- a/crypto/armor_test.go +++ b/crypto/armor_test.go @@ -7,11 +7,12 @@ import ( "io" "testing" + "github.com/stretchr/testify/require" + "github.com/tendermint/crypto/bcrypt" + ostcrypto "github.com/Finschia/ostracon/crypto" "github.com/Finschia/ostracon/crypto/armor" "github.com/Finschia/ostracon/crypto/xsalsa20symmetric" - "github.com/stretchr/testify/require" - "github.com/tendermint/crypto/bcrypt" "github.com/Finschia/finschia-sdk/codec/legacy" "github.com/Finschia/finschia-sdk/crypto" @@ -46,7 +47,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/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..25cf2f9ba8 100644 --- a/crypto/hd/fundraiser_test.go +++ b/crypto/hd/fundraiser_test.go @@ -7,10 +7,9 @@ import ( "os" "testing" + "github.com/cosmos/go-bip39" "github.com/stretchr/testify/require" - bip39 "github.com/cosmos/go-bip39" - "github.com/Finschia/ostracon/crypto" "github.com/Finschia/finschia-sdk/crypto/hd" @@ -31,6 +30,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 +77,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..86b0388235 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 = "" @@ -185,7 +185,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 +195,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 +206,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 +245,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 +261,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) // @@ -299,7 +299,7 @@ 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..e286e34b61 100644 --- a/crypto/keyring/keyring.go +++ b/crypto/keyring/keyring.go @@ -16,6 +16,8 @@ import ( "github.com/pkg/errors" "github.com/tendermint/crypto/bcrypt" + occrypto "github.com/Finschia/ostracon/crypto" + "github.com/Finschia/finschia-sdk/client/input" "github.com/Finschia/finschia-sdk/codec/legacy" "github.com/Finschia/finschia-sdk/crypto" @@ -112,7 +114,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 +309,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) } @@ -554,7 +556,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 } 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/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..60a422c88e 100644 --- a/crypto/keys/ed25519/ed25519.go +++ b/crypto/keys/ed25519/ed25519.go @@ -6,9 +6,10 @@ import ( "fmt" "io" + "github.com/hdevalence/ed25519consensus" + "github.com/Finschia/ostracon/crypto" "github.com/Finschia/ostracon/crypto/tmhash" - "github.com/hdevalence/ed25519consensus" "github.com/Finschia/finschia-sdk/codec" cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" @@ -92,12 +93,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 +108,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 +175,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 +202,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 +217,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..b96d154a78 100644 --- a/crypto/keys/ed25519/ed25519_test.go +++ b/crypto/keys/ed25519/ed25519_test.go @@ -5,15 +5,16 @@ import ( "encoding/base64" "testing" - "github.com/Finschia/ostracon/crypto" - osted25519 "github.com/Finschia/ostracon/crypto/ed25519" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/Finschia/ostracon/crypto" + osted25519 "github.com/Finschia/ostracon/crypto/ed25519" + "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 +32,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..a666631ee9 100644 --- a/crypto/keys/internal/ecdsa/privkey_internal_test.go +++ b/crypto/keys/internal/ecdsa/privkey_internal_test.go @@ -7,9 +7,9 @@ import ( "math/big" "testing" - "github.com/Finschia/ostracon/crypto" - "github.com/stretchr/testify/suite" + + "github.com/Finschia/ostracon/crypto" ) func TestSKSuite(t *testing.T) { @@ -40,10 +40,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 +93,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/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..3255439a24 100644 --- a/crypto/keys/secp256k1/secp256k1.go +++ b/crypto/keys/secp256k1/secp256k1.go @@ -53,12 +53,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 +68,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 +179,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 +194,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..65e87c8eb5 100644 --- a/crypto/keys/secp256k1/secp256k1_internal_test.go +++ b/crypto/keys/secp256k1/secp256k1_internal_test.go @@ -36,8 +36,8 @@ func Test_genPrivKey(t *testing.T) { return } got := genPrivKey(bytes.NewReader(tt.notSoRand)) - fe := new(big.Int).SetBytes(got[:]) - require.True(t, fe.Cmp(btcSecp256k1.S256().N) < 0) + fe := new(big.Int).SetBytes(got) + require.True(t, fe.Cmp(secp.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..b2eae1f115 100644 --- a/crypto/keys/secp256k1/secp256k1_nocgo.go +++ b/crypto/keys/secp256k1/secp256k1_nocgo.go @@ -31,7 +31,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/secp256r1/privkey_internal_test.go b/crypto/keys/secp256r1/privkey_internal_test.go index 227baa6afb..f43de87771 100644 --- a/crypto/keys/secp256r1/privkey_internal_test.go +++ b/crypto/keys/secp256r1/privkey_internal_test.go @@ -6,10 +6,11 @@ import ( "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" + "github.com/Finschia/ostracon/crypto" + "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 +52,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 +60,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..6d02432839 100644 --- a/crypto/keys/secp256r1/pubkey.go +++ b/crypto/keys/secp256r1/pubkey.go @@ -1,9 +1,10 @@ package secp256r1 import ( - tmcrypto "github.com/Finschia/ostracon/crypto" "github.com/gogo/protobuf/proto" + tmcrypto "github.com/Finschia/ostracon/crypto" + ecdsa "github.com/Finschia/finschia-sdk/crypto/keys/internal/ecdsa" cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" ) @@ -41,7 +42,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_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/types.go b/crypto/types/types.go index 09746f5a2f..5519ee5e30 100644 --- a/crypto/types/types.go +++ b/crypto/types/types.go @@ -1,8 +1,9 @@ package types import ( - occrypto "github.com/Finschia/ostracon/crypto" proto "github.com/gogo/protobuf/proto" + + occrypto "github.com/Finschia/ostracon/crypto" ) // PubKey defines a public key and extends proto.Message. @@ -11,7 +12,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..16f75c452c 100644 --- a/server/api/server.go +++ b/server/api/server.go @@ -18,13 +18,12 @@ import ( 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 +58,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 +75,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/cmd/execute.go b/server/cmd/execute.go index bca3ae5218..acd4ecbd84 100644 --- a/server/cmd/execute.go +++ b/server/cmd/execute.go @@ -3,9 +3,10 @@ package cmd import ( "context" + "github.com/spf13/cobra" + ostcfg "github.com/Finschia/ostracon/config" ostcli "github.com/Finschia/ostracon/libs/cli" - "github.com/spf13/cobra" "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" 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..abd0b1e97f 100644 --- a/server/config/toml.go +++ b/server/config/toml.go @@ -4,8 +4,9 @@ import ( "bytes" "text/template" - ostos "github.com/Finschia/ostracon/libs/os" "github.com/spf13/viper" + + ostos "github.com/Finschia/ostracon/libs/os" ) const DefaultConfigTemplate = `# This is a TOML config file. @@ -236,5 +237,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..fd9bbfeb3f 100644 --- a/server/export.go +++ b/server/export.go @@ -6,11 +6,12 @@ import ( "fmt" "os" - ostjson "github.com/Finschia/ostracon/libs/json" - octypes "github.com/Finschia/ostracon/types" "github.com/spf13/cobra" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + ostjson "github.com/Finschia/ostracon/libs/json" + octypes "github.com/Finschia/ostracon/types" + "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/server/types" sdk "github.com/Finschia/finschia-sdk/types" diff --git a/server/export_test.go b/server/export_test.go index db08cc37c3..526dde07de 100644 --- a/server/export_test.go +++ b/server/export_test.go @@ -12,14 +12,14 @@ import ( "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" 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" - abci "github.com/tendermint/tendermint/abci/types" - dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" @@ -123,6 +123,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..3ce667d9fe 100644 --- a/server/grpc/gogoreflection/serverreflection.go +++ b/server/grpc/gogoreflection/serverreflection.go @@ -46,7 +46,6 @@ import ( "sort" "sync" - //nolint: staticcheck "github.com/golang/protobuf/proto" dpb "github.com/golang/protobuf/protoc-gen-go/descriptor" "google.golang.org/grpc" @@ -290,8 +289,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 +323,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 +348,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 { diff --git a/server/mock/app.go b/server/mock/app.go index d8ddf0616e..545005b49c 100644 --- a/server/mock/app.go +++ b/server/mock/app.go @@ -7,10 +7,11 @@ import ( "fmt" "path/filepath" + abci "github.com/tendermint/tendermint/abci/types" + ocabci "github.com/Finschia/ostracon/abci/types" "github.com/Finschia/ostracon/libs/log" "github.com/Finschia/ostracon/types" - abci "github.com/tendermint/tendermint/abci/types" bam "github.com/Finschia/finschia-sdk/baseapp" "github.com/Finschia/finschia-sdk/codec" 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..79a16ce8e8 100644 --- a/server/oc_cmds.go +++ b/server/oc_cmds.go @@ -95,7 +95,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..99813ee0cc 100644 --- a/server/oc_cmds_test.go +++ b/server/oc_cmds_test.go @@ -3,8 +3,8 @@ package server import ( "bytes" "context" + "errors" "fmt" - "io/ioutil" "os" "testing" @@ -22,9 +22,7 @@ import ( tmtime "github.com/Finschia/ostracon/types/time" ) -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 +30,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); 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 +55,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 +76,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 +96,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); 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 +111,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 +119,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 +136,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 +204,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/start_test.go b/server/start_test.go index 2cd2fe012b..ae7a1f5be9 100644 --- a/server/start_test.go +++ b/server/start_test.go @@ -1,10 +1,12 @@ package server import ( - "github.com/Finschia/ostracon/config" - "github.com/stretchr/testify/assert" "os" "testing" + + "github.com/stretchr/testify/assert" + + "github.com/Finschia/ostracon/config" ) func TestGenPvFileOnlyWhenKmsAddressEmptyGenerateFiles(t *testing.T) { diff --git a/server/types/app.go b/server/types/app.go index 21a1a8d589..5768a57ea5 100644 --- a/server/types/app.go +++ b/server/types/app.go @@ -6,12 +6,12 @@ import ( "github.com/gogo/protobuf/grpc" "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/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" - abci "github.com/tendermint/tendermint/abci/types" "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..033bc800cb 100644 --- a/server/util.go +++ b/server/util.go @@ -24,6 +24,10 @@ import ( dbm "github.com/tendermint/tm-db" "golang.org/x/sync/errgroup" + ostcmd "github.com/Finschia/ostracon/cmd/ostracon/commands" + ostcfg "github.com/Finschia/ostracon/config" + ostlog "github.com/Finschia/ostracon/libs/log" + "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/server/config" "github.com/Finschia/finschia-sdk/server/types" @@ -67,7 +71,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 +99,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 diff --git a/server/util_test.go b/server/util_test.go index 7899c7947f..aa1124a9cd 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); 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); 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); 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); err != errCancelledInPreRun { t.Fatalf("function failed with [%T] %v", err, err) } @@ -216,7 +216,7 @@ func TestInterceptConfigsPreRunHandlerReadsEnvVars(t *testing.T) { serverCtx := &Context{} ctx := context.WithValue(context.Background(), ServerContextKey, serverCtx) - if err := cmd.ExecuteContext(ctx); err != cancelledInPreRun { + if err := cmd.ExecuteContext(ctx); err != errCancelledInPreRun { t.Fatalf("function failed with [%T] %v", err, err) } @@ -245,6 +245,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 +286,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 +322,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); err != errCancelledInPreRun { t.Fatalf("function failed with [%T] %v", err, err) } @@ -336,7 +338,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); err != errCancelledInPreRun { t.Fatalf("function failed with [%T] %v", err, err) } @@ -352,7 +354,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); err != errCancelledInPreRun { t.Fatalf("function failed with [%T] %v", err, err) } @@ -368,11 +370,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); 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..c706c93dd8 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -20,6 +20,8 @@ import ( "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 +111,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..b1e34532a2 100644 --- a/simapp/app_test.go +++ b/simapp/app_test.go @@ -7,7 +7,6 @@ import ( "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" 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..a0897141e2 100644 --- a/simapp/genesis_account_test.go +++ b/simapp/genesis_account_test.go @@ -4,13 +4,14 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + + "github.com/Finschia/ostracon/crypto" + "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) { diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 89133376a7..161e6c22bd 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -9,10 +9,10 @@ import ( "github.com/spf13/cast" "github.com/spf13/cobra" "github.com/spf13/viper" + dbm "github.com/tendermint/tm-db" 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" "github.com/Finschia/finschia-sdk/client" diff --git a/simapp/simd/cmd/root_test.go b/simapp/simd/cmd/root_test.go index 8ac22f33d3..9644c1051f 100644 --- a/simapp/simd/cmd/root_test.go +++ b/simapp/simd/cmd/root_test.go @@ -6,11 +6,11 @@ import ( "testing" "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tm-db" "github.com/Finschia/ostracon/libs/log" octypes "github.com/Finschia/ostracon/types" - abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/server" @@ -87,5 +87,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..c70b73084e 100644 --- a/simapp/simd/cmd/testnet.go +++ b/simapp/simd/cmd/testnet.go @@ -384,16 +384,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/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..34dac4cdc0 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -98,7 +98,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 +347,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 +370,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 +383,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 +437,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 +471,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/types.go b/simapp/types.go index 1f0314978f..d1d641f788 100644 --- a/simapp/types.go +++ b/simapp/types.go @@ -1,9 +1,10 @@ package simapp import ( - ocabci "github.com/Finschia/ostracon/abci/types" abci "github.com/tendermint/tendermint/abci/types" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/finschia-sdk/codec" "github.com/Finschia/finschia-sdk/server/types" sdk "github.com/Finschia/finschia-sdk/types" diff --git a/simapp/utils.go b/simapp/utils.go index 4324b1e1e3..5d03f4b8a7 100644 --- a/simapp/utils.go +++ b/simapp/utils.go @@ -5,9 +5,10 @@ import ( "fmt" "os" - "github.com/Finschia/ostracon/libs/log" dbm "github.com/tendermint/tm-db" + "github.com/Finschia/ostracon/libs/log" + "github.com/Finschia/finschia-sdk/codec" "github.com/Finschia/finschia-sdk/simapp/helpers" sdk "github.com/Finschia/finschia-sdk/types" diff --git a/snapshots/helpers_test.go b/snapshots/helpers_test.go index 21965edd80..12d0be6bfc 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 @@ -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/store.go b/store/cachekv/store.go index 0b8203c670..dcfe546547 100644 --- a/store/cachekv/store.go +++ b/store/cachekv/store.go @@ -74,7 +74,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 +368,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 +398,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..96c8951127 100644 --- a/store/cachekv/store_test.go +++ b/store/cachekv/store_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" ostrand "github.com/Finschia/ostracon/libs/rand" - dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/store/cachekv" "github.com/Finschia/finschia-sdk/store/dbadapter" @@ -326,6 +326,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 +352,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 +382,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 +395,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 +427,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 +437,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 +453,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 +462,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..147591a8b9 100644 --- a/store/iavl/store.go +++ b/store/iavl/store.go @@ -200,7 +200,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 +229,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..3393e00c0e 100644 --- a/store/iavl/store_test.go +++ b/store/iavl/store_test.go @@ -7,10 +7,10 @@ import ( "github.com/cosmos/iavl" "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tm-db" "github.com/Finschia/ostracon/libs/log" - abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/store/cachekv" "github.com/Finschia/finschia-sdk/store/types" @@ -34,17 +34,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 +124,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 +300,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 +485,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 +603,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) 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/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..f44e6f706c 100644 --- a/store/rootmulti/proof_test.go +++ b/store/rootmulti/proof_test.go @@ -4,10 +4,10 @@ import ( "testing" "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tm-db" "github.com/Finschia/ostracon/libs/log" - abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/store/iavl" "github.com/Finschia/finschia-sdk/store/types" diff --git a/store/rootmulti/snapshot_test.go b/store/rootmulti/snapshot_test.go index 49fe681df5..8f0df40681 100644 --- a/store/rootmulti/snapshot_test.go +++ b/store/rootmulti/snapshot_test.go @@ -10,16 +10,17 @@ import ( "math/rand" "testing" - "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/ostracon/libs/log" "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 +33,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 +53,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 +67,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 +102,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{} @@ -224,6 +235,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 +271,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..c293a7c53c 100644 --- a/store/rootmulti/store.go +++ b/store/rootmulti/store.go @@ -311,7 +311,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() { @@ -670,7 +670,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) } @@ -1055,7 +1055,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 +1067,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 +1081,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..f3a293a92f 100644 --- a/store/rootmulti/store_test.go +++ b/store/rootmulti/store_test.go @@ -2,18 +2,15 @@ package rootmulti import ( "bytes" - "encoding/binary" "fmt" - "math/rand" "testing" "time" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tm-db" "github.com/Finschia/ostracon/libs/log" - abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/codec" codecTypes "github.com/Finschia/finschia-sdk/codec/types" @@ -484,7 +481,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) @@ -577,32 +574,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 +627,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 +670,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 +682,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 +785,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 +807,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/store.go b/store/store.go index aa43a22833..858e63509b 100644 --- a/store/store.go +++ b/store/store.go @@ -1,9 +1,10 @@ package store import ( - "github.com/Finschia/ostracon/libs/log" dbm "github.com/tendermint/tm-db" + "github.com/Finschia/ostracon/libs/log" + "github.com/Finschia/finschia-sdk/store/cache" "github.com/Finschia/finschia-sdk/store/rootmulti" "github.com/Finschia/finschia-sdk/store/types" 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..4ef1affe0a 100644 --- a/store/streaming/file/service.go +++ b/store/streaming/file/service.go @@ -26,7 +26,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..9414422007 100644 --- a/store/streaming/file/service_test.go +++ b/store/streaming/file/service_test.go @@ -107,13 +107,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 +129,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 +143,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 +213,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 +271,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 +329,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/iterator_test.go b/store/types/iterator_test.go index 0f6582baff..2ce1344006 100644 --- a/store/types/iterator_test.go +++ b/store/types/iterator_test.go @@ -13,6 +13,7 @@ import ( ) 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) 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..10f3a787e7 100644 --- a/store/types/proof.go +++ b/store/types/proof.go @@ -1,10 +1,10 @@ package types import ( + ics23 "github.com/confio/ics23/go" tmmerkle "github.com/tendermint/tendermint/proto/tendermint/crypto" "github.com/Finschia/ostracon/crypto/merkle" - ics23 "github.com/confio/ics23/go" sdkerrors "github.com/Finschia/finschia-sdk/types/errors" ) @@ -48,7 +48,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.go b/store/types/store.go index 9fc6961a82..b61b74899f 100644 --- a/store/types/store.go +++ b/store/types/store.go @@ -4,10 +4,11 @@ import ( "fmt" "io" - oststrings "github.com/Finschia/ostracon/libs/strings" abci "github.com/tendermint/tendermint/abci/types" dbm "github.com/tendermint/tm-db" + oststrings "github.com/Finschia/ostracon/libs/strings" + snapshottypes "github.com/Finschia/finschia-sdk/snapshots/types" "github.com/Finschia/finschia-sdk/types/kv" ) 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..2e0ff5e78c 100644 --- a/store/types/utils_test.go +++ b/store/types/utils_test.go @@ -14,6 +14,7 @@ import ( ) 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..03d61acac3 100644 --- a/testutil/context.go +++ b/testutil/context.go @@ -11,7 +11,7 @@ import ( ) // 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..095fd16800 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -13,6 +13,10 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" + "google.golang.org/grpc" + ostcfg "github.com/Finschia/ostracon/config" "github.com/Finschia/ostracon/libs/log" ostrand "github.com/Finschia/ostracon/libs/rand" @@ -170,6 +174,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 +403,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 +430,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/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_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..61bf36318e 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()), @@ -437,25 +448,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 +503,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/context_test.go b/types/context_test.go index cc106e99bf..5688cfe61f 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 diff --git a/types/decimal.go b/types/decimal.go index 3ebdb5c727..8be1f3820f 100644 --- a/types/decimal.go +++ b/types/decimal.go @@ -807,5 +807,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..9aa31affe1 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) @@ -75,7 +75,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..6c1e50ab4d 100644 --- a/types/decimal_test.go +++ b/types/decimal_test.go @@ -606,10 +606,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_test.go b/types/errors/abci_test.go index 996e9c34e5..13e7c8455c 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, 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/int.go b/types/int.go index a13e19aa0a..b18be80776 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) } @@ -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/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..182c4a114f 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -35,6 +35,7 @@ import ( "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" ocabci "github.com/Finschia/ostracon/abci/types" abci "github.com/tendermint/tendermint/abci/types" 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..c058daaa23 100644 --- a/types/module/module_test.go +++ b/types/module/module_test.go @@ -5,16 +5,15 @@ 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" + ocabci "github.com/Finschia/ostracon/abci/types" + "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 +28,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..1b9a5bb0cd 100644 --- a/types/result.go +++ b/types/result.go @@ -7,9 +7,9 @@ import ( "strings" "github.com/gogo/protobuf/proto" + abci "github.com/tendermint/tendermint/abci/types" ctypes "github.com/Finschia/ostracon/rpc/core/types" - abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/codec" codectypes "github.com/Finschia/finschia-sdk/codec/types" 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..90ed92030d 100644 --- a/types/store_test.go +++ b/types/store_test.go @@ -64,8 +64,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..5e59780e76 100644 --- a/types/uint.go +++ b/types/uint.go @@ -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/version/command.go b/version/command.go index 6e6a0ab944..ed4bf0b935 100644 --- a/version/command.go +++ b/version/command.go @@ -4,9 +4,10 @@ import ( "encoding/json" "strings" - "github.com/Finschia/ostracon/libs/cli" "github.com/spf13/cobra" yaml "gopkg.in/yaml.v2" + + "github.com/Finschia/ostracon/libs/cli" ) const flagLong = "long" diff --git a/version/version_test.go b/version/version_test.go index 0bfe235496..9bf95efae6 100644 --- a/version/version_test.go +++ b/version/version_test.go @@ -6,10 +6,11 @@ import ( "runtime" "testing" - "github.com/Finschia/ostracon/libs/cli" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/Finschia/ostracon/libs/cli" + "github.com/Finschia/finschia-sdk/testutil" "github.com/Finschia/finschia-sdk/version" ) 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/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_benchmark_test.go b/x/auth/ante/sigverify_benchmark_test.go index 581c5554a5..1374cbe875 100644 --- a/x/auth/ante/sigverify_benchmark_test.go +++ b/x/auth/ante/sigverify_benchmark_test.go @@ -3,9 +3,10 @@ package ante_test import ( "testing" - tmcrypto "github.com/Finschia/ostracon/crypto" "github.com/stretchr/testify/require" + tmcrypto "github.com/Finschia/ostracon/crypto" + "github.com/Finschia/finschia-sdk/crypto/keys/secp256k1" "github.com/Finschia/finschia-sdk/crypto/keys/secp256r1" ) 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..28f721d9d5 100644 --- a/x/auth/client/cli/query.go +++ b/x/auth/client/cli/query.go @@ -5,9 +5,10 @@ import ( "fmt" "strings" - octypes "github.com/Finschia/ostracon/types" "github.com/spf13/cobra" + octypes "github.com/Finschia/ostracon/types" + "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" sdk "github.com/Finschia/finschia-sdk/types" @@ -246,7 +247,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..8a4e06238d 100644 --- a/x/auth/client/testutil/suite.go +++ b/x/auth/client/testutil/suite.go @@ -1429,10 +1429,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_test.go b/x/auth/client/tx_test.go index 5a4ada8a6a..de086fe19b 100644 --- a/x/auth/client/tx_test.go +++ b/x/auth/client/tx_test.go @@ -137,9 +137,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/keeper.go b/x/auth/keeper/keeper.go index 7944f9a140..df8088e9de 100644 --- a/x/auth/keeper/keeper.go +++ b/x/auth/keeper/keeper.go @@ -3,9 +3,10 @@ package keeper import ( "fmt" - "github.com/Finschia/ostracon/libs/log" gogotypes "github.com/gogo/protobuf/types" + "github.com/Finschia/ostracon/libs/log" + "github.com/Finschia/finschia-sdk/codec" cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" sdk "github.com/Finschia/finschia-sdk/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..f6fb1c91a7 100644 --- a/x/auth/legacy/legacytx/stdtx_test.go +++ b/x/auth/legacy/legacytx/stdtx_test.go @@ -13,7 +13,6 @@ import ( 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 +30,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 +206,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..2d72024791 100644 --- a/x/auth/legacy/v043/store_test.go +++ b/x/auth/legacy/v043/store_test.go @@ -578,8 +578,8 @@ func TestMigrateVestingAccounts(t *testing.T) { } trackingCorrected( - ctx, t, + ctx, app.AccountKeeper, savedAccount.GetAddress(), expVested, @@ -589,7 +589,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 +646,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/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..9c546cdb5e 100644 --- a/x/auth/tx/encode_decode_test.go +++ b/x/auth/tx/encode_decode_test.go @@ -171,6 +171,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, 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..8089f74fee 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. @@ -158,7 +158,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 +199,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 +278,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 +353,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 +381,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 +433,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()) @@ -474,7 +474,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 +535,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 +551,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 +595,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 +608,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 +646,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 +698,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 +742,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.go b/x/auth/types/account.go index ac6f977080..bbac1f74dc 100644 --- a/x/auth/types/account.go +++ b/x/auth/types/account.go @@ -7,10 +7,11 @@ import ( "fmt" "strings" - "github.com/Finschia/ostracon/crypto" "github.com/gogo/protobuf/proto" "gopkg.in/yaml.v2" + "github.com/Finschia/ostracon/crypto" + "github.com/Finschia/finschia-sdk/codec" codectypes "github.com/Finschia/finschia-sdk/codec/types" cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" 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/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/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..51dc5940db 100644 --- a/x/auth/vesting/types/vesting_account_test.go +++ b/x/auth/vesting/types/vesting_account_test.go @@ -4,9 +4,10 @@ import ( "testing" "time" - osttime "github.com/Finschia/ostracon/types/time" "github.com/stretchr/testify/require" + osttime "github.com/Finschia/ostracon/types/time" + "github.com/Finschia/finschia-sdk/crypto/keys/secp256k1" "github.com/Finschia/finschia-sdk/testutil/testdata" sdk "github.com/Finschia/finschia-sdk/types" diff --git a/x/authz/client/testutil/grpc.go b/x/authz/client/testutil/grpc.go index 6f2c393f5a..7b5bbb6adf 100644 --- a/x/authz/client/testutil/grpc.go +++ b/x/authz/client/testutil/grpc.go @@ -71,7 +71,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()) } @@ -157,7 +158,6 @@ func (s *IntegrationTestSuite) TestQueryGrantsGRPC() { s.Require().NoError(err) tc.postRun(&authorizations) } - }) } } 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/grpc_query_test.go b/x/authz/keeper/grpc_query_test.go index a65c48e83b..efc5b1226a 100644 --- a/x/authz/keeper/grpc_query_test.go +++ b/x/authz/keeper/grpc_query_test.go @@ -228,6 +228,8 @@ func (suite *TestSuite) TestGRPCQueryGranterGrants() { } for _, tc := range testCases { + tc := tc + suite.Run(fmt.Sprintf("Case %s", tc.msg), func() { tc.preRun() result, err := queryClient.GranterGrants(gocontext.Background(), &tc.request) @@ -313,6 +315,8 @@ func (suite *TestSuite) TestGRPCQueryGranteeGrants() { } for _, tc := range testCases { + tc := tc + suite.Run(fmt.Sprintf("Case %s", tc.msg), func() { tc.preRun() result, err := queryClient.GranteeGrants(gocontext.Background(), &tc.request) diff --git a/x/authz/keeper/keeper.go b/x/authz/keeper/keeper.go index aec81fb22f..02e0fe09c5 100644 --- a/x/authz/keeper/keeper.go +++ b/x/authz/keeper/keeper.go @@ -6,9 +6,9 @@ import ( "time" "github.com/gogo/protobuf/proto" + abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/ostracon/libs/log" - abci "github.com/tendermint/tendermint/abci/types" "github.com/Finschia/finschia-sdk/baseapp" "github.com/Finschia/finschia-sdk/codec" @@ -49,7 +49,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 +58,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 +162,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 +178,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 +194,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 +211,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/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..fc43ef917d 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}}, }, } 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..0cbbb53903 100644 --- a/x/authz/simulation/operations_test.go +++ b/x/authz/simulation/operations_test.go @@ -106,7 +106,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 +145,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 +180,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..1dcbb7e031 100644 --- a/x/bank/bench_test.go +++ b/x/bank/bench_test.go @@ -12,7 +12,6 @@ import ( "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 +26,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/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_test.go b/x/bank/keeper/keeper_test.go index 2c91672454..2967382432 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -192,15 +192,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 +288,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 +314,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 +1128,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 +1140,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/genesis_test.go b/x/bank/simulation/genesis_test.go index efbdf4cf42..40d9afe119 100644 --- a/x/bank/simulation/genesis_test.go +++ b/x/bank/simulation/genesis_test.go @@ -70,6 +70,8 @@ func TestRandomizedGenState1(t *testing.T) { } for _, tt := range tests { + tt := tt + require.Panicsf(t, func() { simulation.RandomizedGenState(&tt.simState) }, tt.panicMsg) } } 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..160e775d3a 100644 --- a/x/bank/simulation/operations_test.go +++ b/x/bank/simulation/operations_test.go @@ -80,7 +80,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 +110,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 +149,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 +180,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..b18a0f7b13 100644 --- a/x/bank/types/balance_test.go +++ b/x/bank/types/balance_test.go @@ -191,6 +191,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/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..54a2ee64a9 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) 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..90dde7d516 100644 --- a/x/bankplus/keeper/inactive_test.go +++ b/x/bankplus/keeper/inactive_test.go @@ -1,7 +1,7 @@ package keeper import ( - "math/rand" + "crypto/rand" "testing" "github.com/stretchr/testify/require" @@ -22,7 +22,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 +44,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/capability/capability_test.go b/x/capability/capability_test.go index ae48072ce0..d85efc602b 100644 --- a/x/capability/capability_test.go +++ b/x/capability/capability_test.go @@ -6,6 +6,8 @@ import ( "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/codec" "github.com/Finschia/finschia-sdk/simapp" sdk "github.com/Finschia/finschia-sdk/types" @@ -14,7 +16,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..1f7f4d72ba 100644 --- a/x/capability/genesis_test.go +++ b/x/capability/genesis_test.go @@ -1,10 +1,10 @@ package capability_test import ( + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" "github.com/Finschia/ostracon/libs/log" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "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..736cdf4164 100644 --- a/x/capability/module.go +++ b/x/capability/module.go @@ -8,9 +8,9 @@ import ( "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" + 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/client" "github.com/Finschia/finschia-sdk/codec" diff --git a/x/capability/simulation/genesis_test.go b/x/capability/simulation/genesis_test.go index 46b2687b50..ab49833f1d 100644 --- a/x/capability/simulation/genesis_test.go +++ b/x/capability/simulation/genesis_test.go @@ -66,6 +66,8 @@ func TestRandomizedGenState1(t *testing.T) { } for _, tt := range tests { + tt := tt + require.Panicsf(t, func() { simulation.RandomizedGenState(&tt.simState) }, tt.panicMsg) } } 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..3cc43b2308 100644 --- a/x/collection/client/testutil/query.go +++ b/x/collection/client/testutil/query.go @@ -3,9 +3,10 @@ package testutil import ( "fmt" - ostcli "github.com/Finschia/ostracon/libs/cli" "github.com/gogo/protobuf/proto" + ostcli "github.com/Finschia/ostracon/libs/cli" + "github.com/Finschia/finschia-sdk/client/flags" codectypes "github.com/Finschia/finschia-sdk/codec/types" clitestutil "github.com/Finschia/finschia-sdk/testutil/cli" 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/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..9f8ebba60d 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 { 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/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/module.go b/x/distribution/module.go index b2fc955f6c..4b320a4894 100644 --- a/x/distribution/module.go +++ b/x/distribution/module.go @@ -7,11 +7,11 @@ import ( "math/rand" "github.com/grpc-ecosystem/grpc-gateway/runtime" - - ocabci "github.com/Finschia/ostracon/abci/types" "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" + ocabci "github.com/Finschia/ostracon/abci/types" + sdkclient "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/codec" cdctypes "github.com/Finschia/finschia-sdk/codec/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/genesis_test.go b/x/distribution/simulation/genesis_test.go index 1724ef5fa9..8db6652da6 100644 --- a/x/distribution/simulation/genesis_test.go +++ b/x/distribution/simulation/genesis_test.go @@ -76,6 +76,8 @@ func TestRandomizedGenState1(t *testing.T) { } for _, tt := range tests { + tt := tt + require.Panicsf(t, func() { simulation.RandomizedGenState(&tt.simState) }, tt.panicMsg) } } 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..145506127d 100644 --- a/x/distribution/simulation/operations_test.go +++ b/x/distribution/simulation/operations_test.go @@ -14,7 +14,6 @@ import ( 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 +37,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 +70,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 +112,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 +156,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 +169,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 +196,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/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/abci.go b/x/evidence/abci.go index 5341a62c12..5c1cbecf88 100644 --- a/x/evidence/abci.go +++ b/x/evidence/abci.go @@ -4,9 +4,10 @@ import ( "fmt" "time" - ocabci "github.com/Finschia/ostracon/abci/types" abci "github.com/tendermint/tendermint/abci/types" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/finschia-sdk/telemetry" sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/x/evidence/keeper" 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/exported/evidence.go b/x/evidence/exported/evidence.go index a501c75648..1b652512e6 100644 --- a/x/evidence/exported/evidence.go +++ b/x/evidence/exported/evidence.go @@ -1,9 +1,10 @@ package exported import ( - ostbytes "github.com/Finschia/ostracon/libs/bytes" "github.com/gogo/protobuf/proto" + ostbytes "github.com/Finschia/ostracon/libs/bytes" + sdk "github.com/Finschia/finschia-sdk/types" ) diff --git a/x/evidence/genesis_test.go b/x/evidence/genesis_test.go index e2440b64e5..c63de58094 100644 --- a/x/evidence/genesis_test.go +++ b/x/evidence/genesis_test.go @@ -4,10 +4,11 @@ import ( "fmt" "testing" - "github.com/Finschia/ostracon/types/time" "github.com/stretchr/testify/suite" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + "github.com/Finschia/ostracon/types/time" + "github.com/Finschia/finschia-sdk/crypto/keys/ed25519" "github.com/Finschia/finschia-sdk/simapp" sdk "github.com/Finschia/finschia-sdk/types" 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..ed36dd0087 100644 --- a/x/evidence/module.go +++ b/x/evidence/module.go @@ -7,11 +7,10 @@ import ( "math/rand" "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" + 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/client" "github.com/Finschia/finschia-sdk/codec" diff --git a/x/evidence/types/evidence.go b/x/evidence/types/evidence.go index 9c259fb2db..6eae1b10d2 100644 --- a/x/evidence/types/evidence.go +++ b/x/evidence/types/evidence.go @@ -4,11 +4,12 @@ import ( "fmt" "time" - "github.com/Finschia/ostracon/crypto/tmhash" - ostbytes "github.com/Finschia/ostracon/libs/bytes" abci "github.com/tendermint/tendermint/abci/types" "gopkg.in/yaml.v2" + "github.com/Finschia/ostracon/crypto/tmhash" + ostbytes "github.com/Finschia/ostracon/libs/bytes" + sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/x/evidence/exported" ) diff --git a/x/evidence/types/genesis_test.go b/x/evidence/types/genesis_test.go index 2614fc632a..c1bc30b065 100644 --- a/x/evidence/types/genesis_test.go +++ b/x/evidence/types/genesis_test.go @@ -5,9 +5,10 @@ import ( "testing" "time" - ostbytes "github.com/Finschia/ostracon/libs/bytes" "github.com/stretchr/testify/require" + ostbytes "github.com/Finschia/ostracon/libs/bytes" + "github.com/Finschia/finschia-sdk/codec" codectypes "github.com/Finschia/finschia-sdk/codec/types" "github.com/Finschia/finschia-sdk/crypto/keys/ed25519" 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/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/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..5851f8e978 100644 --- a/x/feegrant/keeper/keeper_test.go +++ b/x/feegrant/keeper/keeper_test.go @@ -247,12 +247,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..989387f831 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}}, }, } 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..d7009c490d 100644 --- a/x/feegrant/simulation/operations_test.go +++ b/x/feegrant/simulation/operations_test.go @@ -112,7 +112,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 +155,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/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..7f16e5675f 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" ) diff --git a/x/foundation/client/testutil/query.go b/x/foundation/client/testutil/query.go index 3677af29f6..6f3e372eb0 100644 --- a/x/foundation/client/testutil/query.go +++ b/x/foundation/client/testutil/query.go @@ -3,9 +3,10 @@ package testutil import ( "fmt" - ostcli "github.com/Finschia/ostracon/libs/cli" "github.com/gogo/protobuf/proto" + ostcli "github.com/Finschia/ostracon/libs/cli" + "github.com/Finschia/finschia-sdk/client/flags" clitestutil "github.com/Finschia/finschia-sdk/testutil/cli" sdk "github.com/Finschia/finschia-sdk/types" 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/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..ba0807f6b6 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" ) @@ -408,14 +407,16 @@ func TestValidateGenesis(t *testing.T) { } for name, tc := range testCases { + tc := tc + t.Run(name, func(t *testing.T) { var unmarshalled foundation.GenesisState 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/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/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/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..befca53514 100644 --- a/x/foundation/module/module.go +++ b/x/foundation/module/module.go @@ -5,11 +5,12 @@ import ( "encoding/json" "fmt" - 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" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/codec" codectypes "github.com/Finschia/finschia-sdk/codec/types" @@ -79,7 +80,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 +155,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..ff79d17620 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() @@ -726,7 +727,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 diff --git a/x/genutil/client/cli/collect.go b/x/genutil/client/cli/collect.go index 7c0f0d69c2..ed08661d98 100644 --- a/x/genutil/client/cli/collect.go +++ b/x/genutil/client/cli/collect.go @@ -4,10 +4,11 @@ import ( "encoding/json" "path/filepath" - octypes "github.com/Finschia/ostracon/types" "github.com/pkg/errors" "github.com/spf13/cobra" + octypes "github.com/Finschia/ostracon/types" + "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/server" diff --git a/x/genutil/client/cli/gentx.go b/x/genutil/client/cli/gentx.go index 9bfca7d23d..982baa54ff 100644 --- a/x/genutil/client/cli/gentx.go +++ b/x/genutil/client/cli/gentx.go @@ -9,11 +9,12 @@ import ( "os" "path/filepath" - ostos "github.com/Finschia/ostracon/libs/os" - octypes "github.com/Finschia/ostracon/types" "github.com/pkg/errors" "github.com/spf13/cobra" + ostos "github.com/Finschia/ostracon/libs/os" + octypes "github.com/Finschia/ostracon/types" + "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" "github.com/Finschia/finschia-sdk/client/tx" @@ -214,7 +215,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_test.go b/x/genutil/client/cli/init_test.go index 61a487ed64..a0c79603a6 100644 --- a/x/genutil/client/cli/init_test.go +++ b/x/genutil/client/cli/init_test.go @@ -10,18 +10,18 @@ import ( "testing" "time" - abci_server "github.com/Finschia/ostracon/abci/server" - "github.com/Finschia/ostracon/libs/cli" - "github.com/Finschia/ostracon/libs/log" "github.com/spf13/viper" "github.com/stretchr/testify/require" - ed255192 "github.com/Finschia/finschia-sdk/crypto/keys/ed25519" + abci_server "github.com/Finschia/ostracon/abci/server" + "github.com/Finschia/ostracon/libs/cli" + "github.com/Finschia/ostracon/libs/log" "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" @@ -153,7 +153,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 +201,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/cli/migrate.go b/x/genutil/client/cli/migrate.go index affafa21f3..ed9569d27a 100644 --- a/x/genutil/client/cli/migrate.go +++ b/x/genutil/client/cli/migrate.go @@ -6,10 +6,11 @@ import ( "sort" "time" - ocjson "github.com/Finschia/ostracon/libs/json" "github.com/pkg/errors" "github.com/spf13/cobra" + ocjson "github.com/Finschia/ostracon/libs/json" + "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/client/flags" sdk "github.com/Finschia/finschia-sdk/types" diff --git a/x/genutil/client/cli/validate_genesis.go b/x/genutil/client/cli/validate_genesis.go index 2ee51b3892..ee867cb1d6 100644 --- a/x/genutil/client/cli/validate_genesis.go +++ b/x/genutil/client/cli/validate_genesis.go @@ -4,9 +4,10 @@ import ( "encoding/json" "fmt" - octypes "github.com/Finschia/ostracon/types" "github.com/spf13/cobra" + octypes "github.com/Finschia/ostracon/types" + "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/server" "github.com/Finschia/finschia-sdk/types/module" diff --git a/x/genutil/client/testutil/helpers.go b/x/genutil/client/testutil/helpers.go index afd035a1a0..95fbf5eb2f 100644 --- a/x/genutil/client/testutil/helpers.go +++ b/x/genutil/client/testutil/helpers.go @@ -4,10 +4,11 @@ import ( "context" "fmt" + "github.com/spf13/viper" + ostcfg "github.com/Finschia/ostracon/config" "github.com/Finschia/ostracon/libs/cli" "github.com/Finschia/ostracon/libs/log" - "github.com/spf13/viper" "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/codec" 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..afb8463296 100644 --- a/x/genutil/utils.go +++ b/x/genutil/utils.go @@ -6,13 +6,14 @@ import ( "path/filepath" "time" + "github.com/cosmos/go-bip39" + cfg "github.com/Finschia/ostracon/config" osted25519 "github.com/Finschia/ostracon/crypto/ed25519" ostos "github.com/Finschia/ostracon/libs/os" "github.com/Finschia/ostracon/p2p" "github.com/Finschia/ostracon/privval" octypes "github.com/Finschia/ostracon/types" - "github.com/cosmos/go-bip39" cryptocodec "github.com/Finschia/finschia-sdk/crypto/codec" cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" @@ -68,12 +69,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..fd8fc1c019 100644 --- a/x/genutil/utils_test.go +++ b/x/genutil/utils_test.go @@ -7,8 +7,9 @@ import ( "testing" "time" - "github.com/Finschia/ostracon/config" "github.com/stretchr/testify/require" + + "github.com/Finschia/ostracon/config" ) func TestExportGenesisFileWithTime(t *testing.T) { diff --git a/x/gov/abci_test.go b/x/gov/abci_test.go index 6073dcb403..8c046adcfa 100644 --- a/x/gov/abci_test.go +++ b/x/gov/abci_test.go @@ -4,6 +4,7 @@ import ( "testing" "time" + "github.com/golang/protobuf/proto" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" @@ -14,7 +15,6 @@ import ( "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/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..dc54ee1b86 100644 --- a/x/gov/client/utils/query_test.go +++ b/x/gov/client/utils/query_test.go @@ -164,8 +164,8 @@ 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 +178,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..b6dba61a9c 100644 --- a/x/gov/genesis_test.go +++ b/x/gov/genesis_test.go @@ -4,13 +4,13 @@ import ( "encoding/json" "testing" + "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/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/simapp" sdk "github.com/Finschia/finschia-sdk/types" 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..65cf29e116 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) 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..3debd3da85 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)), @@ -391,6 +397,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/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/genesis_test.go b/x/gov/simulation/genesis_test.go index 5602c79b5f..2e0fc7217f 100644 --- a/x/gov/simulation/genesis_test.go +++ b/x/gov/simulation/genesis_test.go @@ -79,6 +79,8 @@ func TestRandomizedGenState1(t *testing.T) { } for _, tt := range tests { + tt := tt + require.Panicsf(t, func() { simulation.RandomizedGenState(&tt.simState) }, tt.panicMsg) } } diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index e2ffb9724b..6ba9e985f3 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 diff --git a/x/gov/simulation/operations_test.go b/x/gov/simulation/operations_test.go index ba492587f7..640b87c4b2 100644 --- a/x/gov/simulation/operations_test.go +++ b/x/gov/simulation/operations_test.go @@ -6,10 +6,11 @@ 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" @@ -265,6 +266,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..2104ef6842 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,7 +167,6 @@ func (status *ProposalStatus) Unmarshal(data []byte) error { } // Format implements the fmt.Formatter interface. -// nolint: errcheck func (status ProposalStatus) Format(s fmt.State, verb rune) { switch verb { case 's': diff --git a/x/mint/client/testutil/grpc.go b/x/mint/client/testutil/grpc.go index eaf8188d9b..aa3cf59c51 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" ) 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/module.go b/x/mint/module.go index 07e328d46e..f98bf5b2c8 100644 --- a/x/mint/module.go +++ b/x/mint/module.go @@ -6,11 +6,12 @@ import ( "fmt" "math/rand" - 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" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/codec" cdctypes "github.com/Finschia/finschia-sdk/codec/types" diff --git a/x/mint/simulation/genesis_test.go b/x/mint/simulation/genesis_test.go index 84101358c4..621426ad80 100644 --- a/x/mint/simulation/genesis_test.go +++ b/x/mint/simulation/genesis_test.go @@ -79,6 +79,8 @@ func TestRandomizedGenState1(t *testing.T) { } for _, tt := range tests { + tt := tt + require.Panicsf(t, func() { simulation.RandomizedGenState(&tt.simState) }, tt.panicMsg) } } 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/suite.go b/x/params/client/testutil/suite.go index 3d885d52d4..72a4e9032c 100644 --- a/x/params/client/testutil/suite.go +++ b/x/params/client/testutil/suite.go @@ -4,9 +4,10 @@ import ( "fmt" "strings" - ostcli "github.com/Finschia/ostracon/libs/cli" "github.com/stretchr/testify/suite" + ostcli "github.com/Finschia/ostracon/libs/cli" + clitestutil "github.com/Finschia/finschia-sdk/testutil/cli" "github.com/Finschia/finschia-sdk/testutil/network" "github.com/Finschia/finschia-sdk/x/params/client/cli" diff --git a/x/params/keeper/keeper_test.go b/x/params/keeper/keeper_test.go index cc9c6df606..c4ae41351f 100644 --- a/x/params/keeper/keeper_test.go +++ b/x/params/keeper/keeper_test.go @@ -165,9 +165,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)}, } 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/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..12bc0c2355 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, diff --git a/x/params/types/subspace_test.go b/x/params/types/subspace_test.go index eebb9818dd..da7e0cd73a 100644 --- a/x/params/types/subspace_test.go +++ b/x/params/types/subspace_test.go @@ -50,7 +50,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()) }) } diff --git a/x/simulation/mock_ostracon.go b/x/simulation/mock_ostracon.go index 0fea9e6243..54625d4379 100644 --- a/x/simulation/mock_ostracon.go +++ b/x/simulation/mock_ostracon.go @@ -88,6 +88,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..82547c3891 100644 --- a/x/simulation/operation.go +++ b/x/simulation/operation.go @@ -73,7 +73,7 @@ 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 } diff --git a/x/simulation/params.go b/x/simulation/params.go index ab32df5163..7269a21e28 100644 --- a/x/simulation/params.go +++ b/x/simulation/params.go @@ -5,10 +5,11 @@ import ( "fmt" "math/rand" - "github.com/Finschia/ostracon/types" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + "github.com/Finschia/ostracon/types" + "github.com/Finschia/finschia-sdk/codec" "github.com/Finschia/finschia-sdk/types/simulation" stakingtypes "github.com/Finschia/finschia-sdk/x/staking/types" 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/app_test.go b/x/slashing/app_test.go index 14c6aab848..bff61cdaec 100644 --- a/x/slashing/app_test.go +++ b/x/slashing/app_test.go @@ -28,6 +28,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 +36,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/suite.go b/x/slashing/client/testutil/suite.go index c2ccdf929e..831b248cf5 100644 --- a/x/slashing/client/testutil/suite.go +++ b/x/slashing/client/testutil/suite.go @@ -4,10 +4,11 @@ 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" clitestutil "github.com/Finschia/finschia-sdk/testutil/cli" "github.com/Finschia/finschia-sdk/testutil/network" 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/module.go b/x/slashing/module.go index 3e336c2f0d..6576e7227a 100644 --- a/x/slashing/module.go +++ b/x/slashing/module.go @@ -7,11 +7,10 @@ import ( "math/rand" "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" + 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/client" "github.com/Finschia/finschia-sdk/codec" diff --git a/x/slashing/simulation/genesis_test.go b/x/slashing/simulation/genesis_test.go index c5d3615b94..e63bc3c14c 100644 --- a/x/slashing/simulation/genesis_test.go +++ b/x/slashing/simulation/genesis_test.go @@ -78,6 +78,8 @@ func TestRandomizedGenState1(t *testing.T) { } for _, tt := range tests { + tt := tt + require.Panicsf(t, func() { simulation.RandomizedGenState(&tt.simState) }, tt.panicMsg) } } 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..2ba7d26ece 100644 --- a/x/slashing/simulation/operations_test.go +++ b/x/slashing/simulation/operations_test.go @@ -67,7 +67,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 +96,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 +117,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 +134,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..899a69b1ed 100644 --- a/x/staking/app_test.go +++ b/x/staking/app_test.go @@ -16,6 +16,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 +28,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/tx_test.go b/x/staking/client/cli/tx_test.go index 0110d667a7..e326e4490b 100644 --- a/x/staking/client/cli/tx_test.go +++ b/x/staking/client/cli/tx_test.go @@ -38,44 +38,47 @@ 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"), }, diff --git a/x/staking/client/testutil/suite.go b/x/staking/client/testutil/suite.go index 556275a938..451346fba4 100644 --- a/x/staking/client/testutil/suite.go +++ b/x/staking/client/testutil/suite.go @@ -1351,7 +1351,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.go b/x/staking/genesis.go index 269b38336c..f5b5b851d4 100644 --- a/x/staking/genesis.go +++ b/x/staking/genesis.go @@ -4,9 +4,10 @@ import ( "fmt" "log" - octypes "github.com/Finschia/ostracon/types" abci "github.com/tendermint/tendermint/abci/types" + octypes "github.com/Finschia/ostracon/types" + cryptocodec "github.com/Finschia/finschia-sdk/crypto/codec" sdk "github.com/Finschia/finschia-sdk/types" "github.com/Finschia/finschia-sdk/x/staking/keeper" diff --git a/x/staking/handler_test.go b/x/staking/handler_test.go index f9d10be53e..cf1dea5a10 100644 --- a/x/staking/handler_test.go +++ b/x/staking/handler_test.go @@ -5,13 +5,14 @@ import ( "testing" "time" - octypes "github.com/Finschia/ostracon/types" "github.com/golang/protobuf/proto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + octypes "github.com/Finschia/ostracon/types" + cryptocodec "github.com/Finschia/finschia-sdk/crypto/codec" "github.com/Finschia/finschia-sdk/crypto/keys/ed25519" "github.com/Finschia/finschia-sdk/crypto/keys/secp256k1" @@ -26,6 +27,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 +81,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 +130,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 +308,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 +439,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 +758,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 @@ -1043,21 +1049,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..ca609e9c11 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) @@ -354,7 +355,7 @@ func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) { 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/msg_server.go b/x/staking/keeper/msg_server.go index 40d124ee3e..1a197bd3db 100644 --- a/x/staking/keeper/msg_server.go +++ b/x/staking/keeper/msg_server.go @@ -7,6 +7,8 @@ import ( oststrings "github.com/Finschia/ostracon/libs/strings" metrics "github.com/hashicorp/go-metrics" + oststrings "github.com/Finschia/ostracon/libs/strings" + cryptotypes "github.com/Finschia/finschia-sdk/crypto/types" "github.com/Finschia/finschia-sdk/telemetry" sdk "github.com/Finschia/finschia-sdk/types" 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..4c6aed6d0b 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() { 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..cbc917103d 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) diff --git a/x/staking/module.go b/x/staking/module.go index fa038e479d..c9ec999167 100644 --- a/x/staking/module.go +++ b/x/staking/module.go @@ -7,11 +7,11 @@ import ( "math/rand" "github.com/grpc-ecosystem/grpc-gateway/runtime" - - ocabci "github.com/Finschia/ostracon/abci/types" "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/codec" cdctypes "github.com/Finschia/finschia-sdk/codec/types" diff --git a/x/staking/simulation/decoder_test.go b/x/staking/simulation/decoder_test.go index 7e215029f4..cc4a936deb 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) diff --git a/x/staking/simulation/genesis_test.go b/x/staking/simulation/genesis_test.go index c80a3a8a9d..40ea16a9a2 100644 --- a/x/staking/simulation/genesis_test.go +++ b/x/staking/simulation/genesis_test.go @@ -101,6 +101,8 @@ func TestRandomizedGenState1(t *testing.T) { } for _, tt := range tests { + tt := tt + require.Panicsf(t, func() { simulation.RandomizedGenState(&tt.simState) }, tt.panicMsg) } } 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..55cc37c7a6 100644 --- a/x/staking/simulation/operations_test.go +++ b/x/staking/simulation/operations_test.go @@ -80,7 +80,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 +118,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 +157,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 +203,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 +254,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 +280,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 +297,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..a722adf6f6 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", 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/msg_test.go b/x/staking/types/msg_test.go index 9929819d6b..328c0b4102 100644 --- a/x/staking/types/msg_test.go +++ b/x/staking/types/msg_test.go @@ -105,6 +105,8 @@ func TestMsgEditValidator(t *testing.T) { } for _, tc := range tests { + tc := tc + description := types.NewDescription(tc.moniker, tc.identity, tc.website, tc.securityContact, tc.details) newRate := sdk.ZeroDec() 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..7f04924b95 100644 --- a/x/staking/types/validator_test.go +++ b/x/staking/types/validator_test.go @@ -5,10 +5,11 @@ import ( "sort" "testing" - octypes "github.com/Finschia/ostracon/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + octypes "github.com/Finschia/ostracon/types" + "github.com/Finschia/finschia-sdk/codec/legacy" cryptocodec "github.com/Finschia/finschia-sdk/crypto/codec" "github.com/Finschia/finschia-sdk/crypto/keys/ed25519" @@ -260,9 +261,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 +344,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..cd5827d7f8 100644 --- a/x/stakingplus/module/module.go +++ b/x/stakingplus/module/module.go @@ -3,21 +3,19 @@ package module import ( "encoding/json" - ocabci "github.com/Finschia/ostracon/abci/types" abci "github.com/tendermint/tendermint/abci/types" - "github.com/Finschia/finschia-sdk/codec" - "github.com/Finschia/finschia-sdk/types/module" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/finschia-sdk/codec" 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 +35,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..422615ac40 100644 --- a/x/token/client/testutil/query.go +++ b/x/token/client/testutil/query.go @@ -3,9 +3,10 @@ package testutil import ( "fmt" - ostcli "github.com/Finschia/ostracon/libs/cli" "github.com/gogo/protobuf/proto" + 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/types/query" 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/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..298dfb6c4b 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 { diff --git a/x/upgrade/abci_test.go b/x/upgrade/abci_test.go index e78ac83d80..2927f039b0 100644 --- a/x/upgrade/abci_test.go +++ b/x/upgrade/abci_test.go @@ -8,12 +8,12 @@ import ( "time" "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" - abci "github.com/tendermint/tendermint/abci/types" - dbm "github.com/tendermint/tm-db" "github.com/Finschia/finschia-sdk/simapp" storetypes "github.com/Finschia/finschia-sdk/store/types" @@ -29,7 +29,6 @@ import ( type TestSuite struct { module module.BeginBlockAppModule keeper keeper.Keeper - querier sdk.Querier handler govtypes.Handler ctx sdk.Context } @@ -55,7 +54,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 +94,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 +115,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 +170,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 +223,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..5c3c500f07 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) { @@ -172,6 +174,8 @@ func (suite *UpgradeTestSuite) TestModuleVersions() { mv := suite.app.UpgradeKeeper.GetModuleVersions(suite.ctx) for _, tc := range testCases { + tc := tc + suite.Run(fmt.Sprintf("Case %s", tc.msg), func() { suite.SetupTest() // reset 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..6558b0a893 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, }, @@ -169,7 +170,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 +219,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/module.go b/x/upgrade/module.go index 2b320521a4..edcb3ccd7c 100644 --- a/x/upgrade/module.go +++ b/x/upgrade/module.go @@ -4,11 +4,12 @@ import ( "context" "encoding/json" - 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" + ocabci "github.com/Finschia/ostracon/abci/types" + "github.com/Finschia/finschia-sdk/client" "github.com/Finschia/finschia-sdk/codec" codectypes "github.com/Finschia/finschia-sdk/codec/types" diff --git a/x/upgrade/types/storeloader_test.go b/x/upgrade/types/storeloader_test.go index 429baf50c0..28805f47ce 100644 --- a/x/upgrade/types/storeloader_test.go +++ b/x/upgrade/types/storeloader_test.go @@ -30,6 +30,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 +48,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 +79,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