Skip to content

Commit

Permalink
chore: sdk.Int to math.Int (#12132)
Browse files Browse the repository at this point in the history
## Description

When locally working with golangci-lint, we can see that there were many deprecation warnings about sdk.Int.  This PR resolves that and makes 1-2 other linting related changes.  Issue on linting coming next.

This also moves BitCurve to bitCurve.

I expect that this set of changes will require several pull requests, one of them to the settings for the linter. 

It also does a gofumpt, because we had various formatting-related linters fail, too. 


---

### Author Checklist

*All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.*

I have...

- [x] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title
- [ ] added `!` to the type prefix if API or client breaking change
- [x] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#pr-targeting))
- [x] provided a link to the relevant issue or specification
- [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/main/docs/building-modules)
- [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/main/CONTRIBUTING.md#testing)
- [x] added a changelog entry to `CHANGELOG.md`
- [ ] included comments for [documenting Go code](https://blog.golang.org/godoc)
- [ ] updated the relevant documentation or specification
- [x] reviewed "Files changed" and left comments if necessary
- [x] confirmed all CI checks have passed

### Reviewers Checklist

*All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.*

I have...

- [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title
- [ ] confirmed `!` in the type prefix if API or client breaking change
- [ ] confirmed all author checklist items have been addressed 
- [ ] reviewed state machine logic
- [ ] reviewed API design and naming
- [ ] reviewed documentation is accurate
- [ ] reviewed tests and test coverage
- [ ] manually tested (if applicable)
  • Loading branch information
faddat committed Jun 3, 2022
1 parent 9461c65 commit 78e2e35
Show file tree
Hide file tree
Showing 78 changed files with 235 additions and 234 deletions.
2 changes: 0 additions & 2 deletions .golangci.yml
Expand Up @@ -10,7 +10,6 @@ linters:
- deadcode
- depguard
- dogsled
# - errcheck
- exportloopref
- goconst
- gocritic
Expand All @@ -32,7 +31,6 @@ linters:
- unconvert
- unparam
- unused
# - wsl

issues:
exclude-rules:
Expand Down
2 changes: 1 addition & 1 deletion CHANGELOG.md
Expand Up @@ -50,7 +50,7 @@ Ref: https://keepachangelog.com/en/1.0.0/
* (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.

### 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.
Expand Down
3 changes: 1 addition & 2 deletions baseapp/baseapp.go
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down
1 change: 0 additions & 1 deletion baseapp/baseapp_test.go
Expand Up @@ -1294,7 +1294,6 @@ func TestTxGasLimits(t *testing.T) {

return newCtx, nil
})

}

routerOpt := func(bapp *BaseApp) {
Expand Down
2 changes: 1 addition & 1 deletion client/cmd.go
Expand Up @@ -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")
Expand Down
4 changes: 2 additions & 2 deletions client/grpc/tmservice/block.go
Expand Up @@ -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
}
2 changes: 1 addition & 1 deletion client/grpc_query.go
Expand Up @@ -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
}

Expand Down
2 changes: 1 addition & 1 deletion client/keys/add.go
Expand Up @@ -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)
}
}
Expand Down
1 change: 0 additions & 1 deletion core/appconfig/config.go
Expand Up @@ -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)
}

Expand Down
2 changes: 1 addition & 1 deletion crypto/keyring/keyring_test.go
Expand Up @@ -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()
Expand Down
50 changes: 25 additions & 25 deletions crypto/keys/secp256k1/internal/secp256k1/curve.go
Expand Up @@ -79,53 +79,53 @@ 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
}

// 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 {
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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])
Expand All @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion depinject/debug.go
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion pruning/manager.go
Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions runtime/app.go
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion runtime/module.go
Expand Up @@ -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()

Expand Down
6 changes: 4 additions & 2 deletions server/mock/tx.go
Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion server/rosetta/converter.go
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down
2 changes: 0 additions & 2 deletions server/tm_cmds.go
Expand Up @@ -165,7 +165,6 @@ func makeKeyMigrateCmd() *cobra.Command {
ID: dbctx,
Config: config,
})

if err != nil {
return fmt.Errorf("constructing database handle: %w", err)
}
Expand All @@ -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)

}
}
}
Expand Down
7 changes: 4 additions & 3 deletions simapp/app.go
Expand Up @@ -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...)

Expand Down Expand Up @@ -434,7 +436,6 @@ func (app *SimApp) setAnteHandler(txConfig client.TxConfig, indexEventsStr []str
SigGasConsumer: ante.DefaultSigVerificationGasConsumer,
},
)

if err != nil {
panic(err)
}
Expand Down
13 changes: 7 additions & 6 deletions simapp/test_helpers.go
Expand Up @@ -6,8 +6,6 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
"github.com/cosmos/cosmos-sdk/depinject"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
"strconv"
"testing"
"time"
Expand All @@ -21,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"
Expand Down Expand Up @@ -306,7 +307,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 {
Expand All @@ -316,17 +317,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))
Expand Down
2 changes: 1 addition & 1 deletion snapshots/types/util.go
Expand Up @@ -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{
Expand Down

0 comments on commit 78e2e35

Please sign in to comment.