chore: fix linting issues exposed by fixing golangci-lint (#12895)

Co-authored-by: Marko <marbar3778@yahoo.com>
Co-authored-by: Julien Robert <julien@rbrt.fr>
This commit is contained in:
Jacob Gadikian 2022-08-12 03:00:24 +07:00 committed by GitHub
parent 15b04c2a87
commit 0943a70215
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
148 changed files with 570 additions and 468 deletions

View File

@ -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

View File

@ -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 {

View File

@ -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

View File

@ -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)
}

View File

@ -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)

View File

@ -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

View File

@ -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) {

View File

@ -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{}

View File

@ -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{}

View File

@ -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 {

View File

@ -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
}

View File

@ -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.

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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()

View File

@ -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"

View File

@ -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.

View File

@ -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

View File

@ -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)

View File

@ -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])
}

View File

@ -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.

View File

@ -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

View File

@ -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])

View File

@ -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

View File

@ -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) {

View File

@ -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.

View File

@ -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 {

View File

@ -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"

View File

@ -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"

View File

@ -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()
}

View File

@ -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

View File

@ -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)
}

View File

@ -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 {

View File

@ -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"

View File

@ -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
}

View File

@ -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 {

View File

@ -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 {

View File

@ -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 {

View File

@ -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

View File

@ -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
}

View File

@ -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.

View File

@ -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)

View File

@ -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)

View File

@ -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}}
}

View File

@ -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)

View File

@ -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

View File

@ -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")

View File

@ -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))

View File

@ -31,7 +31,6 @@ type IntegrationTestSuite struct {
}
func TestIntegrationTestSuite(t *testing.T) {
suite.Run(t, new(IntegrationTestSuite))
}

View File

@ -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)

View File

@ -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

View File

@ -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
}

View File

@ -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)
}

View File

@ -9,8 +9,7 @@ import (
)
// bytesValueRenderer implements ValueRenderer for bytes
type bytesValueRenderer struct {
}
type bytesValueRenderer struct{}
var _ ValueRenderer = bytesValueRenderer{}

View File

@ -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)

View File

@ -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)

View File

@ -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})

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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) {

View File

@ -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)
}

View File

@ -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 {

View File

@ -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 (

View File

@ -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,

View File

@ -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,

View File

@ -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{

View File

@ -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)
}

View File

@ -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()

View File

@ -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"

View File

@ -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{

View File

@ -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 {

View File

@ -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{

View File

@ -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

View File

@ -15,7 +15,6 @@ import (
//
// - 0x01<grant_Bytes>: Grant
// - 0x02<grant_expiration_Bytes>: 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<grant_expiration_Bytes>: GrantQueueItem
//
// 0x02<grant_expiration_Bytes>: GrantQueueItem
func GrantQueueKey(expiration time.Time, granter sdk.AccAddress, grantee sdk.AccAddress) []byte {
exp := sdk.FormatTimeBytes(expiration)
granter = address.MustLengthPrefix(granter)

View File

@ -14,7 +14,6 @@ import (
//
// - 0x01<grant_Bytes>: Grant
// - 0x02<grant_expiration_Bytes>: GrantQueueItem
//
var (
GrantPrefix = []byte{0x01}
GrantQueuePrefix = []byte{0x02}

View File

@ -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{})

View File

@ -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))

View File

@ -26,6 +26,7 @@ var (
)
// Simulation operation weights constants
//
//nolint:gosec // these are not hardcoded credentials.
const (
OpWeightMsgGrant = "op_weight_msg_grant"

View File

@ -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 {

View File

@ -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{

View File

@ -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) {

View File

@ -17,6 +17,7 @@ import (
)
// Simulation operation weights constants
//
//nolint:gosec // these are not hardcoded credentials.
const (
OpWeightMsgSend = "op_weight_msg_send"

View File

@ -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,

View File

@ -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")

View File

@ -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{

View File

@ -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)

View File

@ -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}
}

View File

@ -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())

View File

@ -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)

View File

@ -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{

View File

@ -19,6 +19,7 @@ import (
)
// Simulation operation weights constants
//
//nolint:gosec // these are not hardcoded credentials.
const (
OpWeightMsgSetWithdrawAddress = "op_weight_msg_set_withdraw_address"

View File

@ -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}

View File

@ -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}

View File

@ -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,

View File

@ -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"

View File

@ -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"

View File

@ -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)

View File

@ -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)

Some files were not shown because too many files have changed in this diff Show More