From 6bc71c16bc9bf62d5c6040471225eda81f333a1b Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 15:24:11 +0700 Subject: [PATCH 01/27] mainly sdk.int to cosmossdk.io/math --- .golangci.yml | 3 +- baseapp/baseapp.go | 3 +- client/cmd.go | 2 +- client/grpc/tmservice/block.go | 4 +- client/grpc_query.go | 2 +- client/keys/add.go | 2 +- .../secp256k1/internal/secp256k1/curve.go | 50 +++++++++---------- pruning/manager.go | 2 +- runtime/app.go | 8 +-- server/rosetta/converter.go | 3 +- simapp/test_helpers.go | 14 +++--- snapshots/types/util.go | 2 +- store/v2alpha1/smt/ics23.go | 2 +- testutil/network/network.go | 7 +-- types/address.go | 6 +-- types/coin.go | 2 +- types/kv/list.go | 1 - types/simulation/rand_util.go | 9 ++-- x/auth/client/testutil/suite.go | 3 +- x/auth/tx/builder.go | 10 ++-- x/authz/module/abci.go | 2 +- x/bank/client/testutil/suite.go | 3 +- x/bank/keeper/grpc_query.go | 4 +- x/bank/keeper/keeper.go | 7 +-- x/bank/keeper/view.go | 5 +- x/gov/keeper/msg_server.go | 2 +- x/gov/keeper/querier.go | 6 --- x/gov/migrations/v046/convert.go | 2 +- x/gov/types/expected_keepers.go | 3 +- x/gov/types/v1/proposal.go | 2 +- x/gov/types/v1/tally.go | 7 +-- x/gov/types/v1beta1/proposal.go | 2 +- x/gov/types/v1beta1/tally.go | 7 +-- x/group/client/testutil/tx.go | 15 ------ x/group/keeper/msg_server.go | 2 +- x/mint/keeper/keeper.go | 3 +- x/mint/types/expected_keepers.go | 3 +- x/mint/types/minter.go | 4 +- x/simulation/simulate.go | 2 +- x/slashing/types/expected_keepers.go | 3 +- x/staking/client/cli/tx.go | 4 +- x/staking/keeper/delegation.go | 15 +++--- x/staking/keeper/params.go | 4 +- x/staking/keeper/pool.go | 13 ++--- x/staking/keeper/power_reduction.go | 5 +- x/staking/keeper/slash.go | 8 +-- x/staking/keeper/validator.go | 7 +-- x/staking/teststaking/helper.go | 11 ++-- x/staking/teststaking/tm.go | 6 +-- x/staking/types/delegation.go | 18 +++---- x/staking/types/expected_keepers.go | 7 +-- x/staking/types/exported.go | 43 ++++++++-------- x/staking/types/historical_info.go | 5 +- x/staking/types/msg.go | 5 +- x/staking/types/params.go | 3 +- x/staking/types/pool.go | 4 +- x/staking/types/validator.go | 35 ++++++------- x/upgrade/module.go | 5 +- 58 files changed, 216 insertions(+), 201 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 3ed11ffc0aad..af649229d62d 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -10,7 +10,7 @@ linters: - deadcode - depguard - dogsled - # - errcheck + - errcheck - exportloopref - goconst - gocritic @@ -32,7 +32,6 @@ linters: - unconvert - unparam - unused - # - wsl issues: exclude-rules: diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 6908101862d8..34f62c7b075f 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -11,7 +11,6 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" - "github.com/cosmos/cosmos-sdk/codec/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/snapshots" "github.com/cosmos/cosmos-sdk/store" @@ -54,7 +53,7 @@ type BaseApp struct { // nolint: maligned queryRouter sdk.QueryRouter // router for redirecting query calls grpcQueryRouter *GRPCQueryRouter // router for redirecting gRPC query calls msgServiceRouter *MsgServiceRouter // router for redirecting Msg service messages - interfaceRegistry types.InterfaceRegistry + interfaceRegistry codectypes.InterfaceRegistry txDecoder sdk.TxDecoder // unmarshal []byte into sdk.Tx anteHandler sdk.AnteHandler // ante handler for fee and auth diff --git a/client/cmd.go b/client/cmd.go index ce6faba09e06..77b404bcb575 100644 --- a/client/cmd.go +++ b/client/cmd.go @@ -268,7 +268,7 @@ func readTxCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Context, err isAux, _ := flagSet.GetBool(flags.FlagAux) clientCtx = clientCtx.WithAux(isAux) if isAux { - // If the user didn't explicity set an --output flag, use JSON by + // If the user didn't explicitly set an --output flag, use JSON by // default. if clientCtx.OutputFormat == "" || !flagSet.Changed(cli.OutputFlag) { clientCtx = clientCtx.WithOutputFormat("json") diff --git a/client/grpc/tmservice/block.go b/client/grpc/tmservice/block.go index 6f3b1e556993..f941c9093a83 100644 --- a/client/grpc/tmservice/block.go +++ b/client/grpc/tmservice/block.go @@ -27,7 +27,7 @@ func GetProtoBlock(ctx context.Context, clientCtx client.Context, height *int64) if err != nil { return tmproto.BlockID{}, nil, err } - protoBlockId := block.BlockID.ToProto() + protoBlockID := block.BlockID.ToProto() - return protoBlockId, protoBlock, nil + return protoBlockID, protoBlock, nil } diff --git a/client/grpc_query.go b/client/grpc_query.go index dd0f5ab11335..a5b348ca1058 100644 --- a/client/grpc_query.go +++ b/client/grpc_query.go @@ -156,7 +156,7 @@ func (f failingInterfaceRegistry) UnpackAny(any *types.Any, iface interface{}) e return errCodecNotSet } -func (f failingInterfaceRegistry) Resolve(typeUrl string) (proto.Message, error) { +func (f failingInterfaceRegistry) Resolve(typeURL string) (proto.Message, error) { return nil, errCodecNotSet } diff --git a/client/keys/add.go b/client/keys/add.go index 76d15b8b9a9e..13b58018b5f2 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -298,7 +298,7 @@ func printCreate(cmd *cobra.Command, k *keyring.Record, showMnemonic bool, mnemo // print mnemonic unless requested not to. if showMnemonic { - if _, err := fmt.Fprintln(cmd.ErrOrStderr(), fmt.Sprintf("\n**Important** write this mnemonic phrase in a safe place.\nIt is the only way to recover your account if you ever forget your password.\n\n%s\n", mnemonic)); err != nil { + if _, err := fmt.Fprintf(cmd.ErrOrStderr(), fmt.Sprintf("\n**Important** write this mnemonic phrase in a safe place.\nIt is the only way to recover your account if you ever forget your password.\n\n%s\n", mnemonic)); err != nil { return fmt.Errorf("failed to print mnemonic: %v", err) } } diff --git a/crypto/keys/secp256k1/internal/secp256k1/curve.go b/crypto/keys/secp256k1/internal/secp256k1/curve.go index b5c80b23ad62..d83bf62ca2fe 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/curve.go +++ b/crypto/keys/secp256k1/internal/secp256k1/curve.go @@ -79,28 +79,28 @@ type BitCurve struct { BitSize int // the size of the underlying field } -func (BitCurve *BitCurve) Params() *elliptic.CurveParams { +func (bitCurve *BitCurve) Params() *elliptic.CurveParams { return &elliptic.CurveParams{ - P: BitCurve.P, - N: BitCurve.N, - B: BitCurve.B, - Gx: BitCurve.Gx, - Gy: BitCurve.Gy, - BitSize: BitCurve.BitSize, + P: bitCurve.P, + N: bitCurve.N, + B: bitCurve.B, + Gx: bitCurve.Gx, + Gy: bitCurve.Gy, + BitSize: bitCurve.BitSize, } } // IsOnCurve returns true if the given (x,y) lies on the BitCurve. -func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { +func (bitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { // y² = x³ + b y2 := new(big.Int).Mul(y, y) // y² - y2.Mod(y2, BitCurve.P) // y²%P + y2.Mod(y2, bitCurve.P) // y²%P x3 := new(big.Int).Mul(x, x) // x² x3.Mul(x3, x) // x³ - x3.Add(x3, BitCurve.B) // x³+B - x3.Mod(x3, BitCurve.P) //(x³+B)%P + x3.Add(x3, bitCurve.B) // x³+B + x3.Mod(x3, bitCurve.P) // (x³+B)%P return x3.Cmp(y2) == 0 } @@ -108,24 +108,24 @@ func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { // TODO: double check if the function is okay // affineFromJacobian reverses the Jacobian transform. See the comment at the // top of the file. -func (BitCurve *BitCurve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) { +func (bitCurve *BitCurve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) { if z.Sign() == 0 { return new(big.Int), new(big.Int) } - zinv := new(big.Int).ModInverse(z, BitCurve.P) + zinv := new(big.Int).ModInverse(z, bitCurve.P) zinvsq := new(big.Int).Mul(zinv, zinv) xOut = new(big.Int).Mul(x, zinvsq) - xOut.Mod(xOut, BitCurve.P) + xOut.Mod(xOut, bitCurve.P) zinvsq.Mul(zinvsq, zinv) yOut = new(big.Int).Mul(y, zinvsq) - yOut.Mod(yOut, BitCurve.P) + yOut.Mod(yOut, bitCurve.P) return } // Add returns the sum of (x1,y1) and (x2,y2) -func (BitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { +func (bitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { // If one point is at infinity, return the other point. // Adding the point at infinity to any point will preserve the other point. if x1.Sign() == 0 && y1.Sign() == 0 { @@ -136,9 +136,9 @@ func (BitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { } z := new(big.Int).SetInt64(1) if x1.Cmp(x2) == 0 && y1.Cmp(y2) == 0 { - return BitCurve.affineFromJacobian(BitCurve.doubleJacobian(x1, y1, z)) + return bitCurve.affineFromJacobian(bitCurve.doubleJacobian(x1, y1, z)) } - return BitCurve.affineFromJacobian(BitCurve.addJacobian(x1, y1, z, x2, y2, z)) + return bitCurve.affineFromJacobian(bitCurve.addJacobian(x1, y1, z, x2, y2, z)) } // addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and @@ -222,9 +222,9 @@ func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, c := new(big.Int).Mul(b, b) // B² d := new(big.Int).Add(x, b) // X1+B - d.Mul(d, d) //(X1+B)² - d.Sub(d, a) //(X1+B)²-A - d.Sub(d, c) //(X1+B)²-A-C + d.Mul(d, d) // (X1+B)² + d.Sub(d, a) // (X1+B)²-A + d.Sub(d, c) // (X1+B)²-A-C d.Mul(d, big.NewInt(2)) // 2*((X1+B)²-A-C) e := new(big.Int).Mul(big.NewInt(3), a) // 3*A @@ -254,8 +254,8 @@ func (BitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { // Marshal converts a point into the form specified in section 4.3.6 of ANSI // X9.62. -func (BitCurve *BitCurve) Marshal(x, y *big.Int) []byte { - byteLen := (BitCurve.BitSize + 7) >> 3 +func (bitCurve *BitCurve) Marshal(x, y *big.Int) []byte { + byteLen := (bitCurve.BitSize + 7) >> 3 ret := make([]byte, 1+2*byteLen) ret[0] = 4 // uncompressed point flag readBits(x, ret[1:1+byteLen]) @@ -265,8 +265,8 @@ func (BitCurve *BitCurve) Marshal(x, y *big.Int) []byte { // Unmarshal converts a point, serialised by Marshal, into an x, y pair. On // error, x = nil. -func (BitCurve *BitCurve) Unmarshal(data []byte) (x, y *big.Int) { - byteLen := (BitCurve.BitSize + 7) >> 3 +func (bitCurve *BitCurve) Unmarshal(data []byte) (x, y *big.Int) { + byteLen := (bitCurve.BitSize + 7) >> 3 if len(data) != 1+2*byteLen { return } diff --git a/pruning/manager.go b/pruning/manager.go index 8e7c61cc9ef6..ac1172ebb86e 100644 --- a/pruning/manager.go +++ b/pruning/manager.go @@ -13,7 +13,7 @@ import ( ) // Manager is an abstraction to handle the logic needed for -// determinging when to prune old heights of the store +// determining when to prune old heights of the store // based on the strategy described by the pruning options. type Manager struct { db dbm.DB diff --git a/runtime/app.go b/runtime/app.go index 8802337fe6a2..504e26b1ef8b 100644 --- a/runtime/app.go +++ b/runtime/app.go @@ -106,13 +106,13 @@ func (a *App) Load(loadLatest bool) error { } // BeginBlocker application updates every begin block -func (app *App) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - return app.ModuleManager.BeginBlock(ctx, req) +func (a *App) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { + return a.ModuleManager.BeginBlock(ctx, req) } // EndBlocker application updates every end block -func (app *App) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - return app.ModuleManager.EndBlock(ctx, req) +func (a *App) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { + return a.ModuleManager.EndBlock(ctx, req) } // InitChainer initializes the chain. diff --git a/server/rosetta/converter.go b/server/rosetta/converter.go index 54c154579861..a58927207ab5 100644 --- a/server/rosetta/converter.go +++ b/server/rosetta/converter.go @@ -6,6 +6,7 @@ import ( "fmt" "reflect" + "cosmossdk.io/math" "github.com/btcsuite/btcd/btcec" rosettatypes "github.com/coinbase/rosetta-sdk-go/types" abci "github.com/tendermint/tendermint/abci/types" @@ -408,7 +409,7 @@ func sdkEventToBalanceOperations(status string, event abci.Event) (operations [] // Amounts converts []sdk.Coin to rosetta amounts func (c converter) Amounts(ownedCoins []sdk.Coin, availableCoins sdk.Coins) []*rosettatypes.Amount { amounts := make([]*rosettatypes.Amount, len(availableCoins)) - ownedCoinsMap := make(map[string]sdk.Int, len(availableCoins)) + ownedCoinsMap := make(map[string]math.Int, len(availableCoins)) for _, ownedCoin := range ownedCoins { ownedCoinsMap[ownedCoin.Denom] = ownedCoin.Amount diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 3c9beddc7ca7..c66cc825c50e 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -6,12 +6,14 @@ import ( "encoding/hex" "encoding/json" "fmt" - "github.com/cosmos/cosmos-sdk/depinject" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" "strconv" "testing" "time" + "github.com/cosmos/cosmos-sdk/depinject" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + + "cosmossdk.io/math" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmjson "github.com/tendermint/tendermint/libs/json" @@ -306,7 +308,7 @@ func createIncrementalAccounts(accNum int) []sdk.AccAddress { } // AddTestAddrsFromPubKeys adds the addresses into the SimApp providing only the public keys. -func AddTestAddrsFromPubKeys(app *SimApp, ctx sdk.Context, pubKeys []cryptotypes.PubKey, accAmt sdk.Int) { +func AddTestAddrsFromPubKeys(app *SimApp, ctx sdk.Context, pubKeys []cryptotypes.PubKey, accAmt math.Int) { initCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt)) for _, pk := range pubKeys { @@ -316,17 +318,17 @@ func AddTestAddrsFromPubKeys(app *SimApp, ctx sdk.Context, pubKeys []cryptotypes // AddTestAddrs constructs and returns accNum amount of accounts with an // initial balance of accAmt in random order -func AddTestAddrs(app *SimApp, ctx sdk.Context, accNum int, accAmt sdk.Int) []sdk.AccAddress { +func AddTestAddrs(app *SimApp, ctx sdk.Context, accNum int, accAmt math.Int) []sdk.AccAddress { return addTestAddrs(app, ctx, accNum, accAmt, createRandomAccounts) } // AddTestAddrsIncremental constructs and returns accNum amount of accounts with an // initial balance of accAmt in random order -func AddTestAddrsIncremental(app *SimApp, ctx sdk.Context, accNum int, accAmt sdk.Int) []sdk.AccAddress { +func AddTestAddrsIncremental(app *SimApp, ctx sdk.Context, accNum int, accAmt math.Int) []sdk.AccAddress { return addTestAddrs(app, ctx, accNum, accAmt, createIncrementalAccounts) } -func addTestAddrs(app *SimApp, ctx sdk.Context, accNum int, accAmt sdk.Int, strategy GenerateAccountStrategy) []sdk.AccAddress { +func addTestAddrs(app *SimApp, ctx sdk.Context, accNum int, accAmt math.Int, strategy GenerateAccountStrategy) []sdk.AccAddress { testAddrs := strategy(accNum) initCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt)) diff --git a/snapshots/types/util.go b/snapshots/types/util.go index 125ea6fb4610..348b5057682d 100644 --- a/snapshots/types/util.go +++ b/snapshots/types/util.go @@ -4,7 +4,7 @@ import ( protoio "github.com/gogo/protobuf/io" ) -// WriteExtensionItem writes an item payload for current extention snapshotter. +// WriteExtensionItem writes an item payload for current extension snapshotter. func WriteExtensionItem(protoWriter protoio.Writer, item []byte) error { return protoWriter.WriteMsg(&SnapshotItem{ Item: &SnapshotItem_ExtensionPayload{ diff --git a/store/v2alpha1/smt/ics23.go b/store/v2alpha1/smt/ics23.go index 31d78f993dc0..3c4299227298 100644 --- a/store/v2alpha1/smt/ics23.go +++ b/store/v2alpha1/smt/ics23.go @@ -104,7 +104,7 @@ func convertInnerOps(path []byte, sideNodes [][]byte) []*ics23.InnerOp { Hash: ics23.HashOp_SHA256, Prefix: []byte{1}, } - if getBitAtFromMSB(path[:], depth-1-i) == 1 { + if getBitAtFromMSB(path, depth-1-i) == 1 { // right child is on path op.Prefix = append(op.Prefix, sideNodes[i]...) } else { diff --git a/testutil/network/network.go b/testutil/network/network.go index b4675a769f7c..815117cca1a9 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -24,6 +24,7 @@ import ( dbm "github.com/tendermint/tm-db" "google.golang.org/grpc" + "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" @@ -84,9 +85,9 @@ type Config struct { Mnemonics []string // custom user-provided validator operator mnemonics BondDenom string // the staking bond denomination MinGasPrices string // the minimum gas prices each validator will accept - AccountTokens sdk.Int // the amount of unique validator tokens (e.g. 1000node0) - StakingTokens sdk.Int // the amount of tokens each validator has available to stake - BondedTokens sdk.Int // the amount of tokens each validator stakes + AccountTokens math.Int // the amount of unique validator tokens (e.g. 1000node0) + StakingTokens math.Int // the amount of tokens each validator has available to stake + BondedTokens math.Int // the amount of tokens each validator stakes PruningStrategy string // the pruning strategy each validator will have EnableTMLogging bool // enable Tendermint logging to STDOUT CleanupDir bool // remove base temporary directory during cleanup diff --git a/types/address.go b/types/address.go index 3da2bffdfd38..5e28d1e9f295 100644 --- a/types/address.go +++ b/types/address.go @@ -285,7 +285,7 @@ func (aa AccAddress) String() string { } // Format implements the fmt.Formatter interface. -// nolint: errcheck + func (aa AccAddress) Format(s fmt.State, verb rune) { switch verb { case 's': @@ -435,7 +435,7 @@ func (va ValAddress) String() string { } // Format implements the fmt.Formatter interface. -// nolint: errcheck + func (va ValAddress) Format(s fmt.State, verb rune) { switch verb { case 's': @@ -614,7 +614,7 @@ func MustBech32ifyAddressBytes(prefix string, bs []byte) string { } // Format implements the fmt.Formatter interface. -// nolint: errcheck + func (ca ConsAddress) Format(s fmt.State, verb rune) { switch verb { case 's': diff --git a/types/coin.go b/types/coin.go index c5bf96aeac04..142476f4b390 100644 --- a/types/coin.go +++ b/types/coin.go @@ -411,7 +411,7 @@ func (coins Coins) SafeSub(coinsB ...Coin) (Coins, bool) { } // MulInt performs the scalar multiplication of coins with a `multiplier` -// All coins are multipled by x +// All coins are multiplied by x // e.g. // {2A, 3B} * 2 = {4A, 6B} // {2A} * 0 panics diff --git a/types/kv/list.go b/types/kv/list.go index 2b0793d343cd..f038ccfa0ec0 100644 --- a/types/kv/list.go +++ b/types/kv/list.go @@ -113,7 +113,6 @@ func (l *List) remove(e *Element) *Element { } // move moves e to next to at and returns e. -// nolint: unparam func (l *List) move(e, at *Element) *Element { if e == at { return e diff --git a/types/simulation/rand_util.go b/types/simulation/rand_util.go index ce64bd7e8645..cc62fd7e89fd 100644 --- a/types/simulation/rand_util.go +++ b/types/simulation/rand_util.go @@ -7,6 +7,7 @@ import ( "time" "unsafe" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -39,10 +40,10 @@ func RandStringOfLength(r *rand.Rand, n int) string { return *(*string)(unsafe.Pointer(&b)) } -// RandPositiveInt get a rand positive sdk.Int -func RandPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) { +// RandPositiveInt get a rand positive math.Int +func RandPositiveInt(r *rand.Rand, max math.Int) (math.Int, error) { if !max.GTE(sdk.OneInt()) { - return sdk.Int{}, errors.New("max too small") + return math.Int{}, errors.New("max too small") } max = max.Sub(sdk.OneInt()) @@ -52,7 +53,7 @@ func RandPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) { // RandomAmount generates a random amount // Note: The range of RandomAmount includes max, and is, in fact, biased to return max as well as 0. -func RandomAmount(r *rand.Rand, max sdk.Int) sdk.Int { +func RandomAmount(r *rand.Rand, max math.Int) math.Int { randInt := big.NewInt(0) switch r.Intn(10) { diff --git a/x/auth/client/testutil/suite.go b/x/auth/client/testutil/suite.go index 86da20fb8be5..90a02685d8a2 100644 --- a/x/auth/client/testutil/suite.go +++ b/x/auth/client/testutil/suite.go @@ -14,6 +14,7 @@ import ( "github.com/stretchr/testify/suite" tmcli "github.com/tendermint/tendermint/libs/cli" + "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" @@ -1827,7 +1828,7 @@ func (s *IntegrationTestSuite) createBankMsg(val *network.Validator, toAddr sdk. return bankcli.MsgSendExec(val.ClientCtx, val.Address, toAddr, amount, flags...) } -func (s *IntegrationTestSuite) getBalances(clientCtx client.Context, addr sdk.AccAddress, denom string) sdk.Int { +func (s *IntegrationTestSuite) getBalances(clientCtx client.Context, addr sdk.AccAddress, denom string) math.Int { resp, err := bankcli.QueryBalancesExec(clientCtx, addr) s.Require().NoError(err) diff --git a/x/auth/tx/builder.go b/x/auth/tx/builder.go index 052da8785ee8..ab875867107c 100644 --- a/x/auth/tx/builder.go +++ b/x/auth/tx/builder.go @@ -34,12 +34,12 @@ type wrapper struct { } var ( - _ authsigning.Tx = &wrapper{} - _ client.TxBuilder = &wrapper{} - _ tx.TipTx = &wrapper{} + _ authsigning.Tx = &wrapper{} + _ client.TxBuilder = &wrapper{} + _ tx.TipTx = &wrapper{} _ ante.HasExtensionOptionsTx = &wrapper{} - _ ExtensionOptionsTxBuilder = &wrapper{} - _ tx.TipTx = &wrapper{} + _ ExtensionOptionsTxBuilder = &wrapper{} + _ tx.TipTx = &wrapper{} ) // ExtensionOptionsTxBuilder defines a TxBuilder that can also set extensions. diff --git a/x/authz/module/abci.go b/x/authz/module/abci.go index c9e6fef5e7a6..c1015abae841 100644 --- a/x/authz/module/abci.go +++ b/x/authz/module/abci.go @@ -5,7 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/authz/keeper" ) -// BeginBlocker is called at the begining of every block +// BeginBlocker is called at the beginning of every block func BeginBlocker(ctx sdk.Context, keeper keeper.Keeper) { // delete all the mature grants if err := keeper.DequeueAndDeleteExpiredGrants(ctx); err != nil { diff --git a/x/bank/client/testutil/suite.go b/x/bank/client/testutil/suite.go index 4afad13f5b3c..73201fd5dacb 100644 --- a/x/bank/client/testutil/suite.go +++ b/x/bank/client/testutil/suite.go @@ -5,6 +5,7 @@ import ( "io/ioutil" "os" + "cosmossdk.io/math" "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" tmcli "github.com/tendermint/tendermint/libs/cli" @@ -658,7 +659,7 @@ func (s *IntegrationTestSuite) TestNewMultiSendTxCmd() { } } -func NewCoin(denom string, amount sdk.Int) *sdk.Coin { +func NewCoin(denom string, amount math.Int) *sdk.Coin { coin := sdk.NewCoin(denom, amount) return &coin } diff --git a/x/bank/keeper/grpc_query.go b/x/bank/keeper/grpc_query.go index 2afc4c585f70..a4df106ab7cd 100644 --- a/x/bank/keeper/grpc_query.go +++ b/x/bank/keeper/grpc_query.go @@ -3,6 +3,8 @@ package keeper import ( "context" + "cosmossdk.io/math" + "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -60,7 +62,7 @@ func (k BaseKeeper) AllBalances(ctx context.Context, req *types.QueryAllBalances accountStore := k.getAccountStore(sdkCtx, addr) pageRes, err := query.Paginate(accountStore, req.Pagination, func(key, value []byte) error { - var amount sdk.Int + var amount math.Int if err := amount.Unmarshal(value); err != nil { return err } diff --git a/x/bank/keeper/keeper.go b/x/bank/keeper/keeper.go index e25d8b809097..c7f308d8c54d 100644 --- a/x/bank/keeper/keeper.go +++ b/x/bank/keeper/keeper.go @@ -3,6 +3,7 @@ package keeper import ( "fmt" + "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/internal/conv" "github.com/cosmos/cosmos-sdk/store/prefix" @@ -70,7 +71,7 @@ func (k BaseKeeper) GetPaginatedTotalSupply(ctx sdk.Context, pagination *query.P supply := sdk.NewCoins() pageRes, err := query.Paginate(supplyStore, pagination, func(key, value []byte) error { - var amount sdk.Int + var amount math.Int err := amount.Unmarshal(value) if err != nil { return fmt.Errorf("unable to convert amount string to Int %v", err) @@ -228,7 +229,7 @@ func (k BaseKeeper) GetSupply(ctx sdk.Context, denom string) sdk.Coin { } } - var amount sdk.Int + var amount math.Int err := amount.Unmarshal(bz) if err != nil { panic(fmt.Errorf("unable to unmarshal supply value %v", err)) @@ -532,7 +533,7 @@ func (k BaseViewKeeper) IterateTotalSupply(ctx sdk.Context, cb func(sdk.Coin) bo defer iterator.Close() for ; iterator.Valid(); iterator.Next() { - var amount sdk.Int + var amount math.Int err := amount.Unmarshal(iterator.Value()) if err != nil { panic(fmt.Errorf("unable to unmarshal supply value %v", err)) diff --git a/x/bank/keeper/view.go b/x/bank/keeper/view.go index cf66c1962002..5fc3446c2da5 100644 --- a/x/bank/keeper/view.go +++ b/x/bank/keeper/view.go @@ -3,6 +3,7 @@ package keeper import ( "fmt" + "cosmossdk.io/math" "github.com/tendermint/tendermint/libs/log" "github.com/cosmos/cosmos-sdk/codec" @@ -121,7 +122,7 @@ func (k BaseViewKeeper) IterateAccountBalances(ctx sdk.Context, addr sdk.AccAddr defer iterator.Close() for ; iterator.Valid(); iterator.Next() { - var amount sdk.Int + var amount math.Int if err := amount.Unmarshal(iterator.Value()); err != nil { panic(err) } @@ -151,7 +152,7 @@ func (k BaseViewKeeper) IterateAllBalances(ctx sdk.Context, cb func(sdk.AccAddre panic(err) } - var amount sdk.Int + var amount math.Int if err := amount.Unmarshal(iterator.Value()); err != nil { panic(err) } diff --git a/x/gov/keeper/msg_server.go b/x/gov/keeper/msg_server.go index 8800d2d79eca..6c5d9be5a673 100644 --- a/x/gov/keeper/msg_server.go +++ b/x/gov/keeper/msg_server.go @@ -12,7 +12,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1" + v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) diff --git a/x/gov/keeper/querier.go b/x/gov/keeper/querier.go index 14e8bc83b2b4..d528f33cf7ec 100644 --- a/x/gov/keeper/querier.go +++ b/x/gov/keeper/querier.go @@ -75,7 +75,6 @@ func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, keeper K } } -// nolint: unparam func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryProposalParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -96,7 +95,6 @@ func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper return bz, nil } -// nolint: unparam func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryDepositParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -113,7 +111,6 @@ func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper return bz, nil } -// nolint: unparam func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryVoteParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -130,7 +127,6 @@ func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Kee return bz, nil } -// nolint: unparam func queryDeposits(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryProposalParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -151,7 +147,6 @@ func queryDeposits(ctx sdk.Context, path []string, req abci.RequestQuery, keeper return bz, nil } -// nolint: unparam func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryProposalParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -188,7 +183,6 @@ func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Ke return bz, nil } -// nolint: unparam func queryVotes(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryProposalVotesParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) diff --git a/x/gov/migrations/v046/convert.go b/x/gov/migrations/v046/convert.go index a3f383006b5c..54ff7d4911ad 100644 --- a/x/gov/migrations/v046/convert.go +++ b/x/gov/migrations/v046/convert.go @@ -6,7 +6,7 @@ import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1" + v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) diff --git a/x/gov/types/expected_keepers.go b/x/gov/types/expected_keepers.go index a6e521647f31..556387c62ac4 100644 --- a/x/gov/types/expected_keepers.go +++ b/x/gov/types/expected_keepers.go @@ -1,6 +1,7 @@ package types import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -19,7 +20,7 @@ type StakingKeeper interface { sdk.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool), ) - TotalBondedTokens(sdk.Context) sdk.Int // total bonded tokens within the validator set + TotalBondedTokens(sdk.Context) math.Int // total bonded tokens within the validator set IterateDelegations( ctx sdk.Context, delegator sdk.AccAddress, fn func(index int64, delegation stakingtypes.DelegationI) (stop bool), diff --git a/x/gov/types/v1/proposal.go b/x/gov/types/v1/proposal.go index 63982fef0432..cb04be0d45a5 100644 --- a/x/gov/types/v1/proposal.go +++ b/x/gov/types/v1/proposal.go @@ -106,7 +106,7 @@ func (status *ProposalStatus) Unmarshal(data []byte) error { } // Format implements the fmt.Formatter interface. -// nolint: errcheck + func (status ProposalStatus) Format(s fmt.State, verb rune) { switch verb { case 's': diff --git a/x/gov/types/v1/tally.go b/x/gov/types/v1/tally.go index 6613f640f6e5..7a09625737ce 100644 --- a/x/gov/types/v1/tally.go +++ b/x/gov/types/v1/tally.go @@ -1,20 +1,21 @@ package v1 import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" ) // ValidatorGovInfo used for tallying type ValidatorGovInfo struct { Address sdk.ValAddress // address of the validator operator - BondedTokens sdk.Int // Power of a Validator + BondedTokens math.Int // Power of a Validator DelegatorShares sdk.Dec // Total outstanding delegator shares DelegatorDeductions sdk.Dec // Delegator deductions from validator's delegators voting independently Vote WeightedVoteOptions // Vote of the validator } // NewValidatorGovInfo creates a ValidatorGovInfo instance -func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens sdk.Int, delegatorShares, +func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens math.Int, delegatorShares, delegatorDeductions sdk.Dec, options WeightedVoteOptions, ) ValidatorGovInfo { return ValidatorGovInfo{ @@ -27,7 +28,7 @@ func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens sdk.Int, delegator } // NewTallyResult creates a new TallyResult instance -func NewTallyResult(yes, abstain, no, noWithVeto sdk.Int) TallyResult { +func NewTallyResult(yes, abstain, no, noWithVeto math.Int) TallyResult { return TallyResult{ YesCount: yes.String(), AbstainCount: abstain.String(), diff --git a/x/gov/types/v1beta1/proposal.go b/x/gov/types/v1beta1/proposal.go index 6946a40216c4..09b6db0041e5 100644 --- a/x/gov/types/v1beta1/proposal.go +++ b/x/gov/types/v1beta1/proposal.go @@ -149,7 +149,7 @@ func (status *ProposalStatus) Unmarshal(data []byte) error { } // Format implements the fmt.Formatter interface. -// nolint: errcheck + func (status ProposalStatus) Format(s fmt.State, verb rune) { switch verb { case 's': diff --git a/x/gov/types/v1beta1/tally.go b/x/gov/types/v1beta1/tally.go index 616ca6b7bb7c..cf44f59b6c69 100644 --- a/x/gov/types/v1beta1/tally.go +++ b/x/gov/types/v1beta1/tally.go @@ -1,6 +1,7 @@ package v1beta1 import ( + "cosmossdk.io/math" "sigs.k8s.io/yaml" sdk "github.com/cosmos/cosmos-sdk/types" @@ -9,14 +10,14 @@ import ( // ValidatorGovInfo used for tallying type ValidatorGovInfo struct { Address sdk.ValAddress // address of the validator operator - BondedTokens sdk.Int // Power of a Validator + BondedTokens math.Int // Power of a Validator DelegatorShares sdk.Dec // Total outstanding delegator shares DelegatorDeductions sdk.Dec // Delegator deductions from validator's delegators voting independently Vote WeightedVoteOptions // Vote of the validator } // NewValidatorGovInfo creates a ValidatorGovInfo instance -func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens sdk.Int, delegatorShares, +func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens math.Int, delegatorShares, delegatorDeductions sdk.Dec, options WeightedVoteOptions, ) ValidatorGovInfo { return ValidatorGovInfo{ @@ -29,7 +30,7 @@ func NewValidatorGovInfo(address sdk.ValAddress, bondedTokens sdk.Int, delegator } // NewTallyResult creates a new TallyResult instance -func NewTallyResult(yes, abstain, no, noWithVeto sdk.Int) TallyResult { +func NewTallyResult(yes, abstain, no, noWithVeto math.Int) TallyResult { return TallyResult{ Yes: yes, Abstain: abstain, diff --git a/x/group/client/testutil/tx.go b/x/group/client/testutil/tx.go index 1458dc4fd338..e761c4ab9500 100644 --- a/x/group/client/testutil/tx.go +++ b/x/group/client/testutil/tx.go @@ -213,7 +213,6 @@ func (s *IntegrationTestSuite) TestTxCreateGroup() { val := s.network.Validators[0] clientCtx := val.ClientCtx - validMembers := fmt.Sprintf(`{"members": [{ "address": "%s", "weight": "1", @@ -366,7 +365,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupAdmin() { clientCtx := val.ClientCtx require := s.Require() - groupIDs := make([]string, 2) for i := 0; i < 2; i++ { validMembers := fmt.Sprintf(`{"members": [{ @@ -487,7 +485,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupMetadata() { val := s.network.Validators[0] clientCtx := val.ClientCtx - testCases := []struct { name string args []string @@ -568,7 +565,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupMembers() { val := s.network.Validators[0] clientCtx := val.ClientCtx - weights := []string{"1", "1", "1"} accounts := s.createAccounts(3) @@ -691,9 +687,6 @@ func (s *IntegrationTestSuite) TestTxCreateGroupWithPolicy() { val := s.network.Validators[0] clientCtx := val.ClientCtx - - - validMembers := fmt.Sprintf(`{"members": [{ "address": "%s", "weight": "1", @@ -899,7 +892,6 @@ func (s *IntegrationTestSuite) TestTxCreateGroupPolicy() { wrongAdmin := s.network.Validators[1].Address clientCtx := val.ClientCtx - groupID := s.group.Id testCases := []struct { @@ -1067,7 +1059,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupPolicyAdmin() { clientCtx := val.ClientCtx groupPolicy := s.groupPolicies[3] - commonFlags := s.commonFlags commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) @@ -1168,7 +1159,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupPolicyDecisionPolicy() { clientCtx := val.ClientCtx groupPolicy := s.groupPolicies[2] - commonFlags := s.commonFlags commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) @@ -1314,7 +1304,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupPolicyMetadata() { clientCtx := val.ClientCtx groupPolicy := s.groupPolicies[2] - commonFlags := s.commonFlags commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) @@ -1428,7 +1417,6 @@ func (s *IntegrationTestSuite) TestTxSubmitProposal() { val := s.network.Validators[0] clientCtx := val.ClientCtx - testCases := []struct { name string args []string @@ -1617,7 +1605,6 @@ func (s *IntegrationTestSuite) TestTxVote() { val := s.network.Validators[0] clientCtx := val.ClientCtx - ids := make([]string, 4) weights := []string{"1", "1", "1"} accounts := s.createAccounts(3) @@ -1811,7 +1798,6 @@ func (s *IntegrationTestSuite) TestTxWithdrawProposal() { val := s.network.Validators[0] clientCtx := val.ClientCtx - ids := make([]string, 2) for i := 0; i < 2; i++ { @@ -1954,7 +1940,6 @@ func (s *IntegrationTestSuite) TestTxExec() { clientCtx := val.ClientCtx require := s.Require() - var proposalIDs []string // create proposals and vote for i := 0; i < 2; i++ { diff --git a/x/group/keeper/msg_server.go b/x/group/keeper/msg_server.go index 6a25c5dce3f1..b732e958cab6 100644 --- a/x/group/keeper/msg_server.go +++ b/x/group/keeper/msg_server.go @@ -161,7 +161,7 @@ func (k Keeper) UpdateGroupMembers(goCtx context.Context, req *group.MsgUpdateGr if err != nil { return err } - // Substract previous weight from the group total weight. + // Subtract previous weight from the group total weight. totalWeight, err = math.SubNonNegative(totalWeight, previousMemberWeight) if err != nil { return err diff --git a/x/mint/keeper/keeper.go b/x/mint/keeper/keeper.go index fd064ff7b4d6..51ade6abef63 100644 --- a/x/mint/keeper/keeper.go +++ b/x/mint/keeper/keeper.go @@ -1,6 +1,7 @@ package keeper import ( + "cosmossdk.io/math" "github.com/tendermint/tendermint/libs/log" "github.com/cosmos/cosmos-sdk/codec" @@ -83,7 +84,7 @@ func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { // StakingTokenSupply implements an alias call to the underlying staking keeper's // StakingTokenSupply to be used in BeginBlocker. -func (k Keeper) StakingTokenSupply(ctx sdk.Context) sdk.Int { +func (k Keeper) StakingTokenSupply(ctx sdk.Context) math.Int { return k.stakingKeeper.StakingTokenSupply(ctx) } diff --git a/x/mint/types/expected_keepers.go b/x/mint/types/expected_keepers.go index 85b6d776c5c5..68fb5765bf6d 100644 --- a/x/mint/types/expected_keepers.go +++ b/x/mint/types/expected_keepers.go @@ -1,13 +1,14 @@ package types // noalias import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/types" ) // StakingKeeper defines the expected staking keeper type StakingKeeper interface { - StakingTokenSupply(ctx sdk.Context) sdk.Int + StakingTokenSupply(ctx sdk.Context) math.Int BondedRatio(ctx sdk.Context) sdk.Dec } diff --git a/x/mint/types/minter.go b/x/mint/types/minter.go index 3285d6ddf0e8..8f2353217536 100644 --- a/x/mint/types/minter.go +++ b/x/mint/types/minter.go @@ -3,6 +3,8 @@ package types import ( "fmt" + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -68,7 +70,7 @@ func (m Minter) NextInflationRate(params Params, bondedRatio sdk.Dec) sdk.Dec { // NextAnnualProvisions returns the annual provisions based on current total // supply and inflation rate. -func (m Minter) NextAnnualProvisions(_ Params, totalSupply sdk.Int) sdk.Dec { +func (m Minter) NextAnnualProvisions(_ Params, totalSupply math.Int) sdk.Dec { return m.Inflation.MulInt(totalSupply) } diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index cd792659bd15..73012502566b 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -319,7 +319,7 @@ Comment: %s`, } } -// nolint: errcheck + func runQueuedOperations(queueOps map[int][]simulation.Operation, height int, tb testing.TB, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simulation.Account, logWriter LogWriter, diff --git a/x/slashing/types/expected_keepers.go b/x/slashing/types/expected_keepers.go index 5f9a4fee8c72..9e15820dc418 100644 --- a/x/slashing/types/expected_keepers.go +++ b/x/slashing/types/expected_keepers.go @@ -3,6 +3,7 @@ package types import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" auth "github.com/cosmos/cosmos-sdk/x/auth/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" @@ -42,7 +43,7 @@ type StakingKeeper interface { ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) stakingtypes.ValidatorI // get a particular validator by consensus address // slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction - Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) sdk.Int + Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) math.Int Jail(sdk.Context, sdk.ConsAddress) // jail a validator Unjail(sdk.Context, sdk.ConsAddress) // unjail a validator diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index 6426df2f31fe..b70b0b120700 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -6,6 +6,8 @@ import ( "strconv" "strings" + "cosmossdk.io/math" + "github.com/spf13/cobra" flag "github.com/spf13/pflag" @@ -121,7 +123,7 @@ func NewEditValidatorCmd() *cobra.Command { newRate = &rate } - var newMinSelfDelegation *sdk.Int + var newMinSelfDelegation *math.Int minSelfDelegationString, _ := cmd.Flags().GetString(FlagMinSelfDelegation) if minSelfDelegationString != "" { diff --git a/x/staking/keeper/delegation.go b/x/staking/keeper/delegation.go index 4c99e4adaedb..51eb0e17d062 100644 --- a/x/staking/keeper/delegation.go +++ b/x/staking/keeper/delegation.go @@ -5,6 +5,7 @@ import ( "fmt" "time" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -186,7 +187,7 @@ func (k Keeper) IterateUnbondingDelegations(ctx sdk.Context, fn func(index int64 } // GetDelegatorUnbonding returns the total amount a delegator has unbonding. -func (k Keeper) GetDelegatorUnbonding(ctx sdk.Context, delegator sdk.AccAddress) sdk.Int { +func (k Keeper) GetDelegatorUnbonding(ctx sdk.Context, delegator sdk.AccAddress) math.Int { unbonding := sdk.ZeroInt() k.IterateDelegatorUnbondingDelegations(ctx, delegator, func(ubd types.UnbondingDelegation) bool { for _, entry := range ubd.Entries { @@ -213,7 +214,7 @@ func (k Keeper) IterateDelegatorUnbondingDelegations(ctx sdk.Context, delegator } // GetDelegatorBonded returs the total amount a delegator has bonded. -func (k Keeper) GetDelegatorBonded(ctx sdk.Context, delegator sdk.AccAddress) sdk.Int { +func (k Keeper) GetDelegatorBonded(ctx sdk.Context, delegator sdk.AccAddress) math.Int { bonded := sdk.ZeroDec() k.IterateDelegatorDelegations(ctx, delegator, func(delegation types.Delegation) bool { @@ -311,7 +312,7 @@ func (k Keeper) RemoveUnbondingDelegation(ctx sdk.Context, ubd types.UnbondingDe // the given addresses. It creates the unbonding delegation if it does not exist. func (k Keeper) SetUnbondingDelegationEntry( ctx sdk.Context, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, - creationHeight int64, minTime time.Time, balance sdk.Int, + creationHeight int64, minTime time.Time, balance math.Int, ) types.UnbondingDelegation { ubd, found := k.GetUnbondingDelegation(ctx, delegatorAddr, validatorAddr) if found { @@ -496,7 +497,7 @@ func (k Keeper) SetRedelegation(ctx sdk.Context, red types.Redelegation) { func (k Keeper) SetRedelegationEntry(ctx sdk.Context, delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress, creationHeight int64, - minTime time.Time, balance sdk.Int, + minTime time.Time, balance math.Int, sharesSrc, sharesDst sdk.Dec, ) types.Redelegation { red, found := k.GetRedelegation(ctx, delegatorAddr, validatorSrcAddr, validatorDstAddr) @@ -626,7 +627,7 @@ func (k Keeper) DequeueAllMatureRedelegationQueue(ctx sdk.Context, currTime time // Delegate performs a delegation, set/update everything necessary within the store. // tokenSrc indicates the bond status of the incoming funds. func (k Keeper) Delegate( - ctx sdk.Context, delAddr sdk.AccAddress, bondAmt sdk.Int, tokenSrc types.BondStatus, + ctx sdk.Context, delAddr sdk.AccAddress, bondAmt math.Int, tokenSrc types.BondStatus, validator types.Validator, subtractAccount bool, ) (newShares sdk.Dec, err error) { // In some situations, the exchange rate becomes invalid, e.g. if @@ -716,7 +717,7 @@ func (k Keeper) Delegate( // Unbond unbonds a particular delegation and perform associated store operations. func (k Keeper) Unbond( ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, shares sdk.Dec, -) (amount sdk.Int, err error) { +) (amount math.Int, err error) { // check if a delegation object exists in the store delegation, found := k.GetDelegation(ctx, delAddr, valAddr) if !found { @@ -991,7 +992,7 @@ func (k Keeper) CompleteRedelegation( // valied based on upon the converted shares. If the amount is valid, the total // amount of respective shares is returned, otherwise an error is returned. func (k Keeper) ValidateUnbondAmount( - ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, amt sdk.Int, + ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, amt math.Int, ) (shares sdk.Dec, err error) { validator, found := k.GetValidator(ctx, valAddr) if !found { diff --git a/x/staking/keeper/params.go b/x/staking/keeper/params.go index 498576fea53f..7e816f353143 100644 --- a/x/staking/keeper/params.go +++ b/x/staking/keeper/params.go @@ -3,6 +3,8 @@ package keeper import ( "time" + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -43,7 +45,7 @@ func (k Keeper) BondDenom(ctx sdk.Context) (res string) { // Currently, this returns a global variable that the app developer can tweak. // TODO: we might turn this into an on-chain param: // https://github.com/cosmos/cosmos-sdk/issues/8365 -func (k Keeper) PowerReduction(ctx sdk.Context) sdk.Int { +func (k Keeper) PowerReduction(ctx sdk.Context) math.Int { return sdk.DefaultPowerReduction } diff --git a/x/staking/keeper/pool.go b/x/staking/keeper/pool.go index b281b45784dc..06d87422da44 100644 --- a/x/staking/keeper/pool.go +++ b/x/staking/keeper/pool.go @@ -1,6 +1,7 @@ package keeper import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -17,7 +18,7 @@ func (k Keeper) GetNotBondedPool(ctx sdk.Context) (notBondedPool authtypes.Modul } // bondedTokensToNotBonded transfers coins from the bonded to the not bonded pool within staking -func (k Keeper) bondedTokensToNotBonded(ctx sdk.Context, tokens sdk.Int) { +func (k Keeper) bondedTokensToNotBonded(ctx sdk.Context, tokens math.Int) { coins := sdk.NewCoins(sdk.NewCoin(k.BondDenom(ctx), tokens)) if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.BondedPoolName, types.NotBondedPoolName, coins); err != nil { panic(err) @@ -25,7 +26,7 @@ func (k Keeper) bondedTokensToNotBonded(ctx sdk.Context, tokens sdk.Int) { } // notBondedTokensToBonded transfers coins from the not bonded to the bonded pool within staking -func (k Keeper) notBondedTokensToBonded(ctx sdk.Context, tokens sdk.Int) { +func (k Keeper) notBondedTokensToBonded(ctx sdk.Context, tokens math.Int) { coins := sdk.NewCoins(sdk.NewCoin(k.BondDenom(ctx), tokens)) if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.NotBondedPoolName, types.BondedPoolName, coins); err != nil { panic(err) @@ -33,7 +34,7 @@ func (k Keeper) notBondedTokensToBonded(ctx sdk.Context, tokens sdk.Int) { } // burnBondedTokens removes coins from the bonded pool module account -func (k Keeper) burnBondedTokens(ctx sdk.Context, amt sdk.Int) error { +func (k Keeper) burnBondedTokens(ctx sdk.Context, amt math.Int) error { if !amt.IsPositive() { // skip as no coins need to be burned return nil @@ -45,7 +46,7 @@ func (k Keeper) burnBondedTokens(ctx sdk.Context, amt sdk.Int) error { } // burnNotBondedTokens removes coins from the not bonded pool module account -func (k Keeper) burnNotBondedTokens(ctx sdk.Context, amt sdk.Int) error { +func (k Keeper) burnNotBondedTokens(ctx sdk.Context, amt math.Int) error { if !amt.IsPositive() { // skip as no coins need to be burned return nil @@ -57,13 +58,13 @@ func (k Keeper) burnNotBondedTokens(ctx sdk.Context, amt sdk.Int) error { } // TotalBondedTokens total staking tokens supply which is bonded -func (k Keeper) TotalBondedTokens(ctx sdk.Context) sdk.Int { +func (k Keeper) TotalBondedTokens(ctx sdk.Context) math.Int { bondedPool := k.GetBondedPool(ctx) return k.bankKeeper.GetBalance(ctx, bondedPool.GetAddress(), k.BondDenom(ctx)).Amount } // StakingTokenSupply staking tokens from the total supply -func (k Keeper) StakingTokenSupply(ctx sdk.Context) sdk.Int { +func (k Keeper) StakingTokenSupply(ctx sdk.Context) math.Int { return k.bankKeeper.GetSupply(ctx, k.BondDenom(ctx)).Amount } diff --git a/x/staking/keeper/power_reduction.go b/x/staking/keeper/power_reduction.go index d979228b36fa..abed52d12f4c 100644 --- a/x/staking/keeper/power_reduction.go +++ b/x/staking/keeper/power_reduction.go @@ -1,15 +1,16 @@ package keeper import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" ) // TokensToConsensusPower - convert input tokens to potential consensus-engine power -func (k Keeper) TokensToConsensusPower(ctx sdk.Context, tokens sdk.Int) int64 { +func (k Keeper) TokensToConsensusPower(ctx sdk.Context, tokens math.Int) int64 { return sdk.TokensToConsensusPower(tokens, k.PowerReduction(ctx)) } // TokensFromConsensusPower - convert input power to tokens -func (k Keeper) TokensFromConsensusPower(ctx sdk.Context, power int64) sdk.Int { +func (k Keeper) TokensFromConsensusPower(ctx sdk.Context, power int64) math.Int { return sdk.TokensFromConsensusPower(power, k.PowerReduction(ctx)) } diff --git a/x/staking/keeper/slash.go b/x/staking/keeper/slash.go index d09fb56c270f..ff2ace8f8627 100644 --- a/x/staking/keeper/slash.go +++ b/x/staking/keeper/slash.go @@ -3,6 +3,8 @@ package keeper import ( "fmt" + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" types "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -21,7 +23,7 @@ import ( // CONTRACT: // 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) sdk.Int { +func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeight int64, power int64, slashFactor sdk.Dec) math.Int { logger := k.Logger(ctx) if slashFactor.IsNegative() { @@ -166,7 +168,7 @@ func (k Keeper) Unjail(ctx sdk.Context, consAddr sdk.ConsAddress) { // insufficient stake remaining) func (k Keeper) SlashUnbondingDelegation(ctx sdk.Context, unbondingDelegation types.UnbondingDelegation, infractionHeight int64, slashFactor sdk.Dec, -) (totalSlashAmount sdk.Int) { +) (totalSlashAmount math.Int) { now := ctx.BlockHeader().Time totalSlashAmount = sdk.ZeroInt() burnedAmount := sdk.ZeroInt() @@ -220,7 +222,7 @@ func (k Keeper) SlashUnbondingDelegation(ctx sdk.Context, unbondingDelegation ty // NOTE this is only slashing for prior infractions from the source validator func (k Keeper) SlashRedelegation(ctx sdk.Context, srcValidator types.Validator, redelegation types.Redelegation, infractionHeight int64, slashFactor sdk.Dec, -) (totalSlashAmount sdk.Int) { +) (totalSlashAmount math.Int) { now := ctx.BlockHeader().Time totalSlashAmount = sdk.ZeroInt() bondedBurnedAmount, notBondedBurnedAmount := sdk.ZeroInt(), sdk.ZeroInt() diff --git a/x/staking/keeper/validator.go b/x/staking/keeper/validator.go index 9b51577c5a06..556280575e86 100644 --- a/x/staking/keeper/validator.go +++ b/x/staking/keeper/validator.go @@ -6,6 +6,7 @@ import ( gogotypes "github.com/gogo/protobuf/types" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -96,7 +97,7 @@ func (k Keeper) SetNewValidatorByPowerIndex(ctx sdk.Context, validator types.Val // Update the tokens of an existing validator, update the validators power index key func (k Keeper) AddValidatorTokensAndShares(ctx sdk.Context, validator types.Validator, - tokensToAdd sdk.Int, + tokensToAdd math.Int, ) (valOut types.Validator, addedShares sdk.Dec) { k.DeleteValidatorByPowerIndex(ctx, validator) validator, addedShares = validator.AddTokensFromDel(tokensToAdd) @@ -109,7 +110,7 @@ func (k Keeper) AddValidatorTokensAndShares(ctx sdk.Context, validator types.Val // Update the tokens of an existing validator, update the validators power index key func (k Keeper) RemoveValidatorTokensAndShares(ctx sdk.Context, validator types.Validator, sharesToRemove sdk.Dec, -) (valOut types.Validator, removedTokens sdk.Int) { +) (valOut types.Validator, removedTokens math.Int) { k.DeleteValidatorByPowerIndex(ctx, validator) validator, removedTokens = validator.RemoveDelShares(sharesToRemove) k.SetValidator(ctx, validator) @@ -120,7 +121,7 @@ func (k Keeper) RemoveValidatorTokensAndShares(ctx sdk.Context, validator types. // Update the tokens of an existing validator, update the validators power index key func (k Keeper) RemoveValidatorTokens(ctx sdk.Context, - validator types.Validator, tokensToRemove sdk.Int, + validator types.Validator, tokensToRemove math.Int, ) types.Validator { k.DeleteValidatorByPowerIndex(ctx, validator) validator = validator.RemoveTokens(tokensToRemove) diff --git a/x/staking/teststaking/helper.go b/x/staking/teststaking/helper.go index 012f21f00eda..92ebb5454fd1 100644 --- a/x/staking/teststaking/helper.go +++ b/x/staking/teststaking/helper.go @@ -5,6 +5,7 @@ import ( "testing" "time" + "cosmossdk.io/math" "github.com/stretchr/testify/require" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -33,14 +34,14 @@ func NewHelper(t *testing.T, ctx sdk.Context, k keeper.Keeper) *Helper { } // CreateValidator calls staking module `MsgServer/CreateValidator` to create a new validator -func (sh *Helper) CreateValidator(addr sdk.ValAddress, pk cryptotypes.PubKey, stakeAmount sdk.Int, ok bool) { +func (sh *Helper) CreateValidator(addr sdk.ValAddress, pk cryptotypes.PubKey, stakeAmount math.Int, ok bool) { coin := sdk.NewCoin(sh.Denom, stakeAmount) sh.createValidator(addr, pk, coin, ok) } // CreateValidatorWithValPower calls staking module `MsgServer/CreateValidator` to create a new validator with zero // commission -func (sh *Helper) CreateValidatorWithValPower(addr sdk.ValAddress, pk cryptotypes.PubKey, valPower int64, ok bool) sdk.Int { +func (sh *Helper) CreateValidatorWithValPower(addr sdk.ValAddress, pk cryptotypes.PubKey, valPower int64, ok bool) math.Int { amount := sh.k.TokensFromConsensusPower(sh.Ctx, valPower) coin := sdk.NewCoin(sh.Denom, amount) sh.createValidator(addr, pk, coin, ok) @@ -48,7 +49,7 @@ func (sh *Helper) CreateValidatorWithValPower(addr sdk.ValAddress, pk cryptotype } // CreateValidatorMsg returns a message used to create validator in this service. -func (sh *Helper) CreateValidatorMsg(addr sdk.ValAddress, pk cryptotypes.PubKey, stakeAmount sdk.Int) *stakingtypes.MsgCreateValidator { +func (sh *Helper) CreateValidatorMsg(addr sdk.ValAddress, pk cryptotypes.PubKey, stakeAmount math.Int) *stakingtypes.MsgCreateValidator { coin := sdk.NewCoin(sh.Denom, stakeAmount) msg, err := stakingtypes.NewMsgCreateValidator(addr, pk, coin, stakingtypes.Description{}, sh.Commission, sdk.OneInt()) require.NoError(sh.t, err) @@ -74,7 +75,7 @@ func (sh *Helper) createValidator(addr sdk.ValAddress, pk cryptotypes.PubKey, co } // Delegate calls staking module staking module `MsgServer/Delegate` to delegate stake for a validator -func (sh *Helper) Delegate(delegator sdk.AccAddress, val sdk.ValAddress, amount sdk.Int) { +func (sh *Helper) Delegate(delegator sdk.AccAddress, val sdk.ValAddress, amount math.Int) { coin := sdk.NewCoin(sh.Denom, amount) msg := stakingtypes.NewMsgDelegate(delegator, val, coin) res, err := sh.msgSrvr.Delegate(sdk.WrapSDKContext(sh.Ctx), msg) @@ -92,7 +93,7 @@ func (sh *Helper) DelegateWithPower(delegator sdk.AccAddress, val sdk.ValAddress } // Undelegate calls staking module `MsgServer/Undelegate` to unbound some stake from a validator. -func (sh *Helper) Undelegate(delegator sdk.AccAddress, val sdk.ValAddress, amount sdk.Int, ok bool) { +func (sh *Helper) Undelegate(delegator sdk.AccAddress, val sdk.ValAddress, amount math.Int, ok bool) { unbondAmt := sdk.NewCoin(sh.Denom, amount) msg := stakingtypes.NewMsgUndelegate(delegator, val, unbondAmt) res, err := sh.msgSrvr.Undelegate(sdk.WrapSDKContext(sh.Ctx), msg) diff --git a/x/staking/teststaking/tm.go b/x/staking/teststaking/tm.go index e927c0e0387a..2d1ee1beee89 100644 --- a/x/staking/teststaking/tm.go +++ b/x/staking/teststaking/tm.go @@ -1,11 +1,11 @@ package teststaking import ( + "cosmossdk.io/math" tmcrypto "github.com/tendermint/tendermint/crypto" tmtypes "github.com/tendermint/tendermint/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -20,7 +20,7 @@ func GetTmConsPubKey(v types.Validator) (tmcrypto.PubKey, error) { } // ToTmValidator casts an SDK validator to a tendermint type Validator. -func ToTmValidator(v types.Validator, r sdk.Int) (*tmtypes.Validator, error) { +func ToTmValidator(v types.Validator, r math.Int) (*tmtypes.Validator, error) { tmPk, err := GetTmConsPubKey(v) if err != nil { return nil, err @@ -30,7 +30,7 @@ func ToTmValidator(v types.Validator, r sdk.Int) (*tmtypes.Validator, error) { } // ToTmValidators casts all validators to the corresponding tendermint type. -func ToTmValidators(v types.Validators, r sdk.Int) ([]*tmtypes.Validator, error) { +func ToTmValidators(v types.Validators, r math.Int) ([]*tmtypes.Validator, error) { validators := make([]*tmtypes.Validator, len(v)) var err error for i, val := range v { diff --git a/x/staking/types/delegation.go b/x/staking/types/delegation.go index 07438c4f40af..d644ee8047ad 100644 --- a/x/staking/types/delegation.go +++ b/x/staking/types/delegation.go @@ -6,10 +6,10 @@ import ( "strings" "time" - "sigs.k8s.io/yaml" - + "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "sigs.k8s.io/yaml" ) // Implements Delegation interface @@ -93,7 +93,7 @@ func (d Delegations) String() (out string) { return strings.TrimSpace(out) } -func NewUnbondingDelegationEntry(creationHeight int64, completionTime time.Time, balance sdk.Int) UnbondingDelegationEntry { +func NewUnbondingDelegationEntry(creationHeight int64, completionTime time.Time, balance math.Int) UnbondingDelegationEntry { return UnbondingDelegationEntry{ CreationHeight: creationHeight, CompletionTime: completionTime, @@ -117,7 +117,7 @@ func (e UnbondingDelegationEntry) IsMature(currentTime time.Time) bool { //nolint:interfacer func NewUnbondingDelegation( delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress, - creationHeight int64, minTime time.Time, balance sdk.Int, + creationHeight int64, minTime time.Time, balance math.Int, ) UnbondingDelegation { return UnbondingDelegation{ DelegatorAddress: delegatorAddr.String(), @@ -129,7 +129,7 @@ func NewUnbondingDelegation( } // AddEntry - append entry to the unbonding delegation -func (ubd *UnbondingDelegation) AddEntry(creationHeight int64, minTime time.Time, balance sdk.Int) { +func (ubd *UnbondingDelegation) AddEntry(creationHeight int64, minTime time.Time, balance math.Int) { entry := NewUnbondingDelegationEntry(creationHeight, minTime, balance) ubd.Entries = append(ubd.Entries, entry) } @@ -188,7 +188,7 @@ func (ubds UnbondingDelegations) String() (out string) { return strings.TrimSpace(out) } -func NewRedelegationEntry(creationHeight int64, completionTime time.Time, balance sdk.Int, sharesDst sdk.Dec) RedelegationEntry { +func NewRedelegationEntry(creationHeight int64, completionTime time.Time, balance math.Int, sharesDst sdk.Dec) RedelegationEntry { return RedelegationEntry{ CreationHeight: creationHeight, CompletionTime: completionTime, @@ -211,7 +211,7 @@ func (e RedelegationEntry) IsMature(currentTime time.Time) bool { //nolint:interfacer func NewRedelegation( delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress, - creationHeight int64, minTime time.Time, balance sdk.Int, sharesDst sdk.Dec, + creationHeight int64, minTime time.Time, balance math.Int, sharesDst sdk.Dec, ) Redelegation { return Redelegation{ DelegatorAddress: delegatorAddr.String(), @@ -224,7 +224,7 @@ func NewRedelegation( } // AddEntry - append entry to the unbonding delegation -func (red *Redelegation) AddEntry(creationHeight int64, minTime time.Time, balance sdk.Int, sharesDst sdk.Dec) { +func (red *Redelegation) AddEntry(creationHeight int64, minTime time.Time, balance math.Int, sharesDst sdk.Dec) { entry := NewRedelegationEntry(creationHeight, minTime, balance, sharesDst) red.Entries = append(red.Entries, entry) } @@ -351,7 +351,7 @@ func NewRedelegationResponse( // NewRedelegationEntryResponse creates a new RedelegationEntryResponse instance. func NewRedelegationEntryResponse( - creationHeight int64, completionTime time.Time, sharesDst sdk.Dec, initialBalance, balance sdk.Int, + creationHeight int64, completionTime time.Time, sharesDst sdk.Dec, initialBalance, balance math.Int, ) RedelegationEntryResponse { return RedelegationEntryResponse{ RedelegationEntry: NewRedelegationEntry(creationHeight, completionTime, initialBalance, sharesDst), diff --git a/x/staking/types/expected_keepers.go b/x/staking/types/expected_keepers.go index 785a969f36e4..4eb85458179b 100644 --- a/x/staking/types/expected_keepers.go +++ b/x/staking/types/expected_keepers.go @@ -1,6 +1,7 @@ package types import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -55,11 +56,11 @@ type ValidatorSet interface { Validator(sdk.Context, sdk.ValAddress) ValidatorI // get a particular validator by operator address ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) ValidatorI // get a particular validator by consensus address - TotalBondedTokens(sdk.Context) sdk.Int // total bonded tokens within the validator set - StakingTokenSupply(sdk.Context) sdk.Int // total staking token supply + TotalBondedTokens(sdk.Context) math.Int // total bonded tokens within the validator set + StakingTokenSupply(sdk.Context) math.Int // total staking token supply // slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction - Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) sdk.Int + Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) math.Int Jail(sdk.Context, sdk.ConsAddress) // jail a validator Unjail(sdk.Context, sdk.ConsAddress) // unjail a validator diff --git a/x/staking/types/exported.go b/x/staking/types/exported.go index 9599da100d20..60e16e55d7fc 100644 --- a/x/staking/types/exported.go +++ b/x/staking/types/exported.go @@ -1,6 +1,7 @@ package types import ( + "cosmossdk.io/math" tmprotocrypto "github.com/tendermint/tendermint/proto/tendermint/crypto" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" @@ -16,25 +17,25 @@ type DelegationI interface { // ValidatorI expected validator functions type ValidatorI interface { - IsJailed() bool // whether the validator is jailed - GetMoniker() string // moniker of the validator - GetStatus() BondStatus // status of the validator - IsBonded() bool // check if has a bonded status - IsUnbonded() bool // check if has status unbonded - IsUnbonding() bool // check if has status unbonding - GetOperator() sdk.ValAddress // operator address to receive/return validators coins - ConsPubKey() (cryptotypes.PubKey, error) // validation consensus pubkey (cryptotypes.PubKey) - TmConsPublicKey() (tmprotocrypto.PublicKey, error) // validation consensus pubkey (Tendermint) - GetConsAddr() (sdk.ConsAddress, error) // validation consensus address - GetTokens() sdk.Int // validation tokens - GetBondedTokens() sdk.Int // validator bonded tokens - GetConsensusPower(sdk.Int) int64 // validation power in tendermint - GetCommission() sdk.Dec // validator commission rate - GetMinSelfDelegation() sdk.Int // validator minimum self delegation - GetDelegatorShares() sdk.Dec // total outstanding delegator shares - TokensFromShares(sdk.Dec) sdk.Dec // token worth of provided delegator shares - TokensFromSharesTruncated(sdk.Dec) sdk.Dec // token worth of provided delegator shares, truncated - TokensFromSharesRoundUp(sdk.Dec) sdk.Dec // token worth of provided delegator shares, rounded up - SharesFromTokens(amt sdk.Int) (sdk.Dec, error) // shares worth of delegator's bond - SharesFromTokensTruncated(amt sdk.Int) (sdk.Dec, error) // truncated shares worth of delegator's bond + IsJailed() bool // whether the validator is jailed + GetMoniker() string // moniker of the validator + GetStatus() BondStatus // status of the validator + IsBonded() bool // check if has a bonded status + IsUnbonded() bool // check if has status unbonded + IsUnbonding() bool // check if has status unbonding + GetOperator() sdk.ValAddress // operator address to receive/return validators coins + ConsPubKey() (cryptotypes.PubKey, error) // validation consensus pubkey (cryptotypes.PubKey) + TmConsPublicKey() (tmprotocrypto.PublicKey, error) // validation consensus pubkey (Tendermint) + GetConsAddr() (sdk.ConsAddress, error) // validation consensus address + GetTokens() math.Int // validation tokens + GetBondedTokens() math.Int // validator bonded tokens + GetConsensusPower(math.Int) int64 // validation power in tendermint + GetCommission() sdk.Dec // validator commission rate + GetMinSelfDelegation() math.Int // validator minimum self delegation + GetDelegatorShares() sdk.Dec // total outstanding delegator shares + TokensFromShares(sdk.Dec) sdk.Dec // token worth of provided delegator shares + TokensFromSharesTruncated(sdk.Dec) sdk.Dec // token worth of provided delegator shares, truncated + TokensFromSharesRoundUp(sdk.Dec) sdk.Dec // token worth of provided delegator shares, rounded up + SharesFromTokens(amt math.Int) (sdk.Dec, error) // shares worth of delegator's bond + SharesFromTokensTruncated(amt math.Int) (sdk.Dec, error) // truncated shares worth of delegator's bond } diff --git a/x/staking/types/historical_info.go b/x/staking/types/historical_info.go index 447a559bda7b..fb1030f6c8c3 100644 --- a/x/staking/types/historical_info.go +++ b/x/staking/types/historical_info.go @@ -3,18 +3,19 @@ package types import ( "sort" + "cosmossdk.io/math" + "github.com/gogo/protobuf/proto" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) // NewHistoricalInfo will create a historical information struct from header and valset // it will first sort valset before inclusion into historical info -func NewHistoricalInfo(header tmproto.Header, valSet Validators, powerReduction sdk.Int) HistoricalInfo { +func NewHistoricalInfo(header tmproto.Header, valSet Validators, powerReduction math.Int) HistoricalInfo { // Must sort in the same way that tendermint does sort.SliceStable(valSet, func(i, j int) bool { return ValidatorsByVotingPower(valSet).Less(i, j, powerReduction) diff --git a/x/staking/types/msg.go b/x/staking/types/msg.go index a1ae89d15751..4cacc16ca6c8 100644 --- a/x/staking/types/msg.go +++ b/x/staking/types/msg.go @@ -1,6 +1,7 @@ package types import ( + "cosmossdk.io/math" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -32,7 +33,7 @@ var ( // Delegator address and validator address are the same. func NewMsgCreateValidator( valAddr sdk.ValAddress, pubKey cryptotypes.PubKey, //nolint:interfacer - selfDelegation sdk.Coin, description Description, commission CommissionRates, minSelfDelegation sdk.Int, + selfDelegation sdk.Coin, description Description, commission CommissionRates, minSelfDelegation math.Int, ) (*MsgCreateValidator, error) { var pkAny *codectypes.Any if pubKey != nil { @@ -139,7 +140,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 *sdk.Int) *MsgEditValidator { +func NewMsgEditValidator(valAddr sdk.ValAddress, description Description, newRate *sdk.Dec, newMinSelfDelegation *math.Int) *MsgEditValidator { return &MsgEditValidator{ Description: description, CommissionRate: newRate, diff --git a/x/staking/types/params.go b/x/staking/types/params.go index 191b66e4c809..46405e3ad308 100644 --- a/x/staking/types/params.go +++ b/x/staking/types/params.go @@ -6,6 +6,7 @@ import ( "strings" "time" + "cosmossdk.io/math" "sigs.k8s.io/yaml" "github.com/cosmos/cosmos-sdk/codec" @@ -204,7 +205,7 @@ func validateBondDenom(i interface{}) error { } func ValidatePowerReduction(i interface{}) error { - v, ok := i.(sdk.Int) + v, ok := i.(math.Int) if !ok { return fmt.Errorf("invalid parameter type: %T", i) } diff --git a/x/staking/types/pool.go b/x/staking/types/pool.go index c71d1684f9aa..79f24d33705c 100644 --- a/x/staking/types/pool.go +++ b/x/staking/types/pool.go @@ -1,7 +1,7 @@ package types import ( - sdk "github.com/cosmos/cosmos-sdk/types" + "cosmossdk.io/math" ) // names used as root for pool module accounts: @@ -15,7 +15,7 @@ const ( ) // NewPool creates a new Pool instance used for queries -func NewPool(notBonded, bonded sdk.Int) Pool { +func NewPool(notBonded, bonded math.Int) Pool { return Pool{ NotBondedTokens: notBonded, BondedTokens: bonded, diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index 4296181ec9b5..afcec7e168a1 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -7,6 +7,7 @@ import ( "strings" "time" + "cosmossdk.io/math" abci "github.com/tendermint/tendermint/abci/types" tmprotocrypto "github.com/tendermint/tendermint/proto/tendermint/crypto" "sigs.k8s.io/yaml" @@ -123,7 +124,7 @@ type ValidatorsByVotingPower []Validator func (valz ValidatorsByVotingPower) Len() int { return len(valz) } -func (valz ValidatorsByVotingPower) Less(i, j int, r sdk.Int) bool { +func (valz ValidatorsByVotingPower) Less(i, j int, r math.Int) bool { if valz[i].ConsensusPower(r) == valz[j].ConsensusPower(r) { addrI, errI := valz[i].GetConsAddr() addrJ, errJ := valz[j].GetConsAddr() @@ -264,7 +265,7 @@ func (d Description) EnsureLength() (Description, error) { // ABCIValidatorUpdate returns an abci.ValidatorUpdate from a staking validator type // with the full validator power -func (v Validator) ABCIValidatorUpdate(r sdk.Int) abci.ValidatorUpdate { +func (v Validator) ABCIValidatorUpdate(r math.Int) abci.ValidatorUpdate { tmProtoPk, err := v.TmConsPublicKey() if err != nil { panic(err) @@ -327,7 +328,7 @@ func (v Validator) TokensFromSharesRoundUp(shares sdk.Dec) sdk.Dec { // SharesFromTokens returns the shares of a delegation given a bond amount. It // returns an error if the validator has no tokens. -func (v Validator) SharesFromTokens(amt sdk.Int) (sdk.Dec, error) { +func (v Validator) SharesFromTokens(amt math.Int) (sdk.Dec, error) { if v.Tokens.IsZero() { return sdk.ZeroDec(), ErrInsufficientShares } @@ -337,7 +338,7 @@ func (v Validator) SharesFromTokens(amt sdk.Int) (sdk.Dec, error) { // SharesFromTokensTruncated returns the truncated shares of a delegation given // a bond amount. It returns an error if the validator has no tokens. -func (v Validator) SharesFromTokensTruncated(amt sdk.Int) (sdk.Dec, error) { +func (v Validator) SharesFromTokensTruncated(amt math.Int) (sdk.Dec, error) { if v.Tokens.IsZero() { return sdk.ZeroDec(), ErrInsufficientShares } @@ -346,7 +347,7 @@ func (v Validator) SharesFromTokensTruncated(amt sdk.Int) (sdk.Dec, error) { } // get the bonded tokens which the validator holds -func (v Validator) BondedTokens() sdk.Int { +func (v Validator) BondedTokens() math.Int { if v.IsBonded() { return v.Tokens } @@ -356,7 +357,7 @@ func (v Validator) BondedTokens() sdk.Int { // ConsensusPower gets the consensus-engine power. Aa reduction of 10^6 from // validator tokens is applied -func (v Validator) ConsensusPower(r sdk.Int) int64 { +func (v Validator) ConsensusPower(r math.Int) int64 { if v.IsBonded() { return v.PotentialConsensusPower(r) } @@ -365,7 +366,7 @@ func (v Validator) ConsensusPower(r sdk.Int) int64 { } // PotentialConsensusPower returns the potential consensus-engine power. -func (v Validator) PotentialConsensusPower(r sdk.Int) int64 { +func (v Validator) PotentialConsensusPower(r math.Int) int64 { return sdk.TokensToConsensusPower(v.Tokens, r) } @@ -377,7 +378,7 @@ func (v Validator) UpdateStatus(newStatus BondStatus) Validator { } // AddTokensFromDel adds tokens to a validator -func (v Validator) AddTokensFromDel(amount sdk.Int) (Validator, sdk.Dec) { +func (v Validator) AddTokensFromDel(amount math.Int) (Validator, sdk.Dec) { // calculate the shares to issue var issuedShares sdk.Dec if v.DelegatorShares.IsZero() { @@ -399,7 +400,7 @@ func (v Validator) AddTokensFromDel(amount sdk.Int) (Validator, sdk.Dec) { } // RemoveTokens removes tokens from a validator -func (v Validator) RemoveTokens(tokens sdk.Int) Validator { +func (v Validator) RemoveTokens(tokens math.Int) Validator { if tokens.IsNegative() { panic(fmt.Sprintf("should not happen: trying to remove negative tokens %v", tokens)) } @@ -416,10 +417,10 @@ func (v Validator) RemoveTokens(tokens sdk.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. -func (v Validator) RemoveDelShares(delShares sdk.Dec) (Validator, sdk.Int) { +func (v Validator) RemoveDelShares(delShares sdk.Dec) (Validator, math.Int) { remainingShares := v.DelegatorShares.Sub(delShares) - var issuedTokens sdk.Int + var issuedTokens math.Int if remainingShares.IsZero() { // last delegation share gets any trimmings issuedTokens = v.Tokens @@ -510,14 +511,14 @@ func (v Validator) GetConsAddr() (sdk.ConsAddress, error) { return sdk.ConsAddress(pk.Address()), nil } -func (v Validator) GetTokens() sdk.Int { return v.Tokens } -func (v Validator) GetBondedTokens() sdk.Int { return v.BondedTokens() } -func (v Validator) GetConsensusPower(r sdk.Int) int64 { +func (v Validator) GetTokens() math.Int { return v.Tokens } +func (v Validator) GetBondedTokens() math.Int { return v.BondedTokens() } +func (v Validator) GetConsensusPower(r math.Int) int64 { return v.ConsensusPower(r) } -func (v Validator) GetCommission() sdk.Dec { return v.Commission.Rate } -func (v Validator) GetMinSelfDelegation() sdk.Int { return v.MinSelfDelegation } -func (v Validator) GetDelegatorShares() sdk.Dec { return v.DelegatorShares } +func (v Validator) GetCommission() sdk.Dec { return v.Commission.Rate } +func (v Validator) GetMinSelfDelegation() math.Int { return v.MinSelfDelegation } +func (v Validator) GetDelegatorShares() sdk.Dec { return v.DelegatorShares } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces func (v Validator) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { diff --git a/x/upgrade/module.go b/x/upgrade/module.go index e4e2ad5a006e..2bece77259a0 100644 --- a/x/upgrade/module.go +++ b/x/upgrade/module.go @@ -101,7 +101,10 @@ func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterQueryServer(cfg.QueryServer(), am.keeper) m := keeper.NewMigrator(am.keeper) - cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2) + err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2) + if err != nil { + panic(err) + } } // InitGenesis is ignored, no sense in serializing future upgrades From 2b3991e8ce3046a7e77a1109ced3825ac081c20e Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 15:43:46 +0700 Subject: [PATCH 02/27] staking keys --- x/staking/types/keys.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/x/staking/types/keys.go b/x/staking/types/keys.go index 74d73bf19c7e..ca0023d71080 100644 --- a/x/staking/types/keys.go +++ b/x/staking/types/keys.go @@ -7,6 +7,8 @@ import ( "strconv" "time" + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" "github.com/cosmos/cosmos-sdk/types/kv" @@ -78,7 +80,7 @@ func AddressFromLastValidatorPowerKey(key []byte) []byte { // Power index is the key used in the power-store, and represents the relative // power ranking of the validator. // VALUE: validator operator address ([]byte) -func GetValidatorsByPowerIndexKey(validator Validator, powerReduction sdk.Int) []byte { +func GetValidatorsByPowerIndexKey(validator Validator, powerReduction math.Int) []byte { // NOTE the address doesn't need to be stored because counter bytes must always be different // NOTE the larger values are of higher value From 9f5cd2b6a6a6e417191b181cc5cf18f5b2a58739 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 15:45:32 +0700 Subject: [PATCH 03/27] fumpt --- baseapp/baseapp_test.go | 1 - core/appconfig/config.go | 1 - crypto/keyring/keyring_test.go | 2 +- depinject/debug.go | 2 +- runtime/module.go | 3 ++- server/mock/tx.go | 6 ++++-- server/tm_cmds.go | 2 -- simapp/app.go | 7 ++++--- store/streaming/constructor_test.go | 1 - x/auth/ante/ante_test.go | 1 - x/auth/ante/basic_test.go | 2 -- x/auth/ante/setup.go | 4 +--- x/auth/ante/sigverify.go | 1 - x/auth/module.go | 4 ++-- x/bank/module.go | 5 ++--- x/gov/types/v1beta1/proposals_test.go | 1 - x/group/client/testutil/tx.go | 4 +--- x/group/keeper/keeper_test.go | 1 - x/params/module.go | 1 - x/simulation/simulate.go | 1 - 20 files changed, 18 insertions(+), 32 deletions(-) diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index 8d67a7a5f001..5be9331b6260 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -1294,7 +1294,6 @@ func TestTxGasLimits(t *testing.T) { return newCtx, nil }) - } routerOpt := func(bapp *BaseApp) { diff --git a/core/appconfig/config.go b/core/appconfig/config.go index b77330bb4440..6aabcfcec957 100644 --- a/core/appconfig/config.go +++ b/core/appconfig/config.go @@ -80,7 +80,6 @@ func Compose(appConfig *appv1alpha1.Config) depinject.Config { config := init.ConfigProtoMessage.ProtoReflect().Type().New().Interface() err = anypb.UnmarshalTo(module.Config, config, proto.UnmarshalOptions{}) if err != nil { - return depinject.Error(err) } diff --git a/crypto/keyring/keyring_test.go b/crypto/keyring/keyring_test.go index 235a66d2687e..66c326598b71 100644 --- a/crypto/keyring/keyring_test.go +++ b/crypto/keyring/keyring_test.go @@ -157,7 +157,7 @@ func TestKeyManagementKeyRing(t *testing.T) { // create some random directory inside the keyring directory to check migrate ignores // all files other than *.info newPath := filepath.Join(tempDir, "random") - require.NoError(t, os.Mkdir(newPath, 0755)) + require.NoError(t, os.Mkdir(newPath, 0o755)) items, err := os.ReadDir(tempDir) require.GreaterOrEqual(t, len(items), 2) keyS, err = kb.List() diff --git a/depinject/debug.go b/depinject/debug.go index 473076f28a84..820354426aa4 100644 --- a/depinject/debug.go +++ b/depinject/debug.go @@ -236,7 +236,7 @@ func (c *debugConfig) enableLogVisualizer() { func (c *debugConfig) addFileVisualizer(filename string) { c.visualizers = append(c.visualizers, func(_ string) { dotStr := c.graph.String() - err := os.WriteFile(filename, []byte(dotStr), 0644) + err := os.WriteFile(filename, []byte(dotStr), 0o644) if err != nil { c.logf("Error saving graphviz file %s: %+v", filename, err) } else { diff --git a/runtime/module.go b/runtime/module.go index ac053b1f6310..399e9ad2c0b6 100644 --- a/runtime/module.go +++ b/runtime/module.go @@ -43,7 +43,8 @@ func provideCodecs(moduleBasics map[string]AppModuleBasicWrapper) ( codec.Codec, *codec.LegacyAmino, appWrapper, - codec.ProtoCodecMarshaler) { + codec.ProtoCodecMarshaler, +) { interfaceRegistry := codectypes.NewInterfaceRegistry() amino := codec.NewLegacyAmino() diff --git a/server/mock/tx.go b/server/mock/tx.go index 0cb79c28986f..3c93ffb83410 100644 --- a/server/mock/tx.go +++ b/server/mock/tx.go @@ -21,8 +21,10 @@ func (msg kvstoreTx) Reset() {} func (msg kvstoreTx) String() string { return "TODO" } func (msg kvstoreTx) ProtoMessage() {} -var _ sdk.Tx = kvstoreTx{} -var _ sdk.Msg = kvstoreTx{} +var ( + _ sdk.Tx = kvstoreTx{} + _ sdk.Msg = kvstoreTx{} +) func NewTx(key, value string) kvstoreTx { bytes := fmt.Sprintf("%s=%s", key, value) diff --git a/server/tm_cmds.go b/server/tm_cmds.go index 6cc63850ff74..a664131894cf 100644 --- a/server/tm_cmds.go +++ b/server/tm_cmds.go @@ -165,7 +165,6 @@ func makeKeyMigrateCmd() *cobra.Command { ID: dbctx, Config: config, }) - if err != nil { return fmt.Errorf("constructing database handle: %w", err) } @@ -178,7 +177,6 @@ func makeKeyMigrateCmd() *cobra.Command { if dbctx == "blockstore" { if err := scmigrate.Migrate(ctx, db); err != nil { return fmt.Errorf("running seen commit migration: %w", err) - } } } diff --git a/simapp/app.go b/simapp/app.go index 51cfbaf7ff03..02d711bf1e83 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -346,11 +346,13 @@ func NewSimApp( // NOTE: Capability module must occur first so that it can initialize any capabilities // so that other modules that want to create or claim capabilities afterwards in InitChain // can do so safely. - genesisModuleOrder := []string{capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, + genesisModuleOrder := []string{ + capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, distrtypes.ModuleName, stakingtypes.ModuleName, slashingtypes.ModuleName, govtypes.ModuleName, minttypes.ModuleName, crisistypes.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName, authz.ModuleName, feegrant.ModuleName, nft.ModuleName, group.ModuleName, paramstypes.ModuleName, upgradetypes.ModuleName, - vestingtypes.ModuleName} + vestingtypes.ModuleName, + } app.ModuleManager.SetOrderInitGenesis(genesisModuleOrder...) app.ModuleManager.SetOrderExportGenesis(genesisModuleOrder...) @@ -434,7 +436,6 @@ func (app *SimApp) setAnteHandler(txConfig client.TxConfig, indexEventsStr []str SigGasConsumer: ante.DefaultSigVerificationGasConsumer, }, ) - if err != nil { panic(err) } diff --git a/store/streaming/constructor_test.go b/store/streaming/constructor_test.go index 79051d16500a..1b0479cc7d51 100644 --- a/store/streaming/constructor_test.go +++ b/store/streaming/constructor_test.go @@ -81,7 +81,6 @@ func TestLoadStreamingServices(t *testing.T) { require.Equal(t, tc.activeStreamersLen, len(activeStreamers)) }) } - } type streamingAppOptions struct { diff --git a/x/auth/ante/ante_test.go b/x/auth/ante/ante_test.go index 6ff5532a4386..1e6f8ace5bcd 100644 --- a/x/auth/ante/ante_test.go +++ b/x/auth/ante/ante_test.go @@ -511,7 +511,6 @@ func (suite *AnteTestSuite) TestAnteHandlerFees() { for _, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { - suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() tc.malleate() diff --git a/x/auth/ante/basic_test.go b/x/auth/ante/basic_test.go index 4a8cb830fdf6..761e7a2b8e88 100644 --- a/x/auth/ante/basic_test.go +++ b/x/auth/ante/basic_test.go @@ -168,10 +168,8 @@ func (suite *AnteTestSuite) TestConsumeGasForTxSize() { // require that antehandler passes and does not underestimate decorator cost suite.Require().Nil(err, "ConsumeTxSizeGasDecorator returned error: %v", err) suite.Require().True(consumedSimGas >= expectedGas, "Simulate mode underestimates gas on AnteDecorator. Simulated cost: %d, expected cost: %d", consumedSimGas, expectedGas) - }) } - } func (suite *AnteTestSuite) TestTxHeightTimeoutDecorator() { diff --git a/x/auth/ante/setup.go b/x/auth/ante/setup.go index 6d6d4344c0c3..4e9ffe862b9c 100644 --- a/x/auth/ante/setup.go +++ b/x/auth/ante/setup.go @@ -8,9 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" ) -var ( - _ GasTx = (*legacytx.StdTx)(nil) // assert StdTx implements GasTx -) +var _ GasTx = (*legacytx.StdTx)(nil) // assert StdTx implements GasTx // GasTx defines a Tx with a GetGas() method which is needed to use SetUpContextDecorator type GasTx interface { diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index c77632a7d020..7363307af12b 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -425,7 +425,6 @@ func ConsumeMultisignatureVerificationGas( meter sdk.GasMeter, sig *signing.MultiSignatureData, pubkey multisig.PubKey, params types.Params, accSeq uint64, ) error { - size := sig.BitArray.Count() sigIndex := 0 diff --git a/x/auth/module.go b/x/auth/module.go index dd68ec62da80..feec8ccaccea 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -219,8 +219,8 @@ func provideModule( config *modulev1.Module, key *store.KVStoreKey, cdc codec.Codec, - subspace paramtypes.Subspace) authOutputs { - + subspace paramtypes.Subspace, +) authOutputs { maccPerms := map[string][]string{} for _, permission := range config.ModuleAccountPermissions { maccPerms[permission.Account] = permission.Permissions diff --git a/x/bank/module.go b/x/bank/module.go index e8b5266f6ace..687f1a39d55f 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" "fmt" + "math/rand" + "time" modulev1 "cosmossdk.io/api/cosmos/bank/module/v1" "github.com/cosmos/cosmos-sdk/depinject" @@ -11,9 +13,6 @@ import ( paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" "github.com/tendermint/tendermint/crypto" - "math/rand" - "time" - "cosmossdk.io/core/appmodule" gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" diff --git a/x/gov/types/v1beta1/proposals_test.go b/x/gov/types/v1beta1/proposals_test.go index 2a29fda28753..6f3bee6092f6 100644 --- a/x/gov/types/v1beta1/proposals_test.go +++ b/x/gov/types/v1beta1/proposals_test.go @@ -54,5 +54,4 @@ func TestContentFromProposalType(t *testing.T) { require.NotNil(t, content) require.Equal(t, test.expectedType, content.ProposalType()) } - } diff --git a/x/group/client/testutil/tx.go b/x/group/client/testutil/tx.go index e761c4ab9500..879c7baef22c 100644 --- a/x/group/client/testutil/tx.go +++ b/x/group/client/testutil/tx.go @@ -2413,10 +2413,8 @@ func (s *IntegrationTestSuite) TestExecProposalsWhenMemberLeavesOrIsUpdated() { if tc.expectLogErr { s.Require().Contains(execResp.RawLog, tc.errMsg) } - }) } - } func (s *IntegrationTestSuite) getGroupIDFromTxResponse(txResp sdk.TxResponse) string { @@ -2536,7 +2534,7 @@ func (s *IntegrationTestSuite) createGroupThresholdPolicyWithBalance(adminAddres s.commonFlags..., ), ) - var txResp = sdk.TxResponse{} + txResp := sdk.TxResponse{} s.Require().NoError(err, out.String()) s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) s.Require().Equal(uint32(0), txResp.Code, out.String()) diff --git a/x/group/keeper/keeper_test.go b/x/group/keeper/keeper_test.go index 84ee34bcdf81..c82ad1b1e49b 100644 --- a/x/group/keeper/keeper_test.go +++ b/x/group/keeper/keeper_test.go @@ -2829,7 +2829,6 @@ func (s *TestSuite) TestLeaveGroup() { } } - func (s *TestSuite) TestPruneProposals() { addrs := s.addrs expirationTime := time.Hour * 24 * 15 // 15 days diff --git a/x/params/module.go b/x/params/module.go index 6df8b234d3df..87c463883bc6 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -174,7 +174,6 @@ func provideModule( cdc codec.Codec, amino *codec.LegacyAmino, ) (keeper.Keeper, runtime.AppModuleWrapper, runtime.BaseAppOption) { - k := keeper.NewKeeper(cdc, amino, kvStoreKey, transientStoreKey) m := NewAppModule(k) baseappOpt := func(app *baseapp.BaseApp) { diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index 73012502566b..973f6d0fbd4a 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -319,7 +319,6 @@ Comment: %s`, } } - func runQueuedOperations(queueOps map[int][]simulation.Operation, height int, tb testing.TB, r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simulation.Account, logWriter LogWriter, From 1b2320c28fa88b32bdb9f010fc5f829c62f32465 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 16:14:37 +0700 Subject: [PATCH 04/27] var-naming linter errors and a fumpt --- baseapp/baseapp_test.go | 1 - client/cmd.go | 2 +- client/grpc/tmservice/block.go | 4 +- client/grpc_query.go | 2 +- core/appconfig/config.go | 1 - crypto/keyring/keyring_test.go | 2 +- .../secp256k1/internal/secp256k1/curve.go | 8 +- depinject/debug.go | 2 +- pruning/manager.go | 2 +- runtime/module.go | 3 +- server/mock/tx.go | 6 +- server/tm_cmds.go | 2 - simapp/app.go | 7 +- simapp/test_helpers.go | 5 +- snapshots/types/util.go | 2 +- store/streaming/constructor_test.go | 1 - store/v2alpha1/smt/ics23.go | 2 +- types/coin.go | 2 +- types/kv/list.go | 2 +- x/auth/ante/ante_test.go | 1 - x/auth/ante/basic_test.go | 2 - x/auth/ante/setup.go | 4 +- x/auth/ante/sigverify.go | 1 - x/auth/module.go | 4 +- x/auth/tx/builder.go | 10 +- x/auth/tx/service.go | 4 +- x/authz/keeper/keeper.go | 8 +- x/authz/module/abci.go | 2 +- x/bank/module.go | 5 +- x/gov/keeper/msg_server.go | 2 +- x/gov/keeper/querier.go | 6 - x/gov/migrations/v046/convert.go | 2 +- x/gov/types/v1beta1/proposals_test.go | 1 - x/group/client/testutil/tx.go | 19 +-- x/group/keeper/grpc_query.go | 4 +- x/group/keeper/keeper.go | 6 +- x/group/keeper/keeper_test.go | 1 - x/group/keeper/msg_server.go | 10 +- x/group/keeper/tally.go | 4 +- x/nft/client/testutil/grpc.go | 160 +++++++++--------- x/params/module.go | 1 - 41 files changed, 140 insertions(+), 173 deletions(-) diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index 8d67a7a5f001..5be9331b6260 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -1294,7 +1294,6 @@ func TestTxGasLimits(t *testing.T) { return newCtx, nil }) - } routerOpt := func(bapp *BaseApp) { diff --git a/client/cmd.go b/client/cmd.go index ce6faba09e06..77b404bcb575 100644 --- a/client/cmd.go +++ b/client/cmd.go @@ -268,7 +268,7 @@ func readTxCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Context, err isAux, _ := flagSet.GetBool(flags.FlagAux) clientCtx = clientCtx.WithAux(isAux) if isAux { - // If the user didn't explicity set an --output flag, use JSON by + // If the user didn't explicitly set an --output flag, use JSON by // default. if clientCtx.OutputFormat == "" || !flagSet.Changed(cli.OutputFlag) { clientCtx = clientCtx.WithOutputFormat("json") diff --git a/client/grpc/tmservice/block.go b/client/grpc/tmservice/block.go index 6f3b1e556993..f941c9093a83 100644 --- a/client/grpc/tmservice/block.go +++ b/client/grpc/tmservice/block.go @@ -27,7 +27,7 @@ func GetProtoBlock(ctx context.Context, clientCtx client.Context, height *int64) if err != nil { return tmproto.BlockID{}, nil, err } - protoBlockId := block.BlockID.ToProto() + protoBlockID := block.BlockID.ToProto() - return protoBlockId, protoBlock, nil + return protoBlockID, protoBlock, nil } diff --git a/client/grpc_query.go b/client/grpc_query.go index dd0f5ab11335..a5b348ca1058 100644 --- a/client/grpc_query.go +++ b/client/grpc_query.go @@ -156,7 +156,7 @@ func (f failingInterfaceRegistry) UnpackAny(any *types.Any, iface interface{}) e return errCodecNotSet } -func (f failingInterfaceRegistry) Resolve(typeUrl string) (proto.Message, error) { +func (f failingInterfaceRegistry) Resolve(typeURL string) (proto.Message, error) { return nil, errCodecNotSet } diff --git a/core/appconfig/config.go b/core/appconfig/config.go index b77330bb4440..6aabcfcec957 100644 --- a/core/appconfig/config.go +++ b/core/appconfig/config.go @@ -80,7 +80,6 @@ func Compose(appConfig *appv1alpha1.Config) depinject.Config { config := init.ConfigProtoMessage.ProtoReflect().Type().New().Interface() err = anypb.UnmarshalTo(module.Config, config, proto.UnmarshalOptions{}) if err != nil { - return depinject.Error(err) } diff --git a/crypto/keyring/keyring_test.go b/crypto/keyring/keyring_test.go index 235a66d2687e..66c326598b71 100644 --- a/crypto/keyring/keyring_test.go +++ b/crypto/keyring/keyring_test.go @@ -157,7 +157,7 @@ func TestKeyManagementKeyRing(t *testing.T) { // create some random directory inside the keyring directory to check migrate ignores // all files other than *.info newPath := filepath.Join(tempDir, "random") - require.NoError(t, os.Mkdir(newPath, 0755)) + require.NoError(t, os.Mkdir(newPath, 0o755)) items, err := os.ReadDir(tempDir) require.GreaterOrEqual(t, len(items), 2) keyS, err = kb.List() diff --git a/crypto/keys/secp256k1/internal/secp256k1/curve.go b/crypto/keys/secp256k1/internal/secp256k1/curve.go index b5c80b23ad62..ab2277f989cd 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/curve.go +++ b/crypto/keys/secp256k1/internal/secp256k1/curve.go @@ -100,7 +100,7 @@ func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { x3.Mul(x3, x) // x³ x3.Add(x3, BitCurve.B) // x³+B - x3.Mod(x3, BitCurve.P) //(x³+B)%P + x3.Mod(x3, BitCurve.P) // (x³+B)%P return x3.Cmp(y2) == 0 } @@ -222,9 +222,9 @@ func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, c := new(big.Int).Mul(b, b) // B² d := new(big.Int).Add(x, b) // X1+B - d.Mul(d, d) //(X1+B)² - d.Sub(d, a) //(X1+B)²-A - d.Sub(d, c) //(X1+B)²-A-C + d.Mul(d, d) // (X1+B)² + d.Sub(d, a) // (X1+B)²-A + d.Sub(d, c) // (X1+B)²-A-C d.Mul(d, big.NewInt(2)) // 2*((X1+B)²-A-C) e := new(big.Int).Mul(big.NewInt(3), a) // 3*A diff --git a/depinject/debug.go b/depinject/debug.go index 473076f28a84..820354426aa4 100644 --- a/depinject/debug.go +++ b/depinject/debug.go @@ -236,7 +236,7 @@ func (c *debugConfig) enableLogVisualizer() { func (c *debugConfig) addFileVisualizer(filename string) { c.visualizers = append(c.visualizers, func(_ string) { dotStr := c.graph.String() - err := os.WriteFile(filename, []byte(dotStr), 0644) + err := os.WriteFile(filename, []byte(dotStr), 0o644) if err != nil { c.logf("Error saving graphviz file %s: %+v", filename, err) } else { diff --git a/pruning/manager.go b/pruning/manager.go index 8e7c61cc9ef6..ac1172ebb86e 100644 --- a/pruning/manager.go +++ b/pruning/manager.go @@ -13,7 +13,7 @@ import ( ) // Manager is an abstraction to handle the logic needed for -// determinging when to prune old heights of the store +// determining when to prune old heights of the store // based on the strategy described by the pruning options. type Manager struct { db dbm.DB diff --git a/runtime/module.go b/runtime/module.go index ac053b1f6310..399e9ad2c0b6 100644 --- a/runtime/module.go +++ b/runtime/module.go @@ -43,7 +43,8 @@ func provideCodecs(moduleBasics map[string]AppModuleBasicWrapper) ( codec.Codec, *codec.LegacyAmino, appWrapper, - codec.ProtoCodecMarshaler) { + codec.ProtoCodecMarshaler, +) { interfaceRegistry := codectypes.NewInterfaceRegistry() amino := codec.NewLegacyAmino() diff --git a/server/mock/tx.go b/server/mock/tx.go index 0cb79c28986f..3c93ffb83410 100644 --- a/server/mock/tx.go +++ b/server/mock/tx.go @@ -21,8 +21,10 @@ func (msg kvstoreTx) Reset() {} func (msg kvstoreTx) String() string { return "TODO" } func (msg kvstoreTx) ProtoMessage() {} -var _ sdk.Tx = kvstoreTx{} -var _ sdk.Msg = kvstoreTx{} +var ( + _ sdk.Tx = kvstoreTx{} + _ sdk.Msg = kvstoreTx{} +) func NewTx(key, value string) kvstoreTx { bytes := fmt.Sprintf("%s=%s", key, value) diff --git a/server/tm_cmds.go b/server/tm_cmds.go index 6cc63850ff74..a664131894cf 100644 --- a/server/tm_cmds.go +++ b/server/tm_cmds.go @@ -165,7 +165,6 @@ func makeKeyMigrateCmd() *cobra.Command { ID: dbctx, Config: config, }) - if err != nil { return fmt.Errorf("constructing database handle: %w", err) } @@ -178,7 +177,6 @@ func makeKeyMigrateCmd() *cobra.Command { if dbctx == "blockstore" { if err := scmigrate.Migrate(ctx, db); err != nil { return fmt.Errorf("running seen commit migration: %w", err) - } } } diff --git a/simapp/app.go b/simapp/app.go index 51cfbaf7ff03..02d711bf1e83 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -346,11 +346,13 @@ func NewSimApp( // NOTE: Capability module must occur first so that it can initialize any capabilities // so that other modules that want to create or claim capabilities afterwards in InitChain // can do so safely. - genesisModuleOrder := []string{capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, + genesisModuleOrder := []string{ + capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, distrtypes.ModuleName, stakingtypes.ModuleName, slashingtypes.ModuleName, govtypes.ModuleName, minttypes.ModuleName, crisistypes.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName, authz.ModuleName, feegrant.ModuleName, nft.ModuleName, group.ModuleName, paramstypes.ModuleName, upgradetypes.ModuleName, - vestingtypes.ModuleName} + vestingtypes.ModuleName, + } app.ModuleManager.SetOrderInitGenesis(genesisModuleOrder...) app.ModuleManager.SetOrderExportGenesis(genesisModuleOrder...) @@ -434,7 +436,6 @@ func (app *SimApp) setAnteHandler(txConfig client.TxConfig, indexEventsStr []str SigGasConsumer: ante.DefaultSigVerificationGasConsumer, }, ) - if err != nil { panic(err) } diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 3c9beddc7ca7..b7dbfedc51e2 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -6,12 +6,13 @@ import ( "encoding/hex" "encoding/json" "fmt" - "github.com/cosmos/cosmos-sdk/depinject" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" "strconv" "testing" "time" + "github.com/cosmos/cosmos-sdk/depinject" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmjson "github.com/tendermint/tendermint/libs/json" diff --git a/snapshots/types/util.go b/snapshots/types/util.go index 125ea6fb4610..348b5057682d 100644 --- a/snapshots/types/util.go +++ b/snapshots/types/util.go @@ -4,7 +4,7 @@ import ( protoio "github.com/gogo/protobuf/io" ) -// WriteExtensionItem writes an item payload for current extention snapshotter. +// WriteExtensionItem writes an item payload for current extension snapshotter. func WriteExtensionItem(protoWriter protoio.Writer, item []byte) error { return protoWriter.WriteMsg(&SnapshotItem{ Item: &SnapshotItem_ExtensionPayload{ diff --git a/store/streaming/constructor_test.go b/store/streaming/constructor_test.go index 79051d16500a..1b0479cc7d51 100644 --- a/store/streaming/constructor_test.go +++ b/store/streaming/constructor_test.go @@ -81,7 +81,6 @@ func TestLoadStreamingServices(t *testing.T) { require.Equal(t, tc.activeStreamersLen, len(activeStreamers)) }) } - } type streamingAppOptions struct { diff --git a/store/v2alpha1/smt/ics23.go b/store/v2alpha1/smt/ics23.go index 31d78f993dc0..3c4299227298 100644 --- a/store/v2alpha1/smt/ics23.go +++ b/store/v2alpha1/smt/ics23.go @@ -104,7 +104,7 @@ func convertInnerOps(path []byte, sideNodes [][]byte) []*ics23.InnerOp { Hash: ics23.HashOp_SHA256, Prefix: []byte{1}, } - if getBitAtFromMSB(path[:], depth-1-i) == 1 { + if getBitAtFromMSB(path, depth-1-i) == 1 { // right child is on path op.Prefix = append(op.Prefix, sideNodes[i]...) } else { diff --git a/types/coin.go b/types/coin.go index c5bf96aeac04..142476f4b390 100644 --- a/types/coin.go +++ b/types/coin.go @@ -411,7 +411,7 @@ func (coins Coins) SafeSub(coinsB ...Coin) (Coins, bool) { } // MulInt performs the scalar multiplication of coins with a `multiplier` -// All coins are multipled by x +// All coins are multiplied by x // e.g. // {2A, 3B} * 2 = {4A, 6B} // {2A} * 0 panics diff --git a/types/kv/list.go b/types/kv/list.go index 2b0793d343cd..872f88932d1c 100644 --- a/types/kv/list.go +++ b/types/kv/list.go @@ -113,7 +113,7 @@ func (l *List) remove(e *Element) *Element { } // move moves e to next to at and returns e. -// nolint: unparam + func (l *List) move(e, at *Element) *Element { if e == at { return e diff --git a/x/auth/ante/ante_test.go b/x/auth/ante/ante_test.go index 6ff5532a4386..1e6f8ace5bcd 100644 --- a/x/auth/ante/ante_test.go +++ b/x/auth/ante/ante_test.go @@ -511,7 +511,6 @@ func (suite *AnteTestSuite) TestAnteHandlerFees() { for _, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { - suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() tc.malleate() diff --git a/x/auth/ante/basic_test.go b/x/auth/ante/basic_test.go index 4a8cb830fdf6..761e7a2b8e88 100644 --- a/x/auth/ante/basic_test.go +++ b/x/auth/ante/basic_test.go @@ -168,10 +168,8 @@ func (suite *AnteTestSuite) TestConsumeGasForTxSize() { // require that antehandler passes and does not underestimate decorator cost suite.Require().Nil(err, "ConsumeTxSizeGasDecorator returned error: %v", err) suite.Require().True(consumedSimGas >= expectedGas, "Simulate mode underestimates gas on AnteDecorator. Simulated cost: %d, expected cost: %d", consumedSimGas, expectedGas) - }) } - } func (suite *AnteTestSuite) TestTxHeightTimeoutDecorator() { diff --git a/x/auth/ante/setup.go b/x/auth/ante/setup.go index 6d6d4344c0c3..4e9ffe862b9c 100644 --- a/x/auth/ante/setup.go +++ b/x/auth/ante/setup.go @@ -8,9 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" ) -var ( - _ GasTx = (*legacytx.StdTx)(nil) // assert StdTx implements GasTx -) +var _ GasTx = (*legacytx.StdTx)(nil) // assert StdTx implements GasTx // GasTx defines a Tx with a GetGas() method which is needed to use SetUpContextDecorator type GasTx interface { diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index c77632a7d020..7363307af12b 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -425,7 +425,6 @@ func ConsumeMultisignatureVerificationGas( meter sdk.GasMeter, sig *signing.MultiSignatureData, pubkey multisig.PubKey, params types.Params, accSeq uint64, ) error { - size := sig.BitArray.Count() sigIndex := 0 diff --git a/x/auth/module.go b/x/auth/module.go index dd68ec62da80..feec8ccaccea 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -219,8 +219,8 @@ func provideModule( config *modulev1.Module, key *store.KVStoreKey, cdc codec.Codec, - subspace paramtypes.Subspace) authOutputs { - + subspace paramtypes.Subspace, +) authOutputs { maccPerms := map[string][]string{} for _, permission := range config.ModuleAccountPermissions { maccPerms[permission.Account] = permission.Permissions diff --git a/x/auth/tx/builder.go b/x/auth/tx/builder.go index 052da8785ee8..ab875867107c 100644 --- a/x/auth/tx/builder.go +++ b/x/auth/tx/builder.go @@ -34,12 +34,12 @@ type wrapper struct { } var ( - _ authsigning.Tx = &wrapper{} - _ client.TxBuilder = &wrapper{} - _ tx.TipTx = &wrapper{} + _ authsigning.Tx = &wrapper{} + _ client.TxBuilder = &wrapper{} + _ tx.TipTx = &wrapper{} _ ante.HasExtensionOptionsTx = &wrapper{} - _ ExtensionOptionsTxBuilder = &wrapper{} - _ tx.TipTx = &wrapper{} + _ ExtensionOptionsTxBuilder = &wrapper{} + _ tx.TipTx = &wrapper{} ) // ExtensionOptionsTxBuilder defines a TxBuilder that can also set extensions. diff --git a/x/auth/tx/service.go b/x/auth/tx/service.go index 414ed31b200e..9e7f19894b47 100644 --- a/x/auth/tx/service.go +++ b/x/auth/tx/service.go @@ -181,7 +181,7 @@ func (s txServer) GetBlockWithTxs(ctx context.Context, req *txtypes.GetBlockWith "or greater than the current height %d", req.Height, currentHeight) } - blockId, block, err := tmservice.GetProtoBlock(ctx, s.clientCtx, &req.Height) + blockID, block, err := tmservice.GetProtoBlock(ctx, s.clientCtx, &req.Height) if err != nil { return nil, err } @@ -230,7 +230,7 @@ func (s txServer) GetBlockWithTxs(ctx context.Context, req *txtypes.GetBlockWith return &txtypes.GetBlockWithTxsResponse{ Txs: txs, - BlockId: &blockId, + BlockId: &blockID, Block: block, Pagination: &pagination.PageResponse{ Total: blockTxsLn, diff --git a/x/authz/keeper/keeper.go b/x/authz/keeper/keeper.go index 5ccb7e0de6fd..137e07dc9444 100644 --- a/x/authz/keeper/keeper.go +++ b/x/authz/keeper/keeper.go @@ -323,10 +323,10 @@ func (keeper Keeper) removeFromGrantQueue(ctx sdk.Context, grantKey []byte, gran _, _, msgType := parseGrantStoreKey(grantKey) queueItems := queueItem.MsgTypeUrls - for index, typeUrl := range queueItems { + for index, typeURL := range queueItems { ctx.GasMeter().ConsumeGas(gasCostPerIteration, "grant queue") - if typeUrl == msgType { + if typeURL == msgType { end := len(queueItem.MsgTypeUrls) - 1 queueItems[index] = queueItems[end] queueItems = queueItems[:end] @@ -363,8 +363,8 @@ func (k Keeper) DequeueAndDeleteExpiredGrants(ctx sdk.Context) error { store.Delete(iterator.Key()) - for _, typeUrl := range queueItem.MsgTypeUrls { - store.Delete(grantStoreKey(grantee, granter, typeUrl)) + for _, typeURL := range queueItem.MsgTypeUrls { + store.Delete(grantStoreKey(grantee, granter, typeURL)) } } diff --git a/x/authz/module/abci.go b/x/authz/module/abci.go index c9e6fef5e7a6..c1015abae841 100644 --- a/x/authz/module/abci.go +++ b/x/authz/module/abci.go @@ -5,7 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/authz/keeper" ) -// BeginBlocker is called at the begining of every block +// BeginBlocker is called at the beginning of every block func BeginBlocker(ctx sdk.Context, keeper keeper.Keeper) { // delete all the mature grants if err := keeper.DequeueAndDeleteExpiredGrants(ctx); err != nil { diff --git a/x/bank/module.go b/x/bank/module.go index e8b5266f6ace..687f1a39d55f 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" "fmt" + "math/rand" + "time" modulev1 "cosmossdk.io/api/cosmos/bank/module/v1" "github.com/cosmos/cosmos-sdk/depinject" @@ -11,9 +13,6 @@ import ( paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" "github.com/tendermint/tendermint/crypto" - "math/rand" - "time" - "cosmossdk.io/core/appmodule" gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" diff --git a/x/gov/keeper/msg_server.go b/x/gov/keeper/msg_server.go index 8800d2d79eca..6c5d9be5a673 100644 --- a/x/gov/keeper/msg_server.go +++ b/x/gov/keeper/msg_server.go @@ -12,7 +12,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1" + v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) diff --git a/x/gov/keeper/querier.go b/x/gov/keeper/querier.go index 14e8bc83b2b4..d528f33cf7ec 100644 --- a/x/gov/keeper/querier.go +++ b/x/gov/keeper/querier.go @@ -75,7 +75,6 @@ func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, keeper K } } -// nolint: unparam func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryProposalParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -96,7 +95,6 @@ func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper return bz, nil } -// nolint: unparam func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryDepositParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -113,7 +111,6 @@ func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper return bz, nil } -// nolint: unparam func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryVoteParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -130,7 +127,6 @@ func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Kee return bz, nil } -// nolint: unparam func queryDeposits(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryProposalParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -151,7 +147,6 @@ func queryDeposits(ctx sdk.Context, path []string, req abci.RequestQuery, keeper return bz, nil } -// nolint: unparam func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryProposalParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -188,7 +183,6 @@ func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Ke return bz, nil } -// nolint: unparam func queryVotes(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryProposalVotesParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) diff --git a/x/gov/migrations/v046/convert.go b/x/gov/migrations/v046/convert.go index a3f383006b5c..54ff7d4911ad 100644 --- a/x/gov/migrations/v046/convert.go +++ b/x/gov/migrations/v046/convert.go @@ -6,7 +6,7 @@ import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1" + v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) diff --git a/x/gov/types/v1beta1/proposals_test.go b/x/gov/types/v1beta1/proposals_test.go index 2a29fda28753..6f3bee6092f6 100644 --- a/x/gov/types/v1beta1/proposals_test.go +++ b/x/gov/types/v1beta1/proposals_test.go @@ -54,5 +54,4 @@ func TestContentFromProposalType(t *testing.T) { require.NotNil(t, content) require.Equal(t, test.expectedType, content.ProposalType()) } - } diff --git a/x/group/client/testutil/tx.go b/x/group/client/testutil/tx.go index 1458dc4fd338..879c7baef22c 100644 --- a/x/group/client/testutil/tx.go +++ b/x/group/client/testutil/tx.go @@ -213,7 +213,6 @@ func (s *IntegrationTestSuite) TestTxCreateGroup() { val := s.network.Validators[0] clientCtx := val.ClientCtx - validMembers := fmt.Sprintf(`{"members": [{ "address": "%s", "weight": "1", @@ -366,7 +365,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupAdmin() { clientCtx := val.ClientCtx require := s.Require() - groupIDs := make([]string, 2) for i := 0; i < 2; i++ { validMembers := fmt.Sprintf(`{"members": [{ @@ -487,7 +485,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupMetadata() { val := s.network.Validators[0] clientCtx := val.ClientCtx - testCases := []struct { name string args []string @@ -568,7 +565,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupMembers() { val := s.network.Validators[0] clientCtx := val.ClientCtx - weights := []string{"1", "1", "1"} accounts := s.createAccounts(3) @@ -691,9 +687,6 @@ func (s *IntegrationTestSuite) TestTxCreateGroupWithPolicy() { val := s.network.Validators[0] clientCtx := val.ClientCtx - - - validMembers := fmt.Sprintf(`{"members": [{ "address": "%s", "weight": "1", @@ -899,7 +892,6 @@ func (s *IntegrationTestSuite) TestTxCreateGroupPolicy() { wrongAdmin := s.network.Validators[1].Address clientCtx := val.ClientCtx - groupID := s.group.Id testCases := []struct { @@ -1067,7 +1059,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupPolicyAdmin() { clientCtx := val.ClientCtx groupPolicy := s.groupPolicies[3] - commonFlags := s.commonFlags commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) @@ -1168,7 +1159,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupPolicyDecisionPolicy() { clientCtx := val.ClientCtx groupPolicy := s.groupPolicies[2] - commonFlags := s.commonFlags commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) @@ -1314,7 +1304,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupPolicyMetadata() { clientCtx := val.ClientCtx groupPolicy := s.groupPolicies[2] - commonFlags := s.commonFlags commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) @@ -1428,7 +1417,6 @@ func (s *IntegrationTestSuite) TestTxSubmitProposal() { val := s.network.Validators[0] clientCtx := val.ClientCtx - testCases := []struct { name string args []string @@ -1617,7 +1605,6 @@ func (s *IntegrationTestSuite) TestTxVote() { val := s.network.Validators[0] clientCtx := val.ClientCtx - ids := make([]string, 4) weights := []string{"1", "1", "1"} accounts := s.createAccounts(3) @@ -1811,7 +1798,6 @@ func (s *IntegrationTestSuite) TestTxWithdrawProposal() { val := s.network.Validators[0] clientCtx := val.ClientCtx - ids := make([]string, 2) for i := 0; i < 2; i++ { @@ -1954,7 +1940,6 @@ func (s *IntegrationTestSuite) TestTxExec() { clientCtx := val.ClientCtx require := s.Require() - var proposalIDs []string // create proposals and vote for i := 0; i < 2; i++ { @@ -2428,10 +2413,8 @@ func (s *IntegrationTestSuite) TestExecProposalsWhenMemberLeavesOrIsUpdated() { if tc.expectLogErr { s.Require().Contains(execResp.RawLog, tc.errMsg) } - }) } - } func (s *IntegrationTestSuite) getGroupIDFromTxResponse(txResp sdk.TxResponse) string { @@ -2551,7 +2534,7 @@ func (s *IntegrationTestSuite) createGroupThresholdPolicyWithBalance(adminAddres s.commonFlags..., ), ) - var txResp = sdk.TxResponse{} + txResp := sdk.TxResponse{} s.Require().NoError(err, out.String()) s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) s.Require().Equal(uint32(0), txResp.Code, out.String()) diff --git a/x/group/keeper/grpc_query.go b/x/group/keeper/grpc_query.go index f9bef8c8b22f..ff26844dde56 100644 --- a/x/group/keeper/grpc_query.go +++ b/x/group/keeper/grpc_query.go @@ -321,9 +321,9 @@ func (k Keeper) getVotesByVoter(ctx sdk.Context, voter sdk.AccAddress, pageReque // TallyResult computes the live tally result of a proposal. func (k Keeper) TallyResult(goCtx context.Context, request *group.QueryTallyResultRequest) (*group.QueryTallyResultResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - proposalId := request.ProposalId + proposalID := request.ProposalId - proposal, err := k.getProposal(ctx, proposalId) + proposal, err := k.getProposal(ctx, proposalID) if err != nil { return nil, err } diff --git a/x/group/keeper/keeper.go b/x/group/keeper/keeper.go index 93cd875da5a3..b5673893051f 100644 --- a/x/group/keeper/keeper.go +++ b/x/group/keeper/keeper.go @@ -369,12 +369,12 @@ func (k Keeper) TallyProposalsAtVPEnd(ctx sdk.Context) error { return true, sdkerrors.Wrap(err, "group") } - proposalId := proposal.Id + proposalID := proposal.Id if proposal.Status == group.PROPOSAL_STATUS_ABORTED || proposal.Status == group.PROPOSAL_STATUS_WITHDRAWN { - if err := k.pruneProposal(ctx, proposalId); err != nil { + if err := k.pruneProposal(ctx, proposalID); err != nil { return true, err } - if err := k.pruneVotes(ctx, proposalId); err != nil { + if err := k.pruneVotes(ctx, proposalID); err != nil { return true, err } } else { diff --git a/x/group/keeper/keeper_test.go b/x/group/keeper/keeper_test.go index 84ee34bcdf81..c82ad1b1e49b 100644 --- a/x/group/keeper/keeper_test.go +++ b/x/group/keeper/keeper_test.go @@ -2829,7 +2829,6 @@ func (s *TestSuite) TestLeaveGroup() { } } - func (s *TestSuite) TestPruneProposals() { addrs := s.addrs expirationTime := time.Hour * 24 * 15 // 15 days diff --git a/x/group/keeper/msg_server.go b/x/group/keeper/msg_server.go index 6a25c5dce3f1..dde4bb222c51 100644 --- a/x/group/keeper/msg_server.go +++ b/x/group/keeper/msg_server.go @@ -161,7 +161,7 @@ func (k Keeper) UpdateGroupMembers(goCtx context.Context, req *group.MsgUpdateGr if err != nil { return err } - // Substract previous weight from the group total weight. + // Subtract previous weight from the group total weight. totalWeight, err = math.SubNonNegative(totalWeight, previousMemberWeight) if err != nil { return err @@ -248,12 +248,12 @@ func (k Keeper) CreateGroupWithPolicy(goCtx context.Context, req *group.MsgCreat if err != nil { return nil, sdkerrors.Wrap(err, "group response") } - groupId := groupRes.GroupId + groupID := groupRes.GroupId var groupPolicyAddr sdk.AccAddress groupPolicyRes, err := k.CreateGroupPolicy(goCtx, &group.MsgCreateGroupPolicy{ Admin: req.Admin, - GroupId: groupId, + GroupId: groupID, Metadata: req.GroupPolicyMetadata, DecisionPolicy: req.DecisionPolicy, }) @@ -270,7 +270,7 @@ func (k Keeper) CreateGroupWithPolicy(goCtx context.Context, req *group.MsgCreat if req.GroupPolicyAsAdmin { updateAdminReq := &group.MsgUpdateGroupAdmin{ - GroupId: groupId, + GroupId: groupID, Admin: req.Admin, NewAdmin: groupPolicyAddress, } @@ -290,7 +290,7 @@ func (k Keeper) CreateGroupWithPolicy(goCtx context.Context, req *group.MsgCreat } } - return &group.MsgCreateGroupWithPolicyResponse{GroupId: groupId, GroupPolicyAddress: groupPolicyAddress}, nil + return &group.MsgCreateGroupWithPolicyResponse{GroupId: groupID, GroupPolicyAddress: groupPolicyAddress}, nil } func (k Keeper) CreateGroupPolicy(goCtx context.Context, req *group.MsgCreateGroupPolicy) (*group.MsgCreateGroupPolicyResponse, error) { diff --git a/x/group/keeper/tally.go b/x/group/keeper/tally.go index 931c949696c6..d3ffedfd5ed7 100644 --- a/x/group/keeper/tally.go +++ b/x/group/keeper/tally.go @@ -10,7 +10,7 @@ import ( // Tally is a function that tallies a proposal by iterating through its votes, // and returns the tally result without modifying the proposal or any state. -func (k Keeper) Tally(ctx sdk.Context, p group.Proposal, groupId uint64) (group.TallyResult, error) { +func (k Keeper) Tally(ctx sdk.Context, p group.Proposal, groupID uint64) (group.TallyResult, error) { // If proposal has already been tallied and updated, then its status is // accepted/rejected, in which case we just return the previously stored result. // @@ -40,7 +40,7 @@ func (k Keeper) Tally(ctx sdk.Context, p group.Proposal, groupId uint64) (group. var member group.GroupMember err := k.groupMemberTable.GetOne(ctx.KVStore(k.key), orm.PrimaryKey(&group.GroupMember{ - GroupId: groupId, + GroupId: groupID, Member: &group.Member{Address: vote.Voter}, }), &member) diff --git a/x/nft/client/testutil/grpc.go b/x/nft/client/testutil/grpc.go index 8d98182c5b7d..11ba5b777240 100644 --- a/x/nft/client/testutil/grpc.go +++ b/x/nft/client/testutil/grpc.go @@ -12,7 +12,7 @@ func (s *IntegrationTestSuite) TestQueryBalanceGRPC() { testCases := []struct { name string args struct { - ClassId string + ClassID string Owner string } expectErr bool @@ -22,10 +22,10 @@ func (s *IntegrationTestSuite) TestQueryBalanceGRPC() { { name: "fail not exist class id", args: struct { - ClassId string + ClassID string Owner string }{ - ClassId: "invalid_class_id", + ClassID: "invalid_class_id", Owner: s.owner.String(), }, expectErr: true, @@ -35,10 +35,10 @@ func (s *IntegrationTestSuite) TestQueryBalanceGRPC() { { name: "fail not exist owner", args: struct { - ClassId string + ClassID string Owner string }{ - ClassId: ExpNFT.ClassId, + ClassID: ExpNFT.ClassId, Owner: s.owner.String(), }, expectErr: false, @@ -47,10 +47,10 @@ func (s *IntegrationTestSuite) TestQueryBalanceGRPC() { { name: "success", args: struct { - ClassId string + ClassID string Owner string }{ - ClassId: ExpNFT.ClassId, + ClassID: ExpNFT.ClassId, Owner: val.Address.String(), }, expectErr: false, @@ -59,7 +59,7 @@ func (s *IntegrationTestSuite) TestQueryBalanceGRPC() { } balanceURL := val.APIAddress + "/cosmos/nft/v1beta1/balance/%s/%s" for _, tc := range testCases { - uri := fmt.Sprintf(balanceURL, tc.args.Owner, tc.args.ClassId) + uri := fmt.Sprintf(balanceURL, tc.args.Owner, tc.args.ClassID) s.Run(tc.name, func() { resp, _ := rest.GetRequest(uri) if tc.expectErr { @@ -80,8 +80,8 @@ func (s *IntegrationTestSuite) TestQueryOwnerGRPC() { testCases := []struct { name string args struct { - ClassId string - Id string + ClassID string + ID string } expectErr bool errMsg string @@ -90,11 +90,11 @@ func (s *IntegrationTestSuite) TestQueryOwnerGRPC() { { name: "class id is invalid", args: struct { - ClassId string - Id string + ClassID string + ID string }{ - ClassId: "invalid_class_id", - Id: ExpNFT.Id, + ClassID: "invalid_class_id", + ID: ExpNFT.Id, }, expectErr: true, errMsg: "invalid class id", @@ -103,11 +103,11 @@ func (s *IntegrationTestSuite) TestQueryOwnerGRPC() { { name: "class id does not exist", args: struct { - ClassId string - Id string + ClassID string + ID string }{ - ClassId: "class-id", - Id: ExpNFT.Id, + ClassID: "class-id", + ID: ExpNFT.Id, }, expectErr: false, expectResult: "", @@ -115,11 +115,11 @@ func (s *IntegrationTestSuite) TestQueryOwnerGRPC() { { name: "nft id is invalid", args: struct { - ClassId string - Id string + ClassID string + ID string }{ - ClassId: ExpNFT.ClassId, - Id: "invalid_nft_id", + ClassID: ExpNFT.ClassId, + ID: "invalid_nft_id", }, expectErr: true, expectResult: "", @@ -127,11 +127,11 @@ func (s *IntegrationTestSuite) TestQueryOwnerGRPC() { { name: "nft id does not exist", args: struct { - ClassId string - Id string + ClassID string + ID string }{ - ClassId: ExpNFT.ClassId, - Id: "nft-id", + ClassID: ExpNFT.ClassId, + ID: "nft-id", }, expectErr: false, expectResult: "", @@ -139,11 +139,11 @@ func (s *IntegrationTestSuite) TestQueryOwnerGRPC() { { name: "nft exist", args: struct { - ClassId string - Id string + ClassID string + ID string }{ - ClassId: ExpNFT.ClassId, - Id: ExpNFT.Id, + ClassID: ExpNFT.ClassId, + ID: ExpNFT.Id, }, expectErr: false, expectResult: val.Address.String(), @@ -151,7 +151,7 @@ func (s *IntegrationTestSuite) TestQueryOwnerGRPC() { } ownerURL := val.APIAddress + "/cosmos/nft/v1beta1/owner/%s/%s" for _, tc := range testCases { - uri := fmt.Sprintf(ownerURL, tc.args.ClassId, tc.args.Id) + uri := fmt.Sprintf(ownerURL, tc.args.ClassID, tc.args.ID) s.Run(tc.name, func() { resp, err := rest.GetRequest(uri) if tc.expectErr { @@ -173,7 +173,7 @@ func (s *IntegrationTestSuite) TestQuerySupplyGRPC() { testCases := []struct { name string args struct { - ClassId string + ClassID string } expectErr bool errMsg string @@ -182,9 +182,9 @@ func (s *IntegrationTestSuite) TestQuerySupplyGRPC() { { name: "class id is invalid", args: struct { - ClassId string + ClassID string }{ - ClassId: "invalid_class_id", + ClassID: "invalid_class_id", }, expectErr: true, errMsg: "invalid class id", @@ -193,9 +193,9 @@ func (s *IntegrationTestSuite) TestQuerySupplyGRPC() { { name: "class id does not exist", args: struct { - ClassId string + ClassID string }{ - ClassId: "class-id", + ClassID: "class-id", }, expectErr: false, expectResult: 0, @@ -203,9 +203,9 @@ func (s *IntegrationTestSuite) TestQuerySupplyGRPC() { { name: "class id exist", args: struct { - ClassId string + ClassID string }{ - ClassId: ExpNFT.ClassId, + ClassID: ExpNFT.ClassId, }, expectErr: false, expectResult: 1, @@ -213,7 +213,7 @@ func (s *IntegrationTestSuite) TestQuerySupplyGRPC() { } supplyURL := val.APIAddress + "/cosmos/nft/v1beta1/supply/%s" for _, tc := range testCases { - uri := fmt.Sprintf(supplyURL, tc.args.ClassId) + uri := fmt.Sprintf(supplyURL, tc.args.ClassID) s.Run(tc.name, func() { resp, err := rest.GetRequest(uri) if tc.expectErr { @@ -234,7 +234,7 @@ func (s *IntegrationTestSuite) TestQueryNFTsGRPC() { testCases := []struct { name string args struct { - ClassId string + ClassID string Owner string } expectErr bool @@ -244,7 +244,7 @@ func (s *IntegrationTestSuite) TestQueryNFTsGRPC() { { name: "classID and owner are both empty", args: struct { - ClassId string + ClassID string Owner string }{}, errorMsg: "must provide at least one of classID or owner", @@ -254,10 +254,10 @@ func (s *IntegrationTestSuite) TestQueryNFTsGRPC() { { name: "classID is invalid", args: struct { - ClassId string + ClassID string Owner string }{ - ClassId: "invalid_class_id", + ClassID: "invalid_class_id", }, expectErr: true, expectResult: []*nft.NFT{}, @@ -265,10 +265,10 @@ func (s *IntegrationTestSuite) TestQueryNFTsGRPC() { { name: "classID does not exist", args: struct { - ClassId string + ClassID string Owner string }{ - ClassId: "class-id", + ClassID: "class-id", }, expectErr: false, expectResult: []*nft.NFT{}, @@ -276,10 +276,10 @@ func (s *IntegrationTestSuite) TestQueryNFTsGRPC() { { name: "success query by classID", args: struct { - ClassId string + ClassID string Owner string }{ - ClassId: ExpNFT.ClassId, + ClassID: ExpNFT.ClassId, }, expectErr: false, expectResult: []*nft.NFT{&ExpNFT}, @@ -287,7 +287,7 @@ func (s *IntegrationTestSuite) TestQueryNFTsGRPC() { { name: "success query by owner", args: struct { - ClassId string + ClassID string Owner string }{ Owner: val.Address.String(), @@ -298,10 +298,10 @@ func (s *IntegrationTestSuite) TestQueryNFTsGRPC() { { name: "success query by owner and classID", args: struct { - ClassId string + ClassID string Owner string }{ - ClassId: ExpNFT.ClassId, + ClassID: ExpNFT.ClassId, Owner: val.Address.String(), }, expectErr: false, @@ -310,7 +310,7 @@ func (s *IntegrationTestSuite) TestQueryNFTsGRPC() { } nftsOfClassURL := val.APIAddress + "/cosmos/nft/v1beta1/nfts?class_id=%s&owner=%s" for _, tc := range testCases { - uri := fmt.Sprintf(nftsOfClassURL, tc.args.ClassId, tc.args.Owner) + uri := fmt.Sprintf(nftsOfClassURL, tc.args.ClassID, tc.args.Owner) s.Run(tc.name, func() { resp, err := rest.GetRequest(uri) if tc.expectErr { @@ -331,8 +331,8 @@ func (s *IntegrationTestSuite) TestQueryNFTGRPC() { testCases := []struct { name string args struct { - ClassId string - Id string + ClassID string + ID string } expectErr bool errorMsg string @@ -340,11 +340,11 @@ func (s *IntegrationTestSuite) TestQueryNFTGRPC() { { name: "class id is invalid", args: struct { - ClassId string - Id string + ClassID string + ID string }{ - ClassId: "invalid_class_id", - Id: ExpNFT.Id, + ClassID: "invalid_class_id", + ID: ExpNFT.Id, }, expectErr: true, errorMsg: "invalid class id", @@ -352,11 +352,11 @@ func (s *IntegrationTestSuite) TestQueryNFTGRPC() { { name: "class id does not exist", args: struct { - ClassId string - Id string + ClassID string + ID string }{ - ClassId: "class", - Id: ExpNFT.Id, + ClassID: "class", + ID: ExpNFT.Id, }, expectErr: true, errorMsg: "not found nft", @@ -364,11 +364,11 @@ func (s *IntegrationTestSuite) TestQueryNFTGRPC() { { name: "nft id is invalid", args: struct { - ClassId string - Id string + ClassID string + ID string }{ - ClassId: ExpNFT.ClassId, - Id: "invalid_nft_id", + ClassID: ExpNFT.ClassId, + ID: "invalid_nft_id", }, expectErr: true, errorMsg: "invalid nft id", @@ -376,11 +376,11 @@ func (s *IntegrationTestSuite) TestQueryNFTGRPC() { { name: "nft id does not exist", args: struct { - ClassId string - Id string + ClassID string + ID string }{ - ClassId: ExpNFT.ClassId, - Id: "nft-id", + ClassID: ExpNFT.ClassId, + ID: "nft-id", }, expectErr: true, errorMsg: "not found nft", @@ -388,18 +388,18 @@ func (s *IntegrationTestSuite) TestQueryNFTGRPC() { { name: "exist nft", args: struct { - ClassId string - Id string + ClassID string + ID string }{ - ClassId: ExpNFT.ClassId, - Id: ExpNFT.Id, + ClassID: ExpNFT.ClassId, + ID: ExpNFT.Id, }, expectErr: false, }, } nftURL := val.APIAddress + "/cosmos/nft/v1beta1/nfts/%s/%s" for _, tc := range testCases { - uri := fmt.Sprintf(nftURL, tc.args.ClassId, tc.args.Id) + uri := fmt.Sprintf(nftURL, tc.args.ClassID, tc.args.ID) s.Run(tc.name, func() { resp, err := rest.GetRequest(uri) if tc.expectErr { @@ -420,7 +420,7 @@ func (s *IntegrationTestSuite) TestQueryClassGRPC() { testCases := []struct { name string args struct { - ClassId string + ClassID string } expectErr bool errorMsg string @@ -428,9 +428,9 @@ func (s *IntegrationTestSuite) TestQueryClassGRPC() { { name: "class id does not exist", args: struct { - ClassId string + ClassID string }{ - ClassId: "class-id", + ClassID: "class-id", }, expectErr: true, errorMsg: "not found class", @@ -438,16 +438,16 @@ func (s *IntegrationTestSuite) TestQueryClassGRPC() { { name: "class id exist", args: struct { - ClassId string + ClassID string }{ - ClassId: ExpNFT.ClassId, + ClassID: ExpNFT.ClassId, }, expectErr: false, }, } classURL := val.APIAddress + "/cosmos/nft/v1beta1/classes/%s" for _, tc := range testCases { - uri := fmt.Sprintf(classURL, tc.args.ClassId) + uri := fmt.Sprintf(classURL, tc.args.ClassID) s.Run(tc.name, func() { resp, err := rest.GetRequest(uri) if tc.expectErr { diff --git a/x/params/module.go b/x/params/module.go index 6df8b234d3df..87c463883bc6 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -174,7 +174,6 @@ func provideModule( cdc codec.Codec, amino *codec.LegacyAmino, ) (keeper.Keeper, runtime.AppModuleWrapper, runtime.BaseAppOption) { - k := keeper.NewKeeper(cdc, amino, kvStoreKey, transientStoreKey) m := NewAppModule(k) baseappOpt := func(app *baseapp.BaseApp) { From 24991625f0da8ea9139029680f60dc26ac6ead2a Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 16:52:48 +0700 Subject: [PATCH 05/27] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e181fe9b0a79..d9125926aef2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Bug Fixes +* (linting) [#12135](https://github.com/cosmos/cosmos-sdk/pull/12135/) Fix variable naming issues per enabled linters. Run gofumpt to ensure easy reviews of ongoing linting work. * (migrations) [#12028](https://github.com/cosmos/cosmos-sdk/pull/12028) Fix v0.45->v0.46 in-place store migrations. * (baseapp) [#12089](https://github.com/cosmos/cosmos-sdk/pull/12089) Include antehandler and runMsgs events in SimulateTx. * (cli) [#12095](https://github.com/cosmos/cosmos-sdk/pull/12095) Fix running a tx with --dry-run returns an error From 9ad16db200f1026ece3f712221851d164410c783 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 16:57:08 +0700 Subject: [PATCH 06/27] Update .golangci.yml --- .golangci.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.golangci.yml b/.golangci.yml index af649229d62d..bbce526a7dc3 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -10,7 +10,6 @@ linters: - deadcode - depguard - dogsled - - errcheck - exportloopref - goconst - gocritic From 838ef649dc96a96a703f0142b7d9da8e72a2f5dd Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 17:00:05 +0700 Subject: [PATCH 07/27] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e678450c462..de7dce261b42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,7 +46,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * [#12089](https://github.com/cosmos/cosmos-sdk/pull/12089) Mark the `TipDecorator` as beta, don't include it in simapp by default. ### Bug Fixes - +* (linting) [#12132](https://github.com/cosmos/cosmos-sdk/pull/12132) Change sdk.Int to math.Int, run `gofumpt -w -l .`, and `golangci-lint run ./... --fix` * (cli) [#12127](https://github.com/cosmos/cosmos-sdk/pull/12127) Fix the CLI not always taking into account `--fee-payer` and `--fee-granter` flags. * (migrations) [#12028](https://github.com/cosmos/cosmos-sdk/pull/12028) Fix v0.45->v0.46 in-place store migrations. * (baseapp) [#12089](https://github.com/cosmos/cosmos-sdk/pull/12089) Include antehandler and runMsgs events in SimulateTx. From f5978a59841173e88853ac228023991397be2e47 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 17:47:11 +0700 Subject: [PATCH 08/27] Update test_helpers.go --- simapp/test_helpers.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index c66cc825c50e..c336bd5fa56a 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -10,10 +10,6 @@ import ( "testing" "time" - "github.com/cosmos/cosmos-sdk/depinject" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - - "cosmossdk.io/math" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmjson "github.com/tendermint/tendermint/libs/json" @@ -23,6 +19,9 @@ import ( dbm "github.com/tendermint/tm-db" bam "github.com/cosmos/cosmos-sdk/baseapp" + "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/depinject" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" "github.com/cosmos/cosmos-sdk/client" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" From 848b2f621471a72be41e4cb523a20f8d452e4a8e Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 17:58:28 +0700 Subject: [PATCH 09/27] Update test_helpers.go --- simapp/test_helpers.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index b7dbfedc51e2..ccadd0f46051 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -10,8 +10,7 @@ import ( "testing" "time" - "github.com/cosmos/cosmos-sdk/depinject" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" @@ -22,6 +21,8 @@ import ( dbm "github.com/tendermint/tm-db" bam "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/depinject" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" "github.com/cosmos/cosmos-sdk/client" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" From 11f096ff9d23efb6be314869800020a2fa0e4c71 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 18:10:44 +0700 Subject: [PATCH 10/27] fumpt and lint --- baseapp/baseapp_test.go | 1 - client/cmd.go | 2 +- core/appconfig/config.go | 1 - crypto/keyring/keyring_test.go | 2 +- .../secp256k1/internal/secp256k1/curve.go | 8 ++++---- depinject/debug.go | 2 +- pruning/manager.go | 2 +- runtime/module.go | 3 ++- server/mock/tx.go | 6 ++++-- server/tm_cmds.go | 2 -- simapp/app.go | 7 ++++--- simapp/test_helpers.go | 5 +++-- snapshots/types/util.go | 2 +- store/streaming/constructor_test.go | 1 - store/v2alpha1/smt/ics23.go | 2 +- types/coin.go | 2 +- types/kv/list.go | 2 +- x/auth/ante/ante_test.go | 1 - x/auth/ante/basic_test.go | 2 -- x/auth/ante/setup.go | 4 +--- x/auth/ante/sigverify.go | 1 - x/auth/module.go | 4 ++-- x/auth/tx/builder.go | 10 +++++----- x/authz/module/abci.go | 2 +- x/bank/module.go | 5 ++--- x/feegrant/client/testutil/suite.go | 4 ++-- x/gov/keeper/msg_server.go | 2 +- x/gov/keeper/querier.go | 12 ++++++------ x/gov/migrations/v046/convert.go | 2 +- x/gov/types/v1beta1/proposals_test.go | 1 - x/group/client/testutil/tx.go | 19 +------------------ x/group/keeper/keeper_test.go | 1 - x/group/keeper/msg_server.go | 2 +- x/params/module.go | 1 - 34 files changed, 48 insertions(+), 75 deletions(-) diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index 8d67a7a5f001..5be9331b6260 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -1294,7 +1294,6 @@ func TestTxGasLimits(t *testing.T) { return newCtx, nil }) - } routerOpt := func(bapp *BaseApp) { diff --git a/client/cmd.go b/client/cmd.go index ce6faba09e06..77b404bcb575 100644 --- a/client/cmd.go +++ b/client/cmd.go @@ -268,7 +268,7 @@ func readTxCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Context, err isAux, _ := flagSet.GetBool(flags.FlagAux) clientCtx = clientCtx.WithAux(isAux) if isAux { - // If the user didn't explicity set an --output flag, use JSON by + // If the user didn't explicitly set an --output flag, use JSON by // default. if clientCtx.OutputFormat == "" || !flagSet.Changed(cli.OutputFlag) { clientCtx = clientCtx.WithOutputFormat("json") diff --git a/core/appconfig/config.go b/core/appconfig/config.go index b77330bb4440..6aabcfcec957 100644 --- a/core/appconfig/config.go +++ b/core/appconfig/config.go @@ -80,7 +80,6 @@ func Compose(appConfig *appv1alpha1.Config) depinject.Config { config := init.ConfigProtoMessage.ProtoReflect().Type().New().Interface() err = anypb.UnmarshalTo(module.Config, config, proto.UnmarshalOptions{}) if err != nil { - return depinject.Error(err) } diff --git a/crypto/keyring/keyring_test.go b/crypto/keyring/keyring_test.go index 235a66d2687e..66c326598b71 100644 --- a/crypto/keyring/keyring_test.go +++ b/crypto/keyring/keyring_test.go @@ -157,7 +157,7 @@ func TestKeyManagementKeyRing(t *testing.T) { // create some random directory inside the keyring directory to check migrate ignores // all files other than *.info newPath := filepath.Join(tempDir, "random") - require.NoError(t, os.Mkdir(newPath, 0755)) + require.NoError(t, os.Mkdir(newPath, 0o755)) items, err := os.ReadDir(tempDir) require.GreaterOrEqual(t, len(items), 2) keyS, err = kb.List() diff --git a/crypto/keys/secp256k1/internal/secp256k1/curve.go b/crypto/keys/secp256k1/internal/secp256k1/curve.go index b5c80b23ad62..ab2277f989cd 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/curve.go +++ b/crypto/keys/secp256k1/internal/secp256k1/curve.go @@ -100,7 +100,7 @@ func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { x3.Mul(x3, x) // x³ x3.Add(x3, BitCurve.B) // x³+B - x3.Mod(x3, BitCurve.P) //(x³+B)%P + x3.Mod(x3, BitCurve.P) // (x³+B)%P return x3.Cmp(y2) == 0 } @@ -222,9 +222,9 @@ func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, c := new(big.Int).Mul(b, b) // B² d := new(big.Int).Add(x, b) // X1+B - d.Mul(d, d) //(X1+B)² - d.Sub(d, a) //(X1+B)²-A - d.Sub(d, c) //(X1+B)²-A-C + d.Mul(d, d) // (X1+B)² + d.Sub(d, a) // (X1+B)²-A + d.Sub(d, c) // (X1+B)²-A-C d.Mul(d, big.NewInt(2)) // 2*((X1+B)²-A-C) e := new(big.Int).Mul(big.NewInt(3), a) // 3*A diff --git a/depinject/debug.go b/depinject/debug.go index 473076f28a84..820354426aa4 100644 --- a/depinject/debug.go +++ b/depinject/debug.go @@ -236,7 +236,7 @@ func (c *debugConfig) enableLogVisualizer() { func (c *debugConfig) addFileVisualizer(filename string) { c.visualizers = append(c.visualizers, func(_ string) { dotStr := c.graph.String() - err := os.WriteFile(filename, []byte(dotStr), 0644) + err := os.WriteFile(filename, []byte(dotStr), 0o644) if err != nil { c.logf("Error saving graphviz file %s: %+v", filename, err) } else { diff --git a/pruning/manager.go b/pruning/manager.go index 8e7c61cc9ef6..ac1172ebb86e 100644 --- a/pruning/manager.go +++ b/pruning/manager.go @@ -13,7 +13,7 @@ import ( ) // Manager is an abstraction to handle the logic needed for -// determinging when to prune old heights of the store +// determining when to prune old heights of the store // based on the strategy described by the pruning options. type Manager struct { db dbm.DB diff --git a/runtime/module.go b/runtime/module.go index ac053b1f6310..399e9ad2c0b6 100644 --- a/runtime/module.go +++ b/runtime/module.go @@ -43,7 +43,8 @@ func provideCodecs(moduleBasics map[string]AppModuleBasicWrapper) ( codec.Codec, *codec.LegacyAmino, appWrapper, - codec.ProtoCodecMarshaler) { + codec.ProtoCodecMarshaler, +) { interfaceRegistry := codectypes.NewInterfaceRegistry() amino := codec.NewLegacyAmino() diff --git a/server/mock/tx.go b/server/mock/tx.go index 0cb79c28986f..3c93ffb83410 100644 --- a/server/mock/tx.go +++ b/server/mock/tx.go @@ -21,8 +21,10 @@ func (msg kvstoreTx) Reset() {} func (msg kvstoreTx) String() string { return "TODO" } func (msg kvstoreTx) ProtoMessage() {} -var _ sdk.Tx = kvstoreTx{} -var _ sdk.Msg = kvstoreTx{} +var ( + _ sdk.Tx = kvstoreTx{} + _ sdk.Msg = kvstoreTx{} +) func NewTx(key, value string) kvstoreTx { bytes := fmt.Sprintf("%s=%s", key, value) diff --git a/server/tm_cmds.go b/server/tm_cmds.go index 6cc63850ff74..a664131894cf 100644 --- a/server/tm_cmds.go +++ b/server/tm_cmds.go @@ -165,7 +165,6 @@ func makeKeyMigrateCmd() *cobra.Command { ID: dbctx, Config: config, }) - if err != nil { return fmt.Errorf("constructing database handle: %w", err) } @@ -178,7 +177,6 @@ func makeKeyMigrateCmd() *cobra.Command { if dbctx == "blockstore" { if err := scmigrate.Migrate(ctx, db); err != nil { return fmt.Errorf("running seen commit migration: %w", err) - } } } diff --git a/simapp/app.go b/simapp/app.go index 51cfbaf7ff03..02d711bf1e83 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -346,11 +346,13 @@ func NewSimApp( // NOTE: Capability module must occur first so that it can initialize any capabilities // so that other modules that want to create or claim capabilities afterwards in InitChain // can do so safely. - genesisModuleOrder := []string{capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, + genesisModuleOrder := []string{ + capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, distrtypes.ModuleName, stakingtypes.ModuleName, slashingtypes.ModuleName, govtypes.ModuleName, minttypes.ModuleName, crisistypes.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName, authz.ModuleName, feegrant.ModuleName, nft.ModuleName, group.ModuleName, paramstypes.ModuleName, upgradetypes.ModuleName, - vestingtypes.ModuleName} + vestingtypes.ModuleName, + } app.ModuleManager.SetOrderInitGenesis(genesisModuleOrder...) app.ModuleManager.SetOrderExportGenesis(genesisModuleOrder...) @@ -434,7 +436,6 @@ func (app *SimApp) setAnteHandler(txConfig client.TxConfig, indexEventsStr []str SigGasConsumer: ante.DefaultSigVerificationGasConsumer, }, ) - if err != nil { panic(err) } diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 3c9beddc7ca7..b7dbfedc51e2 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -6,12 +6,13 @@ import ( "encoding/hex" "encoding/json" "fmt" - "github.com/cosmos/cosmos-sdk/depinject" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" "strconv" "testing" "time" + "github.com/cosmos/cosmos-sdk/depinject" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmjson "github.com/tendermint/tendermint/libs/json" diff --git a/snapshots/types/util.go b/snapshots/types/util.go index 125ea6fb4610..348b5057682d 100644 --- a/snapshots/types/util.go +++ b/snapshots/types/util.go @@ -4,7 +4,7 @@ import ( protoio "github.com/gogo/protobuf/io" ) -// WriteExtensionItem writes an item payload for current extention snapshotter. +// WriteExtensionItem writes an item payload for current extension snapshotter. func WriteExtensionItem(protoWriter protoio.Writer, item []byte) error { return protoWriter.WriteMsg(&SnapshotItem{ Item: &SnapshotItem_ExtensionPayload{ diff --git a/store/streaming/constructor_test.go b/store/streaming/constructor_test.go index 79051d16500a..1b0479cc7d51 100644 --- a/store/streaming/constructor_test.go +++ b/store/streaming/constructor_test.go @@ -81,7 +81,6 @@ func TestLoadStreamingServices(t *testing.T) { require.Equal(t, tc.activeStreamersLen, len(activeStreamers)) }) } - } type streamingAppOptions struct { diff --git a/store/v2alpha1/smt/ics23.go b/store/v2alpha1/smt/ics23.go index 31d78f993dc0..3c4299227298 100644 --- a/store/v2alpha1/smt/ics23.go +++ b/store/v2alpha1/smt/ics23.go @@ -104,7 +104,7 @@ func convertInnerOps(path []byte, sideNodes [][]byte) []*ics23.InnerOp { Hash: ics23.HashOp_SHA256, Prefix: []byte{1}, } - if getBitAtFromMSB(path[:], depth-1-i) == 1 { + if getBitAtFromMSB(path, depth-1-i) == 1 { // right child is on path op.Prefix = append(op.Prefix, sideNodes[i]...) } else { diff --git a/types/coin.go b/types/coin.go index c5bf96aeac04..142476f4b390 100644 --- a/types/coin.go +++ b/types/coin.go @@ -411,7 +411,7 @@ func (coins Coins) SafeSub(coinsB ...Coin) (Coins, bool) { } // MulInt performs the scalar multiplication of coins with a `multiplier` -// All coins are multipled by x +// All coins are multiplied by x // e.g. // {2A, 3B} * 2 = {4A, 6B} // {2A} * 0 panics diff --git a/types/kv/list.go b/types/kv/list.go index 2b0793d343cd..872f88932d1c 100644 --- a/types/kv/list.go +++ b/types/kv/list.go @@ -113,7 +113,7 @@ func (l *List) remove(e *Element) *Element { } // move moves e to next to at and returns e. -// nolint: unparam + func (l *List) move(e, at *Element) *Element { if e == at { return e diff --git a/x/auth/ante/ante_test.go b/x/auth/ante/ante_test.go index 6ff5532a4386..1e6f8ace5bcd 100644 --- a/x/auth/ante/ante_test.go +++ b/x/auth/ante/ante_test.go @@ -511,7 +511,6 @@ func (suite *AnteTestSuite) TestAnteHandlerFees() { for _, tc := range testCases { suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { - suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() tc.malleate() diff --git a/x/auth/ante/basic_test.go b/x/auth/ante/basic_test.go index 4a8cb830fdf6..761e7a2b8e88 100644 --- a/x/auth/ante/basic_test.go +++ b/x/auth/ante/basic_test.go @@ -168,10 +168,8 @@ func (suite *AnteTestSuite) TestConsumeGasForTxSize() { // require that antehandler passes and does not underestimate decorator cost suite.Require().Nil(err, "ConsumeTxSizeGasDecorator returned error: %v", err) suite.Require().True(consumedSimGas >= expectedGas, "Simulate mode underestimates gas on AnteDecorator. Simulated cost: %d, expected cost: %d", consumedSimGas, expectedGas) - }) } - } func (suite *AnteTestSuite) TestTxHeightTimeoutDecorator() { diff --git a/x/auth/ante/setup.go b/x/auth/ante/setup.go index 6d6d4344c0c3..4e9ffe862b9c 100644 --- a/x/auth/ante/setup.go +++ b/x/auth/ante/setup.go @@ -8,9 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" ) -var ( - _ GasTx = (*legacytx.StdTx)(nil) // assert StdTx implements GasTx -) +var _ GasTx = (*legacytx.StdTx)(nil) // assert StdTx implements GasTx // GasTx defines a Tx with a GetGas() method which is needed to use SetUpContextDecorator type GasTx interface { diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index c77632a7d020..7363307af12b 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -425,7 +425,6 @@ func ConsumeMultisignatureVerificationGas( meter sdk.GasMeter, sig *signing.MultiSignatureData, pubkey multisig.PubKey, params types.Params, accSeq uint64, ) error { - size := sig.BitArray.Count() sigIndex := 0 diff --git a/x/auth/module.go b/x/auth/module.go index dd68ec62da80..feec8ccaccea 100644 --- a/x/auth/module.go +++ b/x/auth/module.go @@ -219,8 +219,8 @@ func provideModule( config *modulev1.Module, key *store.KVStoreKey, cdc codec.Codec, - subspace paramtypes.Subspace) authOutputs { - + subspace paramtypes.Subspace, +) authOutputs { maccPerms := map[string][]string{} for _, permission := range config.ModuleAccountPermissions { maccPerms[permission.Account] = permission.Permissions diff --git a/x/auth/tx/builder.go b/x/auth/tx/builder.go index 052da8785ee8..ab875867107c 100644 --- a/x/auth/tx/builder.go +++ b/x/auth/tx/builder.go @@ -34,12 +34,12 @@ type wrapper struct { } var ( - _ authsigning.Tx = &wrapper{} - _ client.TxBuilder = &wrapper{} - _ tx.TipTx = &wrapper{} + _ authsigning.Tx = &wrapper{} + _ client.TxBuilder = &wrapper{} + _ tx.TipTx = &wrapper{} _ ante.HasExtensionOptionsTx = &wrapper{} - _ ExtensionOptionsTxBuilder = &wrapper{} - _ tx.TipTx = &wrapper{} + _ ExtensionOptionsTxBuilder = &wrapper{} + _ tx.TipTx = &wrapper{} ) // ExtensionOptionsTxBuilder defines a TxBuilder that can also set extensions. diff --git a/x/authz/module/abci.go b/x/authz/module/abci.go index c9e6fef5e7a6..c1015abae841 100644 --- a/x/authz/module/abci.go +++ b/x/authz/module/abci.go @@ -5,7 +5,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/authz/keeper" ) -// BeginBlocker is called at the begining of every block +// BeginBlocker is called at the beginning of every block func BeginBlocker(ctx sdk.Context, keeper keeper.Keeper) { // delete all the mature grants if err := keeper.DequeueAndDeleteExpiredGrants(ctx); err != nil { diff --git a/x/bank/module.go b/x/bank/module.go index e8b5266f6ace..687f1a39d55f 100644 --- a/x/bank/module.go +++ b/x/bank/module.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" "fmt" + "math/rand" + "time" modulev1 "cosmossdk.io/api/cosmos/bank/module/v1" "github.com/cosmos/cosmos-sdk/depinject" @@ -11,9 +13,6 @@ import ( paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" "github.com/tendermint/tendermint/crypto" - "math/rand" - "time" - "cosmossdk.io/core/appmodule" gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cobra" diff --git a/x/feegrant/client/testutil/suite.go b/x/feegrant/client/testutil/suite.go index 06042e9b5f7c..dd4e3c7c61e2 100644 --- a/x/feegrant/client/testutil/suite.go +++ b/x/feegrant/client/testutil/suite.go @@ -781,7 +781,8 @@ func (s *IntegrationTestSuite) TestTxWithFeeGrant() { from: grantee.String(), flags: []string{ fmt.Sprintf("--%s=%s", flags.FlagFeePayer, grantee.String()), - fmt.Sprintf("--%s=%s", flags.FlagFeeGranter, granter.String())}, + fmt.Sprintf("--%s=%s", flags.FlagFeeGranter, granter.String()), + }, }, } @@ -798,7 +799,6 @@ func (s *IntegrationTestSuite) TestTxWithFeeGrant() { s.Require().Equal(tc.expErrCode, resp.Code, resp) }) } - } func (s *IntegrationTestSuite) TestFilteredFeeAllowance() { diff --git a/x/gov/keeper/msg_server.go b/x/gov/keeper/msg_server.go index 8800d2d79eca..6c5d9be5a673 100644 --- a/x/gov/keeper/msg_server.go +++ b/x/gov/keeper/msg_server.go @@ -12,7 +12,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1" + v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) diff --git a/x/gov/keeper/querier.go b/x/gov/keeper/querier.go index 14e8bc83b2b4..f150f0484ef2 100644 --- a/x/gov/keeper/querier.go +++ b/x/gov/keeper/querier.go @@ -75,7 +75,7 @@ func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, keeper K } } -// nolint: unparam + func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryProposalParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -96,7 +96,7 @@ func queryProposal(ctx sdk.Context, path []string, req abci.RequestQuery, keeper return bz, nil } -// nolint: unparam + func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryDepositParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -113,7 +113,7 @@ func queryDeposit(ctx sdk.Context, path []string, req abci.RequestQuery, keeper return bz, nil } -// nolint: unparam + func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryVoteParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -130,7 +130,7 @@ func queryVote(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Kee return bz, nil } -// nolint: unparam + func queryDeposits(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryProposalParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -151,7 +151,7 @@ func queryDeposits(ctx sdk.Context, path []string, req abci.RequestQuery, keeper return bz, nil } -// nolint: unparam + func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryProposalParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) @@ -188,7 +188,7 @@ func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Ke return bz, nil } -// nolint: unparam + func queryVotes(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { var params v1.QueryProposalVotesParams err := legacyQuerierCdc.UnmarshalJSON(req.Data, ¶ms) diff --git a/x/gov/migrations/v046/convert.go b/x/gov/migrations/v046/convert.go index a3f383006b5c..54ff7d4911ad 100644 --- a/x/gov/migrations/v046/convert.go +++ b/x/gov/migrations/v046/convert.go @@ -6,7 +6,7 @@ import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1" + v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" ) diff --git a/x/gov/types/v1beta1/proposals_test.go b/x/gov/types/v1beta1/proposals_test.go index 2a29fda28753..6f3bee6092f6 100644 --- a/x/gov/types/v1beta1/proposals_test.go +++ b/x/gov/types/v1beta1/proposals_test.go @@ -54,5 +54,4 @@ func TestContentFromProposalType(t *testing.T) { require.NotNil(t, content) require.Equal(t, test.expectedType, content.ProposalType()) } - } diff --git a/x/group/client/testutil/tx.go b/x/group/client/testutil/tx.go index 1458dc4fd338..879c7baef22c 100644 --- a/x/group/client/testutil/tx.go +++ b/x/group/client/testutil/tx.go @@ -213,7 +213,6 @@ func (s *IntegrationTestSuite) TestTxCreateGroup() { val := s.network.Validators[0] clientCtx := val.ClientCtx - validMembers := fmt.Sprintf(`{"members": [{ "address": "%s", "weight": "1", @@ -366,7 +365,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupAdmin() { clientCtx := val.ClientCtx require := s.Require() - groupIDs := make([]string, 2) for i := 0; i < 2; i++ { validMembers := fmt.Sprintf(`{"members": [{ @@ -487,7 +485,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupMetadata() { val := s.network.Validators[0] clientCtx := val.ClientCtx - testCases := []struct { name string args []string @@ -568,7 +565,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupMembers() { val := s.network.Validators[0] clientCtx := val.ClientCtx - weights := []string{"1", "1", "1"} accounts := s.createAccounts(3) @@ -691,9 +687,6 @@ func (s *IntegrationTestSuite) TestTxCreateGroupWithPolicy() { val := s.network.Validators[0] clientCtx := val.ClientCtx - - - validMembers := fmt.Sprintf(`{"members": [{ "address": "%s", "weight": "1", @@ -899,7 +892,6 @@ func (s *IntegrationTestSuite) TestTxCreateGroupPolicy() { wrongAdmin := s.network.Validators[1].Address clientCtx := val.ClientCtx - groupID := s.group.Id testCases := []struct { @@ -1067,7 +1059,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupPolicyAdmin() { clientCtx := val.ClientCtx groupPolicy := s.groupPolicies[3] - commonFlags := s.commonFlags commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) @@ -1168,7 +1159,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupPolicyDecisionPolicy() { clientCtx := val.ClientCtx groupPolicy := s.groupPolicies[2] - commonFlags := s.commonFlags commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) @@ -1314,7 +1304,6 @@ func (s *IntegrationTestSuite) TestTxUpdateGroupPolicyMetadata() { clientCtx := val.ClientCtx groupPolicy := s.groupPolicies[2] - commonFlags := s.commonFlags commonFlags = append(commonFlags, fmt.Sprintf("--%s=%d", flags.FlagGas, 300000)) @@ -1428,7 +1417,6 @@ func (s *IntegrationTestSuite) TestTxSubmitProposal() { val := s.network.Validators[0] clientCtx := val.ClientCtx - testCases := []struct { name string args []string @@ -1617,7 +1605,6 @@ func (s *IntegrationTestSuite) TestTxVote() { val := s.network.Validators[0] clientCtx := val.ClientCtx - ids := make([]string, 4) weights := []string{"1", "1", "1"} accounts := s.createAccounts(3) @@ -1811,7 +1798,6 @@ func (s *IntegrationTestSuite) TestTxWithdrawProposal() { val := s.network.Validators[0] clientCtx := val.ClientCtx - ids := make([]string, 2) for i := 0; i < 2; i++ { @@ -1954,7 +1940,6 @@ func (s *IntegrationTestSuite) TestTxExec() { clientCtx := val.ClientCtx require := s.Require() - var proposalIDs []string // create proposals and vote for i := 0; i < 2; i++ { @@ -2428,10 +2413,8 @@ func (s *IntegrationTestSuite) TestExecProposalsWhenMemberLeavesOrIsUpdated() { if tc.expectLogErr { s.Require().Contains(execResp.RawLog, tc.errMsg) } - }) } - } func (s *IntegrationTestSuite) getGroupIDFromTxResponse(txResp sdk.TxResponse) string { @@ -2551,7 +2534,7 @@ func (s *IntegrationTestSuite) createGroupThresholdPolicyWithBalance(adminAddres s.commonFlags..., ), ) - var txResp = sdk.TxResponse{} + txResp := sdk.TxResponse{} s.Require().NoError(err, out.String()) s.Require().NoError(val.ClientCtx.Codec.UnmarshalJSON(out.Bytes(), &txResp), out.String()) s.Require().Equal(uint32(0), txResp.Code, out.String()) diff --git a/x/group/keeper/keeper_test.go b/x/group/keeper/keeper_test.go index 84ee34bcdf81..c82ad1b1e49b 100644 --- a/x/group/keeper/keeper_test.go +++ b/x/group/keeper/keeper_test.go @@ -2829,7 +2829,6 @@ func (s *TestSuite) TestLeaveGroup() { } } - func (s *TestSuite) TestPruneProposals() { addrs := s.addrs expirationTime := time.Hour * 24 * 15 // 15 days diff --git a/x/group/keeper/msg_server.go b/x/group/keeper/msg_server.go index 6a25c5dce3f1..b732e958cab6 100644 --- a/x/group/keeper/msg_server.go +++ b/x/group/keeper/msg_server.go @@ -161,7 +161,7 @@ func (k Keeper) UpdateGroupMembers(goCtx context.Context, req *group.MsgUpdateGr if err != nil { return err } - // Substract previous weight from the group total weight. + // Subtract previous weight from the group total weight. totalWeight, err = math.SubNonNegative(totalWeight, previousMemberWeight) if err != nil { return err diff --git a/x/params/module.go b/x/params/module.go index 6df8b234d3df..87c463883bc6 100644 --- a/x/params/module.go +++ b/x/params/module.go @@ -174,7 +174,6 @@ func provideModule( cdc codec.Codec, amino *codec.LegacyAmino, ) (keeper.Keeper, runtime.AppModuleWrapper, runtime.BaseAppOption) { - k := keeper.NewKeeper(cdc, amino, kvStoreKey, transientStoreKey) m := NewAppModule(k) baseappOpt := func(app *baseapp.BaseApp) { From 984e8802ca85d51bec3cc06ed0ed48ae85631780 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 18:37:45 +0700 Subject: [PATCH 11/27] this lints the db module, and makes it easier to use. It adds breaking name changes --- db/adapter.go | 4 +- db/badgerdb/db.go | 16 ++++---- db/dbtest/benchmark.go | 10 ++--- db/dbtest/testcases.go | 17 ++++---- db/dbtest/util.go | 2 +- db/memdb/db.go | 16 ++++---- db/prefix/prefix.go | 78 ++++++++++++++++++------------------ db/prefix/prefix_iterator.go | 2 +- db/types.go | 22 +++++----- 9 files changed, 83 insertions(+), 84 deletions(-) diff --git a/db/adapter.go b/db/adapter.go index 66aeee7e309e..1988e74af9d6 100644 --- a/db/adapter.go +++ b/db/adapter.go @@ -1,11 +1,11 @@ package db -type readerRWAdapter struct{ DBReader } +type readerRWAdapter struct{ Reader } // ReaderAsReadWriter returns a ReadWriter that forwards to a reader and errors if writes are // attempted. Can be used to pass a Reader when a ReadWriter is expected // but no writes will actually occur. -func ReaderAsReadWriter(r DBReader) DBReadWriter { +func ReaderAsReadWriter(r Reader) ReadWriter { return readerRWAdapter{r} } diff --git a/db/badgerdb/db.go b/db/badgerdb/db.go index 532216b88f63..5c697efe59ea 100644 --- a/db/badgerdb/db.go +++ b/db/badgerdb/db.go @@ -22,10 +22,10 @@ import ( var versionsFilename = "versions.csv" var ( - _ db.DBConnection = (*BadgerDB)(nil) - _ db.DBReader = (*badgerTxn)(nil) - _ db.DBWriter = (*badgerWriter)(nil) - _ db.DBReadWriter = (*badgerWriter)(nil) + _ db.Connection = (*BadgerDB)(nil) + _ db.Reader = (*badgerTxn)(nil) + _ db.Writer = (*badgerWriter)(nil) + _ db.ReadWriter = (*badgerWriter)(nil) ) // BadgerDB is a connection to a BadgerDB key-value database. @@ -164,14 +164,14 @@ func writeVersionsFile(vm *versionManager, path string) error { return w.WriteAll(rows) } -func (b *BadgerDB) Reader() db.DBReader { +func (b *BadgerDB) Reader() db.Reader { b.mtx.RLock() ts := b.vmgr.lastTs b.mtx.RUnlock() return &badgerTxn{txn: b.db.NewTransactionAt(ts, false), db: b} } -func (b *BadgerDB) ReaderAt(version uint64) (db.DBReader, error) { +func (b *BadgerDB) ReaderAt(version uint64) (db.Reader, error) { b.mtx.RLock() defer b.mtx.RUnlock() ts, has := b.vmgr.versionTs(version) @@ -181,7 +181,7 @@ func (b *BadgerDB) ReaderAt(version uint64) (db.DBReader, error) { return &badgerTxn{txn: b.db.NewTransactionAt(ts, false), db: b}, nil } -func (b *BadgerDB) ReadWriter() db.DBReadWriter { +func (b *BadgerDB) ReadWriter() db.ReadWriter { atomic.AddInt32(&b.openWriters, 1) b.mtx.RLock() ts := b.vmgr.lastTs @@ -189,7 +189,7 @@ func (b *BadgerDB) ReadWriter() db.DBReadWriter { return &badgerWriter{badgerTxn{txn: b.db.NewTransactionAt(ts, true), db: b}, false} } -func (b *BadgerDB) Writer() db.DBWriter { +func (b *BadgerDB) Writer() db.Writer { // Badger has a WriteBatch, but it doesn't support conflict detection return b.ReadWriter() } diff --git a/db/dbtest/benchmark.go b/db/dbtest/benchmark.go index 680dcabbc0fc..cb4a77ba5a81 100644 --- a/db/dbtest/benchmark.go +++ b/db/dbtest/benchmark.go @@ -21,7 +21,7 @@ func BytesToInt64(buf []byte) int64 { return int64(binary.BigEndian.Uint64(buf)) } -func BenchmarkRangeScans(b *testing.B, db dbm.DBReadWriter, dbSize int64) { +func BenchmarkRangeScans(b *testing.B, db dbm.ReadWriter, dbSize int64) { b.StopTimer() rangeSize := int64(10000) @@ -40,7 +40,7 @@ func BenchmarkRangeScans(b *testing.B, db dbm.DBReadWriter, dbSize int64) { b.StartTimer() for i := 0; i < b.N; i++ { - start := rand.Int63n(dbSize - rangeSize) // nolint: gosec + start := rand.Int63n(dbSize - rangeSize) end := start + rangeSize iter, err := db.Iterator(Int64ToBytes(start), Int64ToBytes(end)) require.NoError(b, err) @@ -53,7 +53,7 @@ func BenchmarkRangeScans(b *testing.B, db dbm.DBReadWriter, dbSize int64) { } } -func BenchmarkRandomReadsWrites(b *testing.B, db dbm.DBReadWriter) { +func BenchmarkRandomReadsWrites(b *testing.B, db dbm.ReadWriter) { b.StopTimer() // create dummy data @@ -67,7 +67,7 @@ func BenchmarkRandomReadsWrites(b *testing.B, db dbm.DBReadWriter) { for i := 0; i < b.N; i++ { { - idx := rand.Int63n(numItems) // nolint: gosec + idx := rand.Int63n(numItems) internal[idx]++ val := internal[idx] idxBytes := Int64ToBytes(idx) @@ -80,7 +80,7 @@ func BenchmarkRandomReadsWrites(b *testing.B, db dbm.DBReadWriter) { } { - idx := rand.Int63n(numItems) // nolint: gosec + idx := rand.Int63n(numItems) valExp := internal[idx] idxBytes := Int64ToBytes(idx) valBytes, err := db.Get(idxBytes) diff --git a/db/dbtest/testcases.go b/db/dbtest/testcases.go index dde135fa36e1..d80196a1b400 100644 --- a/db/dbtest/testcases.go +++ b/db/dbtest/testcases.go @@ -11,7 +11,7 @@ import ( dbm "github.com/cosmos/cosmos-sdk/db" ) -type Loader func(*testing.T, string) dbm.DBConnection +type Loader func(*testing.T, string) dbm.Connection func ikey(i int) []byte { return []byte(fmt.Sprintf("key-%03d", i)) } func ival(i int) []byte { return []byte(fmt.Sprintf("val-%03d", i)) } @@ -20,10 +20,9 @@ func DoTestGetSetHasDelete(t *testing.T, load Loader) { t.Helper() db := load(t, t.TempDir()) - var txn dbm.DBReadWriter - var view dbm.DBReader + var txn dbm.ReadWriter + view := db.Reader() - view = db.Reader() require.NotNil(t, view) // A nonexistent key should return nil. @@ -261,11 +260,11 @@ func DoTestVersioning(t *testing.T, load Loader) { require.False(t, has) require.NoError(t, view.Discard()) - view, err = db.ReaderAt(versions.Last() + 1) + view, err = db.ReaderAt(versions.Last() + 1) //nolint:staticcheck // we nolint here because we are checking for the absence of an error. require.Equal(t, dbm.ErrVersionDoesNotExist, err, "should fail to read a nonexistent version") require.NoError(t, db.DeleteVersion(v2), "should delete version v2") - view, err = db.ReaderAt(v2) + view, err = db.ReaderAt(v2) //nolint:staticcheck // we nolint here because we are checking for the absence of an error. require.Equal(t, dbm.ErrVersionDoesNotExist, err) // Ensure latest version is accurate @@ -298,9 +297,9 @@ func DoTestTransactions(t *testing.T, load Loader, multipleWriters bool) { t.Helper() db := load(t, t.TempDir()) // Both methods should work in a DBWriter context - writerFuncs := []func() dbm.DBWriter{ + writerFuncs := []func() dbm.Writer{ db.Writer, - func() dbm.DBWriter { return db.ReadWriter() }, + func() dbm.Writer { return db.ReadWriter() }, } for _, getWriter := range writerFuncs { @@ -397,7 +396,7 @@ func DoTestRevert(t *testing.T, load Loader, reload bool) { t.Helper() dirname := t.TempDir() db := load(t, dirname) - var txn dbm.DBWriter + var txn dbm.Writer initContents := func() { txn = db.Writer() diff --git a/db/dbtest/util.go b/db/dbtest/util.go index e57c13afaefd..66bc208bf7ad 100644 --- a/db/dbtest/util.go +++ b/db/dbtest/util.go @@ -39,7 +39,7 @@ func AssertKeyPanics(t *testing.T, itr dbm.Iterator) { assert.Panics(t, func() { itr.Key() }, "checkKeyPanics expected panic but didn't") } -func AssertValue(t *testing.T, db dbm.DBReader, key, valueWanted []byte) { +func AssertValue(t *testing.T, db dbm.Reader, key, valueWanted []byte) { t.Helper() valueGot, err := db.Get(key) assert.NoError(t, err) diff --git a/db/memdb/db.go b/db/memdb/db.go index c3c83d525037..498d8e1903f5 100644 --- a/db/memdb/db.go +++ b/db/memdb/db.go @@ -43,10 +43,10 @@ type dbTxn struct { type dbWriter struct{ dbTxn } var ( - _ db.DBConnection = (*MemDB)(nil) - _ db.DBReader = (*dbTxn)(nil) - _ db.DBWriter = (*dbWriter)(nil) - _ db.DBReadWriter = (*dbWriter)(nil) + _ db.Connection = (*MemDB)(nil) + _ db.Reader = (*dbTxn)(nil) + _ db.Writer = (*dbWriter)(nil) + _ db.ReadWriter = (*dbWriter)(nil) ) // item is a btree.Item with byte slices as keys and values @@ -84,7 +84,7 @@ func (dbm *MemDB) Versions() (db.VersionSet, error) { } // Reader implements DBConnection. -func (dbm *MemDB) Reader() db.DBReader { +func (dbm *MemDB) Reader() db.Reader { dbm.mtx.RLock() defer dbm.mtx.RUnlock() ret := dbm.newTxn(dbm.btree) @@ -92,7 +92,7 @@ func (dbm *MemDB) Reader() db.DBReader { } // ReaderAt implements DBConnection. -func (dbm *MemDB) ReaderAt(version uint64) (db.DBReader, error) { +func (dbm *MemDB) ReaderAt(version uint64) (db.Reader, error) { dbm.mtx.RLock() defer dbm.mtx.RUnlock() tree, ok := dbm.saved[version] @@ -104,12 +104,12 @@ func (dbm *MemDB) ReaderAt(version uint64) (db.DBReader, error) { } // Writer implements DBConnection. -func (dbm *MemDB) Writer() db.DBWriter { +func (dbm *MemDB) Writer() db.Writer { return dbm.ReadWriter() } // ReadWriter implements DBConnection. -func (dbm *MemDB) ReadWriter() db.DBReadWriter { +func (dbm *MemDB) ReadWriter() db.ReadWriter { dbm.mtx.RLock() defer dbm.mtx.RUnlock() atomic.AddInt32(&dbm.openWriters, 1) diff --git a/db/prefix/prefix.go b/db/prefix/prefix.go index 3ddf1b41b4d0..9ff2f3e88368 100644 --- a/db/prefix/prefix.go +++ b/db/prefix/prefix.go @@ -7,51 +7,51 @@ import ( ) // prefixed Reader -type prefixR struct { - db db.DBReader +type Reader struct { + db db.Reader prefix []byte } // prefixed ReadWriter -type prefixRW struct { - db db.DBReadWriter +type ReadWriter struct { + db db.ReadWriter prefix []byte } // prefixed Writer -type prefixW struct { - db db.DBWriter +type Writer struct { + db db.Writer prefix []byte } var ( - _ db.DBReader = (*prefixR)(nil) - _ db.DBReadWriter = (*prefixRW)(nil) - _ db.DBWriter = (*prefixW)(nil) + _ db.Reader = (*Reader)(nil) + _ db.ReadWriter = (*ReadWriter)(nil) + _ db.Writer = (*Writer)(nil) ) -// NewPrefixReader returns a DBReader that only has access to the subset of DB keys +// NewReadereader returns a DBReader that only has access to the subset of DB keys // that contain the given prefix. -func NewPrefixReader(dbr db.DBReader, prefix []byte) prefixR { - return prefixR{ +func NewReadereader(dbr db.Reader, prefix []byte) Reader { + return Reader{ prefix: prefix, db: dbr, } } -// NewPrefixReadWriter returns a DBReader that only has access to the subset of DB keys +// NewReadereadWriter returns a DBReader that only has access to the subset of DB keys // that contain the given prefix. -func NewPrefixReadWriter(dbrw db.DBReadWriter, prefix []byte) prefixRW { - return prefixRW{ +func NewReadereadWriter(dbrw db.ReadWriter, prefix []byte) ReadWriter { + return ReadWriter{ prefix: prefix, db: dbrw, } } -// NewPrefixWriter returns a DBWriter that reads/writes only from the subset of DB keys +// NewWriterriter returns a DBWriter that reads/writes only from the subset of DB keys // that contain the given prefix -func NewPrefixWriter(dbw db.DBWriter, prefix []byte) prefixW { - return prefixW{ +func NewWriterriter(dbw db.Writer, prefix []byte) Writer { + return Writer{ prefix: prefix, db: dbw, } @@ -62,7 +62,7 @@ func prefixed(prefix, key []byte) []byte { } // Get implements DBReader. -func (pdb prefixR) Get(key []byte) ([]byte, error) { +func (pdb Reader) Get(key []byte) ([]byte, error) { if len(key) == 0 { return nil, db.ErrKeyEmpty } @@ -70,7 +70,7 @@ func (pdb prefixR) Get(key []byte) ([]byte, error) { } // Has implements DBReader. -func (pdb prefixR) Has(key []byte) (bool, error) { +func (pdb Reader) Has(key []byte) (bool, error) { if len(key) == 0 { return false, db.ErrKeyEmpty } @@ -78,7 +78,7 @@ func (pdb prefixR) Has(key []byte) (bool, error) { } // Iterator implements DBReader. -func (pdb prefixR) Iterator(start, end []byte) (db.Iterator, error) { +func (pdb Reader) Iterator(start, end []byte) (db.Iterator, error) { if (start != nil && len(start) == 0) || (end != nil && len(end) == 0) { return nil, db.ErrKeyEmpty } @@ -97,7 +97,7 @@ func (pdb prefixR) Iterator(start, end []byte) (db.Iterator, error) { } // ReverseIterator implements DBReader. -func (pdb prefixR) ReverseIterator(start, end []byte) (db.Iterator, error) { +func (pdb Reader) ReverseIterator(start, end []byte) (db.Iterator, error) { if (start != nil && len(start) == 0) || (end != nil && len(end) == 0) { return nil, db.ErrKeyEmpty } @@ -116,10 +116,10 @@ func (pdb prefixR) ReverseIterator(start, end []byte) (db.Iterator, error) { } // Discard implements DBReader. -func (pdb prefixR) Discard() error { return pdb.db.Discard() } +func (pdb Reader) Discard() error { return pdb.db.Discard() } // Set implements DBReadWriter. -func (pdb prefixRW) Set(key []byte, value []byte) error { +func (pdb ReadWriter) Set(key []byte, value []byte) error { if len(key) == 0 { return db.ErrKeyEmpty } @@ -127,7 +127,7 @@ func (pdb prefixRW) Set(key []byte, value []byte) error { } // Delete implements DBReadWriter. -func (pdb prefixRW) Delete(key []byte) error { +func (pdb ReadWriter) Delete(key []byte) error { if len(key) == 0 { return db.ErrKeyEmpty } @@ -135,33 +135,33 @@ func (pdb prefixRW) Delete(key []byte) error { } // Get implements DBReadWriter. -func (pdb prefixRW) Get(key []byte) ([]byte, error) { - return NewPrefixReader(pdb.db, pdb.prefix).Get(key) +func (pdb ReadWriter) Get(key []byte) ([]byte, error) { + return NewReadereader(pdb.db, pdb.prefix).Get(key) } // Has implements DBReadWriter. -func (pdb prefixRW) Has(key []byte) (bool, error) { - return NewPrefixReader(pdb.db, pdb.prefix).Has(key) +func (pdb ReadWriter) Has(key []byte) (bool, error) { + return NewReadereader(pdb.db, pdb.prefix).Has(key) } // Iterator implements DBReadWriter. -func (pdb prefixRW) Iterator(start, end []byte) (db.Iterator, error) { - return NewPrefixReader(pdb.db, pdb.prefix).Iterator(start, end) +func (pdb ReadWriter) Iterator(start, end []byte) (db.Iterator, error) { + return NewReadereader(pdb.db, pdb.prefix).Iterator(start, end) } // ReverseIterator implements DBReadWriter. -func (pdb prefixRW) ReverseIterator(start, end []byte) (db.Iterator, error) { - return NewPrefixReader(pdb.db, pdb.prefix).ReverseIterator(start, end) +func (pdb ReadWriter) ReverseIterator(start, end []byte) (db.Iterator, error) { + return NewReadereader(pdb.db, pdb.prefix).ReverseIterator(start, end) } // Close implements DBReadWriter. -func (pdb prefixRW) Commit() error { return pdb.db.Commit() } +func (pdb ReadWriter) Commit() error { return pdb.db.Commit() } // Discard implements DBReadWriter. -func (pdb prefixRW) Discard() error { return pdb.db.Discard() } +func (pdb ReadWriter) Discard() error { return pdb.db.Discard() } // Set implements DBReadWriter. -func (pdb prefixW) Set(key []byte, value []byte) error { +func (pdb Writer) Set(key []byte, value []byte) error { if len(key) == 0 { return db.ErrKeyEmpty } @@ -169,7 +169,7 @@ func (pdb prefixW) Set(key []byte, value []byte) error { } // Delete implements DBWriter. -func (pdb prefixW) Delete(key []byte) error { +func (pdb Writer) Delete(key []byte) error { if len(key) == 0 { return db.ErrKeyEmpty } @@ -177,10 +177,10 @@ func (pdb prefixW) Delete(key []byte) error { } // Close implements DBWriter. -func (pdb prefixW) Commit() error { return pdb.db.Commit() } +func (pdb Writer) Commit() error { return pdb.db.Commit() } // Discard implements DBReadWriter. -func (pdb prefixW) Discard() error { return pdb.db.Discard() } +func (pdb Writer) Discard() error { return pdb.db.Discard() } func cp(bz []byte) (ret []byte) { ret = make([]byte, len(bz)) diff --git a/db/prefix/prefix_iterator.go b/db/prefix/prefix_iterator.go index e7c2239dc05b..0a3a0fe1108e 100644 --- a/db/prefix/prefix_iterator.go +++ b/db/prefix/prefix_iterator.go @@ -9,7 +9,7 @@ import ( // IteratePrefix is a convenience function for iterating over a key domain // restricted by prefix. -func IteratePrefix(dbr db.DBReader, prefix []byte) (db.Iterator, error) { +func IteratePrefix(dbr db.Reader, prefix []byte) (db.Iterator, error) { var start, end []byte if len(prefix) != 0 { start = prefix diff --git a/db/types.go b/db/types.go index 39dc365925e6..fb062c37d022 100644 --- a/db/types.go +++ b/db/types.go @@ -30,19 +30,19 @@ var ( // Records are accessed via transaction objects, and must be safe for concurrent creation // and read and write access. // Past versions are only accessible read-only. -type DBConnection interface { +type Connection interface { // Reader opens a read-only transaction at the current working version. - Reader() DBReader + Reader() Reader // ReaderAt opens a read-only transaction at a specified version. // Returns ErrVersionDoesNotExist for invalid versions. - ReaderAt(uint64) (DBReader, error) + ReaderAt(uint64) (Reader, error) // ReadWriter opens a read-write transaction at the current version. - ReadWriter() DBReadWriter + ReadWriter() ReadWriter // Writer opens a write-only transaction at the current version. - Writer() DBWriter + Writer() Writer // Versions returns all saved versions as an immutable set which is safe for concurrent access. Versions() (VersionSet, error) @@ -74,7 +74,7 @@ type DBConnection interface { // // Keys cannot be nil or empty, while values cannot be nil. Keys and values should be considered // read-only, both when returned and when given, and must be copied before they are modified. -type DBReader interface { +type Reader interface { // Get fetches the value of the given key, or nil if it does not exist. // CONTRACT: key, value readonly []byte Get([]byte) ([]byte, error) @@ -110,7 +110,7 @@ type DBReader interface { // Callers must call Commit or Discard when done with the transaction. // // This can be used to wrap a write-optimized batch object if provided by the backend implementation. -type DBWriter interface { +type Writer interface { // Set sets the value for the given key, replacing it if it already exists. // CONTRACT: key, value readonly []byte Set([]byte, []byte) error @@ -127,9 +127,9 @@ type DBWriter interface { } // DBReadWriter is a transaction interface that allows both reading and writing. -type DBReadWriter interface { - DBReader - DBWriter +type ReadWriter interface { + Reader + Writer } // Iterator represents an iterator over a domain of keys. Callers must call Close when done. @@ -138,7 +138,7 @@ type DBReadWriter interface { // // Callers must make sure the iterator is valid before calling any methods on it, otherwise // these methods will panic. This is in part caused by most backend databases using this convention. -// Note that the iterator is invalid on contruction: Next() must be called to initialize it to its +// Note that the iterator is invalid on construction: Next() must be called to initialize it to its // starting position. // // As with DBReader, keys and values should be considered read-only, and must be copied before they are From ba145fb6cd59e78d3d33a6ca6106d2725a58a8bd Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 18:38:53 +0700 Subject: [PATCH 12/27] DBConnection -> Connection --- db/badgerdb/db_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/badgerdb/db_test.go b/db/badgerdb/db_test.go index 05d9cc4ba132..e043117c7a61 100644 --- a/db/badgerdb/db_test.go +++ b/db/badgerdb/db_test.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/db/dbtest" ) -func load(t *testing.T, dir string) db.DBConnection { +func load(t *testing.T, dir string) db.Connection { d, err := NewDB(dir) require.NoError(t, err) return d From 31743e383b700a728c9cfb4914dba5bd4f82f8b8 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 18:40:27 +0700 Subject: [PATCH 13/27] previous commit contained a merge error --- .../keys/secp256k1/internal/secp256k1/curve.go | 5 ----- simapp/test_helpers.go | 16 +++------------- types/kv/list.go | 4 ---- 3 files changed, 3 insertions(+), 22 deletions(-) diff --git a/crypto/keys/secp256k1/internal/secp256k1/curve.go b/crypto/keys/secp256k1/internal/secp256k1/curve.go index 797f9424c3e4..d83bf62ca2fe 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/curve.go +++ b/crypto/keys/secp256k1/internal/secp256k1/curve.go @@ -99,13 +99,8 @@ func (bitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { x3 := new(big.Int).Mul(x, x) // x² x3.Mul(x3, x) // x³ -<<<<<<< HEAD - x3.Add(x3, BitCurve.B) // x³+B - x3.Mod(x3, BitCurve.P) // (x³+B)%P -======= x3.Add(x3, bitCurve.B) // x³+B x3.Mod(x3, bitCurve.P) // (x³+B)%P ->>>>>>> f5978a59841173e88853ac228023991397be2e47 return x3.Cmp(y2) == 0 } diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 14cd21098e0f..4f0ab8263abc 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -10,13 +10,6 @@ import ( "testing" "time" -<<<<<<< HEAD - "github.com/cosmos/cosmos-sdk/depinject" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" -======= - ->>>>>>> 848b2f621471a72be41e4cb523a20f8d452e4a8e - "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmjson "github.com/tendermint/tendermint/libs/json" @@ -25,19 +18,15 @@ import ( tmtypes "github.com/tendermint/tendermint/types" dbm "github.com/tendermint/tm-db" - bam "github.com/cosmos/cosmos-sdk/baseapp" -<<<<<<< HEAD -======= "cosmossdk.io/math" ->>>>>>> f5978a59841173e88853ac228023991397be2e47 - "github.com/cosmos/cosmos-sdk/depinject" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + bam "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/depinject" "github.com/cosmos/cosmos-sdk/server/types" "github.com/cosmos/cosmos-sdk/simapp/helpers" "github.com/cosmos/cosmos-sdk/simapp/params" @@ -46,6 +35,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/errors" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" diff --git a/types/kv/list.go b/types/kv/list.go index 0fe721d87157..f038ccfa0ec0 100644 --- a/types/kv/list.go +++ b/types/kv/list.go @@ -113,10 +113,6 @@ func (l *List) remove(e *Element) *Element { } // move moves e to next to at and returns e. -<<<<<<< HEAD - -======= ->>>>>>> f5978a59841173e88853ac228023991397be2e47 func (l *List) move(e, at *Element) *Element { if e == at { return e From 631d6be6db6c7db583abb568a8b05e3100bc7f66 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 19:23:08 +0700 Subject: [PATCH 14/27] Update test_helpers.go --- simapp/test_helpers.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 6729eac361e0..06ff061a328e 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -20,8 +20,6 @@ import ( "cosmossdk.io/math" bam "github.com/cosmos/cosmos-sdk/baseapp" - "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/depinject" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" "github.com/cosmos/cosmos-sdk/client" codectypes "github.com/cosmos/cosmos-sdk/codec/types" From 0d566c578f06d3d03ebd35aac56010799ea36a9a Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 19:26:40 +0700 Subject: [PATCH 15/27] Update test_helpers.go --- simapp/test_helpers.go | 1 - 1 file changed, 1 deletion(-) diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 06ff061a328e..4f0ab8263abc 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -20,7 +20,6 @@ import ( "cosmossdk.io/math" bam "github.com/cosmos/cosmos-sdk/baseapp" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" "github.com/cosmos/cosmos-sdk/client" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" From e0392179c25f467187773a8b50ad8aa0d6afa2aa Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 20:43:48 +0700 Subject: [PATCH 16/27] db renamings --- db/README.md | 2 +- db/badgerdb/db.go | 6 +- db/memdb/db.go | 18 +++--- db/memdb/db_test.go | 2 +- db/prefix/prefix.go | 16 ++--- db/prefix/prefix_test.go | 12 ++-- db/rocksdb/db.go | 36 +++++------ db/rocksdb/db_test.go | 2 +- db/types.go | 2 +- docs/core/store.md | 2 +- store/v2alpha1/mem/store.go | 2 +- store/v2alpha1/multi/doc.go | 2 +- store/v2alpha1/multi/migration.go | 2 +- store/v2alpha1/multi/snapshot_test.go | 6 +- store/v2alpha1/multi/store.go | 66 ++++++++++---------- store/v2alpha1/multi/store_test.go | 10 +-- store/v2alpha1/multi/test_util.go | 36 +++++------ store/v2alpha1/multi/view_store.go | 10 +-- store/v2alpha1/smt/store.go | 24 +++---- store/v2alpha1/transient/store.go | 2 +- tests/mocks/db/types.go | 90 +++++++++++++-------------- x/feegrant/simulation/operations.go | 1 + 22 files changed, 175 insertions(+), 174 deletions(-) diff --git a/db/README.md b/db/README.md index 01471f144c61..d2ef4510ae59 100644 --- a/db/README.md +++ b/db/README.md @@ -6,7 +6,7 @@ Databases supporting mappings of arbitrary byte sequences. The database interface types consist of objects to encapsulate the singular connection to the DB, transactions being made to it, historical version state, and iteration. -### `DBConnection` +### `Connection` This interface represents a connection to a versioned key-value database. All versioning operations are performed using methods on this type. diff --git a/db/badgerdb/db.go b/db/badgerdb/db.go index 5c697efe59ea..f5757639ea11 100644 --- a/db/badgerdb/db.go +++ b/db/badgerdb/db.go @@ -201,7 +201,7 @@ func (b *BadgerDB) Close() error { return b.db.Close() } -// Versions implements DBConnection. +// Versions implements Connection. // Returns a VersionSet that is valid until the next call to SaveVersion or DeleteVersion. func (b *BadgerDB) Versions() (db.VersionSet, error) { b.mtx.RLock() @@ -219,12 +219,12 @@ func (b *BadgerDB) save(target uint64) (uint64, error) { return b.vmgr.Save(target) } -// SaveNextVersion implements DBConnection. +// SaveNextVersion implements Connection. func (b *BadgerDB) SaveNextVersion() (uint64, error) { return b.save(0) } -// SaveVersion implements DBConnection. +// SaveVersion implements Connection. func (b *BadgerDB) SaveVersion(target uint64) error { if target == 0 { return db.ErrInvalidVersion diff --git a/db/memdb/db.go b/db/memdb/db.go index 498d8e1903f5..fd558876ac3d 100644 --- a/db/memdb/db.go +++ b/db/memdb/db.go @@ -76,14 +76,14 @@ func (dbm *MemDB) Close() error { return nil } -// Versions implements DBConnection. +// Versions implements Connection. func (dbm *MemDB) Versions() (db.VersionSet, error) { dbm.mtx.RLock() defer dbm.mtx.RUnlock() return dbm.vmgr, nil } -// Reader implements DBConnection. +// Reader implements Connection. func (dbm *MemDB) Reader() db.Reader { dbm.mtx.RLock() defer dbm.mtx.RUnlock() @@ -91,7 +91,7 @@ func (dbm *MemDB) Reader() db.Reader { return &ret } -// ReaderAt implements DBConnection. +// ReaderAt implements Connection. func (dbm *MemDB) ReaderAt(version uint64) (db.Reader, error) { dbm.mtx.RLock() defer dbm.mtx.RUnlock() @@ -103,12 +103,12 @@ func (dbm *MemDB) ReaderAt(version uint64) (db.Reader, error) { return &ret, nil } -// Writer implements DBConnection. +// Writer implements Connection. func (dbm *MemDB) Writer() db.Writer { return dbm.ReadWriter() } -// ReadWriter implements DBConnection. +// ReadWriter implements Connection. func (dbm *MemDB) ReadWriter() db.ReadWriter { dbm.mtx.RLock() defer dbm.mtx.RUnlock() @@ -134,12 +134,12 @@ func (dbm *MemDB) save(target uint64) (uint64, error) { return target, nil } -// SaveVersion implements DBConnection. +// SaveVersion implements Connection. func (dbm *MemDB) SaveNextVersion() (uint64, error) { return dbm.save(0) } -// SaveNextVersion implements DBConnection. +// SaveNextVersion implements Connection. func (dbm *MemDB) SaveVersion(target uint64) error { if target == 0 { return db.ErrInvalidVersion @@ -148,7 +148,7 @@ func (dbm *MemDB) SaveVersion(target uint64) error { return err } -// DeleteVersion implements DBConnection. +// DeleteVersion implements Connection. func (dbm *MemDB) DeleteVersion(target uint64) error { dbm.mtx.Lock() defer dbm.mtx.Unlock() @@ -300,7 +300,7 @@ func (dbm *MemDB) Print() error { return nil } -// Stats implements DBConnection. +// Stats implements Connection. func (dbm *MemDB) Stats() map[string]string { dbm.mtx.RLock() defer dbm.mtx.RUnlock() diff --git a/db/memdb/db_test.go b/db/memdb/db_test.go index bef42d92a8a3..e330718ca6cb 100644 --- a/db/memdb/db_test.go +++ b/db/memdb/db_test.go @@ -28,7 +28,7 @@ func BenchmarkMemDBRandomReadsWrites(b *testing.B) { dbtest.BenchmarkRandomReadsWrites(b, dbm.ReadWriter()) } -func load(t *testing.T, _ string) db.DBConnection { +func load(t *testing.T, _ string) db.Connection { return NewDB() } diff --git a/db/prefix/prefix.go b/db/prefix/prefix.go index 9ff2f3e88368..2d218cedcbe5 100644 --- a/db/prefix/prefix.go +++ b/db/prefix/prefix.go @@ -32,16 +32,16 @@ var ( // NewReadereader returns a DBReader that only has access to the subset of DB keys // that contain the given prefix. -func NewReadereader(dbr db.Reader, prefix []byte) Reader { +func NewReader(dbr db.Reader, prefix []byte) Reader { return Reader{ prefix: prefix, db: dbr, } } -// NewReadereadWriter returns a DBReader that only has access to the subset of DB keys +// NewReadWriter returns a DBReader that only has access to the subset of DB keys // that contain the given prefix. -func NewReadereadWriter(dbrw db.ReadWriter, prefix []byte) ReadWriter { +func NewReadWriter(dbrw db.ReadWriter, prefix []byte) ReadWriter { return ReadWriter{ prefix: prefix, db: dbrw, @@ -50,7 +50,7 @@ func NewReadereadWriter(dbrw db.ReadWriter, prefix []byte) ReadWriter { // NewWriterriter returns a DBWriter that reads/writes only from the subset of DB keys // that contain the given prefix -func NewWriterriter(dbw db.Writer, prefix []byte) Writer { +func NewWriter(dbw db.Writer, prefix []byte) Writer { return Writer{ prefix: prefix, db: dbw, @@ -136,22 +136,22 @@ func (pdb ReadWriter) Delete(key []byte) error { // Get implements DBReadWriter. func (pdb ReadWriter) Get(key []byte) ([]byte, error) { - return NewReadereader(pdb.db, pdb.prefix).Get(key) + return NewReader(pdb.db, pdb.prefix).Get(key) } // Has implements DBReadWriter. func (pdb ReadWriter) Has(key []byte) (bool, error) { - return NewReadereader(pdb.db, pdb.prefix).Has(key) + return NewReader(pdb.db, pdb.prefix).Has(key) } // Iterator implements DBReadWriter. func (pdb ReadWriter) Iterator(start, end []byte) (db.Iterator, error) { - return NewReadereader(pdb.db, pdb.prefix).Iterator(start, end) + return NewReader(pdb.db, pdb.prefix).Iterator(start, end) } // ReverseIterator implements DBReadWriter. func (pdb ReadWriter) ReverseIterator(start, end []byte) (db.Iterator, error) { - return NewReadereader(pdb.db, pdb.prefix).ReverseIterator(start, end) + return NewReader(pdb.db, pdb.prefix).ReverseIterator(start, end) } // Close implements DBReadWriter. diff --git a/db/prefix/prefix_test.go b/db/prefix/prefix_test.go index 5394e75849a7..60247bf5515d 100644 --- a/db/prefix/prefix_test.go +++ b/db/prefix/prefix_test.go @@ -11,7 +11,7 @@ import ( pfx "github.com/cosmos/cosmos-sdk/db/prefix" ) -func fillDBWithStuff(t *testing.T, dbw db.DBWriter) { +func fillDBWithStuff(t *testing.T, dbw db.Writer) { // Under "key" prefix require.NoError(t, dbw.Set([]byte("key"), []byte("value"))) require.NoError(t, dbw.Set([]byte("key1"), []byte("value1"))) @@ -24,16 +24,16 @@ func fillDBWithStuff(t *testing.T, dbw db.DBWriter) { require.NoError(t, dbw.Commit()) } -func mockDBWithStuff(t *testing.T) db.DBConnection { +func mockDBWithStuff(t *testing.T) db.Connection { dbm := memdb.NewDB() fillDBWithStuff(t, dbm.Writer()) return dbm } -func makePrefixReader(t *testing.T, dbc db.DBConnection, pre []byte) db.DBReader { +func makePrefixReader(t *testing.T, dbc db.Connection, pre []byte) db.Reader { view := dbc.Reader() require.NotNil(t, view) - return pfx.NewPrefixReader(view, pre) + return pfx.NewReader(view, pre) } func TestPrefixDBSimple(t *testing.T) { @@ -137,7 +137,7 @@ func TestPrefixDBViewVersion(t *testing.T) { fillDBWithStuff(t, dbm.Writer()) id, err := dbm.SaveNextVersion() require.NoError(t, err) - pdb := pfx.NewPrefixReadWriter(dbm.ReadWriter(), prefix) + pdb := pfx.NewReadWriter(dbm.ReadWriter(), prefix) pdb.Set([]byte("1"), []byte("newvalue1")) pdb.Delete([]byte("2")) @@ -147,7 +147,7 @@ func TestPrefixDBViewVersion(t *testing.T) { dbview, err := dbm.ReaderAt(id) require.NotNil(t, dbview) require.NoError(t, err) - view := pfx.NewPrefixReader(dbview, prefix) + view := pfx.NewReader(dbview, prefix) require.NotNil(t, view) defer view.Discard() diff --git a/db/rocksdb/db.go b/db/rocksdb/db.go index 32a82f817647..3f1e259fdf81 100644 --- a/db/rocksdb/db.go +++ b/db/rocksdb/db.go @@ -22,17 +22,17 @@ var ( ) var ( - _ db.DBConnection = (*RocksDB)(nil) - _ db.DBReader = (*dbTxn)(nil) - _ db.DBWriter = (*dbWriter)(nil) - _ db.DBReadWriter = (*dbWriter)(nil) + _ db.Connection = (*RocksDB)(nil) + _ db.Reader = (*dbTxn)(nil) + _ db.Writer = (*dbWriter)(nil) + _ db.ReadWriter = (*dbWriter)(nil) ) // RocksDB is a connection to a RocksDB key-value database. type RocksDB = dbManager type dbManager struct { - current *dbConnection + current *Connection dir string opts dbOptions vmgr *db.VersionManager @@ -42,7 +42,7 @@ type dbManager struct { cpCache checkpointCache } -type dbConnection = gorocksdb.OptimisticTransactionDB +type Connection = gorocksdb.OptimisticTransactionDB type checkpointCache struct { cache map[uint64]*cpCacheEntry @@ -50,7 +50,7 @@ type checkpointCache struct { } type cpCacheEntry struct { - cxn *dbConnection + cxn *Connection openCount uint } @@ -158,7 +158,7 @@ func (mgr *dbManager) checkpointPath(version uint64) (string, error) { return dbPath, nil } -func (mgr *dbManager) openCheckpoint(version uint64) (*dbConnection, error) { +func (mgr *dbManager) openCheckpoint(version uint64) (*Connection, error) { mgr.cpCache.mtx.Lock() defer mgr.cpCache.mtx.Unlock() cp, has := mgr.cpCache.cache[version] @@ -178,7 +178,7 @@ func (mgr *dbManager) openCheckpoint(version uint64) (*dbConnection, error) { return db, nil } -func (mgr *dbManager) Reader() db.DBReader { +func (mgr *dbManager) Reader() db.Reader { mgr.mtx.RLock() defer mgr.mtx.RUnlock() return &dbTxn{ @@ -189,7 +189,7 @@ func (mgr *dbManager) Reader() db.DBReader { } } -func (mgr *dbManager) ReaderAt(version uint64) (db.DBReader, error) { +func (mgr *dbManager) ReaderAt(version uint64) (db.Reader, error) { mgr.mtx.RLock() defer mgr.mtx.RUnlock() d, err := mgr.openCheckpoint(version) @@ -204,7 +204,7 @@ func (mgr *dbManager) ReaderAt(version uint64) (db.DBReader, error) { }, nil } -func (mgr *dbManager) ReadWriter() db.DBReadWriter { +func (mgr *dbManager) ReadWriter() db.ReadWriter { mgr.mtx.RLock() defer mgr.mtx.RUnlock() atomic.AddInt32(&mgr.openWriters, 1) @@ -214,7 +214,7 @@ func (mgr *dbManager) ReadWriter() db.DBReadWriter { }} } -func (mgr *dbManager) Writer() db.DBWriter { +func (mgr *dbManager) Writer() db.Writer { mgr.mtx.RLock() defer mgr.mtx.RUnlock() atomic.AddInt32(&mgr.openWriters, 1) @@ -227,12 +227,12 @@ func (mgr *dbManager) Versions() (db.VersionSet, error) { return mgr.vmgr, nil } -// SaveNextVersion implements DBConnection. +// SaveNextVersion implements Connection. func (mgr *dbManager) SaveNextVersion() (uint64, error) { return mgr.save(0) } -// SaveVersion implements DBConnection. +// SaveVersion implements Connection. func (mgr *dbManager) SaveVersion(target uint64) error { if target == 0 { return db.ErrInvalidVersion @@ -321,14 +321,14 @@ func (mgr *dbManager) restoreFromCheckpoint(version uint64, path string) error { return nil } -// Close implements DBConnection. +// Close implements Connection. func (mgr *dbManager) Close() error { mgr.current.Close() mgr.opts.destroy() return nil } -// Stats implements DBConnection. +// Stats implements Connection. func (mgr *dbManager) Stats() map[string]string { keys := []string{"rocksdb.stats"} stats := make(map[string]string, len(keys)) @@ -338,7 +338,7 @@ func (mgr *dbManager) Stats() map[string]string { return stats } -// Get implements DBReader. +// Get implements Reader. func (tx *dbTxn) Get(key []byte) ([]byte, error) { if tx.txn == nil { return nil, db.ErrTransactionClosed @@ -353,7 +353,7 @@ func (tx *dbTxn) Get(key []byte) ([]byte, error) { return moveSliceToBytes(res), nil } -// Get implements DBReader. +// Get implements Reader. func (tx *dbWriter) Get(key []byte) ([]byte, error) { if tx.txn == nil { return nil, db.ErrTransactionClosed diff --git a/db/rocksdb/db_test.go b/db/rocksdb/db_test.go index b6268c1ed586..69065c462e6a 100644 --- a/db/rocksdb/db_test.go +++ b/db/rocksdb/db_test.go @@ -13,7 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/db/dbtest" ) -func load(t *testing.T, dir string) db.DBConnection { +func load(t *testing.T, dir string) db.Connection { d, err := NewDB(dir) require.NoError(t, err) return d diff --git a/db/types.go b/db/types.go index fb062c37d022..a800672bebfe 100644 --- a/db/types.go +++ b/db/types.go @@ -26,7 +26,7 @@ var ( ErrInvalidVersion = errors.New("invalid version") ) -// DBConnection represents a connection to a versioned database. +// Connection represents a connection to a versioned database. // Records are accessed via transaction objects, and must be safe for concurrent creation // and read and write access. // Past versions are only accessible read-only. diff --git a/docs/core/store.md b/docs/core/store.md index b9f649b7f05a..5852f3a89c38 100644 --- a/docs/core/store.md +++ b/docs/core/store.md @@ -249,7 +249,7 @@ An interface providing only the basic CRUD functionality (`Get`, `Set`, `Has`, a This is the new interface (or, set of interfaces) for the main client store, replacing the role of `store/types.MultiStore` (v1). There are a few significant differences in behavior compared with v1: * Commits are atomic and are performed on the entire store state; individual substores cannot be committed separately and cannot have different version numbers. -* The store's current version and version history track that of the backing `db.DBConnection`. Past versions are accessible read-only. +* The store's current version and version history track that of the backing `db.Connection`. Past versions are accessible read-only. * The set of valid substores is defined at initialization and cannot be updated dynamically in an existing store instance. ### `CommitMultiStore` diff --git a/store/v2alpha1/mem/store.go b/store/v2alpha1/mem/store.go index 3c8fa82bbaba..47047f4f3516 100644 --- a/store/v2alpha1/mem/store.go +++ b/store/v2alpha1/mem/store.go @@ -17,7 +17,7 @@ var ( // commits and thus between blocks. State in Memory store is not committed as part of app state but maintained privately by each node type Store struct { dbadapter.Store - conn dbm.DBConnection + conn dbm.Connection } // NewStore constructs a new in-memory store. diff --git a/store/v2alpha1/multi/doc.go b/store/v2alpha1/multi/doc.go index 87f5b88705c9..5c0028d580cd 100644 --- a/store/v2alpha1/multi/doc.go +++ b/store/v2alpha1/multi/doc.go @@ -10,7 +10,7 @@ // // A declared persistent substore is initially empty and stores nothing in the backing DB until a value is set. // A non-empty store is stored within a prefixed subdomain of the backing DB (using db/prefix). -// If the MultiStore is configured to use a separate DBConnection for StateCommitmentDB, it will store the +// If the MultiStore is configured to use a separate Connection for StateCommitmentDB, it will store the // state commitment (SC) store (as an SMT) in subdomains there, and the "flat" state is stored in the main DB. // Each substore's SC is allocated as an independent SMT, and query proofs contain two components: a proof // of a key's (non)existence within the substore SMT, and a proof of the substore's existence within the diff --git a/store/v2alpha1/multi/migration.go b/store/v2alpha1/multi/migration.go index 7481b421ac3b..caaddbf45283 100644 --- a/store/v2alpha1/multi/migration.go +++ b/store/v2alpha1/multi/migration.go @@ -11,7 +11,7 @@ import ( ) // MigrateFromV1 will migrate the state from iavl to smt -func MigrateFromV1(rootMultiStore *v1Store.Store, store2db dbm.DBConnection, storeConfig StoreConfig) (*Store, error) { +func MigrateFromV1(rootMultiStore *v1Store.Store, store2db dbm.Connection, storeConfig StoreConfig) (*Store, error) { type namedStore struct { *iavl.Store name string diff --git a/store/v2alpha1/multi/snapshot_test.go b/store/v2alpha1/multi/snapshot_test.go index 77637910e768..94ecb890a128 100644 --- a/store/v2alpha1/multi/snapshot_test.go +++ b/store/v2alpha1/multi/snapshot_test.go @@ -35,7 +35,7 @@ func multiStoreConfig(t *testing.T, stores int) StoreConfig { return opts } -func newMultiStoreWithGeneratedData(t *testing.T, db dbm.DBConnection, stores int, storeKeys uint64) *Store { +func newMultiStoreWithGeneratedData(t *testing.T, db dbm.Connection, stores int, storeKeys uint64) *Store { cfg := multiStoreConfig(t, stores) store, err := NewStore(db, cfg) require.NoError(t, err) @@ -68,7 +68,7 @@ func newMultiStoreWithGeneratedData(t *testing.T, db dbm.DBConnection, stores in return store } -func newMultiStoreWithBasicData(t *testing.T, db dbm.DBConnection, stores int) *Store { +func newMultiStoreWithBasicData(t *testing.T, db dbm.Connection, stores int) *Store { cfg := multiStoreConfig(t, stores) store, err := NewStore(db, cfg) require.NoError(t, err) @@ -85,7 +85,7 @@ func newMultiStoreWithBasicData(t *testing.T, db dbm.DBConnection, stores int) * return store } -func newMultiStore(t *testing.T, db dbm.DBConnection, stores int) *Store { +func newMultiStore(t *testing.T, db dbm.Connection, stores int) *Store { cfg := multiStoreConfig(t, stores) store, err := NewStore(db, cfg) require.NoError(t, err) diff --git a/store/v2alpha1/multi/store.go b/store/v2alpha1/multi/store.go index e4eb13c7d9a1..353b6170cbe1 100644 --- a/store/v2alpha1/multi/store.go +++ b/store/v2alpha1/multi/store.go @@ -62,7 +62,7 @@ type StoreConfig struct { InitialVersion uint64 // The backing DB to use for the state commitment Merkle tree data. // If nil, Merkle data is stored in the state storage DB under a separate prefix. - StateCommitmentDB dbm.DBConnection + StateCommitmentDB dbm.Connection prefixRegistry PersistentCache types.MultiStorePersistentCache @@ -82,10 +82,10 @@ type StoreSchema map[string]types.StoreType // * The state commitment store of each substore consists of a independent SMT. // * The state commitment of the root store consists of a Merkle map of all registered persistent substore names to the root hash of their corresponding SMTs type Store struct { - stateDB dbm.DBConnection - stateTxn dbm.DBReadWriter - StateCommitmentDB dbm.DBConnection - stateCommitmentTxn dbm.DBReadWriter + stateDB dbm.Connection + stateTxn dbm.ReadWriter + StateCommitmentDB dbm.Connection + stateCommitmentTxn dbm.ReadWriter schema StoreSchema mem *mem.Store @@ -104,8 +104,8 @@ type Store struct { type substore struct { root *Store name string - dataBucket dbm.DBReadWriter - indexBucket dbm.DBReadWriter + dataBucket dbm.ReadWriter + indexBucket dbm.ReadWriter stateCommitmentStore *smt.Store } @@ -118,8 +118,8 @@ type cacheStore struct { // Read-only store for querying past versions type viewStore struct { - stateView dbm.DBReader - stateCommitmentView dbm.DBReader + stateView dbm.Reader + stateCommitmentView dbm.Reader substoreCache map[string]*viewSubstore schema StoreSchema } @@ -127,8 +127,8 @@ type viewStore struct { type viewSubstore struct { root *viewStore name string - dataBucket dbm.DBReader - indexBucket dbm.DBReader + dataBucket dbm.Reader + indexBucket dbm.Reader stateCommitmentStore *smt.Store } @@ -193,7 +193,7 @@ func (ss StoreSchema) equal(that StoreSchema) bool { } // Parses a schema from the DB -func readSavedSchema(bucket dbm.DBReader) (*prefixRegistry, error) { +func readSavedSchema(bucket dbm.Reader) (*prefixRegistry, error) { ret := prefixRegistry{StoreSchema: StoreSchema{}} it, err := bucket.Iterator(nil, nil) if err != nil { @@ -215,7 +215,7 @@ func readSavedSchema(bucket dbm.DBReader) (*prefixRegistry, error) { // NewStore constructs a MultiStore directly from a database. // Creates a new store if no data exists; otherwise loads existing data. -func NewStore(db dbm.DBConnection, opts StoreConfig) (ret *Store, err error) { +func NewStore(db dbm.Connection, opts StoreConfig) (ret *Store, err error) { versions, err := db.Versions() if err != nil { return @@ -277,7 +277,7 @@ func NewStore(db dbm.DBConnection, opts StoreConfig) (ret *Store, err error) { } // Now load the substore schema - schemaView := prefixdb.NewPrefixReader(ret.stateDB.Reader(), schemaPrefix) + schemaView := prefixdb.NewReader(ret.stateDB.Reader(), schemaPrefix) defer func() { if err != nil { err = util.CombineErrors(err, schemaView.Discard(), "schemaView.Discard also failed") @@ -309,7 +309,7 @@ func NewStore(db dbm.DBConnection, opts StoreConfig) (ret *Store, err error) { return } } - schemaWriter := prefixdb.NewPrefixWriter(ret.stateTxn, schemaPrefix) + schemaWriter := prefixdb.NewWriter(ret.stateTxn, schemaPrefix) it, err := schemaView.Iterator(nil, nil) if err != nil { return @@ -368,7 +368,7 @@ func (pr *prefixRegistry) migrate(store *Store, upgrades types.StoreUpgrades) er delete(pr.StoreSchema, key) pfx := substorePrefix(key) - subReader := prefixdb.NewPrefixReader(reader, pfx) + subReader := prefixdb.NewReader(reader, pfx) it, err := subReader.Iterator(nil, nil) if err != nil { return err @@ -378,7 +378,7 @@ func (pr *prefixRegistry) migrate(store *Store, upgrades types.StoreUpgrades) er } it.Close() if store.StateCommitmentDB != nil { - subReader = prefixdb.NewPrefixReader(scReader, pfx) + subReader = prefixdb.NewReader(scReader, pfx) it, err = subReader.Iterator(nil, nil) if err != nil { return err @@ -406,8 +406,8 @@ func (pr *prefixRegistry) migrate(store *Store, upgrades types.StoreUpgrades) er oldPrefix := substorePrefix(rename.OldKey) newPrefix := substorePrefix(rename.NewKey) - subReader := prefixdb.NewPrefixReader(reader, oldPrefix) - subWriter := prefixdb.NewPrefixWriter(store.stateTxn, newPrefix) + subReader := prefixdb.NewReader(reader, oldPrefix) + subWriter := prefixdb.NewWriter(store.stateTxn, newPrefix) it, err := subReader.Iterator(nil, nil) if err != nil { return err @@ -417,8 +417,8 @@ func (pr *prefixRegistry) migrate(store *Store, upgrades types.StoreUpgrades) er } it.Close() if store.StateCommitmentDB != nil { - subReader = prefixdb.NewPrefixReader(scReader, oldPrefix) - subWriter = prefixdb.NewPrefixWriter(store.stateCommitmentTxn, newPrefix) + subReader = prefixdb.NewReader(scReader, oldPrefix) + subWriter = prefixdb.NewWriter(store.stateCommitmentTxn, newPrefix) it, err = subReader.Iterator(nil, nil) if err != nil { return err @@ -483,8 +483,8 @@ func (rs *Store) getSubstore(key string) (*substore, error) { return cached, nil } pfx := substorePrefix(key) - stateRW := prefixdb.NewPrefixReadWriter(rs.stateTxn, pfx) - stateCommitmentRW := prefixdb.NewPrefixReadWriter(rs.stateCommitmentTxn, pfx) + stateRW := prefixdb.NewReadWriter(rs.stateTxn, pfx) + stateCommitmentRW := prefixdb.NewReadWriter(rs.stateCommitmentTxn, pfx) var stateCommitmentStore *smt.Store rootHash, err := stateRW.Get(substoreMerkleRootKey) @@ -494,15 +494,15 @@ func (rs *Store) getSubstore(key string) (*substore, error) { if rootHash != nil { stateCommitmentStore = loadSMT(stateCommitmentRW, rootHash) } else { - smtdb := prefixdb.NewPrefixReadWriter(stateCommitmentRW, smtPrefix) + smtdb := prefixdb.NewReadWriter(stateCommitmentRW, smtPrefix) stateCommitmentStore = smt.NewStore(smtdb) } return &substore{ root: rs, name: key, - dataBucket: prefixdb.NewPrefixReadWriter(stateRW, dataPrefix), - indexBucket: prefixdb.NewPrefixReadWriter(stateRW, indexPrefix), + dataBucket: prefixdb.NewReadWriter(stateRW, dataPrefix), + indexBucket: prefixdb.NewReadWriter(stateRW, indexPrefix), stateCommitmentStore: stateCommitmentStore, }, nil } @@ -510,10 +510,10 @@ func (rs *Store) getSubstore(key string) (*substore, error) { // Resets a substore's state after commit (because root stateTxn has been discarded) func (s *substore) refresh(rootHash []byte) { pfx := substorePrefix(s.name) - stateRW := prefixdb.NewPrefixReadWriter(s.root.stateTxn, pfx) - stateCommitmentRW := prefixdb.NewPrefixReadWriter(s.root.stateCommitmentTxn, pfx) - s.dataBucket = prefixdb.NewPrefixReadWriter(stateRW, dataPrefix) - s.indexBucket = prefixdb.NewPrefixReadWriter(stateRW, indexPrefix) + stateRW := prefixdb.NewReadWriter(s.root.stateTxn, pfx) + stateCommitmentRW := prefixdb.NewReadWriter(s.root.stateCommitmentTxn, pfx) + s.dataBucket = prefixdb.NewReadWriter(stateRW, dataPrefix) + s.indexBucket = prefixdb.NewReadWriter(stateRW, indexPrefix) s.stateCommitmentStore = loadSMT(stateCommitmentRW, rootHash) } @@ -584,7 +584,7 @@ func (s *Store) commit(target uint64) (id *types.CommitID, err error) { // Update substore Merkle roots for key, storeHash := range storeHashes { pfx := substorePrefix(key) - stateW := prefixdb.NewPrefixReadWriter(s.stateTxn, pfx) + stateW := prefixdb.NewReadWriter(s.stateTxn, pfx) if err = stateW.Set(substoreMerkleRootKey, storeHash); err != nil { return } @@ -816,8 +816,8 @@ func (rs *Store) Query(req abci.RequestQuery) (res abci.ResponseQuery) { return res } -func loadSMT(stateCommitmentTxn dbm.DBReadWriter, root []byte) *smt.Store { - smtdb := prefixdb.NewPrefixReadWriter(stateCommitmentTxn, smtPrefix) +func loadSMT(stateCommitmentTxn dbm.ReadWriter, root []byte) *smt.Store { + smtdb := prefixdb.NewReadWriter(stateCommitmentTxn, smtPrefix) return smt.LoadStore(smtdb, root) } diff --git a/store/v2alpha1/multi/store_test.go b/store/v2alpha1/multi/store_test.go index de09003518d0..9837a891ced9 100644 --- a/store/v2alpha1/multi/store_test.go +++ b/store/v2alpha1/multi/store_test.go @@ -47,7 +47,7 @@ func storeConfig123(t *testing.T) StoreConfig { return opts } -func newSubStoreWithData(t *testing.T, db dbm.DBConnection, storeData map[string]string) (*Store, types.KVStore) { +func newSubStoreWithData(t *testing.T, db dbm.Connection, storeData map[string]string) (*Store, types.KVStore) { root, err := NewStore(db, simpleStoreConfig(t)) require.NoError(t, err) @@ -259,7 +259,7 @@ func TestCommit(t *testing.T) { // test that we can recover from a failed commit testFailedCommit := func(t *testing.T, store *Store, - db dbm.DBConnection, + db dbm.Connection, opts StoreConfig, ) { if db == nil { @@ -299,7 +299,7 @@ func TestCommit(t *testing.T) { // committed data that belongs to no version: non-atomic behavior from the Store user's perspective. // So, that data must be reverted when the store is reloaded. t.Run("recover after failed SaveVersion and Revert", func(t *testing.T) { - var db dbm.DBConnection + var db dbm.Connection db = dbSaveVersionFails{memdb.NewDB()} // Revert should succeed in initial NewStore call, but fail during Commit db = dbRevertFails{db, []bool{false, true}} @@ -315,7 +315,7 @@ func TestCommit(t *testing.T) { testFailedCommit(t, store, nil, opts) }) t.Run("recover after failed StateCommitmentDB SaveVersion and Revert", func(t *testing.T) { - var db dbm.DBConnection + var db dbm.Connection db = dbSaveVersionFails{memdb.NewDB()} db = dbRevertFails{db, []bool{false, true}} opts.StateCommitmentDB = db @@ -406,7 +406,7 @@ func TestPruning(t *testing.T) { } for tci, tc := range testCases { - dbs := []dbm.DBConnection{memdb.NewDB(), memdb.NewDB()} + dbs := []dbm.Connection{memdb.NewDB(), memdb.NewDB()} opts := simpleStoreConfig(t) opts.Pruning = tc.PruningOptions opts.StateCommitmentDB = dbs[1] diff --git a/store/v2alpha1/multi/test_util.go b/store/v2alpha1/multi/test_util.go index a03d60f54f03..2fdaa3865606 100644 --- a/store/v2alpha1/multi/test_util.go +++ b/store/v2alpha1/multi/test_util.go @@ -8,34 +8,34 @@ import ( ) type ( - dbDeleteVersionFails struct{ dbm.DBConnection } - dbRWCommitFails struct{ dbm.DBConnection } - dbRWCrudFails struct{ dbm.DBConnection } - dbSaveVersionFails struct{ dbm.DBConnection } + dbDeleteVersionFails struct{ dbm.Connection } + dbRWCommitFails struct{ dbm.Connection } + dbRWCrudFails struct{ dbm.Connection } + dbSaveVersionFails struct{ dbm.Connection } dbRevertFails struct { - dbm.DBConnection + dbm.Connection // order of calls to fail on (eg. [1, 0] => first call fails; second succeeds) failOn []bool } ) type dbVersionsIs struct { - dbm.DBConnection + dbm.Connection vset dbm.VersionSet } type ( - dbVersionsFails struct{ dbm.DBConnection } - rwCommitFails struct{ dbm.DBReadWriter } + dbVersionsFails struct{ dbm.Connection } + rwCommitFails struct{ dbm.ReadWriter } rwCrudFails struct { - dbm.DBReadWriter + dbm.ReadWriter onKey []byte } ) func (dbVersionsFails) Versions() (dbm.VersionSet, error) { return nil, errors.New("dbVersionsFails") } func (db dbVersionsIs) Versions() (dbm.VersionSet, error) { return db.vset, nil } -func (db dbRWCrudFails) ReadWriter() dbm.DBReadWriter { - return rwCrudFails{db.DBConnection.ReadWriter(), nil} +func (db dbRWCrudFails) ReadWriter() dbm.ReadWriter { + return rwCrudFails{db.Connection.ReadWriter(), nil} } func (dbSaveVersionFails) SaveVersion(uint64) error { return errors.New("dbSaveVersionFails") } func (db dbRevertFails) Revert() error { @@ -46,7 +46,7 @@ func (db dbRevertFails) Revert() error { if fail { return errors.New("dbRevertFails") } - return db.DBConnection.Revert() + return db.Connection.Revert() } func (dbDeleteVersionFails) DeleteVersion(uint64) error { return errors.New("dbDeleteVersionFails") } func (tx rwCommitFails) Commit() error { @@ -54,34 +54,34 @@ func (tx rwCommitFails) Commit() error { return errors.New("rwCommitFails") } -func (db dbRWCommitFails) ReadWriter() dbm.DBReadWriter { - return rwCommitFails{db.DBConnection.ReadWriter()} +func (db dbRWCommitFails) ReadWriter() dbm.ReadWriter { + return rwCommitFails{db.Connection.ReadWriter()} } func (rw rwCrudFails) Get(k []byte) ([]byte, error) { if rw.onKey == nil || bytes.Equal(rw.onKey, k) { return nil, errors.New("rwCrudFails.Get") } - return rw.DBReadWriter.Get(k) + return rw.ReadWriter.Get(k) } func (rw rwCrudFails) Has(k []byte) (bool, error) { if rw.onKey == nil || bytes.Equal(rw.onKey, k) { return false, errors.New("rwCrudFails.Has") } - return rw.DBReadWriter.Has(k) + return rw.ReadWriter.Has(k) } func (rw rwCrudFails) Set(k []byte, v []byte) error { if rw.onKey == nil || bytes.Equal(rw.onKey, k) { return errors.New("rwCrudFails.Set") } - return rw.DBReadWriter.Set(k, v) + return rw.ReadWriter.Set(k, v) } func (rw rwCrudFails) Delete(k []byte) error { if rw.onKey == nil || bytes.Equal(rw.onKey, k) { return errors.New("rwCrudFails.Delete") } - return rw.DBReadWriter.Delete(k) + return rw.ReadWriter.Delete(k) } diff --git a/store/v2alpha1/multi/view_store.go b/store/v2alpha1/multi/view_store.go index d4b97325dd15..e75f2afd4101 100644 --- a/store/v2alpha1/multi/view_store.go +++ b/store/v2alpha1/multi/view_store.go @@ -123,7 +123,7 @@ func (store *Store) getView(version int64) (ret *viewStore, err error) { }() } // Now read this version's schema - schemaView := prefixdb.NewPrefixReader(stateView, schemaPrefix) + schemaView := prefixdb.NewReader(stateView, schemaPrefix) defer func() { if err != nil { err = util.CombineErrors(err, schemaView.Discard(), "schemaView.Discard also failed") @@ -162,8 +162,8 @@ func (vs *viewStore) getSubstore(key string) (*viewSubstore, error) { return cached, nil } pfx := substorePrefix(key) - stateR := prefixdb.NewPrefixReader(vs.stateView, pfx) - stateCommitmentR := prefixdb.NewPrefixReader(vs.stateCommitmentView, pfx) + stateR := prefixdb.NewReader(vs.stateView, pfx) + stateCommitmentR := prefixdb.NewReader(vs.stateCommitmentView, pfx) rootHash, err := stateR.Get(merkleRootKey) if err != nil { return nil, err @@ -171,8 +171,8 @@ func (vs *viewStore) getSubstore(key string) (*viewSubstore, error) { return &viewSubstore{ root: vs, name: key, - dataBucket: prefixdb.NewPrefixReader(stateR, dataPrefix), - indexBucket: prefixdb.NewPrefixReader(stateR, indexPrefix), + dataBucket: prefixdb.NewReader(stateR, dataPrefix), + indexBucket: prefixdb.NewReader(stateR, indexPrefix), stateCommitmentStore: loadSMT(dbm.ReaderAsReadWriter(stateCommitmentR), rootHash), }, nil } diff --git a/store/v2alpha1/smt/store.go b/store/v2alpha1/smt/store.go index c10f59f00262..e79173c32e18 100644 --- a/store/v2alpha1/smt/store.go +++ b/store/v2alpha1/smt/store.go @@ -30,19 +30,19 @@ var ( // Store Implements types.KVStore and CommitKVStore. type Store struct { tree *smt.SparseMerkleTree - values dbm.DBReadWriter + values dbm.ReadWriter // Map hashed keys back to preimage - preimages dbm.DBReadWriter + preimages dbm.ReadWriter } // An smt.MapStore that wraps Get to raise smt.InvalidKeyError; // smt.SparseMerkleTree expects this error to be returned when a key is not found -type dbMapStore struct{ dbm.DBReadWriter } +type dbMapStore struct{ dbm.ReadWriter } -func NewStore(db dbm.DBReadWriter) *Store { - nodes := prefix.NewPrefixReadWriter(db, nodesPrefix) - values := prefix.NewPrefixReadWriter(db, valuesPrefix) - preimages := prefix.NewPrefixReadWriter(db, preimagesPrefix) +func NewStore(db dbm.ReadWriter) *Store { + nodes := prefix.NewReadWriter(db, nodesPrefix) + values := prefix.NewReadWriter(db, valuesPrefix) + preimages := prefix.NewReadWriter(db, preimagesPrefix) return &Store{ tree: smt.NewSparseMerkleTree(dbMapStore{nodes}, dbMapStore{values}, sha256.New()), values: values, @@ -50,10 +50,10 @@ func NewStore(db dbm.DBReadWriter) *Store { } } -func LoadStore(db dbm.DBReadWriter, root []byte) *Store { - nodes := prefix.NewPrefixReadWriter(db, nodesPrefix) - values := prefix.NewPrefixReadWriter(db, valuesPrefix) - preimages := prefix.NewPrefixReadWriter(db, preimagesPrefix) +func LoadStore(db dbm.ReadWriter, root []byte) *Store { + nodes := prefix.NewReadWriter(db, nodesPrefix) + values := prefix.NewReadWriter(db, valuesPrefix) + preimages := prefix.NewReadWriter(db, preimagesPrefix) return &Store{ tree: smt.ImportSparseMerkleTree(dbMapStore{nodes}, dbMapStore{values}, sha256.New(), root), values: values, @@ -132,7 +132,7 @@ func (s *Store) Delete(key []byte) { } func (ms dbMapStore) Get(key []byte) ([]byte, error) { - val, err := ms.DBReadWriter.Get(key) + val, err := ms.ReadWriter.Get(key) if err != nil { return nil, err } diff --git a/store/v2alpha1/transient/store.go b/store/v2alpha1/transient/store.go index 586cc4e9d36e..8596a350f191 100644 --- a/store/v2alpha1/transient/store.go +++ b/store/v2alpha1/transient/store.go @@ -16,7 +16,7 @@ var ( // Store is a wrapper for a memory store which does not persist data. type Store struct { dbadapter.Store - conn dbm.DBConnection + conn dbm.Connection } // NewStore constructs a new transient store. diff --git a/tests/mocks/db/types.go b/tests/mocks/db/types.go index 269094f7d0d6..7b9429b59277 100644 --- a/tests/mocks/db/types.go +++ b/tests/mocks/db/types.go @@ -11,31 +11,31 @@ import ( gomock "github.com/golang/mock/gomock" ) -// MockDBConnection is a mock of DBConnection interface. -type MockDBConnection struct { +// MockConnection is a mock of Connection interface. +type MockConnection struct { ctrl *gomock.Controller - recorder *MockDBConnectionMockRecorder + recorder *MockConnectionMockRecorder } -// MockDBConnectionMockRecorder is the mock recorder for MockDBConnection. -type MockDBConnectionMockRecorder struct { - mock *MockDBConnection +// MockConnectionMockRecorder is the mock recorder for MockConnection. +type MockConnectionMockRecorder struct { + mock *MockConnection } -// NewMockDBConnection creates a new mock instance. -func NewMockDBConnection(ctrl *gomock.Controller) *MockDBConnection { - mock := &MockDBConnection{ctrl: ctrl} - mock.recorder = &MockDBConnectionMockRecorder{mock} +// NewMockConnection creates a new mock instance. +func NewMockConnection(ctrl *gomock.Controller) *MockConnection { + mock := &MockConnection{ctrl: ctrl} + mock.recorder = &MockConnectionMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockDBConnection) EXPECT() *MockDBConnectionMockRecorder { +func (m *MockConnection) EXPECT() *MockConnectionMockRecorder { return m.recorder } // Close mocks base method. -func (m *MockDBConnection) Close() error { +func (m *MockConnection) Close() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Close") ret0, _ := ret[0].(error) @@ -43,13 +43,13 @@ func (m *MockDBConnection) Close() error { } // Close indicates an expected call of Close. -func (mr *MockDBConnectionMockRecorder) Close() *gomock.Call { +func (mr *MockConnectionMockRecorder) Close() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockDBConnection)(nil).Close)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockConnection)(nil).Close)) } // DeleteVersion mocks base method. -func (m *MockDBConnection) DeleteVersion(arg0 uint64) error { +func (m *MockConnection) DeleteVersion(arg0 uint64) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteVersion", arg0) ret0, _ := ret[0].(error) @@ -57,56 +57,56 @@ func (m *MockDBConnection) DeleteVersion(arg0 uint64) error { } // DeleteVersion indicates an expected call of DeleteVersion. -func (mr *MockDBConnectionMockRecorder) DeleteVersion(arg0 interface{}) *gomock.Call { +func (mr *MockConnectionMockRecorder) DeleteVersion(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteVersion", reflect.TypeOf((*MockDBConnection)(nil).DeleteVersion), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteVersion", reflect.TypeOf((*MockConnection)(nil).DeleteVersion), arg0) } // ReadWriter mocks base method. -func (m *MockDBConnection) ReadWriter() db.DBReadWriter { +func (m *MockConnection) ReadWriter() db.ReadWriter { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ReadWriter") - ret0, _ := ret[0].(db.DBReadWriter) + ret0, _ := ret[0].(db.ReadWriter) return ret0 } // ReadWriter indicates an expected call of ReadWriter. -func (mr *MockDBConnectionMockRecorder) ReadWriter() *gomock.Call { +func (mr *MockConnectionMockRecorder) ReadWriter() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReadWriter", reflect.TypeOf((*MockDBConnection)(nil).ReadWriter)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReadWriter", reflect.TypeOf((*MockConnection)(nil).ReadWriter)) } // Reader mocks base method. -func (m *MockDBConnection) Reader() db.DBReader { +func (m *MockConnection) Reader() db.Reader { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Reader") - ret0, _ := ret[0].(db.DBReader) + ret0, _ := ret[0].(db.Reader) return ret0 } // Reader indicates an expected call of Reader. -func (mr *MockDBConnectionMockRecorder) Reader() *gomock.Call { +func (mr *MockConnectionMockRecorder) Reader() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Reader", reflect.TypeOf((*MockDBConnection)(nil).Reader)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Reader", reflect.TypeOf((*MockConnection)(nil).Reader)) } // ReaderAt mocks base method. -func (m *MockDBConnection) ReaderAt(arg0 uint64) (db.DBReader, error) { +func (m *MockConnection) ReaderAt(arg0 uint64) (db.Reader, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ReaderAt", arg0) - ret0, _ := ret[0].(db.DBReader) + ret0, _ := ret[0].(db.Reader) ret1, _ := ret[1].(error) return ret0, ret1 } // ReaderAt indicates an expected call of ReaderAt. -func (mr *MockDBConnectionMockRecorder) ReaderAt(arg0 interface{}) *gomock.Call { +func (mr *MockConnectionMockRecorder) ReaderAt(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReaderAt", reflect.TypeOf((*MockDBConnection)(nil).ReaderAt), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReaderAt", reflect.TypeOf((*MockConnection)(nil).ReaderAt), arg0) } // Revert mocks base method. -func (m *MockDBConnection) Revert() error { +func (m *MockConnection) Revert() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Revert") ret0, _ := ret[0].(error) @@ -114,13 +114,13 @@ func (m *MockDBConnection) Revert() error { } // Revert indicates an expected call of Revert. -func (mr *MockDBConnectionMockRecorder) Revert() *gomock.Call { +func (mr *MockConnectionMockRecorder) Revert() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Revert", reflect.TypeOf((*MockDBConnection)(nil).Revert)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Revert", reflect.TypeOf((*MockConnection)(nil).Revert)) } // SaveNextVersion mocks base method. -func (m *MockDBConnection) SaveNextVersion() (uint64, error) { +func (m *MockConnection) SaveNextVersion() (uint64, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SaveNextVersion") ret0, _ := ret[0].(uint64) @@ -129,13 +129,13 @@ func (m *MockDBConnection) SaveNextVersion() (uint64, error) { } // SaveNextVersion indicates an expected call of SaveNextVersion. -func (mr *MockDBConnectionMockRecorder) SaveNextVersion() *gomock.Call { +func (mr *MockConnectionMockRecorder) SaveNextVersion() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveNextVersion", reflect.TypeOf((*MockDBConnection)(nil).SaveNextVersion)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveNextVersion", reflect.TypeOf((*MockConnection)(nil).SaveNextVersion)) } // SaveVersion mocks base method. -func (m *MockDBConnection) SaveVersion(arg0 uint64) error { +func (m *MockConnection) SaveVersion(arg0 uint64) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SaveVersion", arg0) ret0, _ := ret[0].(error) @@ -143,13 +143,13 @@ func (m *MockDBConnection) SaveVersion(arg0 uint64) error { } // SaveVersion indicates an expected call of SaveVersion. -func (mr *MockDBConnectionMockRecorder) SaveVersion(arg0 interface{}) *gomock.Call { +func (mr *MockConnectionMockRecorder) SaveVersion(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveVersion", reflect.TypeOf((*MockDBConnection)(nil).SaveVersion), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveVersion", reflect.TypeOf((*MockConnection)(nil).SaveVersion), arg0) } // Versions mocks base method. -func (m *MockDBConnection) Versions() (db.VersionSet, error) { +func (m *MockConnection) Versions() (db.VersionSet, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Versions") ret0, _ := ret[0].(db.VersionSet) @@ -158,23 +158,23 @@ func (m *MockDBConnection) Versions() (db.VersionSet, error) { } // Versions indicates an expected call of Versions. -func (mr *MockDBConnectionMockRecorder) Versions() *gomock.Call { +func (mr *MockConnectionMockRecorder) Versions() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Versions", reflect.TypeOf((*MockDBConnection)(nil).Versions)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Versions", reflect.TypeOf((*MockConnection)(nil).Versions)) } // Writer mocks base method. -func (m *MockDBConnection) Writer() db.DBWriter { +func (m *MockConnection) Writer() db.Writer { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Writer") - ret0, _ := ret[0].(db.DBWriter) + ret0, _ := ret[0].(db.Writer) return ret0 } // Writer indicates an expected call of Writer. -func (mr *MockDBConnectionMockRecorder) Writer() *gomock.Call { +func (mr *MockConnectionMockRecorder) Writer() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Writer", reflect.TypeOf((*MockDBConnection)(nil).Writer)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Writer", reflect.TypeOf((*MockConnection)(nil).Writer)) } // MockDBReader is a mock of DBReader interface. diff --git a/x/feegrant/simulation/operations.go b/x/feegrant/simulation/operations.go index 021e5ee79c96..0a49f7f1f879 100644 --- a/x/feegrant/simulation/operations.go +++ b/x/feegrant/simulation/operations.go @@ -14,6 +14,7 @@ import ( ) // Simulation operation weights constants +//nolint:gosec // These aren't harcoded credentials. const ( OpWeightMsgGrantAllowance = "op_weight_msg_grant_fee_allowance" OpWeightMsgRevokeAllowance = "op_weight_msg_grant_revoke_allowance" From 343e5bf290c462f33b0c837114253eaf8da27101 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 20:58:48 +0700 Subject: [PATCH 17/27] merge master --- .../secp256k1/internal/secp256k1/curve.go | 44 +++++++++---------- store/v2alpha1/dbadapter/store.go | 2 +- store/v2alpha1/multi/store.go | 8 ++-- store/v2alpha1/smt/ics23.go | 4 +- 4 files changed, 29 insertions(+), 29 deletions(-) diff --git a/crypto/keys/secp256k1/internal/secp256k1/curve.go b/crypto/keys/secp256k1/internal/secp256k1/curve.go index d83bf62ca2fe..f1eeba8a10f3 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/curve.go +++ b/crypto/keys/secp256k1/internal/secp256k1/curve.go @@ -143,20 +143,20 @@ func (bitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { // addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and // (x2, y2, z2) and returns their sum, also in Jacobian form. -func (BitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) { +func (bitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) { // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl z1z1 := new(big.Int).Mul(z1, z1) - z1z1.Mod(z1z1, BitCurve.P) + z1z1.Mod(z1z1, bitCurve.P) z2z2 := new(big.Int).Mul(z2, z2) - z2z2.Mod(z2z2, BitCurve.P) + z2z2.Mod(z2z2, bitCurve.P) u1 := new(big.Int).Mul(x1, z2z2) - u1.Mod(u1, BitCurve.P) + u1.Mod(u1, bitCurve.P) u2 := new(big.Int).Mul(x2, z1z1) - u2.Mod(u2, BitCurve.P) + u2.Mod(u2, bitCurve.P) h := new(big.Int).Sub(u2, u1) if h.Sign() == -1 { - h.Add(h, BitCurve.P) + h.Add(h, bitCurve.P) } i := new(big.Int).Lsh(h, 1) i.Mul(i, i) @@ -164,13 +164,13 @@ func (BitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int s1 := new(big.Int).Mul(y1, z2) s1.Mul(s1, z2z2) - s1.Mod(s1, BitCurve.P) + s1.Mod(s1, bitCurve.P) s2 := new(big.Int).Mul(y2, z1) s2.Mul(s2, z1z1) - s2.Mod(s2, BitCurve.P) + s2.Mod(s2, bitCurve.P) r := new(big.Int).Sub(s2, s1) if r.Sign() == -1 { - r.Add(r, BitCurve.P) + r.Add(r, bitCurve.P) } r.Lsh(r, 1) v := new(big.Int).Mul(u1, i) @@ -180,7 +180,7 @@ func (BitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int x3.Sub(x3, j) x3.Sub(x3, v) x3.Sub(x3, v) - x3.Mod(x3, BitCurve.P) + x3.Mod(x3, bitCurve.P) y3 := new(big.Int).Set(r) v.Sub(v, x3) @@ -188,33 +188,33 @@ func (BitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int s1.Mul(s1, j) s1.Lsh(s1, 1) y3.Sub(y3, s1) - y3.Mod(y3, BitCurve.P) + y3.Mod(y3, bitCurve.P) z3 := new(big.Int).Add(z1, z2) z3.Mul(z3, z3) z3.Sub(z3, z1z1) if z3.Sign() == -1 { - z3.Add(z3, BitCurve.P) + z3.Add(z3, bitCurve.P) } z3.Sub(z3, z2z2) if z3.Sign() == -1 { - z3.Add(z3, BitCurve.P) + z3.Add(z3, bitCurve.P) } z3.Mul(z3, h) - z3.Mod(z3, BitCurve.P) + z3.Mod(z3, bitCurve.P) return x3, y3, z3 } // Double returns 2*(x,y) -func (BitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { +func (bitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { z1 := new(big.Int).SetInt64(1) - return BitCurve.affineFromJacobian(BitCurve.doubleJacobian(x1, y1, z1)) + return bitCurve.affineFromJacobian(bitCurve.doubleJacobian(x1, y1, z1)) } // doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and // returns its double, also in Jacobian form. -func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) { +func (bitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) { // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l a := new(big.Int).Mul(x, x) // X1² @@ -232,24 +232,24 @@ func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, x3 := new(big.Int).Mul(big.NewInt(2), d) // 2*D x3.Sub(f, x3) // F-2*D - x3.Mod(x3, BitCurve.P) + x3.Mod(x3, bitCurve.P) y3 := new(big.Int).Sub(d, x3) // D-X3 y3.Mul(e, y3) // E*(D-X3) y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) // E*(D-X3)-8*C - y3.Mod(y3, BitCurve.P) + y3.Mod(y3, bitCurve.P) z3 := new(big.Int).Mul(y, z) // Y1*Z1 z3.Mul(big.NewInt(2), z3) // 3*Y1*Z1 - z3.Mod(z3, BitCurve.P) + z3.Mod(z3, bitCurve.P) return x3, y3, z3 } // ScalarBaseMult returns k*G, where G is the base point of the group and k is // an integer in big-endian form. -func (BitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { - return BitCurve.ScalarMult(BitCurve.Gx, BitCurve.Gy, k) +func (bitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { + return bitCurve.ScalarMult(bitCurve.Gx, bitCurve.Gy, k) } // Marshal converts a point into the form specified in section 4.3.6 of ANSI diff --git a/store/v2alpha1/dbadapter/store.go b/store/v2alpha1/dbadapter/store.go index 1cbd6c83585b..d7096138836c 100644 --- a/store/v2alpha1/dbadapter/store.go +++ b/store/v2alpha1/dbadapter/store.go @@ -15,7 +15,7 @@ var _ types.KVStore = Store{} // Wrapper type for dbm.Db with implementation of KVStore type Store struct { - DB dbm.DBReadWriter + DB dbm.ReadWriter } // Get wraps the underlying DB's Get method panicing on error. diff --git a/store/v2alpha1/multi/store.go b/store/v2alpha1/multi/store.go index 353b6170cbe1..8b56a71e7d5c 100644 --- a/store/v2alpha1/multi/store.go +++ b/store/v2alpha1/multi/store.go @@ -729,7 +729,7 @@ func parsePath(path string) (storeName string, subpath string, err error) { // If latest-1 is not present, use latest (which must be present) // if you care to have the latest data to see a tx results, you must // explicitly set the height you want to see -func (rs *Store) Query(req abci.RequestQuery) (res abci.ResponseQuery) { +func (s *Store) Query(req abci.RequestQuery) (res abci.ResponseQuery) { if len(req.Data) == 0 { return sdkerrors.QueryResult(sdkerrors.Wrap(sdkerrors.ErrTxDecode, "query cannot be zero length"), false) } @@ -737,7 +737,7 @@ func (rs *Store) Query(req abci.RequestQuery) (res abci.ResponseQuery) { // if height is 0, use the latest height height := req.Height if height == 0 { - versions, err := rs.stateDB.Versions() + versions, err := s.stateDB.Versions() if err != nil { return sdkerrors.QueryResult(errors.New("failed to get version info"), false) } @@ -757,7 +757,7 @@ func (rs *Store) Query(req abci.RequestQuery) (res abci.ResponseQuery) { if err != nil { return sdkerrors.QueryResult(sdkerrors.Wrapf(err, "failed to parse path"), false) } - view, err := rs.getView(height) + view, err := s.getView(height) if err != nil { if errors.Is(err, dbm.ErrVersionDoesNotExist) { err = sdkerrors.ErrInvalidHeight @@ -765,7 +765,7 @@ func (rs *Store) Query(req abci.RequestQuery) (res abci.ResponseQuery) { return sdkerrors.QueryResult(sdkerrors.Wrapf(err, "failed to access height"), false) } - if _, has := rs.schema[storeName]; !has { + if _, has := s.schema[storeName]; !has { return sdkerrors.QueryResult(sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "no such store: %s", storeName), false) } substore, err := view.getSubstore(storeName) diff --git a/store/v2alpha1/smt/ics23.go b/store/v2alpha1/smt/ics23.go index 3c4299227298..43b75a19788f 100644 --- a/store/v2alpha1/smt/ics23.go +++ b/store/v2alpha1/smt/ics23.go @@ -31,7 +31,7 @@ func createIcs23Proof(store *Store, key []byte) (*ics23.CommitmentProof, error) if err != nil { return nil, err } - ret.Proof = &ics23.CommitmentProof_Exist{&ics23.ExistenceProof{ + ret.Proof = &ics23.CommitmentProof_Exist{Exist: &ics23.ExistenceProof{ Key: path[:], Value: value, Leaf: ics23.SmtSpec.LeafSpec, @@ -42,7 +42,7 @@ func createIcs23Proof(store *Store, key []byte) (*ics23.CommitmentProof, error) if err != nil { return nil, err } - ret.Proof = &ics23.CommitmentProof_Nonexist{nonexist} + ret.Proof = &ics23.CommitmentProof_Nonexist{Nonexist: nonexist} } return ret, nil } From 9560aebda87bb525b10d41c04203f0650ec0dc40 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 21:04:01 +0700 Subject: [PATCH 18/27] changelog --- CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index afd9133aa7c1..cba07a1301d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,10 +48,12 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### API Breaking Changes * (x/staking) [#12102](https://github.com/cosmos/cosmos-sdk/pull/12102) Staking keeper now is passed by reference instead of copy. Keeper's SetHooks no longer returns keeper. It updates the keeper in place instead. +* (linting) [#12141](https://github.com/cosmos/cosmos-sdk/pull/12141) Fix usability related linting for database. This means removing the infix Prefix from `prefix.NewPrefixWriter` and such so that it is `prefix.NewWriter` and making `db.DBConnection` and such into `db.Connection` + ### Bug Fixes -* (linting) [#12135](https://github.com/cosmos/cosmos-sdk/pull/12135/) Fix variable naming issues per enabled linters. Run gofumpt to ensure easy reviews of ongoing linting work. +* (linting) [#12135](https://github.com/cosmos/cosmos-sdk/pull/12135) Fix variable naming issues per enabled linters. Run gofumpt to ensure easy reviews of ongoing linting work. * (linting) [#12132](https://github.com/cosmos/cosmos-sdk/pull/12132) Change sdk.Int to math.Int, run `gofumpt -w -l .`, and `golangci-lint run ./... --fix` * (cli) [#12127](https://github.com/cosmos/cosmos-sdk/pull/12127) Fix the CLI not always taking into account `--fee-payer` and `--fee-granter` flags. * (migrations) [#12028](https://github.com/cosmos/cosmos-sdk/pull/12028) Fix v0.45->v0.46 in-place store migrations. From 5a7b803062c0ddd787bc313c12fe129b8029a333 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 21:08:47 +0700 Subject: [PATCH 19/27] DBWriter -> Writer --- db/rocksdb/batch.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/rocksdb/batch.go b/db/rocksdb/batch.go index 7e19cae46d68..f551b442eb8c 100644 --- a/db/rocksdb/batch.go +++ b/db/rocksdb/batch.go @@ -15,7 +15,7 @@ type rocksDBBatch struct { mgr *dbManager } -var _ db.DBWriter = (*rocksDBBatch)(nil) +var _ db.Writer = (*rocksDBBatch)(nil) func (mgr *dbManager) newRocksDBBatch() *rocksDBBatch { return &rocksDBBatch{ From 520bf86267a9e948c432b53c38c8f324484520af Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 21:44:26 +0700 Subject: [PATCH 20/27] consistent multistore reciever --- db/rocksdb/batch.go | 8 +++--- store/v2alpha1/multi/store.go | 51 +++++++++++++++++------------------ 2 files changed, 29 insertions(+), 30 deletions(-) diff --git a/db/rocksdb/batch.go b/db/rocksdb/batch.go index f551b442eb8c..22818ed35d4e 100644 --- a/db/rocksdb/batch.go +++ b/db/rocksdb/batch.go @@ -24,7 +24,7 @@ func (mgr *dbManager) newRocksDBBatch() *rocksDBBatch { } } -// Set implements DBWriter. +// Set implements Writer. func (b *rocksDBBatch) Set(key, value []byte) error { if err := dbutil.ValidateKv(key, value); err != nil { return err @@ -36,7 +36,7 @@ func (b *rocksDBBatch) Set(key, value []byte) error { return nil } -// Delete implements DBWriter. +// Delete implements Writer. func (b *rocksDBBatch) Delete(key []byte) error { if len(key) == 0 { return db.ErrKeyEmpty @@ -48,7 +48,7 @@ func (b *rocksDBBatch) Delete(key []byte) error { return nil } -// Write implements DBWriter. +// Write implements Writer. func (b *rocksDBBatch) Commit() (err error) { if b.batch == nil { return db.ErrTransactionClosed @@ -58,7 +58,7 @@ func (b *rocksDBBatch) Commit() (err error) { return } -// Close implements DBWriter. +// Close implements Writer. func (b *rocksDBBatch) Discard() error { if b.batch != nil { defer atomic.AddInt32(&b.mgr.openWriters, -1) diff --git a/store/v2alpha1/multi/store.go b/store/v2alpha1/multi/store.go index 8b56a71e7d5c..c39b8e0e854c 100644 --- a/store/v2alpha1/multi/store.go +++ b/store/v2alpha1/multi/store.go @@ -296,12 +296,11 @@ func NewStore(db dbm.Connection, opts StoreConfig) (ret *Store, err error) { } reg.reserved = make([]string, len(opts.reserved)) copy(reg.reserved, opts.reserved) - } else { - if !reg.equal(opts.StoreSchema) { - err = errors.New("loaded schema does not match configured schema") - return - } + } else if !reg.equal(opts.StoreSchema) { + err = errors.New("loaded schema does not match configured schema") + return } + // Apply migrations, then clear old schema and write the new one for _, upgrades := range opts.Upgrades { err = reg.migrate(ret, upgrades) @@ -336,7 +335,7 @@ func NewStore(db dbm.Connection, opts StoreConfig) (ret *Store, err error) { } } ret.schema = reg.StoreSchema - return + return ret, err } func (s *Store) Close() error { @@ -444,18 +443,18 @@ func substorePrefix(key string) []byte { } // GetKVStore implements BasicMultiStore. -func (rs *Store) GetKVStore(skey types.StoreKey) types.KVStore { +func (s *Store) GetKVStore(skey types.StoreKey) types.KVStore { key := skey.Name() var parent types.KVStore - typ, has := rs.schema[key] + typ, has := s.schema[key] if !has { panic(ErrStoreNotFound(key)) } switch typ { case types.StoreTypeMemory: - parent = rs.mem + parent = s.mem case types.StoreTypeTransient: - parent = rs.tran + parent = s.tran case types.StoreTypePersistent: default: panic(fmt.Errorf("StoreType not supported: %v", typ)) // should never happen @@ -464,27 +463,27 @@ func (rs *Store) GetKVStore(skey types.StoreKey) types.KVStore { if parent != nil { // store is non-persistent ret = prefix.NewStore(parent, []byte(key)) } else { // store is persistent - sub, err := rs.getSubstore(key) + sub, err := s.getSubstore(key) if err != nil { panic(err) } - rs.substoreCache[key] = sub + s.substoreCache[key] = sub ret = sub } // Wrap with trace/listen if needed. Note: we don't cache this, so users must get a new substore after // modifying tracers/listeners. - return rs.wrapTraceListen(ret, skey) + return s.wrapTraceListen(ret, skey) } // Gets a persistent substore. This reads, but does not update the substore cache. // Use it in cases where we need to access a store internally (e.g. read/write Merkle keys, queries) -func (rs *Store) getSubstore(key string) (*substore, error) { - if cached, has := rs.substoreCache[key]; has { +func (s *Store) getSubstore(key string) (*substore, error) { + if cached, has := s.substoreCache[key]; has { return cached, nil } pfx := substorePrefix(key) - stateRW := prefixdb.NewReadWriter(rs.stateTxn, pfx) - stateCommitmentRW := prefixdb.NewReadWriter(rs.stateCommitmentTxn, pfx) + stateRW := prefixdb.NewReadWriter(s.stateTxn, pfx) + stateCommitmentRW := prefixdb.NewReadWriter(s.stateCommitmentTxn, pfx) var stateCommitmentStore *smt.Store rootHash, err := stateRW.Get(substoreMerkleRootKey) @@ -499,7 +498,7 @@ func (rs *Store) getSubstore(key string) (*substore, error) { } return &substore{ - root: rs, + root: s, name: key, dataBucket: prefixdb.NewReadWriter(stateRW, dataPrefix), indexBucket: prefixdb.NewReadWriter(stateRW, indexPrefix), @@ -671,20 +670,20 @@ func (s *Store) LastCommitID() types.CommitID { } // SetInitialVersion implements CommitMultiStore. -func (rs *Store) SetInitialVersion(version uint64) error { - rs.InitialVersion = uint64(version) +func (s *Store) SetInitialVersion(version uint64) error { + s.InitialVersion = version return nil } // GetVersion implements CommitMultiStore. -func (rs *Store) GetVersion(version int64) (types.BasicMultiStore, error) { - return rs.getView(version) +func (s *Store) GetVersion(version int64) (types.BasicMultiStore, error) { + return s.getView(version) } // CacheMultiStore implements BasicMultiStore. -func (rs *Store) CacheMultiStore() types.CacheMultiStore { +func (s *Store) CacheMultiStore() types.CacheMultiStore { return &cacheStore{ - source: rs, + source: s, substores: map[string]types.CacheKVStore{}, traceListenMixin: newTraceListenMixin(), } @@ -694,13 +693,13 @@ func (rs *Store) CacheMultiStore() types.CacheMultiStore { // If PruneNothing, this is a no-op. // If other strategy, this height is persisted until it is // less than - KeepRecent and % Interval == 0 -func (rs *Store) PruneSnapshotHeight(height int64) { +func (s *Store) PruneSnapshotHeight(height int64) { panic("not implemented") } // SetSnapshotInterval sets the interval at which the snapshots are taken. // It is used by the store to determine which heights to retain until after the snapshot is complete. -func (rs *Store) SetSnapshotInterval(snapshotInterval uint64) { +func (s *Store) SetSnapshotInterval(snapshotInterval uint64) { panic("not implemented") } From 8f175a3863da238f8988e26a8b42aac97a0060da Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 21:57:25 +0700 Subject: [PATCH 21/27] standard recievers for multistore v2alpha1 --- store/v2alpha1/multi/view_store.go | 32 +++++++++++++++--------------- x/gov/simulation/operations.go | 3 ++- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/store/v2alpha1/multi/view_store.go b/store/v2alpha1/multi/view_store.go index e75f2afd4101..b3d5acd58f4a 100644 --- a/store/v2alpha1/multi/view_store.go +++ b/store/v2alpha1/multi/view_store.go @@ -72,16 +72,16 @@ func (s *viewSubstore) GetStoreType() types.StoreType { return types.StoreTypePersistent } -func (st *viewSubstore) CacheWrap() types.CacheWrap { - return cachekv.NewStore(st) +func (s *viewSubstore) CacheWrap() types.CacheWrap { + return cachekv.NewStore(s) } -func (st *viewSubstore) CacheWrapWithTrace(w io.Writer, tc types.TraceContext) types.CacheWrap { - return cachekv.NewStore(tracekv.NewStore(st, w, tc)) +func (s *viewSubstore) CacheWrapWithTrace(w io.Writer, tc types.TraceContext) types.CacheWrap { + return cachekv.NewStore(tracekv.NewStore(s, w, tc)) } -func (st *viewSubstore) CacheWrapWithListeners(storeKey types.StoreKey, listeners []types.WriteListener) types.CacheWrap { - return cachekv.NewStore(listenkv.NewStore(st, storeKey, listeners)) +func (s *viewSubstore) CacheWrapWithListeners(storeKey types.StoreKey, listeners []types.WriteListener) types.CacheWrap { + return cachekv.NewStore(listenkv.NewStore(s, storeKey, listeners)) } func (s *viewStore) getMerkleRoots() (ret map[string][]byte, err error) { @@ -140,36 +140,36 @@ func (store *Store) getView(version int64) (ret *viewStore, err error) { substoreCache: map[string]*viewSubstore{}, schema: pr.StoreSchema, } - return + return ret, err } -func (vs *viewStore) GetKVStore(skey types.StoreKey) types.KVStore { +func (s *viewStore) GetKVStore(skey types.StoreKey) types.KVStore { key := skey.Name() - if _, has := vs.schema[key]; !has { + if _, has := s.schema[key]; !has { panic(ErrStoreNotFound(key)) } - ret, err := vs.getSubstore(key) + ret, err := s.getSubstore(key) if err != nil { panic(err) } - vs.substoreCache[key] = ret + s.substoreCache[key] = ret return ret } // Reads but does not update substore cache -func (vs *viewStore) getSubstore(key string) (*viewSubstore, error) { - if cached, has := vs.substoreCache[key]; has { +func (s *viewStore) getSubstore(key string) (*viewSubstore, error) { + if cached, has := s.substoreCache[key]; has { return cached, nil } pfx := substorePrefix(key) - stateR := prefixdb.NewReader(vs.stateView, pfx) - stateCommitmentR := prefixdb.NewReader(vs.stateCommitmentView, pfx) + stateR := prefixdb.NewReader(s.stateView, pfx) + stateCommitmentR := prefixdb.NewReader(s.stateCommitmentView, pfx) rootHash, err := stateR.Get(merkleRootKey) if err != nil { return nil, err } return &viewSubstore{ - root: vs, + root: s, name: key, dataBucket: prefixdb.NewReader(stateR, dataPrefix), indexBucket: prefixdb.NewReader(stateR, indexPrefix), diff --git a/x/gov/simulation/operations.go b/x/gov/simulation/operations.go index 289c9413d6cd..ff7fc4908a49 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" OpWeightMsgVote = "op_weight_msg_vote" @@ -436,7 +437,7 @@ func randomProposalID(r *rand.Rand, k keeper.Keeper, } proposal, ok := k.GetProposal(ctx, proposalID) - if !ok || v1.ProposalStatus(proposal.Status) != status { + if !ok || proposal.Status != status { return proposalID, false } From fcc514e6b3b47774d3f42a800c72b28d55535dd8 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Fri, 3 Jun 2022 22:20:09 +0700 Subject: [PATCH 22/27] general cleanup of linting issues --- .../internal/secp256k1/scalar_mult_cgo.go | 6 +- server/util.go | 2 +- simapp/app.go | 1 - store/v2alpha1/smt/store.go | 2 +- types/address.go | 4 +- x/authz/keeper/keeper.go | 22 +++---- x/authz/simulation/operations.go | 1 + x/distribution/simulation/operations.go | 1 + x/gov/keeper/keeper.go | 4 +- x/gov/types/v1/msgs.go | 4 +- x/gov/types/v1beta1/params.go | 58 ------------------- x/group/internal/orm/testsupport.go | 21 ++++--- x/group/simulation/operations.go | 1 + x/group/types.go | 18 +++--- x/simulation/simulate.go | 4 +- x/staking/simulation/operations.go | 1 + 16 files changed, 47 insertions(+), 103 deletions(-) diff --git a/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go b/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go index 8afa9d023b07..2fe30a4e1acc 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go +++ b/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go @@ -21,7 +21,7 @@ extern int secp256k1_ext_scalar_mul(const secp256k1_context* ctx, const unsigned */ import "C" -func (BitCurve *BitCurve) ScalarMult(Bx, By *big.Int, scalar []byte) (*big.Int, *big.Int) { +func (BitCurve *BitCurve) ScalarMult(bx, by *big.Int, scalar []byte) (*big.Int, *big.Int) { // Ensure scalar is exactly 32 bytes. We pad always, even if // scalar is 32 bytes long, to avoid a timing side channel. if len(scalar) > 32 { @@ -34,8 +34,8 @@ func (BitCurve *BitCurve) ScalarMult(Bx, By *big.Int, scalar []byte) (*big.Int, // Do the multiplication in C, updating point. point := make([]byte, 64) - readBits(Bx, point[:32]) - readBits(By, point[32:]) + readBits(bx, point[:32]) + readBits(by, point[32:]) pointPtr := (*C.uchar)(unsafe.Pointer(&point[0])) scalarPtr := (*C.uchar)(unsafe.Pointer(&scalar[0])) diff --git a/server/util.go b/server/util.go index bea9e16bfc91..a201442025a1 100644 --- a/server/util.go +++ b/server/util.go @@ -96,7 +96,7 @@ func bindFlags(basename string, cmd *cobra.Command, v *viper.Viper) (err error) } }) - return + return err } // InterceptConfigsPreRunHandler performs a pre-run function for the root daemon diff --git a/simapp/app.go b/simapp/app.go index 02d711bf1e83..f878620142ed 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -23,7 +23,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/runtime" - _ "github.com/cosmos/cosmos-sdk/runtime" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/api" "github.com/cosmos/cosmos-sdk/server/config" diff --git a/store/v2alpha1/smt/store.go b/store/v2alpha1/smt/store.go index e79173c32e18..deba9ff18b91 100644 --- a/store/v2alpha1/smt/store.go +++ b/store/v2alpha1/smt/store.go @@ -137,7 +137,7 @@ func (ms dbMapStore) Get(key []byte) ([]byte, error) { return nil, err } if val == nil { - return nil, &smt.InvalidKeyError{key} + return nil, &smt.InvalidKeyError{Key: key} } return val, nil } diff --git a/types/address.go b/types/address.go index 5e28d1e9f295..7adbef1a9961 100644 --- a/types/address.go +++ b/types/address.go @@ -195,7 +195,7 @@ func (aa AccAddress) Equals(aa2 Address) bool { // Returns boolean for whether an AccAddress is empty func (aa AccAddress) Empty() bool { - return aa == nil || len(aa) == 0 + return len(aa) == 0 } // Marshal returns the raw address bytes. It is needed for protobuf @@ -343,7 +343,7 @@ func (va ValAddress) Equals(va2 Address) bool { // Returns boolean for whether an AccAddress is empty func (va ValAddress) Empty() bool { - return va == nil || len(va) == 0 + return len(va) == 0 } // Marshal returns the raw address bytes. It is needed for protobuf diff --git a/x/authz/keeper/keeper.go b/x/authz/keeper/keeper.go index 137e07dc9444..7ae6b6675ce2 100644 --- a/x/authz/keeper/keeper.go +++ b/x/authz/keeper/keeper.go @@ -260,15 +260,15 @@ func (k Keeper) IterateGrants(ctx sdk.Context, } } -func (keeper Keeper) getGrantQueueItem(ctx sdk.Context, expiration time.Time, granter, grantee sdk.AccAddress) (*authz.GrantQueueItem, error) { - store := ctx.KVStore(keeper.storeKey) +func (k Keeper) getGrantQueueItem(ctx sdk.Context, expiration time.Time, granter, grantee sdk.AccAddress) (*authz.GrantQueueItem, error) { + store := ctx.KVStore(k.storeKey) bz := store.Get(GrantQueueKey(expiration, granter, grantee)) if bz == nil { return &authz.GrantQueueItem{}, nil } var queueItems authz.GrantQueueItem - if err := keeper.cdc.Unmarshal(bz, &queueItems); err != nil { + if err := k.cdc.Unmarshal(bz, &queueItems); err != nil { return nil, err } return &queueItems, nil @@ -288,27 +288,27 @@ func (k Keeper) setGrantQueueItem(ctx sdk.Context, expiration time.Time, } // insertIntoGrantQueue inserts a grant key into the grant queue -func (keeper Keeper) insertIntoGrantQueue(ctx sdk.Context, granter, grantee sdk.AccAddress, msgType string, expiration time.Time) error { - queueItems, err := keeper.getGrantQueueItem(ctx, expiration, granter, grantee) +func (k Keeper) insertIntoGrantQueue(ctx sdk.Context, granter, grantee sdk.AccAddress, msgType string, expiration time.Time) error { + queueItems, err := k.getGrantQueueItem(ctx, expiration, granter, grantee) if err != nil { return err } if len(queueItems.MsgTypeUrls) == 0 { - keeper.setGrantQueueItem(ctx, expiration, granter, grantee, &authz.GrantQueueItem{ + k.setGrantQueueItem(ctx, expiration, granter, grantee, &authz.GrantQueueItem{ MsgTypeUrls: []string{msgType}, }) } else { queueItems.MsgTypeUrls = append(queueItems.MsgTypeUrls, msgType) - keeper.setGrantQueueItem(ctx, expiration, granter, grantee, queueItems) + k.setGrantQueueItem(ctx, expiration, granter, grantee, queueItems) } return nil } // removeFromGrantQueue removes a grant key from the grant queue -func (keeper Keeper) removeFromGrantQueue(ctx sdk.Context, grantKey []byte, granter, grantee sdk.AccAddress, expiration time.Time) error { - store := ctx.KVStore(keeper.storeKey) +func (k Keeper) removeFromGrantQueue(ctx sdk.Context, grantKey []byte, granter, grantee sdk.AccAddress, expiration time.Time) error { + store := ctx.KVStore(k.storeKey) key := GrantQueueKey(expiration, granter, grantee) bz := store.Get(key) if bz == nil { @@ -316,7 +316,7 @@ func (keeper Keeper) removeFromGrantQueue(ctx sdk.Context, grantKey []byte, gran } var queueItem authz.GrantQueueItem - if err := keeper.cdc.Unmarshal(bz, &queueItem); err != nil { + if err := k.cdc.Unmarshal(bz, &queueItem); err != nil { return err } @@ -331,7 +331,7 @@ func (keeper Keeper) removeFromGrantQueue(ctx sdk.Context, grantKey []byte, gran queueItems[index] = queueItems[end] queueItems = queueItems[:end] - if err := keeper.setGrantQueueItem(ctx, expiration, granter, grantee, &authz.GrantQueueItem{ + if err := k.setGrantQueueItem(ctx, expiration, granter, grantee, &authz.GrantQueueItem{ MsgTypeUrls: queueItems, }); err != nil { return err diff --git a/x/authz/simulation/operations.go b/x/authz/simulation/operations.go index 956a7b4c325d..8886d2e654fd 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" OpWeightRevoke = "op_weight_msg_revoke" diff --git a/x/distribution/simulation/operations.go b/x/distribution/simulation/operations.go index ba21eb7828a9..d33b1b04d2bc 100644 --- a/x/distribution/simulation/operations.go +++ b/x/distribution/simulation/operations.go @@ -16,6 +16,7 @@ import ( ) // Simulation operation weights constants +//nolint:gosec // these are not hardcoded credentials. const ( OpWeightMsgSetWithdrawAddress = "op_weight_msg_set_withdraw_address" OpWeightMsgWithdrawDelegationReward = "op_weight_msg_withdraw_delegation_reward" diff --git a/x/gov/keeper/keeper.go b/x/gov/keeper/keeper.go index 4558075f48ac..d7496837c51e 100644 --- a/x/gov/keeper/keeper.go +++ b/x/gov/keeper/keeper.go @@ -199,8 +199,8 @@ func (keeper Keeper) InactiveProposalQueueIterator(ctx sdk.Context, endTime time // assertMetadataLength returns an error if given metadata length // is greater than a pre-defined maxMetadataLen. -func (k Keeper) assertMetadataLength(metadata string) error { - if metadata != "" && uint64(len(metadata)) > k.config.MaxMetadataLen { +func (keeper Keeper) assertMetadataLength(metadata string) error { + if metadata != "" && uint64(len(metadata)) > keeper.config.MaxMetadataLen { return types.ErrMetadataTooLong.Wrapf("got metadata with length %d", len(metadata)) } return nil diff --git a/x/gov/types/v1/msgs.go b/x/gov/types/v1/msgs.go index 1391cbf4c673..84b845c55732 100644 --- a/x/gov/types/v1/msgs.go +++ b/x/gov/types/v1/msgs.go @@ -256,7 +256,7 @@ func (c MsgExecLegacyContent) ValidateBasic() error { } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (m MsgExecLegacyContent) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { +func (c MsgExecLegacyContent) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { var content v1beta1.Content - return unpacker.UnpackAny(m.Content, &content) + return unpacker.UnpackAny(c.Content, &content) } diff --git a/x/gov/types/v1beta1/params.go b/x/gov/types/v1beta1/params.go index 98f9b0390cbd..a67d75f5e454 100644 --- a/x/gov/types/v1beta1/params.go +++ b/x/gov/types/v1beta1/params.go @@ -1,7 +1,6 @@ package v1beta1 import ( - "fmt" "time" "sigs.k8s.io/yaml" @@ -49,22 +48,6 @@ func (dp DepositParams) Equal(dp2 DepositParams) bool { return dp.MinDeposit.IsEqual(dp2.MinDeposit) && dp.MaxDepositPeriod == dp2.MaxDepositPeriod } -func validateDepositParams(i interface{}) error { - v, ok := i.(DepositParams) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if !v.MinDeposit.IsValid() { - return fmt.Errorf("invalid minimum deposit: %s", v.MinDeposit) - } - if v.MaxDepositPeriod <= 0 { - return fmt.Errorf("maximum deposit period must be positive: %d", v.MaxDepositPeriod) - } - - return nil -} - // NewTallyParams creates a new TallyParams object func NewTallyParams(quorum, threshold, vetoThreshold sdk.Dec) TallyParams { return TallyParams{ @@ -90,34 +73,6 @@ func (tp TallyParams) String() string { return string(out) } -func validateTallyParams(i interface{}) error { - v, ok := i.(TallyParams) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v.Quorum.IsNegative() { - return fmt.Errorf("quorom cannot be negative: %s", v.Quorum) - } - if v.Quorum.GT(sdk.OneDec()) { - return fmt.Errorf("quorom too large: %s", v) - } - if !v.Threshold.IsPositive() { - return fmt.Errorf("vote threshold must be positive: %s", v.Threshold) - } - if v.Threshold.GT(sdk.OneDec()) { - return fmt.Errorf("vote threshold too large: %s", v) - } - if !v.VetoThreshold.IsPositive() { - return fmt.Errorf("veto threshold must be positive: %s", v.Threshold) - } - if v.VetoThreshold.GT(sdk.OneDec()) { - return fmt.Errorf("veto threshold too large: %s", v) - } - - return nil -} - // NewVotingParams creates a new VotingParams object func NewVotingParams(votingPeriod time.Duration) VotingParams { return VotingParams{ @@ -141,19 +96,6 @@ func (vp VotingParams) String() string { return string(out) } -func validateVotingParams(i interface{}) error { - v, ok := i.(VotingParams) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v.VotingPeriod <= 0 { - return fmt.Errorf("voting period must be positive: %s", v.VotingPeriod) - } - - return nil -} - // Params returns all of the governance params type Params struct { VotingParams VotingParams `json:"voting_params" yaml:"voting_params"` diff --git a/x/group/internal/orm/testsupport.go b/x/group/internal/orm/testsupport.go index df95b0f27414..1b4a6847898a 100644 --- a/x/group/internal/orm/testsupport.go +++ b/x/group/internal/orm/testsupport.go @@ -5,7 +5,6 @@ import ( "github.com/cosmos/cosmos-sdk/store" "github.com/cosmos/cosmos-sdk/store/gaskv" - "github.com/cosmos/cosmos-sdk/store/types" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" dbm "github.com/tendermint/tm-db" @@ -13,7 +12,7 @@ import ( type MockContext struct { db *dbm.MemDB - store types.CommitMultiStore + store storetypes.CommitMultiStore } func NewMockContext() *MockContext { @@ -36,18 +35,18 @@ func (m MockContext) KVStore(key storetypes.StoreKey) sdk.KVStore { } type debuggingGasMeter struct { - g types.GasMeter + g storetypes.GasMeter } -func (d debuggingGasMeter) GasConsumed() types.Gas { +func (d debuggingGasMeter) GasConsumed() storetypes.Gas { return d.g.GasConsumed() } -func (d debuggingGasMeter) GasRemaining() types.Gas { +func (d debuggingGasMeter) GasRemaining() storetypes.Gas { return d.g.GasRemaining() } -func (d debuggingGasMeter) GasConsumedToLimit() types.Gas { +func (d debuggingGasMeter) GasConsumedToLimit() storetypes.Gas { return d.g.GasConsumedToLimit() } @@ -55,11 +54,11 @@ func (d debuggingGasMeter) RefundGas(amount uint64, descriptor string) { d.g.RefundGas(amount, descriptor) } -func (d debuggingGasMeter) Limit() types.Gas { +func (d debuggingGasMeter) Limit() storetypes.Gas { return d.g.Limit() } -func (d debuggingGasMeter) ConsumeGas(amount types.Gas, descriptor string) { +func (d debuggingGasMeter) ConsumeGas(amount storetypes.Gas, descriptor string) { fmt.Printf("++ Consuming gas: %q :%d\n", descriptor, amount) d.g.ConsumeGas(amount, descriptor) } @@ -87,14 +86,14 @@ func NewGasCountingMockContext() *GasCountingMockContext { } func (g GasCountingMockContext) KVStore(store sdk.KVStore) sdk.KVStore { - return gaskv.NewStore(store, g.GasMeter, types.KVGasConfig()) + return gaskv.NewStore(store, g.GasMeter, storetypes.KVGasConfig()) } -func (g GasCountingMockContext) GasConsumed() types.Gas { +func (g GasCountingMockContext) GasConsumed() storetypes.Gas { return g.GasMeter.GasConsumed() } -func (g GasCountingMockContext) GasRemaining() types.Gas { +func (g GasCountingMockContext) GasRemaining() storetypes.Gas { return g.GasMeter.GasRemaining() } diff --git a/x/group/simulation/operations.go b/x/group/simulation/operations.go index f541393771a3..b3187d4f5285 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" OpMsgUpdateGroupAdmin = "op_weight_msg_update_group_admin" diff --git a/x/group/types.go b/x/group/types.go index 86c0dfd9c1d7..1c095174f2dc 100644 --- a/x/group/types.go +++ b/x/group/types.go @@ -368,33 +368,33 @@ func MemberToMemberRequest(m *Member) MemberRequest { } } -func (p Proposal) ValidateBasic() error { - if p.Id == 0 { +func (g Proposal) ValidateBasic() error { + if g.Id == 0 { return sdkerrors.Wrap(errors.ErrEmpty, "proposal id") } - _, err := sdk.AccAddressFromBech32(p.GroupPolicyAddress) + _, err := sdk.AccAddressFromBech32(g.GroupPolicyAddress) if err != nil { return sdkerrors.Wrap(err, "proposal group policy address") } - if p.GroupVersion == 0 { + if g.GroupVersion == 0 { return sdkerrors.Wrap(errors.ErrEmpty, "proposal group version") } - if p.GroupPolicyVersion == 0 { + if g.GroupPolicyVersion == 0 { return sdkerrors.Wrap(errors.ErrEmpty, "proposal group policy version") } - _, err = p.FinalTallyResult.GetYesCount() + _, err = g.FinalTallyResult.GetYesCount() if err != nil { return sdkerrors.Wrap(err, "proposal FinalTallyResult yes count") } - _, err = p.FinalTallyResult.GetNoCount() + _, err = g.FinalTallyResult.GetNoCount() if err != nil { return sdkerrors.Wrap(err, "proposal FinalTallyResult no count") } - _, err = p.FinalTallyResult.GetAbstainCount() + _, err = g.FinalTallyResult.GetAbstainCount() if err != nil { return sdkerrors.Wrap(err, "proposal FinalTallyResult abstain count") } - _, err = p.FinalTallyResult.GetNoWithVetoCount() + _, err = g.FinalTallyResult.GetNoWithVetoCount() if err != nil { return sdkerrors.Wrap(err, "proposal FinalTallyResult veto count") } diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index 973f6d0fbd4a..0372479df4c2 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -335,7 +335,7 @@ func runQueuedOperations(queueOps map[int][]simulation.Operation, numOpsRan = len(queuedOp) for i := 0; i < numOpsRan; i++ { opMsg, futureOps, err := queuedOp[i](r, app, ctx, accounts, chainID) - if futureOps != nil && len(futureOps) > 0 { + if len(futureOps) > 0 { allFutureOps = append(allFutureOps, futureOps...) } @@ -379,7 +379,7 @@ func runQueuedTimeOperations(queueOps []simulation.FutureOperation, tb.FailNow() } - if futureOps != nil && len(futureOps) > 0 { + if len(futureOps) > 0 { allFutureOps = append(allFutureOps, futureOps...) } diff --git a/x/staking/simulation/operations.go b/x/staking/simulation/operations.go index c94347dd5881..263761877d9e 100644 --- a/x/staking/simulation/operations.go +++ b/x/staking/simulation/operations.go @@ -15,6 +15,7 @@ import ( ) // Simulation operation weights constants +//nolint:gosec // these are not hardcoded credentials const ( OpWeightMsgCreateValidator = "op_weight_msg_create_validator" OpWeightMsgEditValidator = "op_weight_msg_edit_validator" From 3c37a4fb865b471187d9cde5f7a6ff710c07f60a Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sat, 4 Jun 2022 03:01:59 +0700 Subject: [PATCH 23/27] more linter fixes --- client/debug/main.go | 27 ++++++++++--------- codec/proto_codec.go | 2 +- .../internal/secp256k1/scalar_mult_cgo.go | 2 +- internal/db/iterator_adapter.go | 10 +++---- server/mock/app.go | 3 ++- server/rosetta/client_online.go | 3 ++- store/v2alpha1/dbadapter/store.go | 4 +-- store/v2alpha1/multi/sub_store.go | 2 +- store/v2alpha1/multi/view_store.go | 4 +-- types/address.go | 2 +- types/tx/ext.go | 4 +-- types/tx/types.go | 2 +- x/auth/ante/fee.go | 2 +- x/auth/migrations/legacytx/stdtx.go | 1 + x/authz/simulation/operations.go | 4 +-- x/bank/simulation/operations.go | 1 + x/crisis/types/params.go | 2 +- x/gov/client/testutil/helpers.go | 1 + x/gov/client/testutil/tx.go | 13 ++++----- x/group/client/cli/util.go | 14 +++++----- x/group/client/testutil/tx.go | 2 +- x/group/simulation/operations.go | 13 +++++---- x/nft/simulation/operations.go | 1 + x/slashing/simulation/operations.go | 1 + x/staking/keeper/keeper.go | 6 +++-- x/upgrade/client/cli/parse.go | 4 +-- x/upgrade/client/cli/tx.go | 18 ++++++------- x/upgrade/handler.go | 3 +++ 28 files changed, 83 insertions(+), 68 deletions(-) diff --git a/client/debug/main.go b/client/debug/main.go index 5eb795ffb9ed..df21d31c82b7 100644 --- a/client/debug/main.go +++ b/client/debug/main.go @@ -17,10 +17,13 @@ import ( "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/version" - legacybech32 "github.com/cosmos/cosmos-sdk/types/bech32/legacybech32" + legacybech32 "github.com/cosmos/cosmos-sdk/types/bech32/legacybech32" //nolint:staticcheck // we do old keys, they're keys after all. ) -var flagPubkeyType = "type" +var ( + flagPubkeyType = "type" + ed = "ed25519" +) // Cmd creates a main CLI command func Cmd() *cobra.Command { @@ -69,7 +72,7 @@ $ %s debug pubkey '{"@type":"/cosmos.crypto.secp256k1.PubKey","key":"AurroA7jvfP } func bytesToPubkey(bz []byte, keytype string) (cryptotypes.PubKey, bool) { - if keytype == "ed25519" { + if keytype == ed { if len(bz) == ed25519.PubKeySize { return &ed25519.PubKey{Key: bz}, true } @@ -102,17 +105,17 @@ func getPubKeyFromRawString(pkstr string, keytype string) (cryptotypes.PubKey, e } } - pk, err := legacybech32.UnmarshalPubKey(legacybech32.AccPK, pkstr) + pk, err := legacybech32.UnmarshalPubKey(legacybech32.AccPK, pkstr) //nolint:staticcheck // we do old keys, they're keys after all. if err == nil { return pk, nil } - pk, err = legacybech32.UnmarshalPubKey(legacybech32.ValPK, pkstr) + pk, err = legacybech32.UnmarshalPubKey(legacybech32.ValPK, pkstr) //nolint:staticcheck // we do old keys, they're keys after all. if err == nil { return pk, nil } - pk, err = legacybech32.UnmarshalPubKey(legacybech32.ConsPK, pkstr) + pk, err = legacybech32.UnmarshalPubKey(legacybech32.ConsPK, pkstr) //nolint:staticcheck // we do old keys, they're keys after all. if err == nil { return pk, nil } @@ -138,7 +141,7 @@ $ %s debug pubkey-raw cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg return err } pubkeyType = strings.ToLower(pubkeyType) - if pubkeyType != "secp256k1" && pubkeyType != "ed25519" { + if pubkeyType != "secp256k1" && pubkeyType != ed { return errors.Wrapf(errors.ErrInvalidType, "invalid pubkey type, expected oneof ed25519 or secp256k1") } @@ -149,8 +152,8 @@ $ %s debug pubkey-raw cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg var consensusPub string edPK, ok := pk.(*ed25519.PubKey) - if ok && pubkeyType == "ed25519" { - consensusPub, err = legacybech32.MarshalPubKey(legacybech32.ConsPK, edPK) + if ok && pubkeyType == ed { + consensusPub, err = legacybech32.MarshalPubKey(legacybech32.ConsPK, edPK) //nolint:staticcheck // we do old keys, they're keys after all. if err != nil { return err } @@ -163,11 +166,11 @@ $ %s debug pubkey-raw cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg if err != nil { return err } - accPub, err := legacybech32.MarshalPubKey(legacybech32.AccPK, pk) + accPub, err := legacybech32.MarshalPubKey(legacybech32.AccPK, pk) //nolint:staticcheck // we do old keys, they're keys after all. if err != nil { return err } - valPub, err := legacybech32.MarshalPubKey(legacybech32.ValPK, pk) + valPub, err := legacybech32.MarshalPubKey(legacybech32.ValPK, pk) //nolint:staticcheck // we do old keys, they're keys after all. if err != nil { return err } @@ -182,7 +185,7 @@ $ %s debug pubkey-raw cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg return nil }, } - cmd.Flags().StringP(flagPubkeyType, "t", "ed25519", "Pubkey type to decode (oneof secp256k1, ed25519)") + cmd.Flags().StringP(flagPubkeyType, "t", ed, "Pubkey type to decode (oneof secp256k1, ed25519)") return cmd } diff --git a/codec/proto_codec.go b/codec/proto_codec.go index 05bdf1b05210..9b5b72b6e4f2 100644 --- a/codec/proto_codec.go +++ b/codec/proto_codec.go @@ -6,7 +6,7 @@ import ( "fmt" "strings" - legacyproto "github.com/golang/protobuf/proto" + legacyproto "github.com/golang/protobuf/proto" //nolint:staticcheck // we're aware this is deprecated and using it anyhow. "google.golang.org/grpc/encoding" "google.golang.org/protobuf/proto" diff --git a/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go b/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go index 2fe30a4e1acc..4090923a3c43 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go +++ b/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go @@ -21,7 +21,7 @@ extern int secp256k1_ext_scalar_mul(const secp256k1_context* ctx, const unsigned */ import "C" -func (BitCurve *BitCurve) ScalarMult(bx, by *big.Int, scalar []byte) (*big.Int, *big.Int) { +func (bitCurve *BitCurve) ScalarMult(bx, by *big.Int, scalar []byte) (*big.Int, *big.Int) { // Ensure scalar is exactly 32 bytes. We pad always, even if // scalar is 32 bytes long, to avoid a timing side channel. if len(scalar) > 32 { diff --git a/internal/db/iterator_adapter.go b/internal/db/iterator_adapter.go index 6e7f366249fb..8bf717041d57 100644 --- a/internal/db/iterator_adapter.go +++ b/internal/db/iterator_adapter.go @@ -7,18 +7,18 @@ import ( var _ = (*storetypes.Iterator)(nil) -type dbAsStoreIter struct { +type AsStoreIter struct { dbm.Iterator valid bool } // DBToStoreIterator returns an iterator wrapping the given iterator so that it satisfies the // (store/types).Iterator interface. -func DBToStoreIterator(source dbm.Iterator) *dbAsStoreIter { - ret := &dbAsStoreIter{Iterator: source} +func ToStoreIterator(source dbm.Iterator) *AsStoreIter { + ret := &AsStoreIter{Iterator: source} ret.Next() // The DB iterator must be primed before it can access the first element, because Next also returns the validity status return ret } -func (it *dbAsStoreIter) Next() { it.valid = it.Iterator.Next() } -func (it *dbAsStoreIter) Valid() bool { return it.valid } +func (it *AsStoreIter) Next() { it.valid = it.Iterator.Next() } +func (it *AsStoreIter) Valid() bool { return it.valid } diff --git a/server/mock/app.go b/server/mock/app.go index b059d62e0e53..57dd93373de2 100644 --- a/server/mock/app.go +++ b/server/mock/app.go @@ -7,6 +7,7 @@ import ( "path/filepath" "github.com/tendermint/tendermint/types" + db "github.com/tendermint/tm-db" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" @@ -21,7 +22,7 @@ import ( // similar to a real app. Make sure rootDir is empty before running the test, // in order to guarantee consistent results func NewApp(rootDir string, logger log.Logger) (abci.Application, error) { - db, err := sdk.NewLevelDB("mock", filepath.Join(rootDir, "data")) + db, err := db.NewGoLevelDB("mock", filepath.Join(rootDir, "data")) if err != nil { return nil, err } diff --git a/server/rosetta/client_online.go b/server/rosetta/client_online.go index 9fc033b460ff..478bfe6aafbe 100644 --- a/server/rosetta/client_online.go +++ b/server/rosetta/client_online.go @@ -16,6 +16,7 @@ import ( abcitypes "github.com/tendermint/tendermint/abci/types" rosettatypes "github.com/coinbase/rosetta-sdk-go/types" + "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/metadata" "github.com/tendermint/tendermint/rpc/client/http" @@ -98,7 +99,7 @@ func NewClient(cfg *Config) (*Client, error) { // Bootstrap is gonna connect the client to the endpoints func (c *Client) Bootstrap() error { - grpcConn, err := grpc.Dial(c.config.GRPCEndpoint, grpc.WithInsecure()) + grpcConn, err := grpc.Dial(c.config.GRPCEndpoint, grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { return err } diff --git a/store/v2alpha1/dbadapter/store.go b/store/v2alpha1/dbadapter/store.go index d7096138836c..927cc1f93ae4 100644 --- a/store/v2alpha1/dbadapter/store.go +++ b/store/v2alpha1/dbadapter/store.go @@ -59,7 +59,7 @@ func (dsa Store) Iterator(start, end []byte) types.Iterator { if err != nil { panic(err) } - return dbutil.DBToStoreIterator(iter) + return dbutil.ToStoreIterator(iter) } // ReverseIterator wraps the underlying DB's ReverseIterator method panicing on error. @@ -68,7 +68,7 @@ func (dsa Store) ReverseIterator(start, end []byte) types.Iterator { if err != nil { panic(err) } - return dbutil.DBToStoreIterator(iter) + return dbutil.ToStoreIterator(iter) } // GetStoreType returns the type of the store. diff --git a/store/v2alpha1/multi/sub_store.go b/store/v2alpha1/multi/sub_store.go index 613b7ac2c412..33df955b920c 100644 --- a/store/v2alpha1/multi/sub_store.go +++ b/store/v2alpha1/multi/sub_store.go @@ -73,7 +73,7 @@ type contentsIterator struct { func (s *substore) newSubstoreIterator(source dbm.Iterator) *contentsIterator { locker := s.root.mtx.RLocker() locker.Lock() - return &contentsIterator{dbutil.DBToStoreIterator(source), locker} + return &contentsIterator{dbutil.ToStoreIterator(source), locker} } func (it *contentsIterator) Close() error { diff --git a/store/v2alpha1/multi/view_store.go b/store/v2alpha1/multi/view_store.go index b3d5acd58f4a..8117a1c41148 100644 --- a/store/v2alpha1/multi/view_store.go +++ b/store/v2alpha1/multi/view_store.go @@ -55,7 +55,7 @@ func (s *viewSubstore) Iterator(start, end []byte) types.Iterator { if err != nil { panic(err) } - return dbutil.DBToStoreIterator(iter) + return dbutil.ToStoreIterator(iter) } // ReverseIterator implements KVStore. @@ -64,7 +64,7 @@ func (s *viewSubstore) ReverseIterator(start, end []byte) types.Iterator { if err != nil { panic(err) } - return dbutil.DBToStoreIterator(iter) + return dbutil.ToStoreIterator(iter) } // GetStoreType implements Store. diff --git a/types/address.go b/types/address.go index 7adbef1a9961..2f1fe31e8789 100644 --- a/types/address.go +++ b/types/address.go @@ -498,7 +498,7 @@ func (ca ConsAddress) Equals(ca2 Address) bool { // Returns boolean for whether an ConsAddress is empty func (ca ConsAddress) Empty() bool { - return ca == nil || len(ca) == 0 + return len(ca) == 0 } // Marshal returns the raw address bytes. It is needed for protobuf diff --git a/types/tx/ext.go b/types/tx/ext.go index fb2e1ed448bc..f532513daa9b 100644 --- a/types/tx/ext.go +++ b/types/tx/ext.go @@ -5,12 +5,12 @@ import ( ) // TxExtensionOptionI defines the interface for tx extension options -type TxExtensionOptionI interface{} +type ExtensionOptionI interface{} // unpackTxExtensionOptionsI unpacks Any's to TxExtensionOptionI's. func unpackTxExtensionOptionsI(unpacker types.AnyUnpacker, anys []*types.Any) error { for _, any := range anys { - var opt TxExtensionOptionI + var opt ExtensionOptionI err := unpacker.UnpackAny(any, &opt) if err != nil { return err diff --git a/types/tx/types.go b/types/tx/types.go index a4816b1283a6..559fb8b8e4fa 100644 --- a/types/tx/types.go +++ b/types/tx/types.go @@ -215,5 +215,5 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) { registry.RegisterInterface("cosmos.tx.v1beta1.Tx", (*sdk.Tx)(nil)) registry.RegisterImplementations((*sdk.Tx)(nil), &Tx{}) - registry.RegisterInterface("cosmos.tx.v1beta1.TxExtensionOptionI", (*TxExtensionOptionI)(nil)) + registry.RegisterInterface("cosmos.tx.v1beta1.TxExtensionOptionI", (*ExtensionOptionI)(nil)) } diff --git a/x/auth/ante/fee.go b/x/auth/ante/fee.go index 7a38dbc399d6..e2c3ef14d48f 100644 --- a/x/auth/ante/fee.go +++ b/x/auth/ante/fee.go @@ -57,7 +57,7 @@ func (dfd DeductFeeDecorator) checkDeductFee(ctx sdk.Context, sdkTx sdk.Tx, fee } if addr := dfd.accountKeeper.GetModuleAddress(types.FeeCollectorName); addr == nil { - return fmt.Errorf("Fee collector module account (%s) has not been set", types.FeeCollectorName) + return fmt.Errorf("fee collector module account (%s) has not been set", types.FeeCollectorName) } feePayer := feeTx.FeePayer() diff --git a/x/auth/migrations/legacytx/stdtx.go b/x/auth/migrations/legacytx/stdtx.go index bfe8502a3ddb..6ded888de93e 100644 --- a/x/auth/migrations/legacytx/stdtx.go +++ b/x/auth/migrations/legacytx/stdtx.go @@ -106,6 +106,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/authz/simulation/operations.go b/x/authz/simulation/operations.go index 8886d2e654fd..07b878b57259 100644 --- a/x/authz/simulation/operations.go +++ b/x/authz/simulation/operations.go @@ -263,9 +263,9 @@ func SimulateMsgExec(ak authz.AccountKeeper, bk authz.BankKeeper, k keeper.Keepe if err != nil { if sdkerrors.ErrInsufficientFunds.Is(err) { return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, err.Error()), nil, nil - } else { - return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, err.Error()), nil, err } + return simtypes.NoOpMsg(authz.ModuleName, TypeMsgExec, err.Error()), nil, err + } msgExec := authz.NewMsgExec(granteeAddr, msg) diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index 56a9919224b7..07cc32a77868 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" OpWeightMsgMultiSend = "op_weight_msg_multisend" diff --git a/x/crisis/types/params.go b/x/crisis/types/params.go index 03c8dd82883f..100bf229c7b0 100644 --- a/x/crisis/types/params.go +++ b/x/crisis/types/params.go @@ -7,7 +7,7 @@ import ( paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) -// key for constant fee parameter +// ParamStoreKeyConstantFee is the constant fee parameter var ParamStoreKeyConstantFee = []byte("ConstantFee") // type declaration for parameters diff --git a/x/gov/client/testutil/helpers.go b/x/gov/client/testutil/helpers.go index 6dbb0d8722cb..174d7af0f429 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{ fmt.Sprintf("--%s=%s", govcli.FlagTitle, title), diff --git a/x/gov/client/testutil/tx.go b/x/gov/client/testutil/tx.go index f3f5a52c4913..3f063e588e94 100644 --- a/x/gov/client/testutil/tx.go +++ b/x/gov/client/testutil/tx.go @@ -188,7 +188,7 @@ func (s *IntegrationTestSuite) TestNewCmdSubmitLegacyProposal() { { "invalid proposal (file)", []string{ - fmt.Sprintf("--%s=%s", cli.FlagProposal, invalidPropFile.Name()), + fmt.Sprintf("--%s=%s", cli.FlagProposal, invalidPropFile.Name()), //nolint:staticcheck // we are intentionally using a deprecated flag here. fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(10))).String()), @@ -198,8 +198,8 @@ func (s *IntegrationTestSuite) TestNewCmdSubmitLegacyProposal() { { "invalid proposal", []string{ - fmt.Sprintf("--%s='Where is the title!?'", cli.FlagDescription), - fmt.Sprintf("--%s=%s", cli.FlagProposalType, v1beta1.ProposalTypeText), + fmt.Sprintf("--%s='Where is the title!?'", cli.FlagDescription), //nolint:staticcheck // we are intentionally using a deprecated flag here. + fmt.Sprintf("--%s=%s", cli.FlagProposalType, v1beta1.ProposalTypeText), //nolint:staticcheck // we are intentionally using a deprecated flag here. fmt.Sprintf("--%s=%s", cli.FlagDeposit, sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(5431)).String()), fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), @@ -209,6 +209,7 @@ func (s *IntegrationTestSuite) TestNewCmdSubmitLegacyProposal() { }, { "valid transaction (file)", + //nolint:staticcheck // we are intentionally using a deprecated flag here. []string{ fmt.Sprintf("--%s=%s", cli.FlagProposal, validPropFile.Name()), fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), @@ -221,9 +222,9 @@ func (s *IntegrationTestSuite) TestNewCmdSubmitLegacyProposal() { { "valid transaction", []string{ - fmt.Sprintf("--%s='Text Proposal'", cli.FlagTitle), - fmt.Sprintf("--%s='Where is the title!?'", cli.FlagDescription), - fmt.Sprintf("--%s=%s", cli.FlagProposalType, v1beta1.ProposalTypeText), + fmt.Sprintf("--%s='Text Proposal'", cli.FlagTitle), //nolint:staticcheck // we are intentionally using a deprecated flag here. + fmt.Sprintf("--%s='Where is the title!?'", cli.FlagDescription), //nolint:staticcheck // we are intentionally using a deprecated flag here. + fmt.Sprintf("--%s=%s", cli.FlagProposalType, v1beta1.ProposalTypeText), //nolint:staticcheck // we are intentionally using a deprecated flag here. fmt.Sprintf("--%s=%s", cli.FlagDeposit, sdk.NewCoin(s.cfg.BondDenom, sdk.NewInt(5431)).String()), fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), diff --git a/x/group/client/cli/util.go b/x/group/client/cli/util.go index 23a8aebcab75..d7a03f9d0912 100644 --- a/x/group/client/cli/util.go +++ b/x/group/client/cli/util.go @@ -40,7 +40,7 @@ func execFromString(execStr string) group.Exec { } // CLIProposal defines a Msg-based group proposal for CLI purposes. -type CLIProposal struct { +type Proposal struct { GroupPolicyAddress string `json:"group_policy_address"` // Messages defines an array of sdk.Msgs proto-JSON-encoded as Anys. Messages []json.RawMessage `json:"messages"` @@ -48,25 +48,25 @@ type CLIProposal struct { Proposers []string `json:"proposers"` } -func getCLIProposal(path string) (CLIProposal, error) { +func getCLIProposal(path string) (Proposal, error) { contents, err := os.ReadFile(path) if err != nil { - return CLIProposal{}, err + return Proposal{}, err } return parseCLIProposal(contents) } -func parseCLIProposal(contents []byte) (CLIProposal, error) { - var p CLIProposal +func parseCLIProposal(contents []byte) (Proposal, error) { + var p Proposal if err := json.Unmarshal(contents, &p); err != nil { - return CLIProposal{}, err + return Proposal{}, err } return p, nil } -func parseMsgs(cdc codec.Codec, p CLIProposal) ([]sdk.Msg, error) { +func parseMsgs(cdc codec.Codec, p Proposal) ([]sdk.Msg, error) { msgs := make([]sdk.Msg, len(p.Messages)) for i, anyJSON := range p.Messages { var msg sdk.Msg diff --git a/x/group/client/testutil/tx.go b/x/group/client/testutil/tx.go index 879c7baef22c..22b1540bcc97 100644 --- a/x/group/client/testutil/tx.go +++ b/x/group/client/testutil/tx.go @@ -2446,7 +2446,7 @@ func (s *IntegrationTestSuite) createCLIProposal(groupPolicyAddress, proposer, s msgJSON, err := s.cfg.Codec.MarshalInterfaceJSON(&msg) s.Require().NoError(err) - p := client.CLIProposal{ + p := client.Proposal{ GroupPolicyAddress: groupPolicyAddress, Messages: []json.RawMessage{msgJSON}, Metadata: metadata, diff --git a/x/group/simulation/operations.go b/x/group/simulation/operations.go index b3187d4f5285..2568acb62341 100644 --- a/x/group/simulation/operations.go +++ b/x/group/simulation/operations.go @@ -433,7 +433,7 @@ func SimulateMsgSubmitProposal(ak group.AccountKeeper, bk group.BankKeeper, k ke // Pick a random member from the group ctx := sdk.WrapSDKContext(sdkCtx) - acc, account, err := randomMember(r, k, ak, ctx, accounts, groupID) + acc, account, err := randomMember(ctx, r, k, ak, accounts, groupID) if err != nil { return simtypes.NoOpMsg(group.ModuleName, TypeMsgSubmitProposal, ""), nil, err } @@ -963,7 +963,7 @@ func SimulateMsgVote(ak group.AccountKeeper, // Pick a random member from the group ctx := sdk.WrapSDKContext(sdkCtx) - acc, account, err := randomMember(r, k, ak, ctx, accounts, g.Id) + acc, account, err := randomMember(ctx, r, k, ak, accounts, g.Id) if err != nil { return simtypes.NoOpMsg(group.ModuleName, TypeMsgVote, ""), nil, err } @@ -1140,7 +1140,7 @@ func SimulateMsgLeaveGroup(k keeper.Keeper, ak group.AccountKeeper, bk group.Ban } // Pick a random member from the group - acc, account, err := randomMember(r, k, ak, ctx, accounts, groupInfo.Id) + acc, account, err := randomMember(ctx, r, k, ak, accounts, groupInfo.Id) if err != nil { return simtypes.NoOpMsg(group.ModuleName, TypeMsgLeaveGroup, ""), nil, err } @@ -1253,8 +1253,8 @@ func randomGroupPolicy(r *rand.Rand, k keeper.Keeper, ak group.AccountKeeper, return groupInfo, groupPolicyInfo, acc, account, nil } -func randomMember(r *rand.Rand, k keeper.Keeper, ak group.AccountKeeper, - ctx context.Context, accounts []simtypes.Account, groupID uint64, +func randomMember(ctx context.Context, r *rand.Rand, k keeper.Keeper, ak group.AccountKeeper, + accounts []simtypes.Account, groupID uint64, ) (acc simtypes.Account, account authtypes.AccountI, err error) { res, err := k.GroupMembers(ctx, &group.QueryGroupMembersRequest{ GroupId: groupID, @@ -1281,9 +1281,8 @@ func randIntInRange(r *rand.Rand, l int) int { } if l == 1 { return 0 - } else { - return simtypes.RandIntBetween(r, 0, l-1) } + return simtypes.RandIntBetween(r, 0, l-1) } func findAccount(accounts []simtypes.Account, addr string) (idx int) { diff --git a/x/nft/simulation/operations.go b/x/nft/simulation/operations.go index c71ab17c3175..b45a56ca1f98 100644 --- a/x/nft/simulation/operations.go +++ b/x/nft/simulation/operations.go @@ -17,6 +17,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/simulation" ) +//nolint:gosec // these are not hardcoded credentials. const ( // OpWeightMsgSend Simulation operation weights constants OpWeightMsgSend = "op_weight_msg_send" diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index 1aaf4387f702..a7a076c44d9d 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -17,6 +17,7 @@ import ( ) // Simulation operation weights constants +//nolint:gosec // these are not hardcoded credentials. const ( OpWeightMsgUnjail = "op_weight_msg_unjail" ) diff --git a/x/staking/keeper/keeper.go b/x/staking/keeper/keeper.go index 247c356bf49a..296c9f3d5034 100644 --- a/x/staking/keeper/keeper.go +++ b/x/staking/keeper/keeper.go @@ -3,6 +3,8 @@ package keeper import ( "fmt" + "cosmossdk.io/math" + storetypes "github.com/cosmos/cosmos-sdk/store/types" "github.com/tendermint/tendermint/libs/log" @@ -72,7 +74,7 @@ func (k *Keeper) SetHooks(sh types.StakingHooks) { } // Load the last total validator power. -func (k Keeper) GetLastTotalPower(ctx sdk.Context) sdk.Int { +func (k Keeper) GetLastTotalPower(ctx sdk.Context) math.Int { store := ctx.KVStore(k.storeKey) bz := store.Get(types.LastTotalPowerKey) @@ -87,7 +89,7 @@ func (k Keeper) GetLastTotalPower(ctx sdk.Context) sdk.Int { } // Set the last total validator power. -func (k Keeper) SetLastTotalPower(ctx sdk.Context, power sdk.Int) { +func (k Keeper) SetLastTotalPower(ctx sdk.Context, power math.Int) { store := ctx.KVStore(k.storeKey) bz := k.cdc.MustMarshal(&sdk.IntProto{Int: power}) store.Set(types.LastTotalPowerKey, bz) diff --git a/x/upgrade/client/cli/parse.go b/x/upgrade/client/cli/parse.go index 8272266b6fb1..e6b103791c4b 100644 --- a/x/upgrade/client/cli/parse.go +++ b/x/upgrade/client/cli/parse.go @@ -8,12 +8,12 @@ import ( ) func parseArgsToContent(fs *pflag.FlagSet, name string) (gov.Content, error) { - title, err := fs.GetString(cli.FlagTitle) + title, err := fs.GetString(cli.FlagTitle) //nolint:staticcheck // we are intentionally using a deprecated flag here. if err != nil { return nil, err } - description, err := fs.GetString(cli.FlagDescription) + description, err := fs.GetString(cli.FlagDescription) //nolint:staticcheck // we are intentionally using a deprecated flag here. if err != nil { return nil, err } diff --git a/x/upgrade/client/cli/tx.go b/x/upgrade/client/cli/tx.go index 6a54d8db3838..affba7151c19 100644 --- a/x/upgrade/client/cli/tx.go +++ b/x/upgrade/client/cli/tx.go @@ -59,7 +59,7 @@ func NewCmdSubmitLegacyUpgradeProposal() *cobra.Command { return err } if !noValidate { - prop := content.(*types.SoftwareUpgradeProposal) + prop := content.(*types.SoftwareUpgradeProposal) //nolint:staticcheck // we are intentionally using a deprecated proposal type. var daemonName string if daemonName, err = cmd.Flags().GetString(FlagDaemonName); err != nil { return err @@ -93,8 +93,8 @@ func NewCmdSubmitLegacyUpgradeProposal() *cobra.Command { }, } - cmd.Flags().String(cli.FlagTitle, "", "title of proposal") - cmd.Flags().String(cli.FlagDescription, "", "description of proposal") + cmd.Flags().String(cli.FlagTitle, "", "title of proposal") //nolint:staticcheck // we are intentionally using a deprecated flag here. + cmd.Flags().String(cli.FlagDescription, "", "description of proposal") //nolint:staticcheck // we are intentionally using a deprecated flag here. cmd.Flags().String(cli.FlagDeposit, "", "deposit of proposal") cmd.Flags().Int64(FlagUpgradeHeight, 0, "The height at which the upgrade must happen") cmd.Flags().String(FlagUpgradeInfo, "", "Info for the upgrade plan such as new version download urls, etc.") @@ -129,12 +129,12 @@ func NewCmdSubmitLegacyCancelUpgradeProposal() *cobra.Command { return err } - title, err := cmd.Flags().GetString(cli.FlagTitle) + title, err := cmd.Flags().GetString(cli.FlagTitle) //nolint:staticcheck // we are intentionally using a deprecated flag here. if err != nil { return err } - description, err := cmd.Flags().GetString(cli.FlagDescription) + description, err := cmd.Flags().GetString(cli.FlagDescription) //nolint:staticcheck // we are intentionally using a deprecated flag here. if err != nil { return err } @@ -150,11 +150,11 @@ func NewCmdSubmitLegacyCancelUpgradeProposal() *cobra.Command { }, } - cmd.Flags().String(cli.FlagTitle, "", "title of proposal") - cmd.Flags().String(cli.FlagDescription, "", "description of proposal") + cmd.Flags().String(cli.FlagTitle, "", "title of proposal") //nolint:staticcheck // we are intentionally using a deprecated flag here. + cmd.Flags().String(cli.FlagDescription, "", "description of proposal") //nolint:staticcheck // we are intentionally using a deprecated flag here. cmd.Flags().String(cli.FlagDeposit, "", "deposit of proposal") - cmd.MarkFlagRequired(cli.FlagTitle) - cmd.MarkFlagRequired(cli.FlagDescription) + cmd.MarkFlagRequired(cli.FlagTitle) //nolint:staticcheck // we are intentionally using a deprecated flag here. + cmd.MarkFlagRequired(cli.FlagDescription) //nolint:staticcheck // we are intentionally using a deprecated flag here. return cmd } diff --git a/x/upgrade/handler.go b/x/upgrade/handler.go index 355952ff1e21..f880cd7f9ec8 100644 --- a/x/upgrade/handler.go +++ b/x/upgrade/handler.go @@ -11,6 +11,7 @@ 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. func NewSoftwareUpgradeProposalHandler(k keeper.Keeper) govtypes.Handler { return func(ctx sdk.Context, content govtypes.Content) error { switch c := content.(type) { @@ -26,10 +27,12 @@ func NewSoftwareUpgradeProposalHandler(k keeper.Keeper) govtypes.Handler { } } +//nolint:staticcheck // we are intentionally using a deprecated proposal here. func handleSoftwareUpgradeProposal(ctx sdk.Context, k keeper.Keeper, p *types.SoftwareUpgradeProposal) error { return k.ScheduleUpgrade(ctx, p.Plan) } +//nolint:staticcheck // we are intentionally using a deprecated proposal here. func handleCancelSoftwareUpgradeProposal(ctx sdk.Context, k keeper.Keeper, _ *types.CancelSoftwareUpgradeProposal) error { k.ClearUpgradePlan(ctx) return nil From cfafb8e25573a9670bf143bb83f5828c1f8c7c23 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Sat, 4 Jun 2022 03:22:22 +0700 Subject: [PATCH 24/27] remove prealloc linter --- .golangci.yml | 1 - testutil/testdata/codec.go | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index bbce526a7dc3..6b2614e740d8 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -22,7 +22,6 @@ linters: - misspell - nakedret - nolintlint - - prealloc - revive - staticcheck - structcheck diff --git a/testutil/testdata/codec.go b/testutil/testdata/codec.go index 5124f506d0d5..2f3aecb98618 100644 --- a/testutil/testdata/codec.go +++ b/testutil/testdata/codec.go @@ -33,7 +33,7 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { &HasHasAnimal{}, ) registry.RegisterImplementations( - (*tx.TxExtensionOptionI)(nil), + (*tx.ExtensionOptionI)(nil), &Cat{}, ) From 3ddfcc8b3d49d8dfcbde7bfff6d00db2c8eedd75 Mon Sep 17 00:00:00 2001 From: faddat Date: Wed, 8 Jun 2022 10:47:01 +0000 Subject: [PATCH 25/27] nolint the secp256k1 import --- .../secp256k1/internal/secp256k1/curve.go | 45 ++++++++++--------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/crypto/keys/secp256k1/internal/secp256k1/curve.go b/crypto/keys/secp256k1/internal/secp256k1/curve.go index f1eeba8a10f3..09def0e854db 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/curve.go +++ b/crypto/keys/secp256k1/internal/secp256k1/curve.go @@ -30,6 +30,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +//nolint // this file shouldn't be linted because we want to use it in its original and unmodified form. package secp256k1 import ( @@ -143,20 +144,20 @@ func (bitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { // addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and // (x2, y2, z2) and returns their sum, also in Jacobian form. -func (bitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) { +func (BitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) { // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl z1z1 := new(big.Int).Mul(z1, z1) - z1z1.Mod(z1z1, bitCurve.P) + z1z1.Mod(z1z1, BitCurve.P) z2z2 := new(big.Int).Mul(z2, z2) - z2z2.Mod(z2z2, bitCurve.P) + z2z2.Mod(z2z2, BitCurve.P) u1 := new(big.Int).Mul(x1, z2z2) - u1.Mod(u1, bitCurve.P) + u1.Mod(u1, BitCurve.P) u2 := new(big.Int).Mul(x2, z1z1) - u2.Mod(u2, bitCurve.P) + u2.Mod(u2, BitCurve.P) h := new(big.Int).Sub(u2, u1) if h.Sign() == -1 { - h.Add(h, bitCurve.P) + h.Add(h, BitCurve.P) } i := new(big.Int).Lsh(h, 1) i.Mul(i, i) @@ -164,13 +165,13 @@ func (bitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int s1 := new(big.Int).Mul(y1, z2) s1.Mul(s1, z2z2) - s1.Mod(s1, bitCurve.P) + s1.Mod(s1, BitCurve.P) s2 := new(big.Int).Mul(y2, z1) s2.Mul(s2, z1z1) - s2.Mod(s2, bitCurve.P) + s2.Mod(s2, BitCurve.P) r := new(big.Int).Sub(s2, s1) if r.Sign() == -1 { - r.Add(r, bitCurve.P) + r.Add(r, BitCurve.P) } r.Lsh(r, 1) v := new(big.Int).Mul(u1, i) @@ -180,7 +181,7 @@ func (bitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int x3.Sub(x3, j) x3.Sub(x3, v) x3.Sub(x3, v) - x3.Mod(x3, bitCurve.P) + x3.Mod(x3, BitCurve.P) y3 := new(big.Int).Set(r) v.Sub(v, x3) @@ -188,33 +189,33 @@ func (bitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int s1.Mul(s1, j) s1.Lsh(s1, 1) y3.Sub(y3, s1) - y3.Mod(y3, bitCurve.P) + y3.Mod(y3, BitCurve.P) z3 := new(big.Int).Add(z1, z2) z3.Mul(z3, z3) z3.Sub(z3, z1z1) if z3.Sign() == -1 { - z3.Add(z3, bitCurve.P) + z3.Add(z3, BitCurve.P) } z3.Sub(z3, z2z2) if z3.Sign() == -1 { - z3.Add(z3, bitCurve.P) + z3.Add(z3, BitCurve.P) } z3.Mul(z3, h) - z3.Mod(z3, bitCurve.P) + z3.Mod(z3, BitCurve.P) return x3, y3, z3 } // Double returns 2*(x,y) -func (bitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { +func (BitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { z1 := new(big.Int).SetInt64(1) - return bitCurve.affineFromJacobian(bitCurve.doubleJacobian(x1, y1, z1)) + return BitCurve.affineFromJacobian(BitCurve.doubleJacobian(x1, y1, z1)) } // doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and // returns its double, also in Jacobian form. -func (bitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) { +func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) { // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l a := new(big.Int).Mul(x, x) // X1² @@ -232,24 +233,24 @@ func (bitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, x3 := new(big.Int).Mul(big.NewInt(2), d) // 2*D x3.Sub(f, x3) // F-2*D - x3.Mod(x3, bitCurve.P) + x3.Mod(x3, BitCurve.P) y3 := new(big.Int).Sub(d, x3) // D-X3 y3.Mul(e, y3) // E*(D-X3) y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) // E*(D-X3)-8*C - y3.Mod(y3, bitCurve.P) + y3.Mod(y3, BitCurve.P) z3 := new(big.Int).Mul(y, z) // Y1*Z1 z3.Mul(big.NewInt(2), z3) // 3*Y1*Z1 - z3.Mod(z3, bitCurve.P) + z3.Mod(z3, BitCurve.P) return x3, y3, z3 } // ScalarBaseMult returns k*G, where G is the base point of the group and k is // an integer in big-endian form. -func (bitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { - return bitCurve.ScalarMult(bitCurve.Gx, bitCurve.Gy, k) +func (BitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { + return BitCurve.ScalarMult(BitCurve.Gx, BitCurve.Gy, k) } // Marshal converts a point into the form specified in section 4.3.6 of ANSI From 84fff6da792a56afc99e557af9ef2623940f6400 Mon Sep 17 00:00:00 2001 From: faddat Date: Wed, 8 Jun 2022 10:52:41 +0000 Subject: [PATCH 26/27] nolint the secp256k1 package --- .../keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go b/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go index 4090923a3c43..2c7a1611c336 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go +++ b/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go @@ -5,6 +5,7 @@ //go:build !gofuzz && cgo // +build !gofuzz,cgo +//nolint package secp256k1 import ( @@ -21,7 +22,7 @@ extern int secp256k1_ext_scalar_mul(const secp256k1_context* ctx, const unsigned */ import "C" -func (bitCurve *BitCurve) ScalarMult(bx, by *big.Int, scalar []byte) (*big.Int, *big.Int) { +func (BitCurve *BitCurve) ScalarMult(Bx, By *big.Int, scalar []byte) (*big.Int, *big.Int) { // Ensure scalar is exactly 32 bytes. We pad always, even if // scalar is 32 bytes long, to avoid a timing side channel. if len(scalar) > 32 { @@ -34,8 +35,8 @@ func (bitCurve *BitCurve) ScalarMult(bx, by *big.Int, scalar []byte) (*big.Int, // Do the multiplication in C, updating point. point := make([]byte, 64) - readBits(bx, point[:32]) - readBits(by, point[32:]) + readBits(Bx, point[:32]) + readBits(By, point[32:]) pointPtr := (*C.uchar)(unsafe.Pointer(&point[0])) scalarPtr := (*C.uchar)(unsafe.Pointer(&scalar[0])) From b6cbe02bd1c6e87ab55d9c4d7e4bfe8ad3013297 Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Wed, 8 Jun 2022 19:15:04 +0700 Subject: [PATCH 27/27] completenolint resulting in a diff that has only nolints --- .../secp256k1/internal/secp256k1/curve.go | 46 +++++++++---------- .../internal/secp256k1/scalar_mult_cgo.go | 7 +-- .../internal/secp256k1/scalar_mult_nocgo.go | 1 + 3 files changed, 28 insertions(+), 26 deletions(-) diff --git a/crypto/keys/secp256k1/internal/secp256k1/curve.go b/crypto/keys/secp256k1/internal/secp256k1/curve.go index f1eeba8a10f3..7db2b81a3db2 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/curve.go +++ b/crypto/keys/secp256k1/internal/secp256k1/curve.go @@ -29,7 +29,7 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - +//nolint package secp256k1 import ( @@ -143,20 +143,20 @@ func (bitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { // addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and // (x2, y2, z2) and returns their sum, also in Jacobian form. -func (bitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) { +func (BitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) { // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl z1z1 := new(big.Int).Mul(z1, z1) - z1z1.Mod(z1z1, bitCurve.P) + z1z1.Mod(z1z1, BitCurve.P) z2z2 := new(big.Int).Mul(z2, z2) - z2z2.Mod(z2z2, bitCurve.P) + z2z2.Mod(z2z2, BitCurve.P) u1 := new(big.Int).Mul(x1, z2z2) - u1.Mod(u1, bitCurve.P) + u1.Mod(u1, BitCurve.P) u2 := new(big.Int).Mul(x2, z1z1) - u2.Mod(u2, bitCurve.P) + u2.Mod(u2, BitCurve.P) h := new(big.Int).Sub(u2, u1) if h.Sign() == -1 { - h.Add(h, bitCurve.P) + h.Add(h, BitCurve.P) } i := new(big.Int).Lsh(h, 1) i.Mul(i, i) @@ -164,13 +164,13 @@ func (bitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int s1 := new(big.Int).Mul(y1, z2) s1.Mul(s1, z2z2) - s1.Mod(s1, bitCurve.P) + s1.Mod(s1, BitCurve.P) s2 := new(big.Int).Mul(y2, z1) s2.Mul(s2, z1z1) - s2.Mod(s2, bitCurve.P) + s2.Mod(s2, BitCurve.P) r := new(big.Int).Sub(s2, s1) if r.Sign() == -1 { - r.Add(r, bitCurve.P) + r.Add(r, BitCurve.P) } r.Lsh(r, 1) v := new(big.Int).Mul(u1, i) @@ -180,7 +180,7 @@ func (bitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int x3.Sub(x3, j) x3.Sub(x3, v) x3.Sub(x3, v) - x3.Mod(x3, bitCurve.P) + x3.Mod(x3, BitCurve.P) y3 := new(big.Int).Set(r) v.Sub(v, x3) @@ -188,33 +188,33 @@ func (bitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int s1.Mul(s1, j) s1.Lsh(s1, 1) y3.Sub(y3, s1) - y3.Mod(y3, bitCurve.P) + y3.Mod(y3, BitCurve.P) z3 := new(big.Int).Add(z1, z2) z3.Mul(z3, z3) z3.Sub(z3, z1z1) if z3.Sign() == -1 { - z3.Add(z3, bitCurve.P) + z3.Add(z3, BitCurve.P) } z3.Sub(z3, z2z2) if z3.Sign() == -1 { - z3.Add(z3, bitCurve.P) + z3.Add(z3, BitCurve.P) } z3.Mul(z3, h) - z3.Mod(z3, bitCurve.P) + z3.Mod(z3, BitCurve.P) return x3, y3, z3 } // Double returns 2*(x,y) -func (bitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { +func (BitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { z1 := new(big.Int).SetInt64(1) - return bitCurve.affineFromJacobian(bitCurve.doubleJacobian(x1, y1, z1)) + return BitCurve.affineFromJacobian(BitCurve.doubleJacobian(x1, y1, z1)) } // doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and // returns its double, also in Jacobian form. -func (bitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) { +func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) { // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l a := new(big.Int).Mul(x, x) // X1² @@ -232,24 +232,24 @@ func (bitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, x3 := new(big.Int).Mul(big.NewInt(2), d) // 2*D x3.Sub(f, x3) // F-2*D - x3.Mod(x3, bitCurve.P) + x3.Mod(x3, BitCurve.P) y3 := new(big.Int).Sub(d, x3) // D-X3 y3.Mul(e, y3) // E*(D-X3) y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) // E*(D-X3)-8*C - y3.Mod(y3, bitCurve.P) + y3.Mod(y3, BitCurve.P) z3 := new(big.Int).Mul(y, z) // Y1*Z1 z3.Mul(big.NewInt(2), z3) // 3*Y1*Z1 - z3.Mod(z3, bitCurve.P) + z3.Mod(z3, BitCurve.P) return x3, y3, z3 } // ScalarBaseMult returns k*G, where G is the base point of the group and k is // an integer in big-endian form. -func (bitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { - return bitCurve.ScalarMult(bitCurve.Gx, bitCurve.Gy, k) +func (BitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { + return BitCurve.ScalarMult(BitCurve.Gx, BitCurve.Gy, k) } // Marshal converts a point into the form specified in section 4.3.6 of ANSI diff --git a/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go b/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go index 4090923a3c43..2c7a1611c336 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go +++ b/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_cgo.go @@ -5,6 +5,7 @@ //go:build !gofuzz && cgo // +build !gofuzz,cgo +//nolint package secp256k1 import ( @@ -21,7 +22,7 @@ extern int secp256k1_ext_scalar_mul(const secp256k1_context* ctx, const unsigned */ import "C" -func (bitCurve *BitCurve) ScalarMult(bx, by *big.Int, scalar []byte) (*big.Int, *big.Int) { +func (BitCurve *BitCurve) ScalarMult(Bx, By *big.Int, scalar []byte) (*big.Int, *big.Int) { // Ensure scalar is exactly 32 bytes. We pad always, even if // scalar is 32 bytes long, to avoid a timing side channel. if len(scalar) > 32 { @@ -34,8 +35,8 @@ func (bitCurve *BitCurve) ScalarMult(bx, by *big.Int, scalar []byte) (*big.Int, // Do the multiplication in C, updating point. point := make([]byte, 64) - readBits(bx, point[:32]) - readBits(by, point[32:]) + readBits(Bx, point[:32]) + readBits(By, point[32:]) pointPtr := (*C.uchar)(unsafe.Pointer(&point[0])) scalarPtr := (*C.uchar)(unsafe.Pointer(&scalar[0])) diff --git a/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_nocgo.go b/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_nocgo.go index 22f53ac6ae65..9588707408c0 100644 --- a/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_nocgo.go +++ b/crypto/keys/secp256k1/internal/secp256k1/scalar_mult_nocgo.go @@ -5,6 +5,7 @@ //go:build gofuzz || !cgo // +build gofuzz !cgo +//nolint package secp256k1 import "math/big"