From 3a4f1fc4d4e1d234d09bab911ed3891084f90aa5 Mon Sep 17 00:00:00 2001 From: Marko Date: Mon, 19 Aug 2019 18:06:27 +0200 Subject: [PATCH] Merge PR #4881: Linting Galore --- .golangci.yml | 46 +++++++++++------------- baseapp/baseapp.go | 6 ++-- baseapp/baseapp_test.go | 4 --- client/context/errors.go | 4 +-- client/keys/add.go | 4 +-- client/keys/codec_test.go | 10 +++--- client/keys/mnemonic.go | 2 +- client/keys/utils.go | 2 +- codec/codec.go | 2 +- crypto/keys/hd/hdpath.go | 8 ++--- crypto/keys/keybase.go | 18 +++++----- crypto/keys/keybase_test.go | 15 +++++--- crypto/keys/lazy_keybase_test.go | 8 ++--- crypto/keys/mintkey/mintkey.go | 14 ++++---- crypto/ledger_secp256k1.go | 6 ++-- server/start.go | 1 + simapp/state.go | 2 +- simapp/utils_test.go | 8 ----- store/cachekv/store.go | 7 ++-- store/cachemulti/store.go | 2 +- store/gaskv/store_test.go | 6 ---- store/rootmulti/store.go | 2 +- store/transient/store.go | 4 +-- store/types/gas_test.go | 1 - store/types/utils.go | 5 ++- types/address.go | 2 +- types/coin.go | 8 ++--- types/dec_coin.go | 7 ++-- types/decimal.go | 4 +-- types/errors/abci_test.go | 6 ++-- types/rest/rest.go | 8 ++--- types/rest/rest_test.go | 2 -- x/auth/client/cli/query.go | 2 +- x/auth/simulation/decoder_test.go | 6 ++-- x/auth/types/account.go | 10 +++--- x/auth/types/account_retriever_test.go | 8 ++--- x/bank/app_test.go | 12 +------ x/bank/simulation/operations/msgs.go | 4 +-- x/distribution/keeper/delegation_test.go | 5 --- x/distribution/keeper/querier.go | 2 +- x/gov/client/cli/query.go | 6 ++-- x/gov/keeper/querier.go | 7 ++-- x/gov/keeper/querier_test.go | 37 ------------------- x/gov/keeper/test_common.go | 5 +-- x/gov/simulation/decoder_test.go | 10 +++--- x/gov/test_common.go | 9 +++-- x/gov/types/genesis.go | 6 ++-- x/gov/types/msgs_test.go | 9 +++-- x/mint/internal/types/params.go | 12 +++---- x/mock/app_test.go | 6 ++-- x/simulation/config.go | 2 +- x/simulation/event_stats.go | 2 +- x/simulation/mock_tendermint.go | 2 +- x/simulation/simulate.go | 2 +- x/simulation/transition_matrix.go | 2 +- x/slashing/client/cli/query.go | 2 +- x/slashing/internal/types/genesis.go | 12 +++---- x/slashing/simulation/decoder_test.go | 1 + x/staking/client/cli/query.go | 2 +- x/staking/genesis.go | 2 +- x/staking/genesis_test.go | 14 ++++---- x/staking/handler.go | 4 +-- x/staking/handler_test.go | 2 +- x/staking/keeper/delegation_test.go | 3 +- x/staking/keeper/querier.go | 9 ++--- x/staking/keeper/querier_test.go | 2 +- x/staking/keeper/test_common.go | 2 +- x/staking/keeper/val_state_change.go | 4 +-- x/staking/keeper/validator.go | 9 ++--- x/staking/keeper/validator_test.go | 10 +++--- x/staking/simulation/decoder_test.go | 7 ++-- x/staking/types/keys.go | 6 ++-- x/staking/types/msg.go | 2 +- x/staking/types/params.go | 8 ++--- x/supply/internal/types/supply.go | 2 +- 75 files changed, 209 insertions(+), 284 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 78b0de8b1b..0373de8806 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,26 +1,22 @@ -linters: - disable-all: true - enable: - - errcheck - - golint - - ineffassign - - unconvert - - misspell - - govet - - unused - - deadcode - - goconst - - gosec - - staticcheck -linters-settings: - gocyclo: - min-complexity: 11 - errcheck: - ignore: fmt:.*,io/ioutil:^Read.*,github.com/spf13/cobra:MarkFlagRequired,github.com/spf13/viper:BindPFlag - golint: - min-confidence: 1.1 -issues: - exclude: - - composite run: - tests: false + deadline: 1m + +linters: + enable-all: true + disable: + - gosimple + - gocyclo + - gochecknoinits + - golint + - gochecknoglobals + - dupl + - interfacer + - gosec + - unparam + - lll + - maligned + - nakedret + - errcheck + - scopelint + - prealloc + - varcheck diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index d336e79fca..04839d2231 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -246,18 +246,18 @@ func UpgradeableStoreLoader(upgradeInfoPath string) StoreLoader { // there is a migration file, let's execute data, err := ioutil.ReadFile(upgradeInfoPath) if err != nil { - return fmt.Errorf("Cannot read upgrade file %s: %v", upgradeInfoPath, err) + return fmt.Errorf("cannot read upgrade file %s: %v", upgradeInfoPath, err) } var upgrades storetypes.StoreUpgrades err = json.Unmarshal(data, &upgrades) if err != nil { - return fmt.Errorf("Cannot parse upgrade file: %v", err) + return fmt.Errorf("cannot parse upgrade file: %v", err) } err = ms.LoadLatestVersionAndUpgrade(&upgrades) if err != nil { - return fmt.Errorf("Load and upgrade database: %v", err) + return fmt.Errorf("load and upgrade database: %v", err) } // if we have a successful load, we delete the file diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index 44043a7809..eb50fc3ed2 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -626,10 +626,6 @@ func handlerMsgCounter(t *testing.T, capKey *sdk.KVStoreKey, deliverKey []byte) } } -func i2b(i int64) []byte { - return []byte{byte(i)} -} - func getIntFromStore(store sdk.KVStore, key []byte) int64 { bz := store.Get(key) if len(bz) == 0 { diff --git a/client/context/errors.go b/client/context/errors.go index 55f11f8453..2c83c375dd 100644 --- a/client/context/errors.go +++ b/client/context/errors.go @@ -9,7 +9,7 @@ import ( // ErrInvalidAccount returns a standardized error reflecting that a given // account address does not exist. func ErrInvalidAccount(addr sdk.AccAddress) error { - return fmt.Errorf(`No account with address %s was found in the state. + return fmt.Errorf(`no account with address %s was found in the state. Are you sure there has been a transaction involving it?`, addr) } @@ -17,6 +17,6 @@ Are you sure there has been a transaction involving it?`, addr) // height can't be verified. The reason is that the base checkpoint of the certifier is // newer than the given height func ErrVerifyCommit(height int64) error { - return fmt.Errorf(`The height of base truststore in the light client is higher than height %d. + return fmt.Errorf(`the height of base truststore in the light client is higher than height %d. Can't verify blockchain proof at this height. Please set --trust-node to true and try again`, height) } diff --git a/client/keys/add.go b/client/keys/add.go index 3ff88c72a0..8ff444010a 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -215,7 +215,7 @@ func runAddCmd(cmd *cobra.Command, args []string) error { return err } - mnemonic, err = bip39.NewMnemonic(entropySeed[:]) + mnemonic, err = bip39.NewMnemonic(entropySeed) if err != nil { return err } @@ -295,7 +295,7 @@ func printCreate(cmd *cobra.Command, info keys.Info, showMnemonic bool, mnemonic } cmd.PrintErrln(string(jsonString)) default: - return fmt.Errorf("I can't speak: %s", output) + return fmt.Errorf("invalid output format %s", output) } return nil diff --git a/client/keys/codec_test.go b/client/keys/codec_test.go index 56f12471d5..54499dcd8a 100644 --- a/client/keys/codec_test.go +++ b/client/keys/codec_test.go @@ -47,12 +47,12 @@ func TestMarshalJSON(t *testing.T) { want []byte wantErr bool }{ - {"basic", args{data.Keys[0]}, []byte(data.JSON[0]), false}, - {"mnemonic is optional", args{data.Keys[1]}, []byte(data.JSON[1]), false}, + {"basic", args{data.Keys[0]}, data.JSON[0], false}, + {"mnemonic is optional", args{data.Keys[1]}, data.JSON[1], false}, // REVIEW: Are the next results expected?? - {"empty name", args{data.Keys[2]}, []byte(data.JSON[2]), false}, - {"empty object", args{data.Keys[3]}, []byte(data.JSON[3]), false}, + {"empty name", args{data.Keys[2]}, data.JSON[2], false}, + {"empty object", args{data.Keys[3]}, data.JSON[3], false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -92,7 +92,7 @@ func TestUnmarshalJSON(t *testing.T) { for idx, tt := range tests { t.Run(tt.name, func(t *testing.T) { if err := UnmarshalJSON(tt.args.bz, tt.args.ptr); (err != nil) != tt.wantErr { - t.Errorf("UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("unmarshalJSON() error = %v, wantErr %v", err, tt.wantErr) } // Confirm deserialized objects are the same diff --git a/client/keys/mnemonic.go b/client/keys/mnemonic.go index fcc73a9805..c5b7f9a08b 100644 --- a/client/keys/mnemonic.go +++ b/client/keys/mnemonic.go @@ -65,7 +65,7 @@ func runMnemonicCmd(cmd *cobra.Command, args []string) error { } } - mnemonic, err := bip39.NewMnemonic(entropySeed[:]) + mnemonic, err := bip39.NewMnemonic(entropySeed) if err != nil { return err } diff --git a/client/keys/utils.go b/client/keys/utils.go index 054f9938dc..b708bdefef 100644 --- a/client/keys/utils.go +++ b/client/keys/utils.go @@ -69,7 +69,7 @@ func ReadPassphraseFromStdin(name string) (string, error) { passphrase, err := input.GetPassword(prompt, buf) if err != nil { - return passphrase, fmt.Errorf("Error reading passphrase: %v", err) + return passphrase, fmt.Errorf("error reading passphrase: %v", err) } return passphrase, nil diff --git a/codec/codec.go b/codec/codec.go index 048a9cca44..6cf2f623d7 100644 --- a/codec/codec.go +++ b/codec/codec.go @@ -5,7 +5,7 @@ import ( "encoding/json" "fmt" - "github.com/tendermint/go-amino" + amino "github.com/tendermint/go-amino" cryptoamino "github.com/tendermint/tendermint/crypto/encoding/amino" tmtypes "github.com/tendermint/tendermint/types" ) diff --git a/crypto/keys/hd/hdpath.go b/crypto/keys/hd/hdpath.go index 94ca286966..165feca3ec 100644 --- a/crypto/keys/hd/hdpath.go +++ b/crypto/keys/hd/hdpath.go @@ -207,7 +207,7 @@ func DerivePrivateKeyForPath(privKeyBytes [32]byte, chainCode [32]byte, path str func derivePrivateKey(privKeyBytes [32]byte, chainCode [32]byte, index uint32, harden bool) ([32]byte, [32]byte) { var data []byte if harden { - index = index | 0x80000000 + index |= 0x80000000 data = append([]byte{byte(0)}, privKeyBytes[:]...) } else { // this can't return an error: @@ -245,14 +245,14 @@ func uint32ToBytes(i uint32) []byte { } // i64 returns the two halfs of the SHA512 HMAC of key and data. -func i64(key []byte, data []byte) (IL [32]byte, IR [32]byte) { +func i64(key []byte, data []byte) (il [32]byte, ir [32]byte) { mac := hmac.New(sha512.New, key) // sha512 does not err _, _ = mac.Write(data) I := mac.Sum(nil) - copy(IL[:], I[:32]) - copy(IR[:], I[32:]) + copy(il[:], I[:32]) + copy(ir[:], I[32:]) return } diff --git a/crypto/keys/keybase.go b/crypto/keys/keybase.go index 068a0c4b06..79840f8b27 100644 --- a/crypto/keys/keybase.go +++ b/crypto/keys/keybase.go @@ -235,22 +235,20 @@ func (kb dbKeybase) Sign(name, passphrase string, msg []byte) (sig []byte, pub t var priv tmcrypto.PrivKey - switch info.(type) { + switch i := info.(type) { case localInfo: - linfo := info.(localInfo) - if linfo.PrivKeyArmor == "" { + if i.PrivKeyArmor == "" { err = fmt.Errorf("private key not available") return } - priv, err = mintkey.UnarmorDecryptPrivKey(linfo.PrivKeyArmor, passphrase) + priv, err = mintkey.UnarmorDecryptPrivKey(i.PrivKeyArmor, passphrase) if err != nil { return nil, nil, err } case ledgerInfo: - linfo := info.(ledgerInfo) - priv, err = crypto.NewPrivKeyLedgerSecp256k1Unsafe(linfo.Path) + priv, err = crypto.NewPrivKeyLedgerSecp256k1Unsafe(i.Path) if err != nil { return } @@ -297,9 +295,9 @@ func (kb dbKeybase) ExportPrivateKeyObject(name string, passphrase string) (tmcr var priv tmcrypto.PrivKey - switch info.(type) { + switch i := info.(type) { case localInfo: - linfo := info.(localInfo) + linfo := i if linfo.PrivKeyArmor == "" { err = fmt.Errorf("private key not available") return nil, err @@ -434,9 +432,9 @@ func (kb dbKeybase) Update(name, oldpass string, getNewpass func() (string, erro if err != nil { return err } - switch info.(type) { + switch i := info.(type) { case localInfo: - linfo := info.(localInfo) + linfo := i key, err := mintkey.UnarmorDecryptPrivKey(linfo.PrivKeyArmor, oldpass) if err != nil { return err diff --git a/crypto/keys/keybase_test.go b/crypto/keys/keybase_test.go index 7670d8afd3..559dccbf9c 100644 --- a/crypto/keys/keybase_test.go +++ b/crypto/keys/keybase_test.go @@ -19,6 +19,11 @@ func init() { mintkey.BcryptSecurityParameter = 1 } +const ( + nums = "1234" + foobar = "foobar" +) + func TestLanguage(t *testing.T) { kb := NewInMemory() _, _, err := kb.CreateMnemonic("something", Japanese, "no_pass", Secp256k1) @@ -68,11 +73,13 @@ func TestCreateLedger(t *testing.T) { // Check that restoring the key gets the same results restoredKey, err := kb.Get("some_account") + assert.NoError(t, err) assert.NotNil(t, restoredKey) assert.Equal(t, "some_account", restoredKey.GetName()) assert.Equal(t, TypeLedger, restoredKey.GetType()) pubKey = restoredKey.GetPubKey() pk, err = sdk.Bech32ifyAccPub(pubKey) + assert.NoError(t, err) assert.Equal(t, "cosmospub1addwnpepqdszcr95mrqqs8lw099aa9h8h906zmet22pmwe9vquzcgvnm93eqygufdlv", pk) path, err := restoredKey.GetPath() @@ -87,7 +94,7 @@ func TestKeyManagement(t *testing.T) { algo := Secp256k1 n1, n2, n3 := "personal", "business", "other" - p1, p2 := "1234", "really-secure!@#$" + p1, p2 := nums, "really-secure!@#$" // Check empty state l, err := cstore.List() @@ -170,7 +177,7 @@ func TestSignVerify(t *testing.T) { algo := Secp256k1 n1, n2, n3 := "some dude", "a dudette", "dude-ish" - p1, p2, p3 := "1234", "foobar", "foobar" + p1, p2, p3 := nums, foobar, foobar // create two users and get their info i1, _, err := cstore.CreateMnemonic(n1, English, p1, algo) @@ -320,7 +327,7 @@ func TestAdvancedKeyManagement(t *testing.T) { algo := Secp256k1 n1, n2 := "old-name", "new name" - p1, p2 := "1234", "foobar" + p1, p2 := nums, foobar // make sure key works with initial password _, _, err := cstore.CreateMnemonic(n1, English, p1, algo) @@ -368,7 +375,7 @@ func TestSeedPhrase(t *testing.T) { algo := Secp256k1 n1, n2 := "lost-key", "found-again" - p1, p2 := "1234", "foobar" + p1, p2 := nums, foobar // make sure key works with initial password info, mnemonic, err := cstore.CreateMnemonic(n1, English, p1, algo) diff --git a/crypto/keys/lazy_keybase_test.go b/crypto/keys/lazy_keybase_test.go index b97ffc40d4..1dabc9b8eb 100644 --- a/crypto/keys/lazy_keybase_test.go +++ b/crypto/keys/lazy_keybase_test.go @@ -30,7 +30,7 @@ func TestLazyKeyManagement(t *testing.T) { algo := Secp256k1 n1, n2, n3 := "personal", "business", "other" - p1, p2 := "1234", "really-secure!@#$" + p1, p2 := nums, "really-secure!@#$" // Check empty state l, err := kb.List() @@ -113,7 +113,7 @@ func TestLazySignVerify(t *testing.T) { algo := Secp256k1 n1, n2, n3 := "some dude", "a dudette", "dude-ish" - p1, p2, p3 := "1234", "foobar", "foobar" + p1, p2, p3 := nums, foobar, foobar // create two users and get their info i1, _, err := kb.CreateMnemonic(n1, English, p1, algo) @@ -301,7 +301,7 @@ func TestLazyAdvancedKeyManagement(t *testing.T) { algo := Secp256k1 n1, n2 := "old-name", "new name" - p1, p2 := "1234", "foobar" + p1, p2 := nums, foobar // make sure key works with initial password _, _, err := kb.CreateMnemonic(n1, English, p1, algo) @@ -349,7 +349,7 @@ func TestLazySeedPhrase(t *testing.T) { algo := Secp256k1 n1, n2 := "lost-key", "found-again" - p1, p2 := "1234", "foobar" + p1, p2 := nums, foobar // make sure key works with initial password info, mnemonic, err := kb.CreateMnemonic(n1, English, p1, algo) diff --git a/crypto/keys/mintkey/mintkey.go b/crypto/keys/mintkey/mintkey.go index 7b24a53894..6b3a3af8ad 100644 --- a/crypto/keys/mintkey/mintkey.go +++ b/crypto/keys/mintkey/mintkey.go @@ -77,11 +77,11 @@ func unarmorBytes(armorStr, blockType string) (bz []byte, err error) { return } if bType != blockType { - err = fmt.Errorf("Unrecognized armor type %q, expected: %q", bType, blockType) + err = fmt.Errorf("unrecognized armor type %q, expected: %q", bType, blockType) return } if header["version"] != "0.0.0" { - err = fmt.Errorf("Unrecognized version: %v", header["version"]) + err = fmt.Errorf("unrecognized version: %v", header["version"]) return } return @@ -123,17 +123,17 @@ func UnarmorDecryptPrivKey(armorStr string, passphrase string) (crypto.PrivKey, return privKey, err } if blockType != blockTypePrivKey { - return privKey, fmt.Errorf("Unrecognized armor type: %v", blockType) + return privKey, fmt.Errorf("unrecognized armor type: %v", blockType) } if header["kdf"] != "bcrypt" { - return privKey, fmt.Errorf("Unrecognized KDF type: %v", header["KDF"]) + return privKey, fmt.Errorf("unrecognized KDF type: %v", header["KDF"]) } if header["salt"] == "" { - return privKey, fmt.Errorf("Missing salt bytes") + return privKey, fmt.Errorf("missing salt bytes") } saltBytes, err := hex.DecodeString(header["salt"]) if err != nil { - return privKey, fmt.Errorf("Error decoding salt: %v", err.Error()) + return privKey, fmt.Errorf("error decoding salt: %v", err.Error()) } privKey, err = decryptPrivKey(saltBytes, encBytes, passphrase) return privKey, err @@ -142,7 +142,7 @@ func UnarmorDecryptPrivKey(armorStr string, passphrase string) (crypto.PrivKey, func decryptPrivKey(saltBytes []byte, encBytes []byte, passphrase string) (privKey crypto.PrivKey, err error) { key, err := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), BcryptSecurityParameter) if err != nil { - cmn.Exit("Error generating bcrypt key from passphrase: " + err.Error()) + cmn.Exit("error generating bcrypt key from passphrase: " + err.Error()) } key = crypto.Sha256(key) // Get 32 bytes privKeyBytes, err := xsalsa20symmetric.DecryptSymmetric(encBytes, key) diff --git a/crypto/ledger_secp256k1.go b/crypto/ledger_secp256k1.go index 7e986adb38..eb1c9efe51 100644 --- a/crypto/ledger_secp256k1.go +++ b/crypto/ledger_secp256k1.go @@ -171,7 +171,7 @@ func warnIfErrors(f func() error) { } func convertDERtoBER(signatureDER []byte) ([]byte, error) { - sigDER, err := btcec.ParseDERSignature(signatureDER[:], btcec.S256()) + sigDER, err := btcec.ParseDERSignature(signatureDER, btcec.S256()) if err != nil { return nil, err } @@ -240,7 +240,7 @@ func getPubKeyUnsafe(device LedgerSECP256K1, path hd.BIP44Params) (tmcrypto.PubK } // re-serialize in the 33-byte compressed format - cmp, err := btcec.ParsePubKey(publicKey[:], btcec.S256()) + cmp, err := btcec.ParsePubKey(publicKey, btcec.S256()) if err != nil { return nil, fmt.Errorf("error parsing public key: %v", err) } @@ -264,7 +264,7 @@ func getPubKeyAddrSafe(device LedgerSECP256K1, path hd.BIP44Params, hrp string) } // re-serialize in the 33-byte compressed format - cmp, err := btcec.ParsePubKey(publicKey[:], btcec.S256()) + cmp, err := btcec.ParsePubKey(publicKey, btcec.S256()) if err != nil { return nil, "", fmt.Errorf("error parsing public key: %v", err) } diff --git a/server/start.go b/server/start.go index faa49cc672..313437763d 100644 --- a/server/start.go +++ b/server/start.go @@ -99,6 +99,7 @@ func startStandAlone(ctx *Context, appCreator AppCreator) error { // run forever (the node will not be returned) select {} + } func startInProcess(ctx *Context, appCreator AppCreator) (*node.Node, error) { diff --git a/simapp/state.go b/simapp/state.go index e9405ddda8..c3a6c55ffa 100644 --- a/simapp/state.go +++ b/simapp/state.go @@ -135,7 +135,7 @@ func AppStateFromGenesisFileFn(r *rand.Rand, config simulation.Config) (json.Raw r.Read(privkeySeed) privKey := secp256k1.GenPrivKeySecp256k1(privkeySeed) - newAccs = append(newAccs, simulation.Account{privKey, privKey.PubKey(), acc.Address}) + newAccs = append(newAccs, simulation.Account{PrivKey: privKey, PubKey: privKey.PubKey(), Address: acc.Address}) } return genesis.AppState, newAccs, genesis.ChainID diff --git a/simapp/utils_test.go b/simapp/utils_test.go index d64ea8999d..ed055f1d9b 100644 --- a/simapp/utils_test.go +++ b/simapp/utils_test.go @@ -6,7 +6,6 @@ import ( "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/ed25519" cmn "github.com/tendermint/tendermint/libs/common" "github.com/cosmos/cosmos-sdk/codec" @@ -16,13 +15,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -var ( - delPk1 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.AccAddress(delPk1.Address()) - valAddr1 = sdk.ValAddress(delPk1.Address()) - consAddr1 = sdk.ConsAddress(delPk1.Address().Bytes()) -) - func makeTestCodec() (cdc *codec.Codec) { cdc = codec.New() sdk.RegisterCodec(cdc) diff --git a/store/cachekv/store.go b/store/cachekv/store.go index eb1c7fddd6..ec457aeb0a 100644 --- a/store/cachekv/store.go +++ b/store/cachekv/store.go @@ -111,11 +111,12 @@ func (store *Store) Write() { // at least happen atomically. for _, key := range keys { cacheValue := store.cache[key] - if cacheValue.deleted { + switch { + case cacheValue.deleted: store.parent.Delete([]byte(key)) - } else if cacheValue.value == nil { + case cacheValue.value == nil: // Skip, it already doesn't exist in parent. - } else { + default: store.parent.Set([]byte(key), cacheValue.value) } } diff --git a/store/cachemulti/store.go b/store/cachemulti/store.go index 1c9f1e43c2..0e42ab00b4 100644 --- a/store/cachemulti/store.go +++ b/store/cachemulti/store.go @@ -58,7 +58,7 @@ func NewStore( stores map[types.StoreKey]types.CacheWrapper, keys map[string]types.StoreKey, traceWriter io.Writer, traceContext types.TraceContext, ) Store { - return NewFromKVStore(dbadapter.Store{db}, stores, keys, traceWriter, traceContext) + return NewFromKVStore(dbadapter.Store{DB: db}, stores, keys, traceWriter, traceContext) } func newCacheMultiStoreFromCMS(cms Store) Store { diff --git a/store/gaskv/store_test.go b/store/gaskv/store_test.go index 811a833775..470a818d94 100644 --- a/store/gaskv/store_test.go +++ b/store/gaskv/store_test.go @@ -13,12 +13,6 @@ import ( "github.com/stretchr/testify/require" ) -func newGasKVStore() types.KVStore { - meter := types.NewGasMeter(10000) - mem := dbadapter.Store{dbm.NewMemDB()} - return gaskv.NewStore(mem, meter, types.KVGasConfig()) -} - func bz(s string) []byte { return []byte(s) } func keyFmt(i int) []byte { return bz(fmt.Sprintf("key%0.8d", i)) } diff --git a/store/rootmulti/store.go b/store/rootmulti/store.go index 896b7dac4e..c1fdb6ad29 100644 --- a/store/rootmulti/store.go +++ b/store/rootmulti/store.go @@ -460,7 +460,7 @@ func (rs *Store) loadCommitStoreFromParams(key types.StoreKey, id types.CommitID return iavl.LoadStore(db, id, rs.pruningOpts, rs.lazyLoading) case types.StoreTypeDB: - return commitDBStoreAdapter{dbadapter.Store{db}}, nil + return commitDBStoreAdapter{Store: dbadapter.Store{DB: db}}, nil case types.StoreTypeTransient: _, ok := key.(*types.TransientStoreKey) diff --git a/store/transient/store.go b/store/transient/store.go index 3c2e6845c7..488965a43a 100644 --- a/store/transient/store.go +++ b/store/transient/store.go @@ -18,13 +18,13 @@ type Store struct { // Constructs new MemDB adapter func NewStore() *Store { - return &Store{dbadapter.Store{dbm.NewMemDB()}} + return &Store{Store: dbadapter.Store{DB: dbm.NewMemDB()}} } // Implements CommitStore // Commit cleans up Store. func (ts *Store) Commit() (id types.CommitID) { - ts.Store = dbadapter.Store{dbm.NewMemDB()} + ts.Store = dbadapter.Store{DB: dbm.NewMemDB()} return } diff --git a/store/types/gas_test.go b/store/types/gas_test.go index 81bb0c9017..71ec66ce7e 100644 --- a/store/types/gas_test.go +++ b/store/types/gas_test.go @@ -40,7 +40,6 @@ func TestGasMeter(t *testing.T) { require.Panics(t, func() { meter.ConsumeGas(1, "") }, "Exceeded but not panicked. tc #%d", tcnum) require.Equal(t, meter.GasConsumedToLimit(), meter.Limit(), "Gas consumption (to limit) not match limit") require.Equal(t, meter.GasConsumed(), meter.Limit()+1, "Gas consumption not match limit+1") - break } } diff --git a/store/types/utils.go b/store/types/utils.go index 9efcd02f16..2abd6db62b 100644 --- a/store/types/utils.go +++ b/store/types/utils.go @@ -82,9 +82,8 @@ func PrefixEndBytes(prefix []byte) []byte { // InclusiveEndBytes returns the []byte that would end a // range query such that the input would be included -func InclusiveEndBytes(inclusiveBytes []byte) (exclusiveBytes []byte) { - exclusiveBytes = append(inclusiveBytes, byte(0x00)) - return exclusiveBytes +func InclusiveEndBytes(inclusiveBytes []byte) []byte { + return append(inclusiveBytes, byte(0x00)) } //---------------------------------------- diff --git a/types/address.go b/types/address.go index 4130adbc60..19e81a1a77 100644 --- a/types/address.go +++ b/types/address.go @@ -119,7 +119,7 @@ func VerifyAddressFormat(bz []byte) error { return verifier(bz) } if len(bz) != AddrLen { - return errors.New("Incorrect address length") + return errors.New("incorrect address length") } return nil } diff --git a/types/coin.go b/types/coin.go index b68948e7a7..2af2abc2df 100644 --- a/types/coin.go +++ b/types/coin.go @@ -495,12 +495,12 @@ func (coins Coins) AmountOf(denom string) Int { default: midIdx := len(coins) / 2 // 2:1, 3:1, 4:2 coin := coins[midIdx] - - if denom < coin.Denom { + switch { + case denom < coin.Denom: return coins[:midIdx].AmountOf(denom) - } else if denom == coin.Denom { + case denom == coin.Denom: return coin.Amount - } else { + default: return coins[midIdx+1:].AmountOf(denom) } } diff --git a/types/dec_coin.go b/types/dec_coin.go index 1ecfd82608..a47fc21894 100644 --- a/types/dec_coin.go +++ b/types/dec_coin.go @@ -423,11 +423,12 @@ func (coins DecCoins) AmountOf(denom string) Dec { midIdx := len(coins) / 2 // 2:1, 3:1, 4:2 coin := coins[midIdx] - if denom < coin.Denom { + switch { + case denom < coin.Denom: return coins[:midIdx].AmountOf(denom) - } else if denom == coin.Denom { + case denom == coin.Denom: return coin.Amount - } else { + default: return coins[midIdx+1:].AmountOf(denom) } } diff --git a/types/decimal.go b/types/decimal.go index 1a16cebc83..7f8d004e5e 100644 --- a/types/decimal.go +++ b/types/decimal.go @@ -149,7 +149,7 @@ func NewDecFromStr(str string) (d Dec, err Error) { if lenDecs == 0 || len(combinedStr) == 0 { return d, ErrUnknownRequest("bad decimal length") } - combinedStr = combinedStr + strs[1] + combinedStr += strs[1] } else if len(strs) > 2 { return d, ErrUnknownRequest("too many periods to be a decimal string") @@ -163,7 +163,7 @@ func NewDecFromStr(str string) (d Dec, err Error) { // add some extra zero's to correct to the Precision factor zerosToAdd := Precision - lenDecs zeros := fmt.Sprintf(`%0`+strconv.Itoa(zerosToAdd)+`s`, "") - combinedStr = combinedStr + zeros + combinedStr += zeros combined, ok := new(big.Int).SetString(combinedStr, 10) // base 10 if !ok { diff --git a/types/errors/abci_test.go b/types/errors/abci_test.go index a1210a6bdc..55b783113f 100644 --- a/types/errors/abci_test.go +++ b/types/errors/abci_test.go @@ -150,10 +150,8 @@ func TestABCIInfoStacktrace(t *testing.T) { if !strings.Contains(log, tc.wantErrMsg) { t.Errorf("log does not contain expected error message: %s", log) } - } else { - if log != tc.wantErrMsg { - t.Fatalf("unexpected log message: %s", log) - } + } else if log != tc.wantErrMsg { + t.Fatalf("unexpected log message: %s", log) } }) } diff --git a/types/rest/rest.go b/types/rest/rest.go index bcaaba62db..89770c9446 100644 --- a/types/rest/rest.go +++ b/types/rest/rest.go @@ -247,9 +247,9 @@ func PostProcessResponseBare(w http.ResponseWriter, cliCtx context.CLIContext, b err error ) - switch body.(type) { + switch b := body.(type) { case []byte: - resp = body.([]byte) + resp = b default: if cliCtx.Indent { @@ -279,9 +279,9 @@ func PostProcessResponse(w http.ResponseWriter, cliCtx context.CLIContext, resp return } - switch resp.(type) { + switch res := resp.(type) { case []byte: - result = resp.([]byte) + result = res default: var err error diff --git a/types/rest/rest_test.go b/types/rest/rest_test.go index dd9d800b1a..17d0e3638b 100644 --- a/types/rest/rest_test.go +++ b/types/rest/rest_test.go @@ -18,8 +18,6 @@ import ( "github.com/cosmos/cosmos-sdk/types" ) -type mockResponseWriter struct{} - func TestBaseReqValidateBasic(t *testing.T) { fromAddr := "cosmos1cq0sxam6x4l0sv9yz3a2vlqhdhvt2k6jtgcse0" tenstakes, err := types.ParseCoins("10stake") diff --git a/x/auth/client/cli/query.go b/x/auth/client/cli/query.go index 6bdf94c1a7..eed8c73f4d 100644 --- a/x/auth/client/cli/query.go +++ b/x/auth/client/cli/query.go @@ -165,7 +165,7 @@ func QueryTxCmd(cdc *codec.Codec) *cobra.Command { } if output.Empty() { - return fmt.Errorf("No transaction found with hash %s", args[0]) + return fmt.Errorf("no transaction found with hash %s", args[0]) } return cliCtx.PrintOutput(output) diff --git a/x/auth/simulation/decoder_test.go b/x/auth/simulation/decoder_test.go index 7b2cbe710a..1041069638 100644 --- a/x/auth/simulation/decoder_test.go +++ b/x/auth/simulation/decoder_test.go @@ -15,10 +15,8 @@ import ( ) var ( - delPk1 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.AccAddress(delPk1.Address()) - valAddr1 = sdk.ValAddress(delPk1.Address()) - consAddr1 = sdk.ConsAddress(delPk1.Address().Bytes()) + delPk1 = ed25519.GenPrivKey().PubKey() + delAddr1 = sdk.AccAddress(delPk1.Address()) ) func makeTestCodec() (cdc *codec.Codec) { diff --git a/x/auth/types/account.go b/x/auth/types/account.go index daaad1ecda..31a77b15c8 100644 --- a/x/auth/types/account.go +++ b/x/auth/types/account.go @@ -371,17 +371,17 @@ func NewContinuousVestingAccountRaw(bva *BaseVestingAccount, // NewContinuousVestingAccount returns a new ContinuousVestingAccount func NewContinuousVestingAccount( - baseAcc *BaseAccount, StartTime, EndTime int64, + baseAcc *BaseAccount, startTime, endTime int64, ) *ContinuousVestingAccount { baseVestingAcc := &BaseVestingAccount{ BaseAccount: baseAcc, OriginalVesting: baseAcc.Coins, - EndTime: EndTime, + EndTime: endTime, } return &ContinuousVestingAccount{ - StartTime: StartTime, + StartTime: startTime, BaseVestingAccount: baseVestingAcc, } } @@ -487,11 +487,11 @@ func NewDelayedVestingAccountRaw(bva *BaseVestingAccount) *DelayedVestingAccount } // NewDelayedVestingAccount returns a DelayedVestingAccount -func NewDelayedVestingAccount(baseAcc *BaseAccount, EndTime int64) *DelayedVestingAccount { +func NewDelayedVestingAccount(baseAcc *BaseAccount, endTime int64) *DelayedVestingAccount { baseVestingAcc := &BaseVestingAccount{ BaseAccount: baseAcc, OriginalVesting: baseAcc.Coins, - EndTime: EndTime, + EndTime: endTime, } return &DelayedVestingAccount{baseVestingAcc} diff --git a/x/auth/types/account_retriever_test.go b/x/auth/types/account_retriever_test.go index 64e232bc53..76126db115 100644 --- a/x/auth/types/account_retriever_test.go +++ b/x/auth/types/account_retriever_test.go @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/tests/mocks" ) -var dummyError = errors.New("dummy") +var errFoo = errors.New("dummy") func TestAccountRetriever(t *testing.T) { mockCtrl := gomock.NewController(t) @@ -23,18 +23,18 @@ func TestAccountRetriever(t *testing.T) { require.NoError(t, err) mockNodeQuerier.EXPECT().QueryWithData(gomock.Eq("custom/acc/account"), - gomock.Eq(bs)).Return(nil, int64(0), dummyError).Times(1) + gomock.Eq(bs)).Return(nil, int64(0), errFoo).Times(1) _, err = accRetr.GetAccount(addr) require.Error(t, err) mockNodeQuerier.EXPECT().QueryWithData(gomock.Eq("custom/acc/account"), - gomock.Eq(bs)).Return(nil, int64(0), dummyError).Times(1) + gomock.Eq(bs)).Return(nil, int64(0), errFoo).Times(1) n, s, err := accRetr.GetAccountNumberSequence(addr) require.Error(t, err) require.Equal(t, uint64(0), n) require.Equal(t, uint64(0), s) mockNodeQuerier.EXPECT().QueryWithData(gomock.Eq("custom/acc/account"), - gomock.Eq(bs)).Return(nil, int64(0), dummyError).Times(1) + gomock.Eq(bs)).Return(nil, int64(0), errFoo).Times(1) require.Error(t, accRetr.EnsureExists(addr)) } diff --git a/x/bank/app_test.go b/x/bank/app_test.go index cfde2d7efc..df7246b928 100644 --- a/x/bank/app_test.go +++ b/x/bank/app_test.go @@ -44,8 +44,6 @@ var ( coins = sdk.Coins{sdk.NewInt64Coin("foocoin", 10)} halfCoins = sdk.Coins{sdk.NewInt64Coin("foocoin", 5)} - manyCoins = sdk.Coins{sdk.NewInt64Coin("foocoin", 1), sdk.NewInt64Coin("barcoin", 1)} - freeFee = auth.NewStdFee(100000, sdk.Coins{sdk.NewInt64Coin("foocoin", 0)}) sendMsg1 = types.NewMsgSend(addr1, addr2, coins) sendMsg2 = types.NewMsgSend(addr1, moduleAccAddr, coins) @@ -80,14 +78,6 @@ var ( }, } multiSendMsg5 = types.MsgMultiSend{ - Inputs: []types.Input{ - types.NewInput(addr1, manyCoins), - }, - Outputs: []types.Output{ - types.NewOutput(addr2, manyCoins), - }, - } - multiSendMsg6 = types.MsgMultiSend{ Inputs: []types.Input{ types.NewInput(addr1, coins), }, @@ -197,7 +187,7 @@ func TestMsgMultiSendWithAccounts(t *testing.T) { privKeys: []crypto.PrivKey{priv1}, }, { - msgs: []sdk.Msg{multiSendMsg6}, + msgs: []sdk.Msg{multiSendMsg5}, accNums: []uint64{0}, accSeqs: []uint64{0}, expSimPass: false, diff --git a/x/bank/simulation/operations/msgs.go b/x/bank/simulation/operations/msgs.go index 32ff0ad6eb..070581a621 100644 --- a/x/bank/simulation/operations/msgs.go +++ b/x/bank/simulation/operations/msgs.go @@ -90,7 +90,7 @@ func sendAndVerifyMsgSend(app *baseapp.BaseApp, mapper types.AccountKeeper, msg res := app.Deliver(tx) if !res.IsOK() { // TODO: Do this in a more 'canonical' way - return fmt.Errorf("Deliver failed %v", res) + return fmt.Errorf("deliver failed %v", res) } } @@ -198,7 +198,7 @@ func sendAndVerifyMsgMultiSend(app *baseapp.BaseApp, mapper types.AccountKeeper, res := app.Deliver(tx) if !res.IsOK() { // TODO: Do this in a more 'canonical' way - return fmt.Errorf("Deliver failed %v", res) + return fmt.Errorf("deliver failed %v", res) } } diff --git a/x/distribution/keeper/delegation_test.go b/x/distribution/keeper/delegation_test.go index b0e47f533d..2faa1da417 100644 --- a/x/distribution/keeper/delegation_test.go +++ b/x/distribution/keeper/delegation_test.go @@ -485,7 +485,6 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { distrAcc.SetCoins(sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1000)))) k.supplyKeeper.SetModuleAccount(ctx, distrAcc) - totalRewards := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.NewDec(initial*2))} tokens := sdk.DecCoins{sdk.NewDecCoinFromDec(sdk.DefaultBondDenom, sdk.NewDec(initial))} // create validator with 50% commission @@ -560,8 +559,6 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { // commission should be zero require.True(t, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1).IsZero()) - totalRewards = totalRewards.Add(tokens) - // next block ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) @@ -589,8 +586,6 @@ func TestCalculateRewardsMultiDelegatorMultWithdraw(t *testing.T) { // commission should be half initial require.Equal(t, sdk.DecCoins{{sdk.DefaultBondDenom, sdk.NewDec(initial / 2)}}, k.GetValidatorAccumulatedCommission(ctx, valOpAddr1)) - totalRewards = k.GetValidatorOutstandingRewards(ctx, valOpAddr1).Add(tokens) - // next block ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) diff --git a/x/distribution/keeper/querier.go b/x/distribution/keeper/querier.go index 25bc5c846d..27c657cb49 100644 --- a/x/distribution/keeper/querier.go +++ b/x/distribution/keeper/querier.go @@ -210,7 +210,7 @@ func queryDelegatorValidators(ctx sdk.Context, _ []string, req abci.RequestQuery k.stakingKeeper.IterateDelegations( ctx, params.DelegatorAddress, func(_ int64, del exported.DelegationI) (stop bool) { - validators = append(validators[:], del.GetValidatorAddr()) + validators = append(validators, del.GetValidatorAddr()) return false }, ) diff --git a/x/gov/client/cli/query.go b/x/gov/client/cli/query.go index 28b957e41b..51d48e7b6d 100644 --- a/x/gov/client/cli/query.go +++ b/x/gov/client/cli/query.go @@ -152,7 +152,7 @@ $ %s query gov proposals --status (DepositPeriod|VotingPeriod|Passed|Rejected) } if len(matchingProposals) == 0 { - return fmt.Errorf("No matching proposals found") + return fmt.Errorf("no matching proposals found") } return cliCtx.PrintOutput(matchingProposals) // nolint:errcheck @@ -319,7 +319,7 @@ $ %s query gov deposit 1 cosmos1skjwj5whet0lpe65qaq4rpq03hjxlwd9nf39lk // check to see if the proposal is in the store _, err = gcutils.QueryProposalByID(proposalID, cliCtx, queryRoute) if err != nil { - return fmt.Errorf("Failed to fetch proposal-id %d: %s", proposalID, err) + return fmt.Errorf("failed to fetch proposal-id %d: %s", proposalID, err) } depositorAddr, err := sdk.AccAddressFromBech32(args[1]) @@ -545,7 +545,7 @@ $ %s query gov param deposit cdc.MustUnmarshalJSON(res, ¶m) out = param default: - return fmt.Errorf("Argument must be one of (voting|tallying|deposit), was %s", args[0]) + return fmt.Errorf("argument must be one of (voting|tallying|deposit), was %s", args[0]) } return cliCtx.PrintOutput(out) diff --git a/x/gov/keeper/querier.go b/x/gov/keeper/querier.go index 4ffcaa04a0..bb6a63256a 100644 --- a/x/gov/keeper/querier.go +++ b/x/gov/keeper/querier.go @@ -147,11 +147,12 @@ func queryTally(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Ke var tallyResult types.TallyResult - if proposal.Status == types.StatusDepositPeriod { + switch { + case proposal.Status == types.StatusDepositPeriod: tallyResult = types.EmptyTallyResult() - } else if proposal.Status == types.StatusPassed || proposal.Status == types.StatusRejected { + case proposal.Status == types.StatusPassed || proposal.Status == types.StatusRejected: tallyResult = proposal.FinalTallyResult - } else { + default: // proposal is in voting period _, _, tallyResult = keeper.Tally(ctx, proposal) } diff --git a/x/gov/keeper/querier_test.go b/x/gov/keeper/querier_test.go index 818b95e3a8..18fd794902 100644 --- a/x/gov/keeper/querier_test.go +++ b/x/gov/keeper/querier_test.go @@ -54,22 +54,6 @@ func getQueriedParams(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier s return depositParams, votingParams, tallyParams } -func getQueriedProposal(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64) types.Proposal { - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryProposal}, "/"), - Data: cdc.MustMarshalJSON(types.NewQueryProposalParams(proposalID)), - } - - bz, err := querier(ctx, []string{types.QueryProposal}, query) - require.NoError(t, err) - require.NotNil(t, bz) - - var proposal types.Proposal - require.NoError(t, cdc.UnmarshalJSON(bz, proposal)) - - return proposal -} - func getQueriedProposals(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, depositor, voter sdk.AccAddress, status types.ProposalStatus, limit uint64) []types.Proposal { query := abci.RequestQuery{ Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryProposals}, "/"), @@ -150,22 +134,6 @@ func getQueriedVotes(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sd return votes } -func getQueriedTally(t *testing.T, ctx sdk.Context, cdc *codec.Codec, querier sdk.Querier, proposalID uint64) types.TallyResult { - query := abci.RequestQuery{ - Path: strings.Join([]string{custom, types.QuerierRoute, types.QueryTally}, "/"), - Data: cdc.MustMarshalJSON(types.NewQueryProposalParams(proposalID)), - } - - bz, err := querier(ctx, []string{types.QueryTally}, query) - require.NoError(t, err) - require.NotNil(t, bz) - - var tally types.TallyResult - require.NoError(t, cdc.UnmarshalJSON(bz, &tally)) - - return tally -} - func TestQueries(t *testing.T) { ctx, _, keeper, _, _ := createTestInput(t, false, 1000) querier := NewQuerier(keeper) @@ -237,11 +205,6 @@ func TestQueries(t *testing.T) { require.Equal(t, deposit2, deposits[0]) require.Equal(t, deposit4, deposits[1]) - deposit = getQueriedDeposit(t, ctx, keeper.cdc, querier, proposal2.ProposalID, TestAddrs[0]) - require.Equal(t, deposit2, deposits[0]) - deposit = getQueriedDeposit(t, ctx, keeper.cdc, querier, proposal2.ProposalID, TestAddrs[1]) - require.Equal(t, deposit4, deposits[1]) - // check deposits on proposal3 match individual deposits deposits = getQueriedDeposits(t, ctx, keeper.cdc, querier, proposal3.ProposalID) require.Len(t, deposits, 1) diff --git a/x/gov/keeper/test_common.go b/x/gov/keeper/test_common.go index 459a6f7ed2..21dce1b1ce 100644 --- a/x/gov/keeper/test_common.go +++ b/x/gov/keeper/test_common.go @@ -152,8 +152,9 @@ func createTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context rtr := types.NewRouter(). AddRoute(types.RouterKey, types.ProposalHandler) - keeper := NewKeeper(cdc, keyGov, pk.Subspace(types.DefaultParamspace).WithKeyTable(types.ParamKeyTable()), - supplyKeeper, sk, types.DefaultCodespace, rtr) + keeper := NewKeeper( + cdc, keyGov, pk.Subspace(types.DefaultParamspace).WithKeyTable(types.ParamKeyTable()), supplyKeeper, sk, types.DefaultCodespace, rtr, + ) keeper.SetProposalID(ctx, types.DefaultStartingProposalID) keeper.SetDepositParams(ctx, types.DefaultDepositParams()) diff --git a/x/gov/simulation/decoder_test.go b/x/gov/simulation/decoder_test.go index 05d980023c..3cf9a08dae 100644 --- a/x/gov/simulation/decoder_test.go +++ b/x/gov/simulation/decoder_test.go @@ -17,10 +17,8 @@ import ( ) var ( - delPk1 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.AccAddress(delPk1.Address()) - valAddr1 = sdk.ValAddress(delPk1.Address()) - consAddr1 = sdk.ConsAddress(delPk1.Address().Bytes()) + delPk1 = ed25519.GenPrivKey().PubKey() + delAddr1 = sdk.AccAddress(delPk1.Address()) ) func makeTestCodec() (cdc *codec.Codec) { @@ -66,9 +64,9 @@ func TestDecodeStore(t *testing.T) { t.Run(tt.name, func(t *testing.T) { switch i { case len(tests) - 1: - require.Panics(t, func() { DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]) }, tt.name) + require.Panics(t, func() { DecodeStore(cdc, kvPairs[i], kvPairs[i]) }, tt.name) default: - require.Equal(t, tt.expectedLog, DecodeStore(cdc, cdc, kvPairs[i], kvPairs[i]), tt.name) + require.Equal(t, tt.expectedLog, DecodeStore(cdc, kvPairs[i], kvPairs[i]), tt.name) } }) } diff --git a/x/gov/test_common.go b/x/gov/test_common.go index 44fbe10fbf..fe0788f725 100644 --- a/x/gov/test_common.go +++ b/x/gov/test_common.go @@ -78,10 +78,13 @@ func getMockApp(t *testing.T, numGenAccs int, genState types.GenesisState, genAc staking.BondedPoolName: {supply.Burner, supply.Staking}, } supplyKeeper := supply.NewKeeper(mApp.Cdc, keySupply, mApp.AccountKeeper, bk, maccPerms) - sk := staking.NewKeeper(mApp.Cdc, keyStaking, tKeyStaking, supplyKeeper, pk.Subspace(staking.DefaultParamspace), staking.DefaultCodespace) + sk := staking.NewKeeper( + mApp.Cdc, keyStaking, tKeyStaking, supplyKeeper, pk.Subspace(staking.DefaultParamspace), staking.DefaultCodespace, + ) - keeper := keep.NewKeeper(mApp.Cdc, keyGov, pk.Subspace(DefaultParamspace).WithKeyTable(ParamKeyTable()), - supplyKeeper, sk, types.DefaultCodespace, rtr) + keeper := keep.NewKeeper( + mApp.Cdc, keyGov, pk.Subspace(DefaultParamspace).WithKeyTable(ParamKeyTable()), supplyKeeper, sk, types.DefaultCodespace, rtr, + ) mApp.Router().AddRoute(types.RouterKey, NewHandler(keeper)) mApp.QueryRouter().AddRoute(types.QuerierRoute, keep.NewQuerier(keeper)) diff --git a/x/gov/types/genesis.go b/x/gov/types/genesis.go index 165606bc47..69f49fa68b 100644 --- a/x/gov/types/genesis.go +++ b/x/gov/types/genesis.go @@ -54,18 +54,18 @@ func (data GenesisState) IsEmpty() bool { func ValidateGenesis(data GenesisState) error { threshold := data.TallyParams.Threshold if threshold.IsNegative() || threshold.GT(sdk.OneDec()) { - return fmt.Errorf("Governance vote threshold should be positive and less or equal to one, is %s", + return fmt.Errorf("governance vote threshold should be positive and less or equal to one, is %s", threshold.String()) } veto := data.TallyParams.Veto if veto.IsNegative() || veto.GT(sdk.OneDec()) { - return fmt.Errorf("Governance vote veto threshold should be positive and less or equal to one, is %s", + return fmt.Errorf("governance vote veto threshold should be positive and less or equal to one, is %s", veto.String()) } if !data.DepositParams.MinDeposit.IsValid() { - return fmt.Errorf("Governance deposit amount must be a valid sdk.Coins amount, is %s", + return fmt.Errorf("governance deposit amount must be a valid sdk.Coins amount, is %s", data.DepositParams.MinDeposit.String()) } diff --git a/x/gov/types/msgs_test.go b/x/gov/types/msgs_test.go index 2e820af9fe..7ca97c432f 100644 --- a/x/gov/types/msgs_test.go +++ b/x/gov/types/msgs_test.go @@ -10,11 +10,10 @@ import ( ) var ( - coinsPos = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000)) - coinsZero = sdk.NewCoins() - coinsPosNotAtoms = sdk.NewCoins(sdk.NewInt64Coin("foo", 10000)) - coinsMulti = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000), sdk.NewInt64Coin("foo", 10000)) - addrs = []sdk.AccAddress{ + coinsPos = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000)) + coinsZero = sdk.NewCoins() + coinsMulti = sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000), sdk.NewInt64Coin("foo", 10000)) + addrs = []sdk.AccAddress{ sdk.AccAddress("test1"), sdk.AccAddress("test2"), } diff --git a/x/mint/internal/types/params.go b/x/mint/internal/types/params.go index 864d8ef32e..04ea580995 100644 --- a/x/mint/internal/types/params.go +++ b/x/mint/internal/types/params.go @@ -91,11 +91,11 @@ func (p Params) String() string { // Implements params.ParamSet func (p *Params) ParamSetPairs() params.ParamSetPairs { return params.ParamSetPairs{ - {KeyMintDenom, &p.MintDenom}, - {KeyInflationRateChange, &p.InflationRateChange}, - {KeyInflationMax, &p.InflationMax}, - {KeyInflationMin, &p.InflationMin}, - {KeyGoalBonded, &p.GoalBonded}, - {KeyBlocksPerYear, &p.BlocksPerYear}, + {Key: KeyMintDenom, Value: &p.MintDenom}, + {Key: KeyInflationRateChange, Value: &p.InflationRateChange}, + {Key: KeyInflationMax, Value: &p.InflationMax}, + {Key: KeyInflationMin, Value: &p.InflationMin}, + {Key: KeyGoalBonded, Value: &p.GoalBonded}, + {Key: KeyBlocksPerYear, Value: &p.BlocksPerYear}, } } diff --git a/x/mock/app_test.go b/x/mock/app_test.go index 83981f039d..552bf2a807 100644 --- a/x/mock/app_test.go +++ b/x/mock/app_test.go @@ -14,9 +14,9 @@ import ( const msgRoute = "testMsg" var ( - numAccts = 2 - genCoins = sdk.Coins{sdk.NewInt64Coin("foocoin", 77)} - accs, addrs, pubKeys, privKeys = CreateGenAccounts(numAccts, genCoins) + numAccts = 2 + genCoins = sdk.Coins{sdk.NewInt64Coin("foocoin", 77)} + accs, addrs, _, privKeys = CreateGenAccounts(numAccts, genCoins) ) // testMsg is a mock transaction that has a validation which can fail. diff --git a/x/simulation/config.go b/x/simulation/config.go index 616da3bcc4..b15a6f2f3d 100644 --- a/x/simulation/config.go +++ b/x/simulation/config.go @@ -20,4 +20,4 @@ type Config struct { OnOperation bool // run slow invariants every operation AllInvariants bool // print all failed invariants if a broken invariant is found -} \ No newline at end of file +} diff --git a/x/simulation/event_stats.go b/x/simulation/event_stats.go index 875a2029d4..1a6201aaca 100644 --- a/x/simulation/event_stats.go +++ b/x/simulation/event_stats.go @@ -38,7 +38,7 @@ func (es EventStats) Print(w io.Writer) { panic(err) } - fmt.Fprintf(w, string(obj)) + fmt.Fprintln(w, string(obj)) } // ExportJSON saves the event stats as a JSON file on a given path diff --git a/x/simulation/mock_tendermint.go b/x/simulation/mock_tendermint.go index efa84aead3..d9ab0ecd65 100644 --- a/x/simulation/mock_tendermint.go +++ b/x/simulation/mock_tendermint.go @@ -158,7 +158,7 @@ func RandomRequestBeginBlock(r *rand.Rand, params Params, } // return if no past times - if len(pastTimes) <= 0 { + if len(pastTimes) == 0 { return abci.RequestBeginBlock{ Header: header, LastCommitInfo: abci.LastCommitInfo{ diff --git a/x/simulation/simulate.go b/x/simulation/simulate.go index e1bf1a4b4d..7ae199f275 100644 --- a/x/simulation/simulate.go +++ b/x/simulation/simulate.go @@ -98,7 +98,7 @@ func SimulateFromSeed( go func() { receivedSignal := <-c fmt.Fprintf(w, "\nExiting early due to %s, on block %d, operation %d\n", receivedSignal, header.Height, opCount) - err = fmt.Errorf("Exited due to %s", receivedSignal) + err = fmt.Errorf("exited due to %s", receivedSignal) stopEarly = true }() diff --git a/x/simulation/transition_matrix.go b/x/simulation/transition_matrix.go index f7d713775d..0a0ee7ebea 100644 --- a/x/simulation/transition_matrix.go +++ b/x/simulation/transition_matrix.go @@ -24,7 +24,7 @@ func CreateTransitionMatrix(weights [][]int) (TransitionMatrix, error) { for i := 0; i < n; i++ { if len(weights[i]) != n { return TransitionMatrix{}, - fmt.Errorf("Transition Matrix: Non-square matrix provided, error on row %d", i) + fmt.Errorf("transition matrix: non-square matrix provided, error on row %d", i) } } totals := make([]int, n) diff --git a/x/slashing/client/cli/query.go b/x/slashing/client/cli/query.go index fabdb1485b..836d2bcb1f 100644 --- a/x/slashing/client/cli/query.go +++ b/x/slashing/client/cli/query.go @@ -63,7 +63,7 @@ $ query slashing signing-info cosmosvalconspub1zcjduepqfhvwcmt7p06fvdge } if len(res) == 0 { - return fmt.Errorf("Validator %s not found in slashing store", consAddr) + return fmt.Errorf("validator %s not found in slashing store", consAddr) } var signingInfo types.ValidatorSigningInfo diff --git a/x/slashing/internal/types/genesis.go b/x/slashing/internal/types/genesis.go index 649c041cbe..4aadb9aaaf 100644 --- a/x/slashing/internal/types/genesis.go +++ b/x/slashing/internal/types/genesis.go @@ -53,32 +53,32 @@ func DefaultGenesisState() GenesisState { func ValidateGenesis(data GenesisState) error { downtime := data.Params.SlashFractionDowntime if downtime.IsNegative() || downtime.GT(sdk.OneDec()) { - return fmt.Errorf("Slashing fraction downtime should be less than or equal to one and greater than zero, is %s", downtime.String()) + return fmt.Errorf("slashing fraction downtime should be less than or equal to one and greater than zero, is %s", downtime.String()) } dblSign := data.Params.SlashFractionDoubleSign if dblSign.IsNegative() || dblSign.GT(sdk.OneDec()) { - return fmt.Errorf("Slashing fraction double sign should be less than or equal to one and greater than zero, is %s", dblSign.String()) + return fmt.Errorf("slashing fraction double sign should be less than or equal to one and greater than zero, is %s", dblSign.String()) } minSign := data.Params.MinSignedPerWindow if minSign.IsNegative() || minSign.GT(sdk.OneDec()) { - return fmt.Errorf("Min signed per window should be less than or equal to one and greater than zero, is %s", minSign.String()) + return fmt.Errorf("min signed per window should be less than or equal to one and greater than zero, is %s", minSign.String()) } maxEvidence := data.Params.MaxEvidenceAge if maxEvidence < 1*time.Minute { - return fmt.Errorf("Max evidence age must be at least 1 minute, is %s", maxEvidence.String()) + return fmt.Errorf("max evidence age must be at least 1 minute, is %s", maxEvidence.String()) } downtimeJail := data.Params.DowntimeJailDuration if downtimeJail < 1*time.Minute { - return fmt.Errorf("Downtime unblond duration must be at least 1 minute, is %s", downtimeJail.String()) + return fmt.Errorf("downtime unblond duration must be at least 1 minute, is %s", downtimeJail.String()) } signedWindow := data.Params.SignedBlocksWindow if signedWindow < 10 { - return fmt.Errorf("Signed blocks window must be at least 10, is %d", signedWindow) + return fmt.Errorf("signed blocks window must be at least 10, is %d", signedWindow) } return nil diff --git a/x/slashing/simulation/decoder_test.go b/x/slashing/simulation/decoder_test.go index 1c8f8f93c5..19444dcaed 100644 --- a/x/slashing/simulation/decoder_test.go +++ b/x/slashing/simulation/decoder_test.go @@ -15,6 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/slashing/internal/types" ) +// nolint:deadcode unused var ( delPk1 = ed25519.GenPrivKey().PubKey() delAddr1 = sdk.AccAddress(delPk1.Address()) diff --git a/x/staking/client/cli/query.go b/x/staking/client/cli/query.go index 9e0352f935..ce7ca6e55b 100644 --- a/x/staking/client/cli/query.go +++ b/x/staking/client/cli/query.go @@ -71,7 +71,7 @@ $ %s query staking validator cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhff } if len(res) == 0 { - return fmt.Errorf("No validator found with address %s", addr) + return fmt.Errorf("no validator found with address %s", addr) } return cliCtx.PrintOutput(types.MustUnmarshalValidator(cdc, res)) diff --git a/x/staking/genesis.go b/x/staking/genesis.go index 91d3a41f60..4c1bbee707 100644 --- a/x/staking/genesis.go +++ b/x/staking/genesis.go @@ -156,7 +156,7 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { }) var lastValidatorPowers []types.LastValidatorPower keeper.IterateLastValidatorPowers(ctx, func(addr sdk.ValAddress, power int64) (stop bool) { - lastValidatorPowers = append(lastValidatorPowers, types.LastValidatorPower{addr, power}) + lastValidatorPowers = append(lastValidatorPowers, types.LastValidatorPower{Address: addr, Power: power}) return false }) diff --git a/x/staking/genesis_test.go b/x/staking/genesis_test.go index 2fb09f2fac..e3d15b25f8 100644 --- a/x/staking/genesis_test.go +++ b/x/staking/genesis_test.go @@ -114,17 +114,17 @@ func TestValidateGenesis(t *testing.T) { {"default", func(*types.GenesisState) {}, false}, // validate genesis validators {"duplicate validator", func(data *types.GenesisState) { - (*data).Validators = genValidators1 - (*data).Validators = append((*data).Validators, genValidators1[0]) + data.Validators = genValidators1 + data.Validators = append(data.Validators, genValidators1[0]) }, true}, {"no delegator shares", func(data *types.GenesisState) { - (*data).Validators = genValidators1 - (*data).Validators[0].DelegatorShares = sdk.ZeroDec() + data.Validators = genValidators1 + data.Validators[0].DelegatorShares = sdk.ZeroDec() }, true}, {"jailed and bonded validator", func(data *types.GenesisState) { - (*data).Validators = genValidators1 - (*data).Validators[0].Jailed = true - (*data).Validators[0].Status = sdk.Bonded + data.Validators = genValidators1 + data.Validators[0].Jailed = true + data.Validators[0].Status = sdk.Bonded }, true}, } diff --git a/x/staking/handler.go b/x/staking/handler.go index ad39070d1c..1d7ba1e847 100644 --- a/x/staking/handler.go +++ b/x/staking/handler.go @@ -196,10 +196,10 @@ func handleMsgEditValidator(ctx sdk.Context, msg types.MsgEditValidator, k keepe } if msg.MinSelfDelegation != nil { - if !(*msg.MinSelfDelegation).GT(validator.MinSelfDelegation) { + if !msg.MinSelfDelegation.GT(validator.MinSelfDelegation) { return ErrMinSelfDelegationDecreased(k.Codespace()).Result() } - if (*msg.MinSelfDelegation).GT(validator.Tokens) { + if msg.MinSelfDelegation.GT(validator.Tokens) { return ErrSelfDelegationBelowMinimum(k.Codespace()).Result() } validator.MinSelfDelegation = (*msg.MinSelfDelegation) diff --git a/x/staking/handler_test.go b/x/staking/handler_test.go index f6329824b3..6a822603a8 100644 --- a/x/staking/handler_test.go +++ b/x/staking/handler_test.go @@ -313,7 +313,7 @@ func TestIncrementsMsgDelegate(t *testing.T) { msgDelegate := NewTestMsgDelegate(delegatorAddr, validatorAddr, bondAmount) for i := int64(0); i < 5; i++ { - ctx = ctx.WithBlockHeight(int64(i)) + ctx = ctx.WithBlockHeight(i) got := handleMsgDelegate(ctx, msgDelegate, keeper) require.True(t, got.IsOK(), "expected msg %d to be ok, got %v", i, got) diff --git a/x/staking/keeper/delegation_test.go b/x/staking/keeper/delegation_test.go index 7d9403b506..01620d762c 100644 --- a/x/staking/keeper/delegation_test.go +++ b/x/staking/keeper/delegation_test.go @@ -208,7 +208,6 @@ func TestUnbondingDelegationsMaxEntries(t *testing.T) { startTokens := sdk.TokensFromConsensusPower(10) bondDenom := keeper.BondDenom(ctx) - bondedPool := keeper.GetBondedPool(ctx) notBondedPool := keeper.GetNotBondedPool(ctx) err := notBondedPool.SetCoins(sdk.NewCoins(sdk.NewCoin(bondDenom, startTokens))) require.NoError(t, err) @@ -240,7 +239,7 @@ func TestUnbondingDelegationsMaxEntries(t *testing.T) { require.NoError(t, err) } - bondedPool = keeper.GetBondedPool(ctx) + bondedPool := keeper.GetBondedPool(ctx) notBondedPool = keeper.GetNotBondedPool(ctx) require.True(sdk.IntEq(t, bondedPool.GetCoins().AmountOf(bondDenom), oldBonded.SubRaw(int64(maxEntries)))) require.True(sdk.IntEq(t, notBondedPool.GetCoins().AmountOf(bondDenom), oldNotBonded.AddRaw(int64(maxEntries)))) diff --git a/x/staking/keeper/querier.go b/x/staking/keeper/querier.go index 19464aabcc..b9c346d01e 100644 --- a/x/staking/keeper/querier.go +++ b/x/staking/keeper/querier.go @@ -60,7 +60,7 @@ func queryValidators(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byte, filteredVals := make([]types.Validator, 0, len(validators)) for _, val := range validators { - if strings.ToLower(val.GetStatus().String()) == strings.ToLower(params.Status) { + if strings.EqualFold(val.GetStatus().String(), params.Status) { filteredVals = append(filteredVals, val) } } @@ -279,16 +279,17 @@ func queryRedelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]byt var redels []types.Redelegation - if !params.DelegatorAddr.Empty() && !params.SrcValidatorAddr.Empty() && !params.DstValidatorAddr.Empty() { + switch { + case !params.DelegatorAddr.Empty() && !params.SrcValidatorAddr.Empty() && !params.DstValidatorAddr.Empty(): redel, found := k.GetRedelegation(ctx, params.DelegatorAddr, params.SrcValidatorAddr, params.DstValidatorAddr) if !found { return nil, types.ErrNoRedelegation(types.DefaultCodespace) } redels = []types.Redelegation{redel} - } else if params.DelegatorAddr.Empty() && !params.SrcValidatorAddr.Empty() && params.DstValidatorAddr.Empty() { + case params.DelegatorAddr.Empty() && !params.SrcValidatorAddr.Empty() && params.DstValidatorAddr.Empty(): redels = k.GetRedelegationsFromSrcValidator(ctx, params.SrcValidatorAddr) - } else { + default: redels = k.GetAllRedelegations(ctx, params.DelegatorAddr, params.SrcValidatorAddr, params.DstValidatorAddr) } diff --git a/x/staking/keeper/querier_test.go b/x/staking/keeper/querier_test.go index c029bd0cdb..2dac9b6f99 100644 --- a/x/staking/keeper/querier_test.go +++ b/x/staking/keeper/querier_test.go @@ -513,7 +513,7 @@ func TestQueryUnbondingDelegation(t *testing.T) { Path: "/custom/staking/unbondingDelegation", Data: bz, } - res, err = queryUnbondingDelegation(ctx, query, keeper) + _, err = queryUnbondingDelegation(ctx, query, keeper) require.NotNil(t, err) // diff --git a/x/staking/keeper/test_common.go b/x/staking/keeper/test_common.go index cc178408ca..40478c71d4 100644 --- a/x/staking/keeper/test_common.go +++ b/x/staking/keeper/test_common.go @@ -174,7 +174,7 @@ func NewPubKey(pk string) (res crypto.PubKey) { } //res, err = crypto.PubKeyFromBytes(pkBytes) var pkEd ed25519.PubKeyEd25519 - copy(pkEd[:], pkBytes[:]) + copy(pkEd[:], pkBytes) return pkEd } diff --git a/x/staking/keeper/val_state_change.go b/x/staking/keeper/val_state_change.go index 81d1ea0cb3..724ebaff05 100644 --- a/x/staking/keeper/val_state_change.go +++ b/x/staking/keeper/val_state_change.go @@ -272,7 +272,7 @@ func (k Keeper) getLastValidatorsByAddr(ctx sdk.Context) validatorsByAddr { // power bytes is just the value powerBytes := iterator.Value() last[valAddr] = make([]byte, len(powerBytes)) - copy(last[valAddr][:], powerBytes[:]) + copy(last[valAddr], powerBytes) } return last } @@ -285,7 +285,7 @@ func sortNoLongerBonded(last validatorsByAddr) [][]byte { index := 0 for valAddrBytes := range last { valAddr := make([]byte, sdk.AddrLen) - copy(valAddr[:], valAddrBytes[:]) + copy(valAddr, valAddrBytes[:]) noLongerBonded[index] = valAddr index++ } diff --git a/x/staking/keeper/validator.go b/x/staking/keeper/validator.go index 5f26071d3f..a594238fc5 100644 --- a/x/staking/keeper/validator.go +++ b/x/staking/keeper/validator.go @@ -370,13 +370,8 @@ func (k Keeper) DeleteValidatorQueueTimeSlice(ctx sdk.Context, timestamp time.Ti // Insert an validator address to the appropriate timeslice in the validator queue func (k Keeper) InsertValidatorQueue(ctx sdk.Context, val types.Validator) { timeSlice := k.GetValidatorQueueTimeSlice(ctx, val.UnbondingCompletionTime) - var keys []sdk.ValAddress - if len(timeSlice) == 0 { - keys = []sdk.ValAddress{val.OperatorAddress} - } else { - keys = append(timeSlice, val.OperatorAddress) - } - k.SetValidatorQueueTimeSlice(ctx, val.UnbondingCompletionTime, keys) + timeSlice = append(timeSlice, val.OperatorAddress) + k.SetValidatorQueueTimeSlice(ctx, val.UnbondingCompletionTime, timeSlice) } // Delete a validator address from the validator queue diff --git a/x/staking/keeper/validator_test.go b/x/staking/keeper/validator_test.go index a5d909a8ae..acc25a107a 100644 --- a/x/staking/keeper/validator_test.go +++ b/x/staking/keeper/validator_test.go @@ -293,7 +293,8 @@ func TestValidatorBasics(t *testing.T) { } // test how the validators are sorted, tests GetBondedValidatorsByPower -func GetValidatorSortingUnmixed(t *testing.T) { +func TestGetValidatorSortingUnmixed(t *testing.T) { + t.SkipNow() ctx, _, keeper, _ := CreateTestInput(t, false, 1000) // initialize some validators into the state @@ -368,7 +369,8 @@ func GetValidatorSortingUnmixed(t *testing.T) { assert.True(ValEq(t, validators[4], resValidators[1])) } -func GetValidatorSortingMixed(t *testing.T) { +func TestGetValidatorSortingMixed(t *testing.T) { + t.SkipNow() ctx, _, keeper, _ := CreateTestInput(t, false, 1000) // now 2 max resValidators @@ -401,7 +403,7 @@ func GetValidatorSortingMixed(t *testing.T) { for i := range amts { TestingUpdateValidator(keeper, ctx, validators[i], true) } - val0, found := keeper.GetValidator(ctx, sdk.ValAddress(sdk.ValAddress(PKs[0].Address().Bytes()))) + val0, found := keeper.GetValidator(ctx, sdk.ValAddress(PKs[0].Address().Bytes())) require.True(t, found) val1, found := keeper.GetValidator(ctx, sdk.ValAddress(Addrs[1])) require.True(t, found) @@ -549,7 +551,7 @@ func TestValidatorBondHeight(t *testing.T) { // initialize some validators into the state var validators [3]types.Validator - validators[0] = types.NewValidator(sdk.ValAddress(sdk.ValAddress(PKs[0].Address().Bytes())), PKs[0], types.Description{}) + validators[0] = types.NewValidator(sdk.ValAddress(PKs[0].Address().Bytes()), PKs[0], types.Description{}) validators[1] = types.NewValidator(sdk.ValAddress(Addrs[1]), PKs[1], types.Description{}) validators[2] = types.NewValidator(sdk.ValAddress(Addrs[2]), PKs[2], types.Description{}) diff --git a/x/staking/simulation/decoder_test.go b/x/staking/simulation/decoder_test.go index 19950c97aa..8774da60e6 100644 --- a/x/staking/simulation/decoder_test.go +++ b/x/staking/simulation/decoder_test.go @@ -16,10 +16,9 @@ import ( ) var ( - delPk1 = ed25519.GenPrivKey().PubKey() - delAddr1 = sdk.AccAddress(delPk1.Address()) - valAddr1 = sdk.ValAddress(delPk1.Address()) - consAddr1 = sdk.ConsAddress(delPk1.Address().Bytes()) + delPk1 = ed25519.GenPrivKey().PubKey() + delAddr1 = sdk.AccAddress(delPk1.Address()) + valAddr1 = sdk.ValAddress(delPk1.Address()) ) func makeTestCodec() (cdc *codec.Codec) { diff --git a/x/staking/types/keys.go b/x/staking/types/keys.go index ce23e4fb85..372b0b9242 100644 --- a/x/staking/types/keys.go +++ b/x/staking/types/keys.go @@ -84,7 +84,7 @@ func getValidatorPowerRank(validator Validator) []byte { consensusPower := sdk.TokensToConsensusPower(validator.Tokens) consensusPowerBytes := make([]byte, 8) - binary.BigEndian.PutUint64(consensusPowerBytes[:], uint64(consensusPower)) + binary.BigEndian.PutUint64(consensusPowerBytes, uint64(consensusPower)) powerBytes := consensusPowerBytes powerBytesLen := len(powerBytes) // 8 @@ -152,8 +152,8 @@ func GetUBDByValIndexKey(delAddr sdk.AccAddress, valAddr sdk.ValAddress) []byte } // rearranges the ValIndexKey to get the UBDKey -func GetUBDKeyFromValIndexKey(IndexKey []byte) []byte { - addrs := IndexKey[1:] // remove prefix bytes +func GetUBDKeyFromValIndexKey(indexKey []byte) []byte { + addrs := indexKey[1:] // remove prefix bytes if len(addrs) != 2*sdk.AddrLen { panic("unexpected key length") } diff --git a/x/staking/types/msg.go b/x/staking/types/msg.go index cc991389ca..80796a94e3 100644 --- a/x/staking/types/msg.go +++ b/x/staking/types/msg.go @@ -198,7 +198,7 @@ func (msg MsgEditValidator) ValidateBasic() sdk.Error { return sdk.NewError(DefaultCodespace, CodeInvalidInput, "transaction must include some information to modify") } - if msg.MinSelfDelegation != nil && !(*msg.MinSelfDelegation).GT(sdk.ZeroInt()) { + if msg.MinSelfDelegation != nil && !msg.MinSelfDelegation.GT(sdk.ZeroInt()) { return ErrMinSelfDelegationInvalid(DefaultCodespace) } diff --git a/x/staking/types/params.go b/x/staking/types/params.go index 82e9c421c5..8be8cff4f2 100644 --- a/x/staking/types/params.go +++ b/x/staking/types/params.go @@ -58,10 +58,10 @@ func NewParams(unbondingTime time.Duration, maxValidators, maxEntries uint16, // Implements params.ParamSet func (p *Params) ParamSetPairs() params.ParamSetPairs { return params.ParamSetPairs{ - {KeyUnbondingTime, &p.UnbondingTime}, - {KeyMaxValidators, &p.MaxValidators}, - {KeyMaxEntries, &p.MaxEntries}, - {KeyBondDenom, &p.BondDenom}, + {Key: KeyUnbondingTime, Value: &p.UnbondingTime}, + {Key: KeyMaxValidators, Value: &p.MaxValidators}, + {Key: KeyMaxEntries, Value: &p.MaxEntries}, + {Key: KeyBondDenom, Value: &p.BondDenom}, } } diff --git a/x/supply/internal/types/supply.go b/x/supply/internal/types/supply.go index 4fecd57b6d..6009b22fac 100644 --- a/x/supply/internal/types/supply.go +++ b/x/supply/internal/types/supply.go @@ -3,7 +3,7 @@ package types import ( "fmt" - "gopkg.in/yaml.v2" + yaml "gopkg.in/yaml.v2" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/supply/exported"