From 0943a702155f359fa8a7ed6e7b441f65e17f44d8 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 12 Aug 2022 03:00:24 +0700 Subject: [PATCH 1/2] chore: fix linting issues exposed by fixing golangci-lint (#12895) Co-authored-by: Marko Co-authored-by: Julien Robert --- baseapp/baseapp.go | 2 +- baseapp/msg_service_router.go | 6 +- client/keys/add.go | 11 +- codec/amino_codec.go | 10 +- codec/proto_codec.go | 10 +- codec/unknownproto/doc.go | 12 +- cosmovisor/args.go | 2 +- cosmovisor/args_test.go | 5 +- cosmovisor/cmd/cosmovisor/help_test.go | 5 +- cosmovisor/cmd/cosmovisor/init_test.go | 10 +- crypto/armor.go | 6 +- crypto/hd/doc.go | 5 +- crypto/hd/hdpath.go | 2 +- crypto/keyring/doc.go | 40 +++---- crypto/keyring/output.go | 2 +- crypto/keys/multisig/codec.go | 3 +- crypto/keys/secp256k1/secp256k1.go | 2 +- crypto/keys/secp256k1/secp256k1_nocgo.go | 4 +- db/types.go | 18 +-- depinject/config.go | 8 +- depinject/container.go | 1 - depinject/inject.go | 5 +- depinject/provider_desc.go | 3 +- depinject/struct_args.go | 8 +- errors/doc.go | 19 ++- errors/stacktrace.go | 3 +- math/dec.go | 13 +- math/dec_test.go | 6 +- orm/internal/testpb/bank.cosmos_orm.go | 1 + orm/internal/testpb/test_schema.cosmos_orm.go | 1 + orm/testing/ormtest/membackend.go | 7 +- runtime/app.go | 2 +- server/config/toml.go | 3 +- .../grpc/gogoreflection/fix_registration.go | 13 +- .../grpc/gogoreflection/serverreflection.go | 4 +- server/mock/helpers.go | 3 +- server/mock/tx.go | 3 +- server/rosetta/client_online.go | 3 +- server/rosetta/converter.go | 6 +- simapp/export.go | 3 +- simapp/simd/cmd/testnet.go | 3 +- snapshots/manager.go | 10 +- snapshots/store.go | 4 +- store/iavl/store.go | 1 + store/mem/store.go | 2 +- store/streaming/file/service.go | 3 +- store/streaming/file/service_test.go | 3 +- store/v2alpha1/multi/test_util.go | 4 +- tests/e2e/bank/client/suite.go | 4 +- .../e2e/client/grpc/tmservice/service_test.go | 1 - tests/integration/bank/keeper/keeper_test.go | 3 +- testutil/network/network.go | 6 +- testutil/network/util.go | 4 +- testutil/rest/rest.go | 4 +- tx/textual/valuerenderer/bytes.go | 3 +- tx/textual/valuerenderer/bytes_test.go | 4 +- .../valuerenderer/valuerenderer_test.go | 6 +- types/coin.go | 18 +-- types/config.go | 3 +- types/errors/errors.go | 4 +- types/handler.go | 31 ++--- types/module/module.go | 51 ++++---- types/msgservice/msg_service.go | 4 +- types/tx/types.go | 6 +- version/version.go | 12 +- x/auth/ante/ante_test.go | 9 +- x/auth/ante/feegrant_test.go | 21 ++-- x/auth/ante/testutil_test.go | 2 +- x/auth/keeper/keeper.go | 2 +- x/auth/migrations/legacytx/stdtx.go | 1 + x/auth/tx/service.go | 2 +- x/auth/types/account.go | 1 + x/auth/types/params.go | 6 +- x/auth/vesting/types/msgs.go | 3 + x/authz/codec/doc.go | 9 +- x/authz/keeper/keys.go | 4 +- x/authz/migrations/v046/keys.go | 1 - x/authz/module/abci_test.go | 1 - x/authz/msgs.go | 3 + x/authz/simulation/operations.go | 1 + x/bank/keeper/keeper.go | 3 +- x/bank/keeper/keeper_test.go | 5 +- x/bank/keeper/send.go | 12 +- x/bank/simulation/operations.go | 1 + x/bank/types/events.go | 4 - x/bank/types/metadata.go | 12 +- x/bank/types/msgs.go | 3 + x/bank/types/params.go | 2 + x/bank/types/querier.go | 5 +- x/bank/types/send_authorization_test.go | 2 +- x/crisis/client/cli/tx_test.go | 3 +- x/crisis/types/msgs.go | 1 + x/distribution/simulation/operations.go | 1 + x/distribution/types/proposal.go | 1 + x/distribution/types/query.go | 1 + x/evidence/keeper/infraction_test.go | 7 +- x/evidence/keeper/keeper_test.go | 3 +- x/evidence/types/expected_keepers.go | 3 +- x/evidence/types/msgs.go | 1 + x/feegrant/grant.go | 1 + x/feegrant/msgs.go | 2 + x/feegrant/simulation/operations.go | 1 + x/genutil/doc.go | 10 +- x/gov/client/cli/query.go | 3 + x/gov/client/testutil/grpc.go | 6 +- x/gov/client/testutil/helpers.go | 1 + x/gov/genesis.go | 2 + x/gov/keeper/grpc_query.go | 3 +- x/gov/keeper/keeper.go | 2 +- x/gov/keeper/msg_server.go | 36 +++--- x/gov/keeper/msg_server_test.go | 3 +- x/gov/module.go | 42 ++++--- x/gov/simulation/operations.go | 1 + x/gov/types/v1/deposit.go | 1 + x/gov/types/v1/msgs.go | 4 + x/gov/types/v1/params.go | 1 - x/gov/types/v1/vote.go | 1 + x/gov/types/v1beta1/deposit.go | 1 + x/gov/types/v1beta1/msgs.go | 4 + x/gov/types/v1beta1/vote.go | 1 + x/group/client/cli/util.go | 5 +- x/group/internal/orm/auto_uint64.go | 13 +- x/group/internal/orm/index.go | 20 ++-- x/group/internal/orm/iterator.go | 14 +-- x/group/internal/orm/key_codec.go | 6 +- x/group/internal/orm/primary_key.go | 13 +- x/group/internal/orm/table.go | 13 +- x/group/simulation/operations.go | 1 + x/simulation/doc.go | 111 +++++++++--------- x/simulation/util.go | 6 +- x/slashing/simulation/operations.go | 1 + x/slashing/types/msg.go | 1 + x/slashing/types/signing_info.go | 1 + x/staking/keeper/delegation_test.go | 4 +- x/staking/keeper/historical_info.go | 4 +- x/staking/keeper/slash.go | 19 ++- x/staking/simulation/operations.go | 1 + x/staking/types/delegation.go | 3 + x/staking/types/msg.go | 5 + x/staking/types/validator.go | 4 +- x/upgrade/abci_test.go | 1 - x/upgrade/doc.go | 25 ++-- x/upgrade/handler.go | 3 +- x/upgrade/keeper/grpc_query.go | 3 +- x/upgrade/keeper/grpc_query_test.go | 1 - x/upgrade/keeper/keeper_test.go | 1 - x/upgrade/plan/downloader.go | 22 ++-- x/upgrade/plan/info.go | 13 +- 148 files changed, 571 insertions(+), 469 deletions(-) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 096228614922..7f0a38d874f4 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -42,7 +42,7 @@ type ( ) // BaseApp reflects the ABCI application implementation. -type BaseApp struct { // nolint: maligned +type BaseApp struct { //nolint: maligned // initialized on creation logger log.Logger name string // application name from abci.Info diff --git a/baseapp/msg_service_router.go b/baseapp/msg_service_router.go index f6c8d4b21ce7..e9f2311cae23 100644 --- a/baseapp/msg_service_router.go +++ b/baseapp/msg_service_router.go @@ -46,9 +46,9 @@ func (msr *MsgServiceRouter) HandlerByTypeURL(typeURL string) MsgServiceHandler // service description, handler is an object which implements that gRPC service. // // This function PANICs: -// - if it is called before the service `Msg`s have been registered using -// RegisterInterfaces, -// - or if a service is being registered twice. +// - if it is called before the service `Msg`s have been registered using +// RegisterInterfaces, +// - or if a service is being registered twice. func (msr *MsgServiceRouter) RegisterService(sd *grpc.ServiceDesc, handler interface{}) { // Adds a top-level query handler based on the gRPC service name. for _, method := range sd.Methods { diff --git a/client/keys/add.go b/client/keys/add.go index 9e26da210f34..62bdc67dbab3 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -93,12 +93,13 @@ func runAddCmdPrepare(cmd *cobra.Command, args []string) error { /* input - - bip39 mnemonic - - bip39 passphrase - - bip44 path - - local encryption password + - bip39 mnemonic + - bip39 passphrase + - bip44 path + - local encryption password + output - - armor encrypted private key (saved to file) + - armor encrypted private key (saved to file) */ func runAddCmd(ctx client.Context, cmd *cobra.Command, args []string, inBuf *bufio.Reader) error { var err error diff --git a/codec/amino_codec.go b/codec/amino_codec.go index 69f4dc133d29..77969d22df25 100644 --- a/codec/amino_codec.go +++ b/codec/amino_codec.go @@ -96,8 +96,9 @@ func (ac *AminoCodec) MarshalInterface(i proto.Message) ([]byte, error) { // NOTE: to unmarshal a concrete type, you should use Unmarshal instead // // Example: -// var x MyInterface -// err := cdc.UnmarshalInterface(bz, &x) +// +// var x MyInterface +// err := cdc.UnmarshalInterface(bz, &x) func (ac *AminoCodec) UnmarshalInterface(bz []byte, ptr interface{}) error { return ac.LegacyAmino.Unmarshal(bz, ptr) } @@ -117,8 +118,9 @@ func (ac *AminoCodec) MarshalInterfaceJSON(i proto.Message) ([]byte, error) { // NOTE: to unmarshal a concrete type, you should use UnmarshalJSON instead // // Example: -// var x MyInterface -// err := cdc.UnmarshalInterfaceJSON(bz, &x) +// +// var x MyInterface +// err := cdc.UnmarshalInterfaceJSON(bz, &x) func (ac *AminoCodec) UnmarshalInterfaceJSON(bz []byte, ptr interface{}) error { return ac.LegacyAmino.UnmarshalJSON(bz, ptr) } diff --git a/codec/proto_codec.go b/codec/proto_codec.go index 9b5b72b6e4f2..317cc33e0481 100644 --- a/codec/proto_codec.go +++ b/codec/proto_codec.go @@ -204,8 +204,9 @@ func (pc *ProtoCodec) MarshalInterface(i gogoproto.Message) ([]byte, error) { // NOTE: to unmarshal a concrete type, you should use Unmarshal instead // // Example: -// var x MyInterface -// err := cdc.UnmarshalInterface(bz, &x) +// +// var x MyInterface +// err := cdc.UnmarshalInterface(bz, &x) func (pc *ProtoCodec) UnmarshalInterface(bz []byte, ptr interface{}) error { any := &types.Any{} err := pc.Unmarshal(bz, any) @@ -233,8 +234,9 @@ func (pc *ProtoCodec) MarshalInterfaceJSON(x gogoproto.Message) ([]byte, error) // NOTE: to unmarshal a concrete type, you should use UnmarshalJSON instead // // Example: -// var x MyInterface // must implement proto.Message -// err := cdc.UnmarshalInterfaceJSON(&x, bz) +// +// var x MyInterface // must implement proto.Message +// err := cdc.UnmarshalInterfaceJSON(&x, bz) func (pc *ProtoCodec) UnmarshalInterfaceJSON(bz []byte, iface interface{}) error { any := &types.Any{} err := pc.UnmarshalJSON(bz, any) diff --git a/codec/unknownproto/doc.go b/codec/unknownproto/doc.go index 0e0a46342291..cef3f8f253e9 100644 --- a/codec/unknownproto/doc.go +++ b/codec/unknownproto/doc.go @@ -8,17 +8,17 @@ b) Mismatched wire types for a field -- this is indicative of mismatched service Its API signature is similar to proto.Unmarshal([]byte, proto.Message) in the strict case - if err := RejectUnknownFieldsStrict(protoBlob, protoMessage, false); err != nil { - // Handle the error. - } + if err := RejectUnknownFieldsStrict(protoBlob, protoMessage, false); err != nil { + // Handle the error. + } and ideally should be added before invoking proto.Unmarshal, if you'd like to enforce the features mentioned above. By default, for security we report every single field that's unknown, whether a non-critical field or not. To customize this behavior, please set the boolean parameter allowUnknownNonCriticals to true to RejectUnknownFields: - if err := RejectUnknownFields(protoBlob, protoMessage, true); err != nil { - // Handle the error. - } + if err := RejectUnknownFields(protoBlob, protoMessage, true); err != nil { + // Handle the error. + } */ package unknownproto diff --git a/cosmovisor/args.go b/cosmovisor/args.go index b50120c36d14..229d5336b293 100644 --- a/cosmovisor/args.go +++ b/cosmovisor/args.go @@ -311,7 +311,7 @@ func (cfg *Config) SetCurrentUpgrade(u upgradetypes.Plan) (rerr error) { return err } _, err = f.Write(bz) - return err + return err } func (cfg *Config) UpgradeInfo() (upgradetypes.Plan, error) { diff --git a/cosmovisor/args_test.go b/cosmovisor/args_test.go index 3ecb6f871b15..e42749e0c76a 100644 --- a/cosmovisor/args_test.go +++ b/cosmovisor/args_test.go @@ -81,8 +81,9 @@ func (c *cosmovisorEnv) Set(envVar, envVal string) { // clearEnv clears environment variables and what they were. // Designed to be used like this: -// initialEnv := clearEnv() -// defer setEnv(nil, initialEnv) +// +// initialEnv := clearEnv() +// defer setEnv(nil, initialEnv) func (s *argsTestSuite) clearEnv() *cosmovisorEnv { s.T().Logf("Clearing environment variables.") rv := cosmovisorEnv{} diff --git a/cosmovisor/cmd/cosmovisor/help_test.go b/cosmovisor/cmd/cosmovisor/help_test.go index 86339cabe422..3332cc777dd0 100644 --- a/cosmovisor/cmd/cosmovisor/help_test.go +++ b/cosmovisor/cmd/cosmovisor/help_test.go @@ -47,8 +47,9 @@ func (c *cosmovisorHelpEnv) Set(envVar, envVal string) { // clearEnv clears environment variables and returns what they were. // Designed to be used like this: -// initialEnv := clearEnv() -// defer setEnv(nil, initialEnv) +// +// initialEnv := clearEnv() +// defer setEnv(nil, initialEnv) func (s *HelpTestSuite) clearEnv() *cosmovisorHelpEnv { s.T().Logf("Clearing environment variables.") rv := cosmovisorHelpEnv{} diff --git a/cosmovisor/cmd/cosmovisor/init_test.go b/cosmovisor/cmd/cosmovisor/init_test.go index 056571f3bbb2..7733bd2ae879 100644 --- a/cosmovisor/cmd/cosmovisor/init_test.go +++ b/cosmovisor/cmd/cosmovisor/init_test.go @@ -53,8 +53,9 @@ func (c *cosmovisorInitEnv) Set(envVar, envVal string) { // clearEnv clears environment variables and returns what they were. // Designed to be used like this: -// initialEnv := clearEnv() -// defer setEnv(nil, initialEnv) +// +// initialEnv := clearEnv() +// defer setEnv(nil, initialEnv) func (s *InitTestSuite) clearEnv() *cosmovisorInitEnv { s.T().Logf("Clearing environment variables.") rv := cosmovisorInitEnv{} @@ -137,8 +138,9 @@ func NewBufferedPipe(name string, replicateTo ...io.Writer) (BufferedPipe, error // StartNewBufferedPipe creates a new BufferedPipe and starts it. // // This is functionally equivalent to: -// p, _ := NewBufferedPipe(name, replicateTo...) -// p.Start() +// +// p, _ := NewBufferedPipe(name, replicateTo...) +// p.Start() func StartNewBufferedPipe(name string, replicateTo ...io.Writer) (BufferedPipe, error) { p, err := NewBufferedPipe(name, replicateTo...) if err != nil { diff --git a/crypto/armor.go b/crypto/armor.go index 1da3e9703326..7ef3da5e6842 100644 --- a/crypto/armor.go +++ b/crypto/armor.go @@ -4,11 +4,11 @@ import ( "bytes" "encoding/hex" "fmt" - "io/ioutil" + "io" "github.com/tendermint/crypto/bcrypt" "github.com/tendermint/tendermint/crypto" - "golang.org/x/crypto/openpgp/armor" // nolint: staticcheck + "golang.org/x/crypto/openpgp/armor" //nolint: staticcheck "github.com/cosmos/cosmos-sdk/codec/legacy" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -235,7 +235,7 @@ func DecodeArmor(armorStr string) (blockType string, headers map[string]string, if err != nil { return "", nil, nil, err } - data, err = ioutil.ReadAll(block.Body) + data, err = io.ReadAll(block.Body) if err != nil { return "", nil, nil, err } diff --git a/crypto/hd/doc.go b/crypto/hd/doc.go index 38d65213c177..85b6369e75e3 100644 --- a/crypto/hd/doc.go +++ b/crypto/hd/doc.go @@ -1,8 +1,9 @@ // Package hd provides support for hierarchical deterministic wallets generation and derivation. // // The user must understand the overall concept of the BIP 32 and the BIP 44 specs: -// https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki -// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki +// +// https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki +// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki // // In combination with the bip39 package in go-crypto this package provides the functionality for // deriving keys using a BIP 44 HD path, or, more general, by passing a BIP 32 path. diff --git a/crypto/hd/hdpath.go b/crypto/hd/hdpath.go index 96056a99b53a..172e3e0f76bd 100644 --- a/crypto/hd/hdpath.go +++ b/crypto/hd/hdpath.go @@ -215,7 +215,7 @@ func DerivePrivateKeyForPath(privKeyBytes, chainCode [32]byte, path string) ([]b // If harden is true, the derivation is 'hardened'. // 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 +// - 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) { var data []byte diff --git a/crypto/keyring/doc.go b/crypto/keyring/doc.go index b642680c0662..c5c17bf160b7 100644 --- a/crypto/keyring/doc.go +++ b/crypto/keyring/doc.go @@ -1,19 +1,18 @@ // Package keys provides common key management API. // -// -// The Keyring interface +// # The Keyring interface // // The Keyring interface defines the methods that a type needs to implement to be used // as key storage backend. This package provides few implementations out-of-the-box. // -// NewInMemory +// # NewInMemory // // The NewInMemory constructor returns an implementation backed by an in-memory, goroutine-safe // map that has historically been used for testing purposes or on-the-fly key generation as the // generated keys are discarded when the process terminates or the type instance is garbage // collected. // -// New +// # New // // The New constructor returns an implementation backed by a keyring library // (https://github.com/99designs/keyring), whose aim is to provide a common abstraction and uniform @@ -21,20 +20,21 @@ // as well as operating system-agnostic encrypted file-based backends. // // The backends: -// os The instance returned by this constructor uses the operating system's default -// credentials store to handle keys storage operations securely. It should be noted -// that the keyring keyring may be kept unlocked for the whole duration of the user -// session. -// file This backend more closely resembles the previous keyring storage used prior to -// v0.38.1. It stores the keyring encrypted within the app's configuration directory. -// This keyring will request a password each time it is accessed, which may occur -// multiple times in a single command resulting in repeated password prompts. -// kwallet This backend uses KDE Wallet Manager as a credentials management application: -// https://github.com/KDE/kwallet -// pass This backend uses the pass command line utility to store and retrieve keys: -// https://www.passwordstore.org/ -// test This backend stores keys insecurely to disk. It does not prompt for a password to -// be unlocked and it should be use only for testing purposes. -// memory Same instance as returned by NewInMemory. This backend uses a transient storage. Keys -// are discarded when the process terminates or the type instance is garbage collected. +// +// os The instance returned by this constructor uses the operating system's default +// credentials store to handle keys storage operations securely. It should be noted +// that the keyring keyring may be kept unlocked for the whole duration of the user +// session. +// file This backend more closely resembles the previous keyring storage used prior to +// v0.38.1. It stores the keyring encrypted within the app's configuration directory. +// This keyring will request a password each time it is accessed, which may occur +// multiple times in a single command resulting in repeated password prompts. +// kwallet This backend uses KDE Wallet Manager as a credentials management application: +// https://github.com/KDE/kwallet +// pass This backend uses the pass command line utility to store and retrieve keys: +// https://www.passwordstore.org/ +// test This backend stores keys insecurely to disk. It does not prompt for a password to +// be unlocked and it should be use only for testing purposes. +// memory Same instance as returned by NewInMemory. This backend uses a transient storage. Keys +// are discarded when the process terminates or the type instance is garbage collected. package keyring diff --git a/crypto/keyring/output.go b/crypto/keyring/output.go index 87bec26ad84e..37ba3bffd124 100644 --- a/crypto/keyring/output.go +++ b/crypto/keyring/output.go @@ -21,7 +21,7 @@ type KeyOutput struct { } // NewKeyOutput creates a default KeyOutput instance without Mnemonic, Threshold and PubKeys -func NewKeyOutput(name string, keyType KeyType, a sdk.Address, pk cryptotypes.PubKey) (KeyOutput, error) { // nolint:interfacer +func NewKeyOutput(name string, keyType KeyType, a sdk.Address, pk cryptotypes.PubKey) (KeyOutput, error) { //nolint:interfacer apk, err := codectypes.NewAnyWithValue(pk) if err != nil { return KeyOutput{}, err diff --git a/crypto/keys/multisig/codec.go b/crypto/keys/multisig/codec.go index d501e1b427cf..54a7deba5dc4 100644 --- a/crypto/keys/multisig/codec.go +++ b/crypto/keys/multisig/codec.go @@ -15,8 +15,7 @@ const ( PubKeyAminoRoute = "tendermint/PubKeyMultisigThreshold" ) -//nolint -// Deprecated: Amino is being deprecated in the SDK. But even if you need to +// AminoCdc is being deprecated in the SDK. But even if you need to // use Amino for some reason, please use `codec/legacy.Cdc` instead. var AminoCdc = codec.NewLegacyAmino() diff --git a/crypto/keys/secp256k1/secp256k1.go b/crypto/keys/secp256k1/secp256k1.go index 51034275cd94..9ec713acbe36 100644 --- a/crypto/keys/secp256k1/secp256k1.go +++ b/crypto/keys/secp256k1/secp256k1.go @@ -10,7 +10,7 @@ import ( secp256k1 "github.com/btcsuite/btcd/btcec" "github.com/tendermint/tendermint/crypto" - "golang.org/x/crypto/ripemd160" // nolint: staticcheck // necessary for Bitcoin address format + "golang.org/x/crypto/ripemd160" //nolint: staticcheck // necessary for Bitcoin address format "github.com/cosmos/cosmos-sdk/codec" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" diff --git a/crypto/keys/secp256k1/secp256k1_nocgo.go b/crypto/keys/secp256k1/secp256k1_nocgo.go index 60fd9577978c..e12a410a81cc 100644 --- a/crypto/keys/secp256k1/secp256k1_nocgo.go +++ b/crypto/keys/secp256k1/secp256k1_nocgo.go @@ -13,8 +13,8 @@ import ( // used to reject malleable signatures // see: -// - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/signature_nocgo.go#L90-L93 -// - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/crypto.go#L39 +// - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/signature_nocgo.go#L90-L93 +// - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/crypto.go#L39 var secp256k1halfN = new(big.Int).Rsh(secp256k1.S256().N, 1) // Sign creates an ECDSA signature on curve Secp256k1, using SHA256 on the msg. diff --git a/db/types.go b/db/types.go index a800672bebfe..d4aac2cf98cc 100644 --- a/db/types.go +++ b/db/types.go @@ -146,16 +146,16 @@ type ReadWriter interface { // // Typical usage: // -// var itr Iterator = ... -// defer itr.Close() +// var itr Iterator = ... +// defer itr.Close() // -// for itr.Next() { -// k, v := itr.Key(); itr.Value() -// ... -// } -// if err := itr.Error(); err != nil { -// ... -// } +// for itr.Next() { +// k, v := itr.Key(); itr.Value() +// ... +// } +// if err := itr.Error(); err != nil { +// ... +// } type Iterator interface { // Domain returns the start (inclusive) and end (exclusive) limits of the iterator. // CONTRACT: start, end readonly []byte diff --git a/depinject/config.go b/depinject/config.go index e489e28a5a4b..156cb7103240 100644 --- a/depinject/config.go +++ b/depinject/config.go @@ -92,6 +92,7 @@ func invoke(ctr *container, key *moduleKey, invokers []interface{}) error { // instance when an interface of type Duck is requested as an input. // // BindInterface( +// // "cosmossdk.io/depinject_test/depinject_test.Duck", // "cosmossdk.io/depinject_test/depinject_test.Canvasback") func BindInterface(inTypeName string, outTypeName string) Config { @@ -106,9 +107,10 @@ func BindInterface(inTypeName string, outTypeName string) Config { // "moduleFoo". // // BindInterfaceInModule( -// "moduleFoo", -// "cosmossdk.io/depinject_test/depinject_test.Duck", -// "cosmossdk.io/depinject_test/depinject_test.Canvasback") +// +// "moduleFoo", +// "cosmossdk.io/depinject_test/depinject_test.Duck", +// "cosmossdk.io/depinject_test/depinject_test.Canvasback") func BindInterfaceInModule(moduleName string, inTypeName string, outTypeName string) Config { return containerConfig(func(ctr *container) error { return bindInterface(ctr, inTypeName, outTypeName, moduleName) diff --git a/depinject/container.go b/depinject/container.go index 47fd95d32b18..13965e9239d7 100644 --- a/depinject/container.go +++ b/depinject/container.go @@ -449,7 +449,6 @@ func (c *container) build(loc Location, outputs ...interface{}) error { if !values[i].CanInterface() { return []reflect.Value{}, fmt.Errorf("depinject.Out struct %s on package can't have unexported field", values[i].String()) - } val.Elem().Set(values[i]) } diff --git a/depinject/inject.go b/depinject/inject.go index 1f3194e37105..609845781a7b 100644 --- a/depinject/inject.go +++ b/depinject/inject.go @@ -7,8 +7,9 @@ package depinject // can be provided by the container. // // Ex: -// var x int -// Inject(Provide(func() int { return 1 }), &x) +// +// var x int +// Inject(Provide(func() int { return 1 }), &x) // // Inject uses the debug mode provided by AutoDebug which means there will be // verbose debugging information if there is an error and nothing upon success. diff --git a/depinject/provider_desc.go b/depinject/provider_desc.go index 16a8f3c7972f..90d1dfd624be 100644 --- a/depinject/provider_desc.go +++ b/depinject/provider_desc.go @@ -9,7 +9,8 @@ import ( // ProviderDescriptor defines a special provider type that is defined by // reflection. It should be passed as a value to the Provide function. // Ex: -// option.Provide(ProviderDescriptor{ ... }) +// +// option.Provide(ProviderDescriptor{ ... }) type ProviderDescriptor struct { // Inputs defines the in parameter types to Fn. Inputs []ProviderInput diff --git a/depinject/struct_args.go b/depinject/struct_args.go index 07dda03c9340..d82dd3c2f856 100644 --- a/depinject/struct_args.go +++ b/depinject/struct_args.go @@ -13,9 +13,10 @@ import ( // positional parameters. // // Fields of the struct may support the following tags: -// optional if set to true, the dependency is optional and will -// be set to its default value if not found, rather than causing -// an error +// +// optional if set to true, the dependency is optional and will +// be set to its default value if not found, rather than causing +// an error type In struct{} func (In) isIn() {} @@ -176,7 +177,6 @@ func buildIn(typ reflect.Type, values []reflect.Value) (reflect.Value, int, erro } if !values[j].CanInterface() { return reflect.Value{}, 0, fmt.Errorf("depinject.Out struct %s on package %s can't have unexported field", res.Elem().String(), f.PkgPath) - } res.Elem().Field(i).Set(values[j]) diff --git a/errors/doc.go b/errors/doc.go index 6cca61580d06..ed6b9a69bfca 100644 --- a/errors/doc.go +++ b/errors/doc.go @@ -11,24 +11,23 @@ of the errors package. If it will be needed my many extensions, please consider registering it in the errors package. To create a new error instance use Register function. You must provide a unique, non zero error code and a short description, for example: - var ErrZeroDivision = errors.Register(9241, "zero division") + var ErrZeroDivision = errors.Register(9241, "zero division") When returning an error, you can attach to it an additional context information by using Wrap function, for example: - func safeDiv(val, div int) (int, err) { - if div == 0 { - return 0, errors.Wrapf(ErrZeroDivision, "cannot divide %d", val) + func safeDiv(val, div int) (int, err) { + if div == 0 { + return 0, errors.Wrapf(ErrZeroDivision, "cannot divide %d", val) + } + return val / div, nil } - return val / div, nil - } The first time an error instance is wrapped a stacktrace is attached as well. Stacktrace information can be printed using %+v and %v formats. - %s is just the error message - %+v is the full stack trace - %v appends a compressed [filename:line] where the error was created - + %s is just the error message + %+v is the full stack trace + %v appends a compressed [filename:line] where the error was created */ package errors diff --git a/errors/stacktrace.go b/errors/stacktrace.go index dc60870763a5..7453284dd378 100644 --- a/errors/stacktrace.go +++ b/errors/stacktrace.go @@ -80,7 +80,8 @@ func writeSimpleFrame(s io.Writer, f errors.Frame) { // %s is just the error message // %+v is the full stack trace // %v appends a compressed [filename:line] where the error -// was created +// +// was created // // Inspired by https://github.com/pkg/errors/blob/v0.8.1/errors.go#L162-L176 func (e *wrappedError) Format(s fmt.State, verb rune) { diff --git a/math/dec.go b/math/dec.go index 90bb8c7ace7c..6d8a473c063b 100644 --- a/math/dec.go +++ b/math/dec.go @@ -128,12 +128,15 @@ func LegacyNewDecFromIntWithPrec(i Int, prec int64) LegacyDec { // create a decimal from an input decimal string. // valid must come in the form: -// (-) whole integers (.) decimal integers +// +// (-) whole integers (.) decimal integers +// // examples of acceptable input include: -// -123.456 -// 456.7890 -// 345 -// -456789 +// +// -123.456 +// 456.7890 +// 345 +// -456789 // // NOTE - An error will return if more decimal places // are provided in the string than the constant Precision. diff --git a/math/dec_test.go b/math/dec_test.go index 637ef71ee083..7bbb8a146697 100644 --- a/math/dec_test.go +++ b/math/dec_test.go @@ -628,7 +628,7 @@ func BenchmarkLegacyQuoMut(b *testing.B) { b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { - sink = b1.QuoMut(b2) + sink = b1.QuoMut(b2) } if sink == nil { @@ -643,7 +643,7 @@ func BenchmarkLegacyQuoTruncateMut(b *testing.B) { b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { - sink = b1.QuoTruncateMut(b2) + sink = b1.QuoTruncateMut(b2) } if sink == nil { @@ -658,7 +658,7 @@ func BenchmarkLegacyQuoRoundupMut(b *testing.B) { b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { - sink = b1.QuoRoundupMut(b2) + sink = b1.QuoRoundupMut(b2) } if sink == nil { diff --git a/orm/internal/testpb/bank.cosmos_orm.go b/orm/internal/testpb/bank.cosmos_orm.go index 0635179c20e8..51a36e5b8035 100644 --- a/orm/internal/testpb/bank.cosmos_orm.go +++ b/orm/internal/testpb/bank.cosmos_orm.go @@ -4,6 +4,7 @@ package testpb import ( context "context" + ormlist "github.com/cosmos/cosmos-sdk/orm/model/ormlist" ormtable "github.com/cosmos/cosmos-sdk/orm/model/ormtable" ormerrors "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" diff --git a/orm/internal/testpb/test_schema.cosmos_orm.go b/orm/internal/testpb/test_schema.cosmos_orm.go index a5cf2a6fbd11..0306c97c8c56 100644 --- a/orm/internal/testpb/test_schema.cosmos_orm.go +++ b/orm/internal/testpb/test_schema.cosmos_orm.go @@ -4,6 +4,7 @@ package testpb import ( context "context" + ormlist "github.com/cosmos/cosmos-sdk/orm/model/ormlist" ormtable "github.com/cosmos/cosmos-sdk/orm/model/ormtable" ormerrors "github.com/cosmos/cosmos-sdk/orm/types/ormerrors" diff --git a/orm/testing/ormtest/membackend.go b/orm/testing/ormtest/membackend.go index 02e6c85f00c4..f757daab1508 100644 --- a/orm/testing/ormtest/membackend.go +++ b/orm/testing/ormtest/membackend.go @@ -10,9 +10,10 @@ import ( // testing purposes independent of any storage layer. // // Example: -// backend := ormtest.NewMemoryBackend() -// ctx := ormtable.WrapContextDefault() -// ... +// +// backend := ormtest.NewMemoryBackend() +// ctx := ormtable.WrapContextDefault() +// ... func NewMemoryBackend() ormtable.Backend { return testkv.NewSplitMemBackend() } diff --git a/runtime/app.go b/runtime/app.go index f9e03d41943b..dbc82543cde9 100644 --- a/runtime/app.go +++ b/runtime/app.go @@ -33,7 +33,7 @@ import ( // done declaratively with an app config and the rest of it is done the old way. // See simapp/app.go for an example of this setup. // -// nolint:unused +//nolint:unused type App struct { *baseapp.BaseApp diff --git a/server/config/toml.go b/server/config/toml.go index a93fffd1ecd6..65dceec60efd 100644 --- a/server/config/toml.go +++ b/server/config/toml.go @@ -3,7 +3,6 @@ package config import ( "bytes" "fmt" - "io/ioutil" "os" "text/template" @@ -280,7 +279,7 @@ func WriteConfigFile(configFilePath string, config interface{}) { } func mustWriteFile(filePath string, contents []byte, mode os.FileMode) { - if err := ioutil.WriteFile(filePath, contents, mode); err != nil { + if err := os.WriteFile(filePath, contents, mode); err != nil { fmt.Printf(fmt.Sprintf("failed to write file: %v", err) + "\n") os.Exit(1) } diff --git a/server/grpc/gogoreflection/fix_registration.go b/server/grpc/gogoreflection/fix_registration.go index ab7750574845..d75c951f7392 100644 --- a/server/grpc/gogoreflection/fix_registration.go +++ b/server/grpc/gogoreflection/fix_registration.go @@ -9,7 +9,7 @@ import ( _ "github.com/gogo/protobuf/gogoproto" // required so it does register the gogoproto file descriptor gogoproto "github.com/gogo/protobuf/proto" - // nolint: staticcheck + //nolint: staticcheck "github.com/golang/protobuf/proto" dpb "github.com/golang/protobuf/protoc-gen-go/descriptor" _ "github.com/regen-network/cosmos-proto" // look above @@ -60,7 +60,8 @@ func init() { } // compress compresses the given file descriptor -// nolint: interfacer +// +//nolint:interfacer func compress(fd *dpb.FileDescriptorProto) ([]byte, error) { fdBytes, err := proto.Marshal(fd) if err != nil { @@ -86,7 +87,7 @@ func getFileDescriptor(filePath string) []byte { if len(fd) != 0 { return fd } - // nolint: staticcheck + //nolint: staticcheck return proto.FileDescriptor(filePath) } @@ -95,7 +96,7 @@ func getMessageType(name string) reflect.Type { if typ != nil { return typ } - // nolint: staticcheck + //nolint: staticcheck return proto.MessageType(name) } @@ -107,7 +108,7 @@ func getExtension(extID int32, m proto.Message) *gogoproto.ExtensionDesc { } } // check into proto registry - // nolint: staticcheck + //nolint: staticcheck for id, desc := range proto.RegisteredExtensions(m) { if id == extID { return &gogoproto.ExtensionDesc{ @@ -133,7 +134,7 @@ func getExtensionsNumbers(m proto.Message) []int32 { if len(out) != 0 { return out } - // nolint: staticcheck + //nolint: staticcheck protoExts := proto.RegisteredExtensions(m) out = make([]int32, 0, len(protoExts)) for id := range protoExts { diff --git a/server/grpc/gogoreflection/serverreflection.go b/server/grpc/gogoreflection/serverreflection.go index e98ffe1e1412..ac1e3c2d0526 100644 --- a/server/grpc/gogoreflection/serverreflection.go +++ b/server/grpc/gogoreflection/serverreflection.go @@ -23,6 +23,7 @@ The service implemented is defined in: https://github.com/grpc/grpc/blob/master/src/proto/grpc/reflection/v1alpha/reflection.proto. To register server reflection on a gRPC server: + import "google.golang.org/grpc/reflection" s := grpc.NewServer() @@ -32,7 +33,6 @@ To register server reflection on a gRPC server: reflection.Register(s) s.Serve(lis) - */ package gogoreflection // import "google.golang.org/grpc/reflection" @@ -46,7 +46,7 @@ import ( "sort" "sync" - // nolint: staticcheck + //nolint: staticcheck "github.com/golang/protobuf/proto" dpb "github.com/golang/protobuf/protoc-gen-go/descriptor" "google.golang.org/grpc" diff --git a/server/mock/helpers.go b/server/mock/helpers.go index 69a8504c3ccc..9aa0ff61c1f9 100644 --- a/server/mock/helpers.go +++ b/server/mock/helpers.go @@ -2,7 +2,6 @@ package mock import ( "fmt" - "io/ioutil" "os" "github.com/rs/zerolog" @@ -23,7 +22,7 @@ func SetupApp() (abci.Application, func(), error) { } logger = logger.With("module", "mock") - rootDir, err := ioutil.TempDir("", "mock-sdk") + rootDir, err := os.MkdirTemp("", "mock-sdk") if err != nil { return nil, nil, err } diff --git a/server/mock/tx.go b/server/mock/tx.go index 3c93ffb83410..af0f52e566ac 100644 --- a/server/mock/tx.go +++ b/server/mock/tx.go @@ -1,4 +1,3 @@ -//nolint package mock import ( @@ -70,7 +69,7 @@ func decodeTx(txBytes []byte) (sdk.Tx, error) { var tx sdk.Tx split := bytes.Split(txBytes, []byte("=")) - if len(split) == 1 { + if len(split) == 1 { //nolint:gocritic k := split[0] tx = kvstoreTx{k, k, txBytes} } else if len(split) == 2 { diff --git a/server/rosetta/client_online.go b/server/rosetta/client_online.go index 478bfe6aafbe..d971518e521f 100644 --- a/server/rosetta/client_online.go +++ b/server/rosetta/client_online.go @@ -256,7 +256,8 @@ func (c *Client) TxOperationsAndSignersAccountIdentifiers(signed bool, txBytes [ } // GetTx returns a transaction given its hash. For Rosetta we make a synthetic transaction for BeginBlock -// and EndBlock to adhere to balance tracking rules. +// +// and EndBlock to adhere to balance tracking rules. func (c *Client) GetTx(ctx context.Context, hash string) (*rosettatypes.Transaction, error) { hashBytes, err := hex.DecodeString(hash) if err != nil { diff --git a/server/rosetta/converter.go b/server/rosetta/converter.go index 02321a1a0e2a..2beca0e47168 100644 --- a/server/rosetta/converter.go +++ b/server/rosetta/converter.go @@ -31,9 +31,9 @@ import ( // Converter is a utility that can be used to convert // back and forth from rosetta to sdk and tendermint types // IMPORTANT NOTES: -// - IT SHOULD BE USED ONLY TO DEAL WITH THINGS -// IN A STATELESS WAY! IT SHOULD NEVER INTERACT DIRECTLY -// WITH TENDERMINT RPC AND COSMOS GRPC +// - IT SHOULD BE USED ONLY TO DEAL WITH THINGS +// IN A STATELESS WAY! IT SHOULD NEVER INTERACT DIRECTLY +// WITH TENDERMINT RPC AND COSMOS GRPC // // - IT SHOULD RETURN cosmos rosetta gateway error types! type Converter interface { diff --git a/simapp/export.go b/simapp/export.go index 990a426c4dc0..d47e23a80f0f 100644 --- a/simapp/export.go +++ b/simapp/export.go @@ -47,7 +47,8 @@ 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 favour of export at a block height func (app *SimApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) { applyAllowedAddrs := false diff --git a/simapp/simd/cmd/testnet.go b/simapp/simd/cmd/testnet.go index 1fd12e5a8727..38e9ed4c1889 100644 --- a/simapp/simd/cmd/testnet.go +++ b/simapp/simd/cmd/testnet.go @@ -6,7 +6,6 @@ import ( "bufio" "encoding/json" "fmt" - "io/ioutil" "net" "os" "path/filepath" @@ -476,7 +475,7 @@ func writeFile(name string, dir string, contents []byte) error { return err } - err = ioutil.WriteFile(file, contents, 0o644) // nolint: gosec + err = os.WriteFile(file, contents, 0o644) //nolint: gosec if err != nil { return err } diff --git a/snapshots/manager.go b/snapshots/manager.go index dbca39ea2be7..05cbad3f5b30 100644 --- a/snapshots/manager.go +++ b/snapshots/manager.go @@ -23,12 +23,12 @@ import ( // Although the ABCI interface (and this manager) passes chunks as byte slices, the internal // snapshot/restore APIs use IO streams (i.e. chan io.ReadCloser), for two reasons: // -// 1) In the future, ABCI should support streaming. Consider e.g. InitChain during chain -// upgrades, which currently passes the entire chain state as an in-memory byte slice. -// https://github.com/tendermint/tendermint/issues/5184 +// 1. In the future, ABCI should support streaming. Consider e.g. InitChain during chain +// upgrades, which currently passes the entire chain state as an in-memory byte slice. +// https://github.com/tendermint/tendermint/issues/5184 // -// 2) io.ReadCloser streams automatically propagate IO errors, and can pass arbitrary -// errors via io.Pipe.CloseWithError(). +// 2. io.ReadCloser streams automatically propagate IO errors, and can pass arbitrary +// errors via io.Pipe.CloseWithError(). type Manager struct { extensions map[string]types.ExtensionSnapshotter // store is the snapshot store where all completed snapshots are persisted. diff --git a/snapshots/store.go b/snapshots/store.go index 8105938b80f1..03c35392542b 100644 --- a/snapshots/store.go +++ b/snapshots/store.go @@ -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() //nolint: staticcheck 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() //nolint: staticcheck chunkHasher.Reset() _, err = io.Copy(io.MultiWriter(file, chunkHasher, snapshotHasher), chunkBody) diff --git a/store/iavl/store.go b/store/iavl/store.go index 1b409101e605..fd57436a4fa5 100644 --- a/store/iavl/store.go +++ b/store/iavl/store.go @@ -417,6 +417,7 @@ var _ types.Iterator = (*iavlIterator)(nil) // newIAVLIterator will create a new iavlIterator. // CONTRACT: Caller must release the iavlIterator, as each one creates a new // goroutine. +// //nolint:deadcode,unused func newIAVLIterator(tree *iavl.ImmutableTree, start, end []byte, ascending bool) *iavlIterator { iterator, err := tree.Iterator(start, end, ascending) diff --git a/store/mem/store.go b/store/mem/store.go index 06d7b63f5506..51968610950f 100644 --- a/store/mem/store.go +++ b/store/mem/store.go @@ -28,7 +28,7 @@ func NewStore() *Store { return NewStoreWithDB(dbm.NewMemDB()) } -func NewStoreWithDB(db *dbm.MemDB) *Store { // nolint: interfacer +func NewStoreWithDB(db *dbm.MemDB) *Store { //nolint: interfacer return &Store{Store: dbadapter.Store{DB: db}} } diff --git a/store/streaming/file/service.go b/store/streaming/file/service.go index dd97ec4dea7a..2f7664af1b86 100644 --- a/store/streaming/file/service.go +++ b/store/streaming/file/service.go @@ -3,7 +3,6 @@ package file import ( "errors" "fmt" - "io/ioutil" "os" "path" "path/filepath" @@ -284,7 +283,7 @@ func (fss *StreamingService) Close() error { // to dir. It returns nil if dir is writable. func isDirWriteable(dir string) error { f := path.Join(dir, ".touch") - if err := ioutil.WriteFile(f, []byte(""), 0o600); err != nil { + if err := os.WriteFile(f, []byte(""), 0o600); err != nil { return err } return os.Remove(f) diff --git a/store/streaming/file/service_test.go b/store/streaming/file/service_test.go index cc9fdca88136..553d9f282795 100644 --- a/store/streaming/file/service_test.go +++ b/store/streaming/file/service_test.go @@ -3,7 +3,6 @@ package file import ( "encoding/binary" "fmt" - "io/ioutil" "os" "path/filepath" "sync" @@ -369,7 +368,7 @@ func testListenEndBlock(t *testing.T) { func readInFile(name string) ([]byte, error) { path := filepath.Join(testDir, name) - return ioutil.ReadFile(path) + return os.ReadFile(path) } // segmentBytes returns all of the protobuf messages contained in the byte array as an array of byte arrays diff --git a/store/v2alpha1/multi/test_util.go b/store/v2alpha1/multi/test_util.go index da2c7f9c9346..78924c8dafa4 100644 --- a/store/v2alpha1/multi/test_util.go +++ b/store/v2alpha1/multi/test_util.go @@ -1,4 +1,4 @@ -// nolint:unused +//nolint:unused package multi import ( @@ -43,7 +43,7 @@ func (dbSaveVersionFails) SaveVersion(uint64) error { return errors.New("dbSaveV func (db dbRevertFails) Revert() error { fail := false if len(db.failOn) > 0 { - fail, db.failOn = db.failOn[0], db.failOn[1:] // nolint:staticcheck + fail, db.failOn = db.failOn[0], db.failOn[1:] //nolint:staticcheck } if fail { return errors.New("dbRevertFails") diff --git a/tests/e2e/bank/client/suite.go b/tests/e2e/bank/client/suite.go index 3ed0faa766c5..2c7f3c2ceb12 100644 --- a/tests/e2e/bank/client/suite.go +++ b/tests/e2e/bank/client/suite.go @@ -2,7 +2,7 @@ package client import ( "fmt" - "io/ioutil" + "io" "os" "github.com/gogo/protobuf/proto" @@ -419,7 +419,7 @@ func (s *EndToEndTestSuite) TestNewSendTxCmdDryRun() { s.Require().NoError(err) w.Close() - out, _ := ioutil.ReadAll(r) + out, _ := io.ReadAll(r) os.Stderr = oldSterr s.Require().Regexp("gas estimate: [0-9]+", string(out)) diff --git a/tests/e2e/client/grpc/tmservice/service_test.go b/tests/e2e/client/grpc/tmservice/service_test.go index f75b15347d77..8ce21b566f34 100644 --- a/tests/e2e/client/grpc/tmservice/service_test.go +++ b/tests/e2e/client/grpc/tmservice/service_test.go @@ -31,7 +31,6 @@ type IntegrationTestSuite struct { } func TestIntegrationTestSuite(t *testing.T) { - suite.Run(t, new(IntegrationTestSuite)) } diff --git a/tests/integration/bank/keeper/keeper_test.go b/tests/integration/bank/keeper/keeper_test.go index bd79a6a3602d..bfdc9d2be978 100644 --- a/tests/integration/bank/keeper/keeper_test.go +++ b/tests/integration/bank/keeper/keeper_test.go @@ -122,7 +122,6 @@ func (suite *IntegrationTestSuite) initKeepersWithmAccPerms(blockedAddrs map[str } func (suite *IntegrationTestSuite) SetupTest() { - var interfaceRegistry codectypes.InterfaceRegistry app, err := sims.Setup( @@ -139,7 +138,7 @@ func (suite *IntegrationTestSuite) SetupTest() { suite.ctx = app.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) suite.fetchStoreKey = app.UnsafeFindStoreKey - //suite.Require().NoError(suite.accountKeeper.SetParams(suite.ctx, authtypes.DefaultParams())) + // suite.Require().NoError(suite.accountKeeper.SetParams(suite.ctx, authtypes.DefaultParams())) suite.Require().NoError(suite.bankKeeper.SetParams(suite.ctx, types.DefaultParams())) queryHelper := baseapp.NewQueryServerTestHelper(suite.ctx, interfaceRegistry) diff --git a/testutil/network/network.go b/testutil/network/network.go index 4b3213c3b714..47e4dcd82646 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -62,8 +62,10 @@ var lock = new(sync.Mutex) // AppConstructor defines a function which accepts a network configuration and // creates an ABCI Application to provide to Tendermint. -type AppConstructor = func(val moduletestutil.Validator) servertypes.Application -type TestFixtureFactory = func() TestFixture +type ( + AppConstructor = func(val moduletestutil.Validator) servertypes.Application + TestFixtureFactory = func() TestFixture +) type TestFixture struct { AppConstructor AppConstructor diff --git a/testutil/network/util.go b/testutil/network/util.go index e3ace5544445..9cb8fbc27507 100644 --- a/testutil/network/util.go +++ b/testutil/network/util.go @@ -3,7 +3,7 @@ package network import ( "encoding/json" "fmt" - "io/ioutil" + "os" "path/filepath" "time" @@ -200,7 +200,7 @@ func writeFile(name string, dir string, contents []byte) error { return err } - err = ioutil.WriteFile(file, contents, 0o644) // nolint: gosec + err = os.WriteFile(file, contents, 0o644) //nolint: gosec if err != nil { return err } diff --git a/testutil/rest/rest.go b/testutil/rest/rest.go index c2cd418d0d14..89a16b3ff286 100644 --- a/testutil/rest/rest.go +++ b/testutil/rest/rest.go @@ -12,7 +12,7 @@ import ( // GetRequest defines a wrapper around an HTTP GET request with a provided URL. // An error is returned if the request or reading the body fails. func GetRequest(url string) ([]byte, error) { - res, err := http.Get(url) // nolint:gosec + res, err := http.Get(url) //nolint:gosec if err != nil { return nil, err } @@ -31,7 +31,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) { - res, err := http.Post(url, contentType, bytes.NewBuffer(data)) // nolint:gosec + 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/tx/textual/valuerenderer/bytes.go b/tx/textual/valuerenderer/bytes.go index 2600c87be20a..79ee076ed0cd 100644 --- a/tx/textual/valuerenderer/bytes.go +++ b/tx/textual/valuerenderer/bytes.go @@ -9,8 +9,7 @@ import ( ) // bytesValueRenderer implements ValueRenderer for bytes -type bytesValueRenderer struct { -} +type bytesValueRenderer struct{} var _ ValueRenderer = bytesValueRenderer{} diff --git a/tx/textual/valuerenderer/bytes_test.go b/tx/textual/valuerenderer/bytes_test.go index 63565282743b..c5853d56214a 100644 --- a/tx/textual/valuerenderer/bytes_test.go +++ b/tx/textual/valuerenderer/bytes_test.go @@ -4,7 +4,7 @@ import ( "context" "encoding/hex" "encoding/json" - "io/ioutil" + "os" "strings" "testing" @@ -14,7 +14,7 @@ import ( func TestFormatBytes(t *testing.T) { var testcases []bytesTest - raw, err := ioutil.ReadFile("../internal/testdata/bytes.json") + raw, err := os.ReadFile("../internal/testdata/bytes.json") require.NoError(t, err) err = json.Unmarshal(raw, &testcases) diff --git a/tx/textual/valuerenderer/valuerenderer_test.go b/tx/textual/valuerenderer/valuerenderer_test.go index 9d5361674554..23d51d84f844 100644 --- a/tx/textual/valuerenderer/valuerenderer_test.go +++ b/tx/textual/valuerenderer/valuerenderer_test.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "os" "strconv" "strings" "testing" @@ -20,7 +20,7 @@ import ( func TestFormatInteger(t *testing.T) { type integerTest []string var testcases []integerTest - raw, err := ioutil.ReadFile("../internal/testdata/integers.json") + raw, err := os.ReadFile("../internal/testdata/integers.json") require.NoError(t, err) err = json.Unmarshal(raw, &testcases) require.NoError(t, err) @@ -67,7 +67,7 @@ func TestFormatInteger(t *testing.T) { func TestFormatDecimal(t *testing.T) { type decimalTest []string var testcases []decimalTest - raw, err := ioutil.ReadFile("../internal/testdata/decimals.json") + raw, err := os.ReadFile("../internal/testdata/decimals.json") require.NoError(t, err) err = json.Unmarshal(raw, &testcases) require.NoError(t, err) diff --git a/types/coin.go b/types/coin.go index 145aa2cdb7a3..52155a6edd13 100644 --- a/types/coin.go +++ b/types/coin.go @@ -489,10 +489,11 @@ func (coins Coins) SafeQuoInt(x Int) (Coins, bool) { // of AmountOf(D) of the inputs. Note that the result might be not // be equal to either input. For any valid Coins a, b, and c, the // following are always true: -// a.IsAllLTE(a.Max(b)) -// b.IsAllLTE(a.Max(b)) -// a.IsAllLTE(c) && b.IsAllLTE(c) == a.Max(b).IsAllLTE(c) -// a.Add(b...).IsEqual(a.Min(b).Add(a.Max(b)...)) +// +// a.IsAllLTE(a.Max(b)) +// b.IsAllLTE(a.Max(b)) +// a.IsAllLTE(c) && b.IsAllLTE(c) == a.Max(b).IsAllLTE(c) +// a.Add(b...).IsEqual(a.Min(b).Add(a.Max(b)...)) // // E.g. // {1A, 3B, 2C}.Max({4A, 2B, 2C} == {4A, 3B, 2C}) @@ -534,10 +535,11 @@ func (coins Coins) Max(coinsB Coins) Coins { // of AmountOf(D) of the inputs. Note that the result might be not // be equal to either input. For any valid Coins a, b, and c, the // following are always true: -// a.Min(b).IsAllLTE(a) -// a.Min(b).IsAllLTE(b) -// c.IsAllLTE(a) && c.IsAllLTE(b) == c.IsAllLTE(a.Min(b)) -// a.Add(b...).IsEqual(a.Min(b).Add(a.Max(b)...)) +// +// a.Min(b).IsAllLTE(a) +// a.Min(b).IsAllLTE(b) +// c.IsAllLTE(a) && c.IsAllLTE(b) == c.IsAllLTE(a.Min(b)) +// a.Add(b...).IsEqual(a.Min(b).Add(a.Max(b)...)) // // E.g. // {1A, 3B, 2C}.Min({4A, 2B, 2C} == {1A, 2B, 2C}) diff --git a/types/config.go b/types/config.go index 00b701a025d7..fce6c73526e2 100644 --- a/types/config.go +++ b/types/config.go @@ -91,7 +91,8 @@ func (config *Config) SetBech32PrefixForAccount(addressPrefix, pubKeyPrefix stri } // SetBech32PrefixForValidator builds the Config with Bech32 addressPrefix and publKeyPrefix for validators -// and returns the config instance +// +// and returns the config instance func (config *Config) SetBech32PrefixForValidator(addressPrefix, pubKeyPrefix string) { config.assertNotSealed() config.bech32AddressPrefix["validator_addr"] = addressPrefix diff --git a/types/errors/errors.go b/types/errors/errors.go index 52cd584b209a..1c2036f8eb75 100644 --- a/types/errors/errors.go +++ b/types/errors/errors.go @@ -7,7 +7,9 @@ import ( // Type Aliases to errors module // // Deprecated: functionality of this package has been moved to it's own module: -// cosmossdk.io/errors +// +// cosmossdk.io/errors +// // Please use the above module instead of this package. var ( SuccessABCICode = errorsmod.SuccessABCICode diff --git a/types/handler.go b/types/handler.go index 03d1f02d5806..87762744ee86 100644 --- a/types/handler.go +++ b/types/handler.go @@ -43,21 +43,22 @@ func ChainAnteDecorators(chain ...AnteDecorator) AnteHandler { // Terminator AnteDecorator will get added to the chain to simplify decorator code // Don't need to check if next == nil further up the chain -// ______ -// <((((((\\\ -// / . }\ -// ;--..--._|} -// (\ '--/\--' ) -// \\ | '-' :'| -// \\ . -==- .-| -// \\ \.__.' \--._ -// [\\ __.--| // _/'--. -// \ \\ .'-._ ('-----'/ __/ \ -// \ \\ / __>| | '--. | -// \ \\ | \ | / / / -// \ '\ / \ | | _/ / -// \ \ \ | | / / -// snd \ \ \ / +// +// ______ +// <((((((\\\ +// / . }\ +// ;--..--._|} +// (\ '--/\--' ) +// \\ | '-' :'| +// \\ . -==- .-| +// \\ \.__.' \--._ +// [\\ __.--| // _/'--. +// \ \\ .'-._ ('-----'/ __/ \ +// \ \\ / __>| | '--. | +// \ \\ | \ | / / / +// \ '\ / \ | | _/ / +// \ \ \ | | / / +// snd \ \ \ / type Terminator struct{} // Simply return provided Context and nil error diff --git a/types/module/module.go b/types/module/module.go index da4719fb7fad..08910d33ca40 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -1,10 +1,10 @@ /* Package module contains application module patterns and associated "manager" functionality. The module pattern has been broken down by: - - independent module functionality (AppModuleBasic) - - inter-dependent module genesis functionality (AppModuleGenesis) - - inter-dependent module simulation functionality (AppModuleSimulation) - - inter-dependent module full functionality (AppModule) + - independent module functionality (AppModuleBasic) + - inter-dependent module genesis functionality (AppModuleGenesis) + - inter-dependent module simulation functionality (AppModuleSimulation) + - inter-dependent module full functionality (AppModule) inter-dependent module functionality is module functionality which somehow depends on other modules, typically through the module keeper. Many of the @@ -364,19 +364,21 @@ type VersionMap map[string]uint64 // returning RunMigrations should be enough: // // Example: -// cfg := module.NewConfigurator(...) -// app.UpgradeKeeper.SetUpgradeHandler("my-plan", func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { -// return app.mm.RunMigrations(ctx, cfg, fromVM) -// }) +// +// cfg := module.NewConfigurator(...) +// app.UpgradeKeeper.SetUpgradeHandler("my-plan", func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { +// return app.mm.RunMigrations(ctx, cfg, fromVM) +// }) // // Internally, RunMigrations will perform the following steps: // - create an `updatedVM` VersionMap of module with their latest ConsensusVersion // - make a diff of `fromVM` and `udpatedVM`, and for each module: -// - if the module's `fromVM` version is less than its `updatedVM` version, -// then run in-place store migrations for that module between those versions. -// - if the module does not exist in the `fromVM` (which means that it's a new module, -// because it was not in the previous x/upgrade's store), then run -// `InitGenesis` on that module. +// - if the module's `fromVM` version is less than its `updatedVM` version, +// then run in-place store migrations for that module between those versions. +// - if the module does not exist in the `fromVM` (which means that it's a new module, +// because it was not in the previous x/upgrade's store), then run +// `InitGenesis` on that module. +// // - return the `updatedVM` to be persisted in the x/upgrade's store. // // Migrations are run in an order defined by `Manager.OrderMigrations` or (if not set) defined by @@ -389,18 +391,19 @@ type VersionMap map[string]uint64 // running anything for foo. // // Example: -// cfg := module.NewConfigurator(...) -// app.UpgradeKeeper.SetUpgradeHandler("my-plan", func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { -// // Assume "foo" is a new module. -// // `fromVM` is fetched from existing x/upgrade store. Since foo didn't exist -// // before this upgrade, `v, exists := fromVM["foo"]; exists == false`, and RunMigration will by default -// // run InitGenesis on foo. -// // To skip running foo's InitGenesis, you need set `fromVM`'s foo to its latest -// // consensus version: -// fromVM["foo"] = foo.AppModule{}.ConsensusVersion() // -// return app.mm.RunMigrations(ctx, cfg, fromVM) -// }) +// cfg := module.NewConfigurator(...) +// app.UpgradeKeeper.SetUpgradeHandler("my-plan", func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { +// // Assume "foo" is a new module. +// // `fromVM` is fetched from existing x/upgrade store. Since foo didn't exist +// // before this upgrade, `v, exists := fromVM["foo"]; exists == false`, and RunMigration will by default +// // run InitGenesis on foo. +// // To skip running foo's InitGenesis, you need set `fromVM`'s foo to its latest +// // consensus version: +// fromVM["foo"] = foo.AppModule{}.ConsensusVersion() +// +// return app.mm.RunMigrations(ctx, cfg, fromVM) +// }) // // Please also refer to docs/core/upgrade.md for more information. func (m Manager) RunMigrations(ctx sdk.Context, cfg Configurator, fromVM VersionMap) (VersionMap, error) { diff --git a/types/msgservice/msg_service.go b/types/msgservice/msg_service.go index f8dc5aff5029..65a81c0ddf21 100644 --- a/types/msgservice/msg_service.go +++ b/types/msgservice/msg_service.go @@ -4,7 +4,7 @@ import ( "bytes" "compress/gzip" "fmt" - "io/ioutil" + "io" "reflect" "github.com/gogo/protobuf/proto" @@ -64,7 +64,7 @@ func unzip(b []byte) []byte { panic(err) } - unzipped, err := ioutil.ReadAll(r) + unzipped, err := io.ReadAll(r) if err != nil { panic(err) } diff --git a/types/tx/types.go b/types/tx/types.go index 0db3cf9529be..089243e5e9ad 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/version/version.go b/version/version.go index cfb37683f12e..a41834e336c2 100644 --- a/version/version.go +++ b/version/version.go @@ -3,17 +3,17 @@ // produces apps versioning information based on flags // passed at compile time. // -// Configure the version command +// # Configure the version command // // The version command can be just added to your cobra root command. // At build time, the variables Name, Version, Commit, and BuildTags // can be passed as build flags as shown in the following example: // -// go build -X github.com/cosmos/cosmos-sdk/version.Name=gaia \ -// -X github.com/cosmos/cosmos-sdk/version.AppName=gaiad \ -// -X github.com/cosmos/cosmos-sdk/version.Version=1.0 \ -// -X github.com/cosmos/cosmos-sdk/version.Commit=f0f7b7dab7e36c20b757cebce0e8f4fc5b95de60 \ -// -X "github.com/cosmos/cosmos-sdk/version.BuildTags=linux darwin amd64" +// go build -X github.com/cosmos/cosmos-sdk/version.Name=gaia \ +// -X github.com/cosmos/cosmos-sdk/version.AppName=gaiad \ +// -X github.com/cosmos/cosmos-sdk/version.Version=1.0 \ +// -X github.com/cosmos/cosmos-sdk/version.Commit=f0f7b7dab7e36c20b757cebce0e8f4fc5b95de60 \ +// -X "github.com/cosmos/cosmos-sdk/version.BuildTags=linux darwin amd64" package version import ( diff --git a/x/auth/ante/ante_test.go b/x/auth/ante/ante_test.go index 017653dc06b7..0ff3cdaefbf0 100644 --- a/x/auth/ante/ante_test.go +++ b/x/auth/ante/ante_test.go @@ -69,7 +69,8 @@ func TestSimulateGasCost(t *testing.T) { testdata.NewTestMsg(accs[1].acc.GetAddress(), accs[2].acc.GetAddress()), } - return TestCaseArgs{accNums: []uint64{0, 1, 2}, + return TestCaseArgs{ + accNums: []uint64{0, 1, 2}, accSeqs: []uint64{0, 0, 0}, feeAmount: feeAmount, gasLimit: simulatedGas, @@ -867,7 +868,8 @@ func TestAnteHandlerMultiSigner(t *testing.T) { privs, accNums, accSeqs = []cryptotypes.PrivKey{accs[0].priv, accs[1].priv, accs[2].priv}, []uint64{0, 1, 2}, []uint64{1, 1, 1} - return TestCaseArgs{accNums: accNums, + return TestCaseArgs{ + accNums: accNums, accSeqs: accSeqs, msgs: msgs, privs: privs, @@ -950,7 +952,7 @@ func TestAnteHandlerBadSignBytes(t *testing.T) { return TestCaseArgs{ chainID: suite.ctx.ChainID(), accNums: []uint64{0}, - accSeqs: []uint64{2}, //wrong accSeq + accSeqs: []uint64{2}, // wrong accSeq feeAmount: feeAmount, gasLimit: gasLimit, msgs: []sdk.Msg{msg0}, @@ -1018,7 +1020,6 @@ func TestAnteHandlerBadSignBytes(t *testing.T) { msgs: []sdk.Msg{msg0}, privs: []cryptotypes.PrivKey{accs[1].priv}, } - }, false, false, diff --git a/x/auth/ante/feegrant_test.go b/x/auth/ante/feegrant_test.go index 9729b14c6879..d14b798df1a1 100644 --- a/x/auth/ante/feegrant_test.go +++ b/x/auth/ante/feegrant_test.go @@ -31,17 +31,18 @@ func TestDeductFeesNoDelegation(t *testing.T) { valid bool err error malleate func(*AnteTestSuite) (signer TestAccount, feeAcc sdk.AccAddress) - }{"paying with low funds": { - fee: 50, - valid: false, - err: sdkerrors.ErrInsufficientFunds, - malleate: func(suite *AnteTestSuite) (TestAccount, sdk.AccAddress) { - accs := suite.CreateTestAccounts(1) - // 2 calls are needed because we run the ante twice - suite.bankKeeper.EXPECT().SendCoinsFromAccountToModule(gomock.Any(), accs[0].acc.GetAddress(), authtypes.FeeCollectorName, gomock.Any()).Return(sdkerrors.ErrInsufficientFunds).Times(2) - return accs[0], nil + }{ + "paying with low funds": { + fee: 50, + valid: false, + err: sdkerrors.ErrInsufficientFunds, + malleate: func(suite *AnteTestSuite) (TestAccount, sdk.AccAddress) { + accs := suite.CreateTestAccounts(1) + // 2 calls are needed because we run the ante twice + suite.bankKeeper.EXPECT().SendCoinsFromAccountToModule(gomock.Any(), accs[0].acc.GetAddress(), authtypes.FeeCollectorName, gomock.Any()).Return(sdkerrors.ErrInsufficientFunds).Times(2) + return accs[0], nil + }, }, - }, "paying with good funds": { fee: 50, valid: true, diff --git a/x/auth/ante/testutil_test.go b/x/auth/ante/testutil_test.go index d996dcc3bddb..93318e7fdb4c 100644 --- a/x/auth/ante/testutil_test.go +++ b/x/auth/ante/testutil_test.go @@ -52,7 +52,7 @@ func SetupTestSuite(t *testing.T, isCheckTx bool) *AnteTestSuite { key := sdk.NewKVStoreKey(types.StoreKey) testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) - suite.ctx = testCtx.Ctx.WithIsCheckTx(isCheckTx).WithBlockHeight(1) //app.BaseApp.NewContext(isCheckTx, tmproto.Header{}).WithBlockHeight(1) + suite.ctx = testCtx.Ctx.WithIsCheckTx(isCheckTx).WithBlockHeight(1) // app.BaseApp.NewContext(isCheckTx, tmproto.Header{}).WithBlockHeight(1) suite.encCfg = moduletestutil.MakeTestEncodingConfig(auth.AppModuleBasic{}) maccPerms := map[string][]string{ diff --git a/x/auth/keeper/keeper.go b/x/auth/keeper/keeper.go index ab1778bd24cd..510e39ebf4ff 100644 --- a/x/auth/keeper/keeper.go +++ b/x/auth/keeper/keeper.go @@ -238,7 +238,7 @@ func (ak AccountKeeper) decodeAccount(bz []byte) types.AccountI { } // MarshalAccount protobuf serializes an Account interface -func (ak AccountKeeper) MarshalAccount(accountI types.AccountI) ([]byte, error) { // nolint:interfacer +func (ak AccountKeeper) MarshalAccount(accountI types.AccountI) ([]byte, error) { //nolint:interfacer return ak.cdc.MarshalInterface(accountI) } diff --git a/x/auth/migrations/legacytx/stdtx.go b/x/auth/migrations/legacytx/stdtx.go index 6d652a040679..ea7de4247602 100644 --- a/x/auth/migrations/legacytx/stdtx.go +++ b/x/auth/migrations/legacytx/stdtx.go @@ -107,6 +107,7 @@ func (tx StdTx) GetMsgs() []sdk.Msg { return tx.Msgs } // ValidateBasic does a simple and lightweight validation check that doesn't // require access to any other information. +// //nolint:revive // we need to change the receiver name here, because otherwise we conflict with tx.MaxGasWanted. func (stdTx StdTx) ValidateBasic() error { stdSigs := stdTx.GetSignatures() diff --git a/x/auth/tx/service.go b/x/auth/tx/service.go index fe23c487e82c..88ee4426413f 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" //nolint: staticcheck "github.com/grpc-ecosystem/grpc-gateway/runtime" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" diff --git a/x/auth/types/account.go b/x/auth/types/account.go index a8331c82c8eb..104fe0e4d333 100644 --- a/x/auth/types/account.go +++ b/x/auth/types/account.go @@ -26,6 +26,7 @@ var ( ) // NewBaseAccount creates a new BaseAccount object +// //nolint:interfacer func NewBaseAccount(address sdk.AccAddress, pubKey cryptotypes.PubKey, accountNumber, sequence uint64) *BaseAccount { acc := &BaseAccount{ diff --git a/x/auth/types/params.go b/x/auth/types/params.go index a97544e6e6b1..ebfb11ca67c0 100644 --- a/x/auth/types/params.go +++ b/x/auth/types/params.go @@ -41,8 +41,10 @@ func DefaultParams() Params { // SigVerifyCostSecp256r1 returns gas fee of secp256r1 signature verification. // Set by benchmarking current implementation: -// BenchmarkSig/secp256k1 4334 277167 ns/op 4128 B/op 79 allocs/op -// BenchmarkSig/secp256r1 10000 108769 ns/op 1672 B/op 33 allocs/op +// +// BenchmarkSig/secp256k1 4334 277167 ns/op 4128 B/op 79 allocs/op +// BenchmarkSig/secp256r1 10000 108769 ns/op 1672 B/op 33 allocs/op +// // Based on the results above secp256k1 is 2.7x is slwer. However we propose to discount it // because we are we don't compare the cgo implementation of secp256k1, which is faster. func (p Params) SigVerifyCostSecp256r1() uint64 { diff --git a/x/auth/vesting/types/msgs.go b/x/auth/vesting/types/msgs.go index 2387513cb3dd..fbce860cede4 100644 --- a/x/auth/vesting/types/msgs.go +++ b/x/auth/vesting/types/msgs.go @@ -23,6 +23,7 @@ var _ sdk.Msg = &MsgCreatePermanentLockedAccount{} var _ sdk.Msg = &MsgCreatePeriodicVestingAccount{} // NewMsgCreateVestingAccount returns a reference to a new MsgCreateVestingAccount. +// //nolint:interfacer func NewMsgCreateVestingAccount(fromAddr, toAddr sdk.AccAddress, amount sdk.Coins, endTime int64, delayed bool) *MsgCreateVestingAccount { return &MsgCreateVestingAccount{ @@ -77,6 +78,7 @@ func (msg MsgCreateVestingAccount) GetSigners() []sdk.AccAddress { } // NewMsgCreatePermanentLockedAccount returns a reference to a new MsgCreatePermanentLockedAccount. +// //nolint:interfacer func NewMsgCreatePermanentLockedAccount(fromAddr, toAddr sdk.AccAddress, amount sdk.Coins) *MsgCreatePermanentLockedAccount { return &MsgCreatePermanentLockedAccount{ @@ -125,6 +127,7 @@ func (msg MsgCreatePermanentLockedAccount) GetSigners() []sdk.AccAddress { } // NewMsgCreatePeriodicVestingAccount returns a reference to a new MsgCreatePeriodicVestingAccount. +// //nolint:interfacer func NewMsgCreatePeriodicVestingAccount(fromAddr, toAddr sdk.AccAddress, startTime int64, periods []Period) *MsgCreatePeriodicVestingAccount { return &MsgCreatePeriodicVestingAccount{ diff --git a/x/authz/codec/doc.go b/x/authz/codec/doc.go index ecc365a2211b..90ba63f6d690 100644 --- a/x/authz/codec/doc.go +++ b/x/authz/codec/doc.go @@ -6,13 +6,12 @@ can be (de)serialized properly. Amino types should be ideally registered inside this codec within the init function of each module's codec.go file as follows: -func init() { - // ... + func init() { + // ... - RegisterLegacyAminoCodec(authzcodec.Amino) -} + RegisterLegacyAminoCodec(authzcodec.Amino) + } The codec instance is put inside this package and not the x/authz package in order to avoid any dependency cycle. - */ package codec diff --git a/x/authz/keeper/keys.go b/x/authz/keeper/keys.go index a079b71ddd6c..c4343d18925c 100644 --- a/x/authz/keeper/keys.go +++ b/x/authz/keeper/keys.go @@ -15,7 +15,6 @@ import ( // // - 0x01: Grant // - 0x02: GrantQueueItem -// var ( GrantKey = []byte{0x01} // prefix for each key GrantQueuePrefix = []byte{0x02} @@ -78,7 +77,8 @@ func parseGrantQueueKey(key []byte) (time.Time, sdk.AccAddress, sdk.AccAddress, // GrantQueueKey - return grant queue store key. If a given grant doesn't have a defined // expiration, then it should not be used in the pruning queue. // Key format is: -// 0x02: GrantQueueItem +// +// 0x02: GrantQueueItem func GrantQueueKey(expiration time.Time, granter sdk.AccAddress, grantee sdk.AccAddress) []byte { exp := sdk.FormatTimeBytes(expiration) granter = address.MustLengthPrefix(granter) diff --git a/x/authz/migrations/v046/keys.go b/x/authz/migrations/v046/keys.go index 9b4c74fb9f3d..8754185a7b9b 100644 --- a/x/authz/migrations/v046/keys.go +++ b/x/authz/migrations/v046/keys.go @@ -14,7 +14,6 @@ import ( // // - 0x01: Grant // - 0x02: GrantQueueItem -// var ( GrantPrefix = []byte{0x01} GrantQueuePrefix = []byte{0x02} diff --git a/x/authz/module/abci_test.go b/x/authz/module/abci_test.go index f8e5b3e820bc..e3dd57ae8312 100644 --- a/x/authz/module/abci_test.go +++ b/x/authz/module/abci_test.go @@ -23,7 +23,6 @@ import ( ) func TestExpiredGrantsQueue(t *testing.T) { - key := sdk.NewKVStoreKey(keeper.StoreKey) testCtx := testutil.DefaultContextWithDB(t, key, sdk.NewTransientStoreKey("transient_test")) encCfg := moduletestutil.MakeTestEncodingConfig(authzmodule.AppModuleBasic{}) diff --git a/x/authz/msgs.go b/x/authz/msgs.go index dd8257e16713..f60e53472005 100644 --- a/x/authz/msgs.go +++ b/x/authz/msgs.go @@ -28,6 +28,7 @@ var ( ) // NewMsgGrant creates a new MsgGrant +// //nolint:interfacer func NewMsgGrant(granter sdk.AccAddress, grantee sdk.AccAddress, a Authorization, expiration *time.Time) (*MsgGrant, error) { m := &MsgGrant{ @@ -118,6 +119,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 { return MsgRevoke{ @@ -171,6 +173,7 @@ func (msg MsgRevoke) GetSignBytes() []byte { } // NewMsgExec creates a new MsgExecAuthorized +// //nolint:interfacer func NewMsgExec(grantee sdk.AccAddress, msgs []sdk.Msg) MsgExec { msgsAny := make([]*cdctypes.Any, len(msgs)) diff --git a/x/authz/simulation/operations.go b/x/authz/simulation/operations.go index 5418d6468d45..ab2e0ac845a5 100644 --- a/x/authz/simulation/operations.go +++ b/x/authz/simulation/operations.go @@ -26,6 +26,7 @@ var ( ) // Simulation operation weights constants +// //nolint:gosec // these are not hardcoded credentials. const ( OpWeightMsgGrant = "op_weight_msg_grant" diff --git a/x/bank/keeper/keeper.go b/x/bank/keeper/keeper.go index 520861526869..f8ce411b4cbe 100644 --- a/x/bank/keeper/keeper.go +++ b/x/bank/keeper/keeper.go @@ -115,7 +115,8 @@ func NewBaseKeeper( // WithMintCoinsRestriction restricts the bank Keeper used within a specific module to // have restricted permissions on minting via function passed in parameter. // Previous restriction functions can be nested as such: -// bankKeeper.WithMintCoinsRestriction(restriction1).WithMintCoinsRestriction(restriction2) +// +// bankKeeper.WithMintCoinsRestriction(restriction1).WithMintCoinsRestriction(restriction2) func (k BaseKeeper) WithMintCoinsRestriction(check MintingRestrictionFn) BaseKeeper { oldRestrictionFn := k.mintCoinsRestrictionFn k.mintCoinsRestrictionFn = func(ctx sdk.Context, coins sdk.Coins) error { diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index a800b19d2387..fd8b4bf46c1c 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -681,8 +681,9 @@ func (suite *KeeperTestSuite) TestMsgMultiSendEvents() { newCoins := sdk.NewCoins(sdk.NewInt64Coin(fooDenom, 50)) newCoins2 := sdk.NewCoins(sdk.NewInt64Coin(barDenom, 100)) inputs := []banktypes.Input{ - {Address: accAddrs[0].String(), - Coins: coins, + { + Address: accAddrs[0].String(), + Coins: coins, }, } outputs := []banktypes.Output{ diff --git a/x/bank/keeper/send.go b/x/bank/keeper/send.go index e21b5bcef41b..e7f7727c98c9 100644 --- a/x/bank/keeper/send.go +++ b/x/bank/keeper/send.go @@ -99,6 +99,7 @@ func (k BaseSendKeeper) GetParams(ctx sdk.Context) (params types.Params) { } // SetParams sets the total set of bank parameters. +// //nolint:staticcheck // params.SendEnabled is deprecated but it should be here regardless. func (k BaseSendKeeper) SetParams(ctx sdk.Context, params types.Params) error { // normally SendEnabled is deprecated but we still support it for backwards compatibility @@ -466,11 +467,12 @@ func (k BaseSendKeeper) GetAllSendEnabledEntries(ctx sdk.Context) []types.SendEn // getSendEnabled returns whether send is enabled and whether that flag was set for a denom. // // Example usage: -// store := ctx.KVStore(k.storeKey) -// sendEnabled, found := getSendEnabled(store, "atom") -// if !found { -// sendEnabled = DefaultSendEnabled -// } +// +// store := ctx.KVStore(k.storeKey) +// sendEnabled, found := getSendEnabled(store, "atom") +// if !found { +// sendEnabled = DefaultSendEnabled +// } func (k BaseSendKeeper) getSendEnabled(store sdk.KVStore, denom string) (bool, bool) { key := types.CreateSendEnabledKey(denom) if !store.Has(key) { diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 44710be84baa..29d0b07df6e2 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -17,6 +17,7 @@ import ( ) // Simulation operation weights constants +// //nolint:gosec // these are not hardcoded credentials. const ( OpWeightMsgSend = "op_weight_msg_send" diff --git a/x/bank/types/events.go b/x/bank/types/events.go index 2293083e512e..330058156fa2 100644 --- a/x/bank/types/events.go +++ b/x/bank/types/events.go @@ -26,7 +26,6 @@ const ( ) // NewCoinSpentEvent constructs a new coin spent sdk.Event -// nolint: interfacer func NewCoinSpentEvent(spender sdk.AccAddress, amount sdk.Coins) sdk.Event { return sdk.NewEvent( EventTypeCoinSpent, @@ -36,7 +35,6 @@ func NewCoinSpentEvent(spender sdk.AccAddress, amount sdk.Coins) sdk.Event { } // NewCoinReceivedEvent constructs a new coin received sdk.Event -// nolint: interfacer func NewCoinReceivedEvent(receiver sdk.AccAddress, amount sdk.Coins) sdk.Event { return sdk.NewEvent( EventTypeCoinReceived, @@ -46,7 +44,6 @@ func NewCoinReceivedEvent(receiver sdk.AccAddress, amount sdk.Coins) sdk.Event { } // NewCoinMintEvent construct a new coin minted sdk.Event -// nolint: interfacer func NewCoinMintEvent(minter sdk.AccAddress, amount sdk.Coins) sdk.Event { return sdk.NewEvent( EventTypeCoinMint, @@ -56,7 +53,6 @@ func NewCoinMintEvent(minter sdk.AccAddress, amount sdk.Coins) sdk.Event { } // NewCoinBurnEvent constructs a new coin burned sdk.Event -// nolint: interfacer func NewCoinBurnEvent(burner sdk.AccAddress, amount sdk.Coins) sdk.Event { return sdk.NewEvent( EventTypeCoinBurn, diff --git a/x/bank/types/metadata.go b/x/bank/types/metadata.go index 9583b85ce44d..a6df1bf426e6 100644 --- a/x/bank/types/metadata.go +++ b/x/bank/types/metadata.go @@ -9,12 +9,12 @@ import ( ) // Validate performs a basic validation of the coin metadata fields. It checks: -// - Name and Symbol are not blank -// - Base and Display denominations are valid coin denominations -// - Base and Display denominations are present in the DenomUnit slice -// - Base denomination has exponent 0 -// - Denomination units are sorted in ascending order -// - Denomination units not duplicated +// - Name and Symbol are not blank +// - Base and Display denominations are valid coin denominations +// - Base and Display denominations are present in the DenomUnit slice +// - Base denomination has exponent 0 +// - Denomination units are sorted in ascending order +// - Denomination units not duplicated func (m Metadata) Validate() error { if strings.TrimSpace(m.Name) == "" { return errors.New("name field cannot be blank") diff --git a/x/bank/types/msgs.go b/x/bank/types/msgs.go index 881126f9cbf7..e164c37ca7da 100644 --- a/x/bank/types/msgs.go +++ b/x/bank/types/msgs.go @@ -20,6 +20,7 @@ var ( ) // NewMsgSend - construct a msg to send coins from one account to another. +// //nolint:interfacer func NewMsgSend(fromAddr, toAddr sdk.AccAddress, amount sdk.Coins) *MsgSend { return &MsgSend{FromAddress: fromAddr.String(), ToAddress: toAddr.String(), Amount: amount} @@ -128,6 +129,7 @@ func (in Input) ValidateBasic() error { } // NewInput - create a transaction input, used with MsgMultiSend +// //nolint:interfacer func NewInput(addr sdk.AccAddress, coins sdk.Coins) Input { return Input{ @@ -154,6 +156,7 @@ func (out Output) ValidateBasic() error { } // NewOutput - create a transaction output, used with MsgMultiSend +// //nolint:interfacer func NewOutput(addr sdk.AccAddress, coins sdk.Coins) Output { return Output{ diff --git a/x/bank/types/params.go b/x/bank/types/params.go index bd93bf85797c..6c03e2fad72b 100644 --- a/x/bank/types/params.go +++ b/x/bank/types/params.go @@ -52,6 +52,7 @@ func (se SendEnabled) Validate() error { } // validateSendEnabledParams is used by the x/params module to validate the params for the bank module. +// //nolint:deadcode,unused func validateSendEnabledParams(i interface{}) error { params, ok := i.([]*SendEnabled) @@ -87,6 +88,7 @@ func (se SendEnabled) String() string { } // validateSendEnabled is used by the x/params module to validate a single SendEnabled entry. +// //nolint:unused func validateSendEnabled(i interface{}) error { param, ok := i.(SendEnabled) diff --git a/x/bank/types/querier.go b/x/bank/types/querier.go index 117b87f17c68..3ffe7a320fa8 100644 --- a/x/bank/types/querier.go +++ b/x/bank/types/querier.go @@ -14,12 +14,14 @@ const ( ) // NewQueryBalanceRequest creates a new instance of QueryBalanceRequest. +// //nolint:interfacer func NewQueryBalanceRequest(addr sdk.AccAddress, denom string) *QueryBalanceRequest { return &QueryBalanceRequest{Address: addr.String(), Denom: denom} } // NewQueryAllBalancesRequest creates a new instance of QueryAllBalancesRequest. +// //nolint:interfacer func NewQueryAllBalancesRequest(addr sdk.AccAddress, req *query.PageRequest) *QueryAllBalancesRequest { return &QueryAllBalancesRequest{Address: addr.String(), Pagination: req} @@ -27,7 +29,8 @@ func NewQueryAllBalancesRequest(addr sdk.AccAddress, req *query.PageRequest) *Qu // NewQuerySpendableBalancesRequest creates a new instance of a // QuerySpendableBalancesRequest. -// nolint:interfacer +// +//nolint:interfacer func NewQuerySpendableBalancesRequest(addr sdk.AccAddress, req *query.PageRequest) *QuerySpendableBalancesRequest { return &QuerySpendableBalancesRequest{Address: addr.String(), Pagination: req} } diff --git a/x/bank/types/send_authorization_test.go b/x/bank/types/send_authorization_test.go index 3143c6a82a74..6ee517769c76 100644 --- a/x/bank/types/send_authorization_test.go +++ b/x/bank/types/send_authorization_test.go @@ -25,7 +25,7 @@ func TestSendAuthorization(t *testing.T) { allowList := make([]sdk.AccAddress, 1) allowList[0] = toAddr authorization := types.NewSendAuthorization(coins1000, nil) - + t.Log("verify authorization returns valid method name") require.Equal(t, authorization.MsgTypeURL(), "/cosmos.bank.v1beta1.MsgSend") require.NoError(t, authorization.ValidateBasic()) diff --git a/x/crisis/client/cli/tx_test.go b/x/crisis/client/cli/tx_test.go index 3729a876fba5..049078568d5e 100644 --- a/x/crisis/client/cli/tx_test.go +++ b/x/crisis/client/cli/tx_test.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "testing" "github.com/stretchr/testify/assert" @@ -97,7 +96,7 @@ func TestNewMsgVerifyInvariantTxCmd(t *testing.T) { ctx := svrcmd.CreateExecuteContext(context.Background()) cmd := cli.NewMsgVerifyInvariantTxCmd() - cmd.SetOut(ioutil.Discard) + cmd.SetOut(io.Discard) assert.NotNil(t, cmd) cmd.SetContext(ctx) diff --git a/x/crisis/types/msgs.go b/x/crisis/types/msgs.go index 02f37af6f912..b7af338a081b 100644 --- a/x/crisis/types/msgs.go +++ b/x/crisis/types/msgs.go @@ -14,6 +14,7 @@ const ( var _, _ sdk.Msg = &MsgVerifyInvariant{}, &MsgUpdateParams{} // NewMsgVerifyInvariant creates a new MsgVerifyInvariant object +// //nolint:interfacer func NewMsgVerifyInvariant(sender sdk.AccAddress, invModeName, invRoute string) *MsgVerifyInvariant { return &MsgVerifyInvariant{ diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index b93e8cf3533f..4a08a1f53acc 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -19,6 +19,7 @@ import ( ) // Simulation operation weights constants +// //nolint:gosec // these are not hardcoded credentials. const ( OpWeightMsgSetWithdrawAddress = "op_weight_msg_set_withdraw_address" diff --git a/x/distribution/types/proposal.go b/x/distribution/types/proposal.go index a60291b9eb24..c2b9130b614d 100644 --- a/x/distribution/types/proposal.go +++ b/x/distribution/types/proposal.go @@ -21,6 +21,7 @@ func init() { } // NewCommunityPoolSpendProposal creates a new community pool spend proposal. +// //nolint:interfacer func NewCommunityPoolSpendProposal(title, description string, recipient sdk.AccAddress, amount sdk.Coins) *CommunityPoolSpendProposal { return &CommunityPoolSpendProposal{title, description, recipient.String(), amount} diff --git a/x/distribution/types/query.go b/x/distribution/types/query.go index ef3d34ceae5a..38f6c0a35264 100644 --- a/x/distribution/types/query.go +++ b/x/distribution/types/query.go @@ -32,6 +32,7 @@ func (res QueryDelegatorTotalRewardsResponse) String() string { } // NewDelegationDelegatorReward constructs a DelegationDelegatorReward. +// //nolint:interfacer func NewDelegationDelegatorReward(valAddr sdk.ValAddress, reward sdk.DecCoins) DelegationDelegatorReward { return DelegationDelegatorReward{ValidatorAddress: valAddr.String(), Reward: reward} diff --git a/x/evidence/keeper/infraction_test.go b/x/evidence/keeper/infraction_test.go index ad9bf8bf8810..8cd9ddbe7702 100644 --- a/x/evidence/keeper/infraction_test.go +++ b/x/evidence/keeper/infraction_test.go @@ -1,6 +1,8 @@ package keeper_test import ( + "time" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/runtime" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" @@ -18,7 +20,6 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - "time" ) type InfractionTestSuite struct { @@ -38,9 +39,7 @@ type InfractionTestSuite struct { } func (suite *InfractionTestSuite) SetupTest() { - var ( - evidenceKeeper keeper.Keeper - ) + var evidenceKeeper keeper.Keeper app, err := simtestutil.Setup(testutil.AppConfig, &evidenceKeeper, diff --git a/x/evidence/keeper/keeper_test.go b/x/evidence/keeper/keeper_test.go index 3d3bddefa5b1..8f6ea80087fc 100644 --- a/x/evidence/keeper/keeper_test.go +++ b/x/evidence/keeper/keeper_test.go @@ -3,13 +3,14 @@ package keeper_test import ( "encoding/hex" "fmt" + "time" + "github.com/cosmos/cosmos-sdk/testutil" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" "github.com/cosmos/cosmos-sdk/x/evidence" evidencetestutil "github.com/cosmos/cosmos-sdk/x/evidence/testutil" "github.com/golang/mock/gomock" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - "time" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" diff --git a/x/evidence/types/expected_keepers.go b/x/evidence/types/expected_keepers.go index 93e1ef72dbea..1101b8ae2031 100644 --- a/x/evidence/types/expected_keepers.go +++ b/x/evidence/types/expected_keepers.go @@ -1,9 +1,10 @@ package types import ( - "github.com/cosmos/cosmos-sdk/x/auth/types" "time" + "github.com/cosmos/cosmos-sdk/x/auth/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" diff --git a/x/evidence/types/msgs.go b/x/evidence/types/msgs.go index 89b0d414d05d..87c1d261a44f 100644 --- a/x/evidence/types/msgs.go +++ b/x/evidence/types/msgs.go @@ -23,6 +23,7 @@ var ( ) // NewMsgSubmitEvidence returns a new MsgSubmitEvidence with a signer/submitter. +// //nolint:interfacer func NewMsgSubmitEvidence(s sdk.AccAddress, evi exported.Evidence) (*MsgSubmitEvidence, error) { msg, ok := evi.(proto.Message) diff --git a/x/feegrant/grant.go b/x/feegrant/grant.go index f8d7823ff06a..f169720cc606 100644 --- a/x/feegrant/grant.go +++ b/x/feegrant/grant.go @@ -11,6 +11,7 @@ import ( var _ types.UnpackInterfacesMessage = &Grant{} // NewGrant creates a new FeeAllowanceGrant. +// //nolint:interfacer func NewGrant(granter, grantee sdk.AccAddress, feeAllowance FeeAllowanceI) (Grant, error) { msg, ok := feeAllowance.(proto.Message) diff --git a/x/feegrant/msgs.go b/x/feegrant/msgs.go index 8cdc0f1962eb..864fd7c5e31f 100644 --- a/x/feegrant/msgs.go +++ b/x/feegrant/msgs.go @@ -17,6 +17,7 @@ var ( ) // NewMsgGrantAllowance creates a new MsgGrantAllowance. +// //nolint:interfacer func NewMsgGrantAllowance(feeAllowance FeeAllowanceI, granter, grantee sdk.AccAddress) (*MsgGrantAllowance, error) { msg, ok := feeAllowance.(proto.Message) @@ -93,6 +94,7 @@ func (msg MsgGrantAllowance) UnpackInterfaces(unpacker types.AnyUnpacker) error // NewMsgRevokeAllowance returns a message to revoke a fee allowance for a given // granter and grantee +// //nolint:interfacer func NewMsgRevokeAllowance(granter sdk.AccAddress, grantee sdk.AccAddress) MsgRevokeAllowance { return MsgRevokeAllowance{Granter: granter.String(), Grantee: grantee.String()} diff --git a/x/feegrant/simulation/operations.go b/x/feegrant/simulation/operations.go index 0bd3993528af..4079a90ef9d4 100644 --- a/x/feegrant/simulation/operations.go +++ b/x/feegrant/simulation/operations.go @@ -15,6 +15,7 @@ import ( ) // Simulation operation weights constants +// //nolint:gosec // These aren't harcoded credentials. const ( OpWeightMsgGrantAllowance = "op_weight_msg_grant_fee_allowance" diff --git a/x/genutil/doc.go b/x/genutil/doc.go index bccc82a1af00..6aa85b97755b 100644 --- a/x/genutil/doc.go +++ b/x/genutil/doc.go @@ -1,10 +1,10 @@ /* Package genutil contains a variety of genesis utility functionality for usage within a blockchain application. Namely: - - Genesis transactions related (gentx) - - commands for collection and creation of gentxs - - initchain processing of gentxs - - Genesis file validation - - Tendermint related initialization + - Genesis transactions related (gentx) + - commands for collection and creation of gentxs + - initchain processing of gentxs + - Genesis file validation + - Tendermint related initialization */ package genutil diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index fc7f73c1a544..f1405f4bdf70 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -509,6 +509,8 @@ $ %s query gov tally 1 } // GetCmdQueryParams implements the query params command. +// +//nolint:staticcheck // this function contains deprecated commands that we need. func GetCmdQueryParams() *cobra.Command { cmd := &cobra.Command{ Use: "params", @@ -589,6 +591,7 @@ $ %s query gov param deposit } var out fmt.Stringer + //nolint:staticcheck // this switch statement contains deprecated commands that we need. switch args[0] { case "voting": out = res.GetVotingParams() diff --git a/x/gov/client/testutil/grpc.go b/x/gov/client/testutil/grpc.go index dbcca6ad1188..aef5abd02211 100644 --- a/x/gov/client/testutil/grpc.go +++ b/x/gov/client/testutil/grpc.go @@ -357,9 +357,9 @@ func (s *IntegrationTestSuite) TestGetParamsGRPC() { val := s.network.Validators[0] params := v1.DefaultParams() - dp := v1.NewDepositParams(params.MinDeposit, params.MaxDepositPeriod) - vp := v1.NewVotingParams(params.VotingPeriod) - tp := v1.NewTallyParams(params.Quorum, params.Threshold, params.VetoThreshold) + dp := v1.NewDepositParams(params.MinDeposit, params.MaxDepositPeriod) //nolint:staticcheck // we use deprecated gov commands here, but we don't want to remove them + vp := v1.NewVotingParams(params.VotingPeriod) //nolint:staticcheck // we use deprecated gov commands here, but we don't want to remove them + tp := v1.NewTallyParams(params.Quorum, params.Threshold, params.VetoThreshold) //nolint:staticcheck // we use deprecated gov commands here, but we don't want to remove them testCases := []struct { name string diff --git a/x/gov/client/testutil/helpers.go b/x/gov/client/testutil/helpers.go index 174d7af0f429..97098783a38e 100644 --- a/x/gov/client/testutil/helpers.go +++ b/x/gov/client/testutil/helpers.go @@ -18,6 +18,7 @@ var commonArgs = []string{ } // MsgSubmitLegacyProposal creates a tx for submit legacy proposal +// //nolint:staticcheck // we are intentionally using a deprecated flag here. func MsgSubmitLegacyProposal(clientCtx client.Context, from, title, description, proposalType string, extraArgs ...string) (testutil.BufferWriter, error) { args := append([]string{ diff --git a/x/gov/genesis.go b/x/gov/genesis.go index 4a29424c2295..b81852b98d1d 100644 --- a/x/gov/genesis.go +++ b/x/gov/genesis.go @@ -53,6 +53,8 @@ func InitGenesis(ctx sdk.Context, ak types.AccountKeeper, bk types.BankKeeper, k } // ExportGenesis - output genesis parameters +// +//nolint:staticcheck func ExportGenesis(ctx sdk.Context, k *keeper.Keeper) *v1.GenesisState { startingProposalID, _ := k.GetProposalID(ctx) proposals := k.GetProposals(ctx) diff --git a/x/gov/keeper/grpc_query.go b/x/gov/keeper/grpc_query.go index a8e859798edd..7ebaf4a59e67 100644 --- a/x/gov/keeper/grpc_query.go +++ b/x/gov/keeper/grpc_query.go @@ -162,6 +162,7 @@ func (q Keeper) Params(c context.Context, req *v1.QueryParamsRequest) (*v1.Query response := &v1.QueryParamsResponse{} + //nolint:staticcheck switch req.ParamsType { case v1.ParamDeposit: depositParams := v1.NewDepositParams(params.MinDeposit, params.MaxDepositPeriod) @@ -371,11 +372,11 @@ func (q legacyQueryServer) Votes(c context.Context, req *v1beta1.QueryVotesReque }, nil } +//nolint:staticcheck func (q legacyQueryServer) Params(c context.Context, req *v1beta1.QueryParamsRequest) (*v1beta1.QueryParamsResponse, error) { resp, err := q.keeper.Params(c, &v1.QueryParamsRequest{ ParamsType: req.ParamsType, }) - if err != nil { return nil, err } diff --git a/x/gov/keeper/keeper.go b/x/gov/keeper/keeper.go index 5cbb3e78ed12..307152f9633a 100644 --- a/x/gov/keeper/keeper.go +++ b/x/gov/keeper/keeper.go @@ -19,7 +19,7 @@ import ( // Keeper defines the governance module Keeper type Keeper struct { // The reference to the Paramstore to get and set gov specific params - paramSpace types.ParamSubspace + paramSpace types.ParamSubspace //nolint:unused authKeeper types.AccountKeeper bankKeeper types.BankKeeper diff --git a/x/gov/keeper/msg_server.go b/x/gov/keeper/msg_server.go index fc0b92756142..c5ef57ddef47 100644 --- a/x/gov/keeper/msg_server.go +++ b/x/gov/keeper/msg_server.go @@ -5,14 +5,12 @@ import ( "fmt" "strconv" + "cosmossdk.io/errors" "github.com/armon/go-metrics" storetypes "github.com/cosmos/cosmos-sdk/store/types" "github.com/cosmos/cosmos-sdk/telemetry" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/gov/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" @@ -59,7 +57,7 @@ func (k msgServer) SubmitProposal(goCtx context.Context, msg *v1.MsgSubmitPropos "submit proposal", ) - defer telemetry.IncrCounter(1, types.ModuleName, "proposal") + defer telemetry.IncrCounter(1, govtypes.ModuleName, "proposal") proposer, _ := sdk.AccAddressFromBech32(msg.GetProposer()) votingStarted, err := k.Keeper.AddDeposit(ctx, proposal.Id, proposer, msg.GetInitialDeposit()) @@ -70,14 +68,14 @@ func (k msgServer) SubmitProposal(goCtx context.Context, msg *v1.MsgSubmitPropos ctx.EventManager().EmitEvent( sdk.NewEvent( sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + sdk.NewAttribute(sdk.AttributeKeyModule, govtypes.AttributeValueCategory), sdk.NewAttribute(sdk.AttributeKeySender, msg.GetProposer()), ), ) if votingStarted { - submitEvent := sdk.NewEvent(types.EventTypeSubmitProposal, - sdk.NewAttribute(types.AttributeKeyVotingPeriodStart, fmt.Sprintf("%d", proposal.Id)), + submitEvent := sdk.NewEvent(govtypes.EventTypeSubmitProposal, + sdk.NewAttribute(govtypes.AttributeKeyVotingPeriodStart, fmt.Sprintf("%d", proposal.Id)), ) ctx.EventManager().EmitEvent(submitEvent) @@ -93,22 +91,22 @@ func (k msgServer) ExecLegacyContent(goCtx context.Context, msg *v1.MsgExecLegac govAcct := k.GetGovernanceAccount(ctx).GetAddress().String() if govAcct != msg.Authority { - return nil, sdkerrors.Wrapf(types.ErrInvalidSigner, "expected %s got %s", govAcct, msg.Authority) + return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "expected %s got %s", govAcct, msg.Authority) } content, err := v1.LegacyContentFromMessage(msg) if err != nil { - return nil, sdkerrors.Wrapf(types.ErrInvalidProposalContent, "%+v", err) + return nil, errors.Wrapf(govtypes.ErrInvalidProposalContent, "%+v", err) } // Ensure that the content has a respective handler if !k.Keeper.legacyRouter.HasRoute(content.ProposalRoute()) { - return nil, sdkerrors.Wrap(types.ErrNoProposalHandlerExists, content.ProposalRoute()) + return nil, errors.Wrap(govtypes.ErrNoProposalHandlerExists, content.ProposalRoute()) } handler := k.Keeper.legacyRouter.GetRoute(content.ProposalRoute()) if err := handler(ctx, content); err != nil { - return nil, sdkerrors.Wrapf(types.ErrInvalidProposalContent, "failed to run legacy handler %s, %+v", content.ProposalRoute(), err) + return nil, errors.Wrapf(govtypes.ErrInvalidProposalContent, "failed to run legacy handler %s, %+v", content.ProposalRoute(), err) } return &v1.MsgExecLegacyContentResponse{}, nil @@ -126,7 +124,7 @@ func (k msgServer) Vote(goCtx context.Context, msg *v1.MsgVote) (*v1.MsgVoteResp } defer telemetry.IncrCounterWithLabels( - []string{types.ModuleName, "vote"}, + []string{govtypes.ModuleName, "vote"}, 1, []metrics.Label{ telemetry.NewLabel("proposal_id", strconv.Itoa(int(msg.ProposalId))), @@ -136,7 +134,7 @@ func (k msgServer) Vote(goCtx context.Context, msg *v1.MsgVote) (*v1.MsgVoteResp ctx.EventManager().EmitEvent( sdk.NewEvent( sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + sdk.NewAttribute(sdk.AttributeKeyModule, govtypes.AttributeValueCategory), sdk.NewAttribute(sdk.AttributeKeySender, msg.Voter), ), ) @@ -156,7 +154,7 @@ func (k msgServer) VoteWeighted(goCtx context.Context, msg *v1.MsgVoteWeighted) } defer telemetry.IncrCounterWithLabels( - []string{types.ModuleName, "vote"}, + []string{govtypes.ModuleName, "vote"}, 1, []metrics.Label{ telemetry.NewLabel("proposal_id", strconv.Itoa(int(msg.ProposalId))), @@ -166,7 +164,7 @@ func (k msgServer) VoteWeighted(goCtx context.Context, msg *v1.MsgVoteWeighted) ctx.EventManager().EmitEvent( sdk.NewEvent( sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + sdk.NewAttribute(sdk.AttributeKeyModule, govtypes.AttributeValueCategory), sdk.NewAttribute(sdk.AttributeKeySender, msg.Voter), ), ) @@ -186,7 +184,7 @@ func (k msgServer) Deposit(goCtx context.Context, msg *v1.MsgDeposit) (*v1.MsgDe } defer telemetry.IncrCounterWithLabels( - []string{types.ModuleName, "deposit"}, + []string{govtypes.ModuleName, "deposit"}, 1, []metrics.Label{ telemetry.NewLabel("proposal_id", strconv.Itoa(int(msg.ProposalId))), @@ -196,7 +194,7 @@ func (k msgServer) Deposit(goCtx context.Context, msg *v1.MsgDeposit) (*v1.MsgDe ctx.EventManager().EmitEvent( sdk.NewEvent( sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), + sdk.NewAttribute(sdk.AttributeKeyModule, govtypes.AttributeValueCategory), sdk.NewAttribute(sdk.AttributeKeySender, msg.Depositor), ), ) @@ -204,8 +202,8 @@ func (k msgServer) Deposit(goCtx context.Context, msg *v1.MsgDeposit) (*v1.MsgDe if votingStarted { ctx.EventManager().EmitEvent( sdk.NewEvent( - types.EventTypeProposalDeposit, - sdk.NewAttribute(types.AttributeKeyVotingPeriodStart, fmt.Sprintf("%d", msg.ProposalId)), + govtypes.EventTypeProposalDeposit, + sdk.NewAttribute(govtypes.AttributeKeyVotingPeriodStart, fmt.Sprintf("%d", msg.ProposalId)), ), ) } diff --git a/x/gov/keeper/msg_server_test.go b/x/gov/keeper/msg_server_test.go index 3c12cc5ef9b5..ee2ddb040f4c 100644 --- a/x/gov/keeper/msg_server_test.go +++ b/x/gov/keeper/msg_server_test.go @@ -740,7 +740,6 @@ func (suite *KeeperTestSuite) TestLegacyMsgDeposit() { } func (suite *KeeperTestSuite) TestMsgUpdateParams() { - authority := suite.app.GovKeeper.GetAuthority() params := v1.DefaultParams() testCases := []struct { @@ -1015,7 +1014,7 @@ func (suite *KeeperTestSuite) TestMsgUpdateParams() { func (suite *KeeperTestSuite) TestSubmitProposal_InitialDeposit() { const meetsDepositValue = baseDepositTestAmount * baseDepositTestPercent / 100 - var baseDepositRatioDec = sdk.NewDec(baseDepositTestPercent).Quo(sdk.NewDec(100)) + baseDepositRatioDec := sdk.NewDec(baseDepositTestPercent).Quo(sdk.NewDec(100)) testcases := map[string]struct { minDeposit sdk.Coins diff --git a/x/gov/module.go b/x/gov/module.go index d71c75ffec00..c984611f2249 100644 --- a/x/gov/module.go +++ b/x/gov/module.go @@ -31,7 +31,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/client/cli" "github.com/cosmos/cosmos-sdk/x/gov/keeper" "github.com/cosmos/cosmos-sdk/x/gov/simulation" - "github.com/cosmos/cosmos-sdk/x/gov/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" @@ -61,7 +60,7 @@ func NewAppModuleBasic(legacyProposalHandlers []govclient.ProposalHandler) AppMo // Name returns the gov module's name. func (AppModuleBasic) Name() string { - return types.ModuleName + return govtypes.ModuleName } // RegisterLegacyAminoCodec registers the gov module's types for the given codec. @@ -80,7 +79,7 @@ func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { var data v1.GenesisState if err := cdc.UnmarshalJSON(bz, &data); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + return fmt.Errorf("failed to unmarshal %s genesis state: %w", govtypes.ModuleName, err) } return v1.ValidateGenesis(&data) @@ -127,19 +126,18 @@ type AppModule struct { AppModuleBasic keeper *keeper.Keeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper + accountKeeper govtypes.AccountKeeper + bankKeeper govtypes.BankKeeper // legacySubspace is used solely for migration of x/params managed parameters - legacySubspace types.ParamSubspace + legacySubspace govtypes.ParamSubspace } // NewAppModule creates a new AppModule object func NewAppModule( cdc codec.Codec, keeper *keeper.Keeper, - ak types.AccountKeeper, bk types.BankKeeper, ss types.ParamSubspace, + ak govtypes.AccountKeeper, bk govtypes.BankKeeper, ss govtypes.ParamSubspace, ) AppModule { - return AppModule{ AppModuleBasic: AppModuleBasic{cdc: cdc}, keeper: keeper, @@ -170,12 +168,12 @@ type govInputs struct { MsgServiceRouter *baseapp.MsgServiceRouter Authority map[string]sdk.AccAddress `optional:"true"` - AccountKeeper types.AccountKeeper - BankKeeper types.BankKeeper - StakingKeeper types.StakingKeeper + AccountKeeper govtypes.AccountKeeper + BankKeeper govtypes.BankKeeper + StakingKeeper govtypes.StakingKeeper // LegacySubspace is used solely for migration of x/params managed parameters - LegacySubspace types.ParamSubspace + LegacySubspace govtypes.ParamSubspace } type govOutputs struct { @@ -187,7 +185,7 @@ type govOutputs struct { } func provideModule(in govInputs) govOutputs { - kConfig := types.DefaultConfig() + kConfig := govtypes.DefaultConfig() if in.Config.MaxMetadataLen != 0 { kConfig.MaxMetadataLen = in.Config.MaxMetadataLen } @@ -208,7 +206,7 @@ func provideModule(in govInputs) govOutputs { authority.String(), ) m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.BankKeeper, in.LegacySubspace) - hr := v1beta1.HandlerRoute{Handler: v1beta1.ProposalHandler, RouteKey: types.RouterKey} + hr := v1beta1.HandlerRoute{Handler: v1beta1.ProposalHandler, RouteKey: govtypes.RouterKey} return govOutputs{Module: runtime.WrapAppModule(m), Keeper: k, HandlerRoute: hr} } @@ -235,7 +233,7 @@ func invokeAddRoutes(keeper *keeper.Keeper, routes []v1beta1.HandlerRoute) { keeper.SetLegacyRouter(router) } -func invokeSetHooks(keeper *keeper.Keeper, govHooks map[string]types.GovHooksWrapper) error { +func invokeSetHooks(keeper *keeper.Keeper, govHooks map[string]govtypes.GovHooksWrapper) error { if keeper == nil || govHooks == nil { return nil } @@ -246,7 +244,7 @@ func invokeSetHooks(keeper *keeper.Keeper, govHooks map[string]types.GovHooksWra order := modNames sort.Strings(order) - var multiHooks types.MultiGovHooks + var multiHooks govtypes.MultiGovHooks for _, modName := range order { hook, ok := govHooks[modName] if !ok { @@ -261,7 +259,7 @@ func invokeSetHooks(keeper *keeper.Keeper, govHooks map[string]types.GovHooksWra // Name returns the gov module's name. func (AppModule) Name() string { - return types.ModuleName + return govtypes.ModuleName } // RegisterInvariants registers module invariants @@ -272,7 +270,7 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { // RegisterServices registers module services. func (am AppModule) RegisterServices(cfg module.Configurator) { msgServer := keeper.NewMsgServerImpl(am.keeper) - v1beta1.RegisterMsgServer(cfg.MsgServer(), keeper.NewLegacyMsgServerImpl(am.accountKeeper.GetModuleAddress(types.ModuleName).String(), msgServer)) + v1beta1.RegisterMsgServer(cfg.MsgServer(), keeper.NewLegacyMsgServerImpl(am.accountKeeper.GetModuleAddress(govtypes.ModuleName).String(), msgServer)) v1.RegisterMsgServer(cfg.MsgServer(), msgServer) legacyQueryServer := keeper.NewLegacyQueryServer(am.keeper) @@ -280,15 +278,15 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { v1.RegisterQueryServer(cfg.QueryServer(), am.keeper) m := keeper.NewMigrator(am.keeper, am.legacySubspace) - err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2) + err := cfg.RegisterMigration(govtypes.ModuleName, 1, m.Migrate1to2) if err != nil { panic(err) } - err = cfg.RegisterMigration(types.ModuleName, 2, m.Migrate2to3) + err = cfg.RegisterMigration(govtypes.ModuleName, 2, m.Migrate2to3) if err != nil { panic(err) } - err = cfg.RegisterMigration(types.ModuleName, 3, m.Migrate3to4) + err = cfg.RegisterMigration(govtypes.ModuleName, 3, m.Migrate3to4) if err != nil { panic(err) } @@ -335,7 +333,7 @@ func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.We // RegisterStoreDecoder registers a decoder for gov module's types func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { - sdr[types.StoreKey] = simulation.NewDecodeStore(am.cdc) + sdr[govtypes.StoreKey] = simulation.NewDecodeStore(am.cdc) } // WeightedOperations returns the all the gov module operations with their respective weights. diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 2bca30c4c12a..bdd53e433f2f 100644 --- a/x/gov/simulation/operations.go +++ b/x/gov/simulation/operations.go @@ -28,6 +28,7 @@ var ( ) // Simulation operation weights constants +// //nolint:gosec // these are not hard-coded credentials. const ( OpWeightMsgDeposit = "op_weight_msg_deposit" diff --git a/x/gov/types/v1/deposit.go b/x/gov/types/v1/deposit.go index 5c374919d9ef..a3e601c8dfde 100644 --- a/x/gov/types/v1/deposit.go +++ b/x/gov/types/v1/deposit.go @@ -7,6 +7,7 @@ import ( ) // NewDeposit creates a new Deposit instance +// //nolint:interfacer func NewDeposit(proposalID uint64, depositor sdk.AccAddress, amount sdk.Coins) Deposit { return Deposit{proposalID, depositor.String(), amount} diff --git a/x/gov/types/v1/msgs.go b/x/gov/types/v1/msgs.go index 56a48b599f05..ed1aa7820966 100644 --- a/x/gov/types/v1/msgs.go +++ b/x/gov/types/v1/msgs.go @@ -18,6 +18,7 @@ var ( ) // NewMsgSubmitProposal creates a new MsgSubmitProposal. +// //nolint:interfacer func NewMsgSubmitProposal(messages []sdk.Msg, initialDeposit sdk.Coins, proposer string, metadata string) (*MsgSubmitProposal, error) { m := &MsgSubmitProposal{ @@ -99,6 +100,7 @@ func (m MsgSubmitProposal) UnpackInterfaces(unpacker codectypes.AnyUnpacker) err } // NewMsgDeposit creates a new MsgDeposit instance +// //nolint:interfacer func NewMsgDeposit(depositor sdk.AccAddress, proposalID uint64, amount sdk.Coins) *MsgDeposit { return &MsgDeposit{proposalID, depositor.String(), amount} @@ -139,6 +141,7 @@ func (msg MsgDeposit) GetSigners() []sdk.AccAddress { } // NewMsgVote creates a message to cast a vote on an active proposal +// //nolint:interfacer func NewMsgVote(voter sdk.AccAddress, proposalID uint64, option VoteOption, metadata string) *MsgVote { return &MsgVote{proposalID, voter.String(), option, metadata} @@ -175,6 +178,7 @@ func (msg MsgVote) GetSigners() []sdk.AccAddress { } // NewMsgVoteWeighted creates a message to cast a vote on an active proposal +// //nolint:interfacer func NewMsgVoteWeighted(voter sdk.AccAddress, proposalID uint64, options WeightedVoteOptions, metadata string) *MsgVoteWeighted { return &MsgVoteWeighted{proposalID, voter.String(), options, metadata} diff --git a/x/gov/types/v1/params.go b/x/gov/types/v1/params.go index 189becbfbc52..6722d49bded4 100644 --- a/x/gov/types/v1/params.go +++ b/x/gov/types/v1/params.go @@ -75,7 +75,6 @@ func DefaultParams() Params { } func (p Params) ValidateBasic() error { - if minDeposit := sdk.Coins(p.MinDeposit); minDeposit.Empty() || !minDeposit.IsValid() { return fmt.Errorf("invalid minimum deposit: %s", minDeposit) } diff --git a/x/gov/types/v1/vote.go b/x/gov/types/v1/vote.go index 64357f54ccae..94d9ab52de62 100644 --- a/x/gov/types/v1/vote.go +++ b/x/gov/types/v1/vote.go @@ -17,6 +17,7 @@ const ( ) // NewVote creates a new Vote instance +// //nolint:interfacer func NewVote(proposalID uint64, voter sdk.AccAddress, options WeightedVoteOptions, metadata string) Vote { return Vote{ProposalId: proposalID, Voter: voter.String(), Options: options, Metadata: metadata} diff --git a/x/gov/types/v1beta1/deposit.go b/x/gov/types/v1beta1/deposit.go index 92d6ab1cb707..23cf422a3a74 100644 --- a/x/gov/types/v1beta1/deposit.go +++ b/x/gov/types/v1beta1/deposit.go @@ -9,6 +9,7 @@ import ( ) // NewDeposit creates a new Deposit instance +// //nolint:interfacer func NewDeposit(proposalID uint64, depositor sdk.AccAddress, amount sdk.Coins) Deposit { return Deposit{proposalID, depositor.String(), amount} diff --git a/x/gov/types/v1beta1/msgs.go b/x/gov/types/v1beta1/msgs.go index 6aafbb51da49..85ef0c66eb7d 100644 --- a/x/gov/types/v1beta1/msgs.go +++ b/x/gov/types/v1beta1/msgs.go @@ -27,6 +27,7 @@ var ( ) // NewMsgSubmitProposal creates a new MsgSubmitProposal. +// //nolint:interfacer func NewMsgSubmitProposal(content Content, initialDeposit sdk.Coins, proposer sdk.AccAddress) (*MsgSubmitProposal, error) { m := &MsgSubmitProposal{ @@ -133,6 +134,7 @@ func (m MsgSubmitProposal) UnpackInterfaces(unpacker codectypes.AnyUnpacker) err } // NewMsgDeposit creates a new MsgDeposit instance +// //nolint:interfacer func NewMsgDeposit(depositor sdk.AccAddress, proposalID uint64, amount sdk.Coins) *MsgDeposit { return &MsgDeposit{proposalID, depositor.String(), amount} @@ -178,6 +180,7 @@ func (msg MsgDeposit) GetSigners() []sdk.AccAddress { } // NewMsgVote creates a message to cast a vote on an active proposal +// //nolint:interfacer func NewMsgVote(voter sdk.AccAddress, proposalID uint64, option VoteOption) *MsgVote { return &MsgVote{proposalID, voter.String(), option} @@ -220,6 +223,7 @@ func (msg MsgVote) GetSigners() []sdk.AccAddress { } // NewMsgVoteWeighted creates a message to cast a vote on an active proposal +// //nolint:interfacer func NewMsgVoteWeighted(voter sdk.AccAddress, proposalID uint64, options WeightedVoteOptions) *MsgVoteWeighted { return &MsgVoteWeighted{proposalID, voter.String(), options} diff --git a/x/gov/types/v1beta1/vote.go b/x/gov/types/v1beta1/vote.go index b2c0469db79b..c5b60b5fc0d9 100644 --- a/x/gov/types/v1beta1/vote.go +++ b/x/gov/types/v1beta1/vote.go @@ -11,6 +11,7 @@ import ( ) // NewVote creates a new Vote instance +// //nolint:interfacer func NewVote(proposalID uint64, voter sdk.AccAddress, options WeightedVoteOptions) Vote { return Vote{ProposalId: proposalID, Voter: voter.String(), Options: options} diff --git a/x/group/client/cli/util.go b/x/group/client/cli/util.go index fccf7626a2df..7afc43873f4b 100644 --- a/x/group/client/cli/util.go +++ b/x/group/client/cli/util.go @@ -3,7 +3,6 @@ package cli import ( "encoding/json" "fmt" - "io/ioutil" "os" "github.com/cosmos/cosmos-sdk/codec" @@ -16,7 +15,7 @@ func parseDecisionPolicy(cdc codec.Codec, decisionPolicyFile string) (group.Deci return nil, fmt.Errorf("decision policy is required") } - contents, err := ioutil.ReadFile(decisionPolicyFile) + contents, err := os.ReadFile(decisionPolicyFile) if err != nil { return nil, err } @@ -36,7 +35,7 @@ func parseMembers(membersFile string) ([]group.MemberRequest, error) { return members.Members, nil } - contents, err := ioutil.ReadFile(membersFile) + contents, err := os.ReadFile(membersFile) if err != nil { return nil, err } diff --git a/x/group/internal/orm/auto_uint64.go b/x/group/internal/orm/auto_uint64.go index 688027268da9..01f1b326d816 100644 --- a/x/group/internal/orm/auto_uint64.go +++ b/x/group/internal/orm/auto_uint64.go @@ -86,12 +86,13 @@ func (a AutoUInt64Table) GetOne(store sdk.KVStore, rowID uint64, dest codec.Prot // WARNING: The use of a PrefixScan can be very expensive in terms of Gas. Please make sure you do not expose // this as an endpoint to the public without further limits. // Example: -// it, err := idx.PrefixScan(ctx, start, end) -// if err !=nil { -// return err -// } -// const defaultLimit = 20 -// it = LimitIterator(it, defaultLimit) +// +// it, err := idx.PrefixScan(ctx, start, end) +// if err !=nil { +// return err +// } +// const defaultLimit = 20 +// it = LimitIterator(it, defaultLimit) // // CONTRACT: No writes may happen within a domain while an iterator exists over it. func (a AutoUInt64Table) PrefixScan(store sdk.KVStore, start, end uint64) (Iterator, error) { diff --git a/x/group/internal/orm/index.go b/x/group/internal/orm/index.go index f19de60d3e40..2c4cc21911cb 100644 --- a/x/group/internal/orm/index.go +++ b/x/group/internal/orm/index.go @@ -123,12 +123,13 @@ func (i MultiKeyIndex) GetPaginated(store sdk.KVStore, searchKey interface{}, pa // WARNING: The use of a PrefixScan can be very expensive in terms of Gas. Please make sure you do not expose // this as an endpoint to the public without further limits. // Example: -// it, err := idx.PrefixScan(ctx, start, end) -// if err !=nil { -// return err -// } -// const defaultLimit = 20 -// it = LimitIterator(it, defaultLimit) +// +// it, err := idx.PrefixScan(ctx, start, end) +// if err !=nil { +// return err +// } +// const defaultLimit = 20 +// it = LimitIterator(it, defaultLimit) // // CONTRACT: No writes may happen within a domain while an iterator exists over it. func (i MultiKeyIndex) PrefixScan(store sdk.KVStore, startI interface{}, endI interface{}) (Iterator, error) { @@ -261,12 +262,13 @@ func (i indexIterator) Close() error { // PrefixRange turns a prefix into a (start, end) range. The start is the given prefix value and // the end is calculated by adding 1 bit to the start value. Nil is not allowed as prefix. -// Example: []byte{1, 3, 4} becomes []byte{1, 3, 5} -// []byte{15, 42, 255, 255} becomes []byte{15, 43, 0, 0} +// +// Example: []byte{1, 3, 4} becomes []byte{1, 3, 5} +// []byte{15, 42, 255, 255} becomes []byte{15, 43, 0, 0} // // In case of an overflow the end is set to nil. -// Example: []byte{255, 255, 255, 255} becomes nil // +// Example: []byte{255, 255, 255, 255} becomes nil func PrefixRange(prefix []byte) ([]byte, []byte) { if prefix == nil { panic("nil key not allowed") diff --git a/x/group/internal/orm/iterator.go b/x/group/internal/orm/iterator.go index 71c3b32272ae..11fb4c64a014 100644 --- a/x/group/internal/orm/iterator.go +++ b/x/group/internal/orm/iterator.go @@ -104,10 +104,10 @@ func First(it Iterator, dest codec.ProtoMarshaler) (RowID, error) { // an non-nil pointer to a slice. // // If pageRequest is nil, then we will use these default values: -// - Offset: 0 -// - Key: nil -// - Limit: 100 -// - CountTotal: true +// - Offset: 0 +// - Key: nil +// - Limit: 100 +// - CountTotal: true // // If pageRequest.Key was provided, it got used beforehand to instantiate the Iterator, // using for instance UInt64Index.GetPaginated method. Only one of pageRequest.Offset or @@ -229,10 +229,10 @@ type ModelSlicePtr interface{} // The slice can be empty when the iterator does not return any values but not nil. The iterator // is closed afterwards. // Example: -// var loaded []testdata.GroupInfo -// rowIDs, err := ReadAll(it, &loaded) -// require.NoError(t, err) // +// var loaded []testdata.GroupInfo +// rowIDs, err := ReadAll(it, &loaded) +// require.NoError(t, err) func ReadAll(it Iterator, dest ModelSlicePtr) ([]RowID, error) { if it == nil { return nil, sdkerrors.Wrap(errors.ErrORMInvalidArgument, "iterator must not be nil") diff --git a/x/group/internal/orm/key_codec.go b/x/group/internal/orm/key_codec.go index 074b67b3ebc4..2203491e8e8a 100644 --- a/x/group/internal/orm/key_codec.go +++ b/x/group/internal/orm/key_codec.go @@ -14,9 +14,9 @@ const MaxBytesLen = 255 // They can be []byte, string, and integer types. The function will return // an error if there is a part of any other type. // Key parts, except the last part, follow these rules: -// - []byte is encoded with a single byte length prefix -// - strings are null-terminated -// - integers are encoded using 8 byte big endian. +// - []byte is encoded with a single byte length prefix +// - strings are null-terminated +// - integers are encoded using 8 byte big endian. func buildKeyFromParts(parts []interface{}) ([]byte, error) { bytesSlice := make([][]byte, len(parts)) totalLen := 0 diff --git a/x/group/internal/orm/primary_key.go b/x/group/internal/orm/primary_key.go index 7655c5a9d535..5b3f257bb1ff 100644 --- a/x/group/internal/orm/primary_key.go +++ b/x/group/internal/orm/primary_key.go @@ -123,12 +123,13 @@ func (a PrimaryKeyTable) GetOne(store sdk.KVStore, primKey RowID, dest codec.Pro // WARNING: The use of a PrefixScan can be very expensive in terms of Gas. Please make sure you do not expose // this as an endpoint to the public without further limits. // Example: -// it, err := idx.PrefixScan(ctx, start, end) -// if err !=nil { -// return err -// } -// const defaultLimit = 20 -// it = LimitIterator(it, defaultLimit) +// +// it, err := idx.PrefixScan(ctx, start, end) +// if err !=nil { +// return err +// } +// const defaultLimit = 20 +// it = LimitIterator(it, defaultLimit) // // CONTRACT: No writes may happen within a domain while an iterator exists over it. func (a PrimaryKeyTable) PrefixScan(store sdk.KVStore, start, end []byte) (Iterator, error) { diff --git a/x/group/internal/orm/table.go b/x/group/internal/orm/table.go index 4d6987bd73b2..e21b15ef61bf 100644 --- a/x/group/internal/orm/table.go +++ b/x/group/internal/orm/table.go @@ -192,12 +192,13 @@ func (a table) GetOne(store sdk.KVStore, rowID RowID, dest codec.ProtoMarshaler) // WARNING: The use of a PrefixScan can be very expensive in terms of Gas. Please make sure you do not expose // this as an endpoint to the public without further limits. // Example: -// it, err := idx.PrefixScan(ctx, start, end) -// if err !=nil { -// return err -// } -// const defaultLimit = 20 -// it = LimitIterator(it, defaultLimit) +// +// it, err := idx.PrefixScan(ctx, start, end) +// if err !=nil { +// return err +// } +// const defaultLimit = 20 +// it = LimitIterator(it, defaultLimit) // // CONTRACT: No writes may happen within a domain while an iterator exists over it. func (a table) PrefixScan(store sdk.KVStore, start, end RowID) (Iterator, error) { diff --git a/x/group/simulation/operations.go b/x/group/simulation/operations.go index 20bd2691050d..d210ff508929 100644 --- a/x/group/simulation/operations.go +++ b/x/group/simulation/operations.go @@ -42,6 +42,7 @@ var ( ) // Simulation operation weights constants +// //nolint:gosec // these are not hardcoded credentials. const ( OpMsgCreateGroup = "op_weight_msg_create_group" diff --git a/x/simulation/doc.go b/x/simulation/doc.go index 6543bc5c1532..f92a6cac8bab 100644 --- a/x/simulation/doc.go +++ b/x/simulation/doc.go @@ -2,7 +2,7 @@ Package simulation implements a full fledged Cosmos SDK application used for executing simulation test suites. -Simulation App +# Simulation App The SimApp type defines an application used for running extensive simulation testing suites. It contains all core modules, including governance, staking, @@ -30,7 +30,7 @@ still be pseudo-randomly simulated. The simulation test suite also supports testing determinism and import/export functionality. -Randomness +# Randomness Currently, simulation uses a single seed (integer) as a source for a PRNG by which all random operations are executed from. Any call to the PRNG changes all @@ -44,75 +44,74 @@ the simulation suite is expected to support a series of PRNGs that can be used uniquely per module and simulation component so that they will not effect each others state execution outcome. -Usage +# Usage To execute a completely pseudo-random simulation: - $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ - -run=TestFullAppSimulation \ - -Enabled=true \ - -NumBlocks=100 \ - -BlockSize=200 \ - -Commit=true \ - -Seed=99 \ - -Period=5 \ - -v -timeout 24h + $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ + -run=TestFullAppSimulation \ + -Enabled=true \ + -NumBlocks=100 \ + -BlockSize=200 \ + -Commit=true \ + -Seed=99 \ + -Period=5 \ + -v -timeout 24h To execute simulation from a genesis file: - $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ - -run=TestFullAppSimulation \ - -Enabled=true \ - -NumBlocks=100 \ - -BlockSize=200 \ - -Commit=true \ - -Seed=99 \ - -Period=5 \ - -Genesis=/path/to/genesis.json \ - -v -timeout 24h + $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ + -run=TestFullAppSimulation \ + -Enabled=true \ + -NumBlocks=100 \ + -BlockSize=200 \ + -Commit=true \ + -Seed=99 \ + -Period=5 \ + -Genesis=/path/to/genesis.json \ + -v -timeout 24h To execute simulation from a simulation params file: - $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ - -run=TestFullAppSimulation \ - -Enabled=true \ - -NumBlocks=100 \ - -BlockSize=200 \ - -Commit=true \ - -Seed=99 \ - -Period=5 \ - -Params=/path/to/params.json \ - -v -timeout 24h + $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ + -run=TestFullAppSimulation \ + -Enabled=true \ + -NumBlocks=100 \ + -BlockSize=200 \ + -Commit=true \ + -Seed=99 \ + -Period=5 \ + -Params=/path/to/params.json \ + -v -timeout 24h To export the simulation params to a file at a given block height: - $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ - -run=TestFullAppSimulation \ - -Enabled=true \ - -NumBlocks=100 \ - -BlockSize=200 \ - -Commit=true \ - -Seed=99 \ - -Period=5 \ - -ExportParamsPath=/path/to/params.json \ - -ExportParamsHeight=50 \ - -v -timeout 24h - + $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ + -run=TestFullAppSimulation \ + -Enabled=true \ + -NumBlocks=100 \ + -BlockSize=200 \ + -Commit=true \ + -Seed=99 \ + -Period=5 \ + -ExportParamsPath=/path/to/params.json \ + -ExportParamsHeight=50 \ + -v -timeout 24h To export the simulation app state (i.e genesis) to a file: - $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ - -run=TestFullAppSimulation \ - -Enabled=true \ - -NumBlocks=100 \ - -BlockSize=200 \ - -Commit=true \ - -Seed=99 \ - -Period=5 \ - -ExportStatePath=/path/to/genesis.json \ - v -timeout 24h - -Params + $ go test -mod=readonly github.com/cosmos/cosmos-sdk/simapp \ + -run=TestFullAppSimulation \ + -Enabled=true \ + -NumBlocks=100 \ + -BlockSize=200 \ + -Commit=true \ + -Seed=99 \ + -Period=5 \ + -ExportStatePath=/path/to/genesis.json \ + v -timeout 24h + +# Params Params that are provided to simulation from a JSON file are used to used to set both module parameters and simulation parameters. See sim_test.go for the full diff --git a/x/simulation/util.go b/x/simulation/util.go index 534b984566b0..f65a3f035b2d 100644 --- a/x/simulation/util.go +++ b/x/simulation/util.go @@ -30,9 +30,9 @@ func getTestingMode(tb testing.TB) (testingMode bool, t *testing.T, b *testing.B // getBlockSize returns a block size as determined from the transition matrix. // It targets making average block size the provided parameter. The three // states it moves between are: -// - "over stuffed" blocks with average size of 2 * avgblocksize, -// - normal sized blocks, hitting avgBlocksize on average, -// - and empty blocks, with no txs / only txs scheduled from the past. +// - "over stuffed" blocks with average size of 2 * avgblocksize, +// - normal sized blocks, hitting avgBlocksize on average, +// - and empty blocks, with no txs / only txs scheduled from the past. func getBlockSize(r *rand.Rand, params Params, lastBlockSizeState, avgBlockSize int) (state, blockSize int) { // TODO: Make default blocksize transition matrix actually make the average // blocksize equal to avgBlockSize. diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index e7e5b8289d49..26228fa88283 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -18,6 +18,7 @@ import ( ) // Simulation operation weights constants +// //nolint:gosec // these are not hardcoded credentials. const ( OpWeightMsgUnjail = "op_weight_msg_unjail" diff --git a/x/slashing/types/msg.go b/x/slashing/types/msg.go index a4b893708153..c3756eb0580f 100644 --- a/x/slashing/types/msg.go +++ b/x/slashing/types/msg.go @@ -17,6 +17,7 @@ var ( ) // NewMsgUnjail creates a new MsgUnjail instance +// //nolint:interfacer func NewMsgUnjail(validatorAddr sdk.ValAddress) *MsgUnjail { return &MsgUnjail{ diff --git a/x/slashing/types/signing_info.go b/x/slashing/types/signing_info.go index d9b00da199e6..3dacd12d630c 100644 --- a/x/slashing/types/signing_info.go +++ b/x/slashing/types/signing_info.go @@ -9,6 +9,7 @@ import ( ) // NewValidatorSigningInfo creates a new ValidatorSigningInfo instance +// //nolint:interfacer func NewValidatorSigningInfo( condAddr sdk.ConsAddress, startHeight, indexOffset int64, diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index 23c466d377fb..a74c14978954 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -317,8 +317,8 @@ func TestUnbondingDelegationsMaxEntries(t *testing.T) { require.True(math.IntEq(t, newNotBonded, oldNotBonded.AddRaw(1))) } -//// test undelegating self delegation from a validator pushing it below MinSelfDelegation -//// shift it from the bonded to unbonding state and jailed +// // test undelegating self delegation from a validator pushing it below MinSelfDelegation +// // shift it from the bonded to unbonding state and jailed func TestUndelegateSelfDelegationBelowMinSelfDelegation(t *testing.T) { _, app, ctx := createTestInput(t) diff --git a/x/staking/keeper/historical_info.go b/x/staking/keeper/historical_info.go index df13dff357f1..243612d38743 100644 --- a/x/staking/keeper/historical_info.go +++ b/x/staking/keeper/historical_info.go @@ -35,7 +35,9 @@ func (k Keeper) DeleteHistoricalInfo(ctx sdk.Context, height int64) { } // IterateHistoricalInfo provides an interator over all stored HistoricalInfo -// objects. For each HistoricalInfo object, cb will be called. If the cb returns +// +// objects. For each HistoricalInfo object, cb will be called. If the cb returns +// // true, the iterator will close and stop. func (k Keeper) IterateHistoricalInfo(ctx sdk.Context, cb func(types.HistoricalInfo) bool) { store := ctx.KVStore(k.storeKey) diff --git a/x/staking/keeper/slash.go b/x/staking/keeper/slash.go index 9d892b18c432..c0a147510963 100644 --- a/x/staking/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -14,15 +14,22 @@ import ( // of it, updating unbonding delegations & redelegations appropriately // // CONTRACT: -// slashFactor is non-negative +// +// slashFactor is non-negative +// // CONTRACT: -// Infraction was committed equal to or less than an unbonding period in the past, -// so all unbonding delegations and redelegations from that height are stored +// +// Infraction was committed equal to or less than an unbonding period in the past, +// so all unbonding delegations and redelegations from that height are stored +// // CONTRACT: -// Slash will not slash unbonded validators (for the above reason) +// +// Slash will not slash unbonded validators (for the above reason) +// // CONTRACT: -// Infraction was committed at the current height or at a past height, -// not at a height in the future +// +// 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) math.Int { logger := k.Logger(ctx) diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index 28704a13b843..542536fc8e82 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -16,6 +16,7 @@ import ( ) // Simulation operation weights constants +// //nolint:gosec // these are not hardcoded credentials const ( OpWeightMsgCreateValidator = "op_weight_msg_create_validator" diff --git a/x/staking/types/delegation.go b/x/staking/types/delegation.go index b86f1a179950..cad8f5f0d497 100644 --- a/x/staking/types/delegation.go +++ b/x/staking/types/delegation.go @@ -28,6 +28,7 @@ func (dvv DVVTriplet) String() string { } // NewDelegation creates a new delegation object +// //nolint:interfacer func NewDelegation(delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, shares sdk.Dec) Delegation { return Delegation{ @@ -112,6 +113,7 @@ func (e UnbondingDelegationEntry) IsMature(currentTime time.Time) bool { } // NewUnbondingDelegation - create a new unbonding delegation object +// //nolint:interfacer func NewUnbondingDelegation( delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, @@ -333,6 +335,7 @@ func (d DelegationResponses) String() (out string) { } // NewRedelegationResponse crates a new RedelegationEntryResponse instance. +// //nolint:interfacer func NewRedelegationResponse( delegatorAddr sdk.AccAddress, validatorSrc, validatorDst sdk.ValAddress, entries []RedelegationEntryResponse, diff --git a/x/staking/types/msg.go b/x/staking/types/msg.go index 32d5ea72f221..e72e68a03963 100644 --- a/x/staking/types/msg.go +++ b/x/staking/types/msg.go @@ -141,6 +141,7 @@ func (msg MsgCreateValidator) UnpackInterfaces(unpacker codectypes.AnyUnpacker) } // NewMsgEditValidator creates a new MsgEditValidator instance +// //nolint:interfacer func NewMsgEditValidator(valAddr sdk.ValAddress, description Description, newRate *sdk.Dec, newMinSelfDelegation *math.Int) *MsgEditValidator { return &MsgEditValidator{ @@ -196,6 +197,7 @@ func (msg MsgEditValidator) ValidateBasic() error { } // NewMsgDelegate creates a new MsgDelegate instance. +// //nolint:interfacer func NewMsgDelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) *MsgDelegate { return &MsgDelegate{ @@ -243,6 +245,7 @@ func (msg MsgDelegate) ValidateBasic() error { } // NewMsgBeginRedelegate creates a new MsgBeginRedelegate instance. +// //nolint:interfacer func NewMsgBeginRedelegate( delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress, amount sdk.Coin, @@ -296,6 +299,7 @@ func (msg MsgBeginRedelegate) ValidateBasic() error { } // NewMsgUndelegate creates a new MsgUndelegate instance. +// //nolint:interfacer func NewMsgUndelegate(delAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) *MsgUndelegate { return &MsgUndelegate{ @@ -343,6 +347,7 @@ func (msg MsgUndelegate) ValidateBasic() error { } // NewMsgCancelUnbondingDelegation creates a new MsgCancelUnbondingDelegation instance. +// //nolint:interfacer func NewMsgCancelUnbondingDelegation(delAddr sdk.AccAddress, valAddr sdk.ValAddress, creationHeight int64, amount sdk.Coin) *MsgCancelUnbondingDelegation { return &MsgCancelUnbondingDelegation{ diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index ffc861bafd96..434589554b91 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -39,6 +39,7 @@ var ( var _ ValidatorI = Validator{} // NewValidator constructs a new Validator +// //nolint:interfacer func NewValidator(operator sdk.ValAddress, pubKey cryptotypes.PubKey, description Description) (Validator, error) { pkAny, err := codectypes.NewAnyWithValue(pubKey) @@ -416,7 +417,8 @@ func (v Validator) RemoveTokens(tokens math.Int) Validator { // RemoveDelShares removes delegator shares from a validator. // NOTE: because token fractions are left in the valiadator, -// the exchange rate of future shares of this validator can increase. +// +// the exchange rate of future shares of this validator can increase. func (v Validator) RemoveDelShares(delShares sdk.Dec) (Validator, math.Int) { remainingShares := v.DelegatorShares.Sub(delShares) diff --git a/x/upgrade/abci_test.go b/x/upgrade/abci_test.go index 1bcfe0a8fcef..7f6490f1277f 100644 --- a/x/upgrade/abci_test.go +++ b/x/upgrade/abci_test.go @@ -42,7 +42,6 @@ type TestSuite struct { var s TestSuite func setupTest(t *testing.T, height int64, skip map[int64]bool) TestSuite { - s.encCfg = moduletestutil.MakeTestEncodingConfig(upgrade.AppModuleBasic{}) key := sdk.NewKVStoreKey(types.StoreKey) testCtx := testutil.DefaultContextWithDB(s.T(), key, sdk.NewTransientStoreKey("transient_test")) diff --git a/x/upgrade/doc.go b/x/upgrade/doc.go index b66fe38c1db0..5589ac6eda92 100644 --- a/x/upgrade/doc.go +++ b/x/upgrade/doc.go @@ -7,7 +7,7 @@ Without software support for upgrades, upgrading a live chain is risky because a their state machines at exactly the same point in the process. If this is not done correctly, there can be state inconsistencies which are hard to recover from. -General Workflow +# General Workflow Let's assume we are running v0.38.0 of our software in our testnet and want to upgrade to v0.40.0. How would this look in practice? First of all, we want to finalize the v0.40.0 release candidate @@ -40,25 +40,27 @@ the rest of the block as normal. Once 2/3 of the voting power has upgraded, the resume the consensus mechanism. If the majority of operators add a custom `do-upgrade` script, this should be a matter of minutes and not even require them to be awake at that time. -Integrating With An App +# Integrating With An App Setup an upgrade Keeper for the app and then define a BeginBlocker that calls the upgrade keeper's BeginBlocker method: - func (app *myApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - app.upgradeKeeper.BeginBlocker(ctx, req) - return abci.ResponseBeginBlock{} - } + + func (app *myApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { + app.upgradeKeeper.BeginBlocker(ctx, req) + return abci.ResponseBeginBlock{} + } The app must then integrate the upgrade keeper with its governance module as appropriate. The governance module should call ScheduleUpgrade to schedule an upgrade and ClearUpgradePlan to cancel a pending upgrade. -Performing Upgrades +# Performing Upgrades Upgrades can be scheduled at a predefined block height. Once this block height is reached, the existing software will cease to process ABCI messages and a new version with code that handles the upgrade must be deployed. All upgrades are coordinated by a unique upgrade name that cannot be reused on the same blockchain. In order for the upgrade module to know that the upgrade has been safely applied, a handler with the name of the upgrade must be installed. Here is an example handler for an upgrade named "my-fancy-upgrade": + app.upgradeKeeper.SetUpgradeHandler("my-fancy-upgrade", func(ctx sdk.Context, plan upgrade.Plan) { // Perform any migrations of the state store needed for this upgrade }) @@ -93,18 +95,20 @@ Here is a sample code to set store migrations with an upgrade: app.SetStoreLoader(upgrade.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades)) } -Halt Behavior +# Halt Behavior Before halting the ABCI state machine in the BeginBlocker method, the upgrade module will log an error that looks like: + UPGRADE "" NEEDED at height : + where Name are Info are the values of the respective fields on the upgrade Plan. To perform the actual halt of the blockchain, the upgrade keeper simply panics which prevents the ABCI state machine from proceeding but doesn't actually exit the process. Exiting the process can cause issues for other nodes that start to lose connectivity with the exiting nodes, thus this module prefers to just halt but not exit. -Automation and Plan.Info +# Automation and Plan.Info We have deprecated calling out to scripts, instead with propose https://github.com/cosmos/cosmos-sdk/tree/main/cosmovisor as a model for a watcher daemon that can launch simd as a subprocess and then read the upgrade log message @@ -113,7 +117,7 @@ specified here https://github.com/cosmos/cosmos-sdk/tree/main/cosmovisor/README. 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 +# Cancelling 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 @@ -134,6 +138,7 @@ If over two-thirds run their nodes with this flag on the old binary, it will all the upgrade with a manual override. (This must be well-documented for anyone syncing from genesis later on). Example: + simd start --unsafe-skip-upgrades ... NOTE: Here simd is used as an example binary, replace it with original binary diff --git a/x/upgrade/handler.go b/x/upgrade/handler.go index f880cd7f9ec8..9825d90a2728 100644 --- a/x/upgrade/handler.go +++ b/x/upgrade/handler.go @@ -11,7 +11,8 @@ import ( // NewSoftwareUpgradeProposalHandler creates a governance handler to manage new proposal types. // It enables SoftwareUpgradeProposal to propose an Upgrade, and CancelSoftwareUpgradeProposal // to abort a previously voted upgrade. -//nolint: staticcheck // we are intentionally using a deprecated proposal here. +// +//nolint:staticcheck // we are intentionally using a deprecated proposal here. func NewSoftwareUpgradeProposalHandler(k keeper.Keeper) govtypes.Handler { return func(ctx sdk.Context, content govtypes.Content) error { switch c := content.(type) { diff --git a/x/upgrade/keeper/grpc_query.go b/x/upgrade/keeper/grpc_query.go index 3c9e667ac935..7b25ad40972e 100644 --- a/x/upgrade/keeper/grpc_query.go +++ b/x/upgrade/keeper/grpc_query.go @@ -35,7 +35,8 @@ func (k Keeper) AppliedPlan(c context.Context, req *types.QueryAppliedPlanReques } // UpgradedConsensusState implements the Query/UpgradedConsensusState gRPC method -// nolint: staticcheck +// +//nolint:staticcheck func (k Keeper) UpgradedConsensusState(c context.Context, req *types.QueryUpgradedConsensusStateRequest) (*types.QueryUpgradedConsensusStateResponse, error) { ctx := sdk.UnwrapSDKContext(c) diff --git a/x/upgrade/keeper/grpc_query_test.go b/x/upgrade/keeper/grpc_query_test.go index 6c98948411fa..41f904ccbede 100644 --- a/x/upgrade/keeper/grpc_query_test.go +++ b/x/upgrade/keeper/grpc_query_test.go @@ -30,7 +30,6 @@ type UpgradeTestSuite struct { } func (suite *UpgradeTestSuite) SetupTest() { - suite.encCfg = moduletestutil.MakeTestEncodingConfig(upgrade.AppModuleBasic{}) key := sdk.NewKVStoreKey(types.StoreKey) testCtx := testutil.DefaultContextWithDB(suite.T(), key, sdk.NewTransientStoreKey("transient_test")) diff --git a/x/upgrade/keeper/keeper_test.go b/x/upgrade/keeper/keeper_test.go index f087f12910fa..795724c1435e 100644 --- a/x/upgrade/keeper/keeper_test.go +++ b/x/upgrade/keeper/keeper_test.go @@ -35,7 +35,6 @@ type KeeperTestSuite struct { } func (s *KeeperTestSuite) SetupTest() { - s.encCfg = moduletestutil.MakeTestEncodingConfig(upgrade.AppModuleBasic{}) key := sdk.NewKVStoreKey(types.StoreKey) testCtx := testutil.DefaultContextWithDB(s.T(), key, sdk.NewTransientStoreKey("transient_test")) diff --git a/x/upgrade/plan/downloader.go b/x/upgrade/plan/downloader.go index 7686b7aec823..d09d4725b8ea 100644 --- a/x/upgrade/plan/downloader.go +++ b/x/upgrade/plan/downloader.go @@ -17,8 +17,10 @@ import ( // This is an opinionated directory structure that corresponds with Cosmovisor requirements. // If the url is not an archive, it is downloaded and saved to {dstRoot}/bin/{daemonName}. // If the url is an archive, it is downloaded and unpacked to {dstRoot}. -// If the archive does not contain a /bin/{daemonName} file, then this will attempt to move /{daemonName} to /bin/{daemonName}. -// If the archive does not contain either /bin/{daemonName} or /{daemonName}, an error is returned. +// +// If the archive does not contain a /bin/{daemonName} file, then this will attempt to move /{daemonName} to /bin/{daemonName}. +// If the archive does not contain either /bin/{daemonName} or /{daemonName}, an error is returned. +// // Note: Because a checksum is required, this function cannot be used to download non-archive directories. // If dstRoot already exists, some or all of its contents might be updated. func DownloadUpgrade(dstRoot, url, daemonName string) error { @@ -74,9 +76,9 @@ func downloadUpgradeAsArchive(dstDir, url, daemonName string) error { // EnsureBinary checks that the given file exists as a regular file and is executable. // An error is returned if: -// - The file does not exist. -// - The path exists, but is one of: Dir, Symlink, NamedPipe, Socket, Device, CharDevice, or Irregular. -// - The file exists, is not executable by all three of User, Group, and Other, and cannot be made executable. +// - The file does not exist. +// - The path exists, but is one of: Dir, Symlink, NamedPipe, Socket, Device, CharDevice, or Irregular. +// - The file exists, is not executable by all three of User, Group, and Other, and cannot be made executable. func EnsureBinary(path string) error { info, err := os.Stat(path) if err != nil { @@ -99,11 +101,11 @@ func EnsureBinary(path string) error { // The provided url must contain a checksum parameter that matches the file being downloaded. // If there isn't an error, the content returned by the url will be returned as a string. // Returns an error if: -// - The url is not a URL or does not contain a checksum parameter. -// - Downloading the URL fails. -// - The checksum does not match what is returned by the URL. -// - The URL does not return a regular file. -// - The downloaded file is empty or only whitespace. +// - The url is not a URL or does not contain a checksum parameter. +// - Downloading the URL fails. +// - The checksum does not match what is returned by the URL. +// - The URL does not return a regular file. +// - The downloaded file is empty or only whitespace. func DownloadURLWithChecksum(url string) (string, error) { if err := ValidateIsURLWithChecksum(url); err != nil { return "", err diff --git a/x/upgrade/plan/info.go b/x/upgrade/plan/info.go index 9661844c2cde..c29ec2ab5a06 100644 --- a/x/upgrade/plan/info.go +++ b/x/upgrade/plan/info.go @@ -50,8 +50,9 @@ func ParseInfo(infoStr string) (*Info, error) { // ValidateFull does all possible validation of this Info. // The provided daemonName is the name of the executable file expected in all downloaded directories. // It checks that: -// * Binaries.ValidateBasic() doesn't return an error -// * Binaries.CheckURLs(daemonName) doesn't return an error. +// - Binaries.ValidateBasic() doesn't return an error +// - Binaries.CheckURLs(daemonName) doesn't return an error. +// // Warning: This is an expensive process. See BinaryDownloadURLMap.CheckURLs for more info. func (m Info) ValidateFull(daemonName string) error { if err := m.Binaries.ValidateBasic(); err != nil { @@ -65,10 +66,10 @@ func (m Info) ValidateFull(daemonName string) error { // ValidateBasic does stateless validation of this BinaryDownloadURLMap. // It validates that: -// * This has at least one entry. -// * All entry keys have the format "os/arch" or are "any". -// * All entry values are valid URLs. -// * All URLs contain a checksum query parameter. +// - This has at least one entry. +// - All entry keys have the format "os/arch" or are "any". +// - All entry values are valid URLs. +// - All URLs contain a checksum query parameter. func (m BinaryDownloadURLMap) ValidateBasic() error { // Make sure there's at least one. if len(m) == 0 { From 4fe7797b6503ec7b45fea2bad5b1b85bff7320de Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 11 Aug 2022 20:19:26 +0000 Subject: [PATCH 2/2] build(deps): Bump github.com/coinbase/rosetta-sdk-go from 0.7.10 to 0.7.11 (#12911) Bumps [github.com/coinbase/rosetta-sdk-go](https://github.com/coinbase/rosetta-sdk-go) from 0.7.10 to 0.7.11.
Commits

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=github.com/coinbase/rosetta-sdk-go&package-manager=go_modules&previous-version=0.7.10&new-version=0.7.11)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
--- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 53a96fd3c278..d1f353cd18f3 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,7 @@ require ( github.com/bgentry/speakeasy v0.1.0 github.com/btcsuite/btcd v0.22.1 github.com/cockroachdb/apd/v2 v2.0.2 - github.com/coinbase/rosetta-sdk-go v0.7.10 + github.com/coinbase/rosetta-sdk-go v0.7.11 github.com/confio/ics23/go v0.7.0 github.com/cosmos/btcutil v1.0.4 github.com/cosmos/cosmos-proto v1.0.0-alpha7 diff --git a/go.sum b/go.sum index 84adc4fdb069..35cc95be3807 100644 --- a/go.sum +++ b/go.sum @@ -264,8 +264,8 @@ github.com/cockroachdb/apd/v2 v2.0.2/go.mod h1:DDxRlzC2lo3/vSlmSoS7JkqbbrARPuFOG github.com/cockroachdb/apd/v3 v3.1.0 h1:MK3Ow7LH0W8zkd5GMKA1PvS9qG3bWFI95WaVNfyZJ/w= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= -github.com/coinbase/rosetta-sdk-go v0.7.10 h1:m5Prrqg9CD1GFZm0tu8z3LEDF/BY5RKUSkODZRpAkEc= -github.com/coinbase/rosetta-sdk-go v0.7.10/go.mod h1:/glajndJEMrp+D7cO2PJZWKeclK8mDyzSCokCMc6Ftc= +github.com/coinbase/rosetta-sdk-go v0.7.11 h1:T7camDGstlX2ENVE0QHR1AVu3asSXED0vg1xDaF6bYE= +github.com/coinbase/rosetta-sdk-go v0.7.11/go.mod h1:HLTqSTSnOGLWHGTxoUJQO2TLuKkas1B9i/7ByerK6lM= github.com/confio/ics23/go v0.7.0 h1:00d2kukk7sPoHWL4zZBZwzxnpA2pec1NPdwbSokJ5w8= github.com/confio/ics23/go v0.7.0/go.mod h1:E45NqnlpxGnpfTWL/xauN7MRwEE28T4Dd4uraToOaKg= github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U=