Merge PR #188: Add linting to CI

* Add some linting to gaia

- closes #187

Signed-off-by: Marko Baricevic <marbar3778@yahoo.com>

* fail tests

* tests pass

* address PR comments

* some more strictness
This commit is contained in:
Marko
2019-11-14 21:04:50 +01:00
committed by Jack Zampolin
parent 1069c5b88a
commit 967fc43f1a
15 changed files with 160 additions and 81 deletions

View File

@@ -1,17 +1,61 @@
linters:
disable-all: true
enable:
- bodyclose
- deadcode
- depguard
- dogsled
- errcheck
- goconst
- gocritic
- gofmt
- goimports
- golint
- gosec
- gosimple
- govet
- ineffassign
- unconvert
- interfacer
- misspell
- maligned
- nakedret
- prealloc
- scopelint
- staticcheck
- structcheck
- stylecheck
- typecheck
- unconvert
- unused
- varcheck
issues:
exclude-rules:
- text: "Use of weak random number generator"
linters:
- gosec
- text: "ST1003:"
linters:
- stylecheck
linters-settings:
gocyclo:
min-complexity: 11
dogsled:
max-blank-identifiers: 3
maligned:
# print struct with more effective memory layout or not, false by default
suggest-new: true
errcheck:
ignore: fmt:.*,io/ioutil:^Read.*,github.com/spf13/cobra:MarkFlagRequired,github.com/spf13/viper:BindPFlag
# report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`;
# default is false: such cases aren't reported by default.
check-blank: true
golint:
min-confidence: 1.1
run:
tests: false
# minimal confidence for issues, default is 0.8
min-confidence: 0
prealloc:
# XXX: we don't recommend using this linter before doing performance profiling.
# For most programs usage of prealloc will be a premature optimization.
# Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them.
# True by default.
simple: false
range-loops: true # Report preallocation suggestions on range loops, true by default
for-loops: true # Report preallocation suggestions on for loops, false by default

View File

@@ -34,13 +34,13 @@ import (
const appName = "GaiaApp"
var (
// default home directories for gaiacli
// DefaultCLIHome default home directories for gaiacli
DefaultCLIHome = os.ExpandEnv("$HOME/.gaiacli")
// default home directories for gaiad
// DefaultNodeHome default home directories for gaiad
DefaultNodeHome = os.ExpandEnv("$HOME/.gaiad")
// The module BasicManager is in charge of setting up basic,
// ModuleBasics The module BasicManager is in charge of setting up basic,
// non-dependant module elements, such as codec registration
// and genesis verification.
ModuleBasics = module.NewBasicManager(

View File

@@ -17,11 +17,12 @@ import (
func TestGaiadExport(t *testing.T) {
db := db.NewMemDB()
gapp := NewGaiaApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0)
setGenesis(gapp)
err := setGenesis(gapp)
require.NoError(t, err)
// Making a new app object with the db, so that initchain hasn't been called
newGapp := NewGaiaApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0)
_, _, err := newGapp.ExportAppStateAndValidators(false, []string{})
_, _, err = newGapp.ExportAppStateAndValidators(false, []string{})
require.NoError(t, err, "ExportAppStateAndValidators should not have an error")
}

View File

@@ -31,7 +31,10 @@ func ExampleTxSendSize() {
fee := auth.NewStdFee(gas, coins)
signBytes := auth.StdSignBytes("example-chain-ID",
1, 1, fee, []sdk.Msg{msg1}, "")
sig, _ := priv1.Sign(signBytes)
sig, err := priv1.Sign(signBytes)
if err != nil {
return
}
sigs := []auth.StdSignature{{nil, sig}}
tx := auth.NewStdTx([]sdk.Msg{msg1}, fee, sigs, "")
fmt.Println(len(cdc.MustMarshalBinaryBare([]sdk.Msg{msg1})))

View File

@@ -60,14 +60,20 @@ func (app *GaiaApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []st
// withdraw all validator commission
app.stakingKeeper.IterateValidators(ctx, func(_ int64, val staking.ValidatorI) (stop bool) {
_, _ = app.distrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator())
_, err := app.distrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator())
if err != nil {
log.Fatal(err)
}
return false
})
// withdraw all delegator rewards
dels := app.stakingKeeper.GetAllDelegations(ctx)
for _, delegation := range dels {
_, _ = app.distrKeeper.WithdrawDelegationRewards(ctx, delegation.DelegatorAddress, delegation.ValidatorAddress)
_, err := app.distrKeeper.WithdrawDelegationRewards(ctx, delegation.DelegatorAddress, delegation.ValidatorAddress)
if err != nil {
log.Fatal(err)
}
}
// clear validator slash events
@@ -128,7 +134,6 @@ func (app *GaiaApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []st
iter := sdk.KVStoreReversePrefixIterator(store, staking.ValidatorsKey)
counter := int16(0)
var valConsAddrs []sdk.ConsAddress
for ; iter.Valid(); iter.Next() {
addr := sdk.ValAddress(iter.Key()[1:])
validator, found := app.stakingKeeper.GetValidator(ctx, addr)
@@ -137,7 +142,6 @@ func (app *GaiaApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []st
}
validator.UnbondingHeight = 0
valConsAddrs = append(valConsAddrs, validator.ConsAddress())
if applyWhiteList && !whiteListMap[addr.String()] {
validator.Jailed = true
}

View File

@@ -252,8 +252,16 @@ func BenchmarkFullAppSimulation(b *testing.B) {
config := simapp.NewConfigFromFlags()
var db dbm.DB
dir, _ := ioutil.TempDir("", "goleveldb-app-sim")
db, _ = sdk.NewLevelDB("Simulation", dir)
dir, err := ioutil.TempDir("", "goleveldb-app-sim")
if err != nil {
fmt.Println(err)
b.Fail()
}
db, err = sdk.NewLevelDB("Simulation", dir)
if err != nil {
fmt.Println(err)
b.Fail()
}
defer func() {
db.Close()
_ = os.RemoveAll(dir)
@@ -310,8 +318,10 @@ func TestFullAppSimulation(t *testing.T) {
}
var db dbm.DB
dir, _ := ioutil.TempDir("", "goleveldb-app-sim")
db, _ = sdk.NewLevelDB("Simulation", dir)
dir, err := ioutil.TempDir("", "goleveldb-app-sim")
require.NoError(t, err)
db, err = sdk.NewLevelDB("Simulation", dir)
require.NoError(t, err)
defer func() {
db.Close()
@@ -364,8 +374,10 @@ func TestAppImportExport(t *testing.T) {
}
var db dbm.DB
dir, _ := ioutil.TempDir("", "goleveldb-app-sim")
db, _ = sdk.NewLevelDB("Simulation", dir)
dir, err := ioutil.TempDir("", "goleveldb-app-sim")
require.NoError(t, err)
db, err = sdk.NewLevelDB("Simulation", dir)
require.NoError(t, err)
defer func() {
db.Close()
@@ -408,8 +420,10 @@ func TestAppImportExport(t *testing.T) {
require.NoError(t, err)
fmt.Printf("importing genesis...\n")
newDir, _ := ioutil.TempDir("", "goleveldb-app-sim-2")
newDB, _ := sdk.NewLevelDB("Simulation-2", dir)
newDir, err := ioutil.TempDir("", "goleveldb-app-sim-2")
require.NoError(t, err)
newDB, err := sdk.NewLevelDB("Simulation-2", dir)
require.NoError(t, err)
defer func() {
newDB.Close()
@@ -480,8 +494,10 @@ func TestAppSimulationAfterImport(t *testing.T) {
logger = log.NewNopLogger()
}
dir, _ := ioutil.TempDir("", "goleveldb-app-sim")
db, _ := sdk.NewLevelDB("Simulation", dir)
dir, err := ioutil.TempDir("", "goleveldb-app-sim")
require.NoError(t, err)
db, err := sdk.NewLevelDB("Simulation", dir)
require.NoError(t, err)
defer func() {
db.Close()
@@ -534,8 +550,10 @@ func TestAppSimulationAfterImport(t *testing.T) {
fmt.Printf("Importing genesis...\n")
newDir, _ := ioutil.TempDir("", "goleveldb-app-sim-2")
newDB, _ := sdk.NewLevelDB("Simulation-2", dir)
newDir, err := ioutil.TempDir("", "goleveldb-app-sim-2")
require.NoError(t, err)
newDB, err := sdk.NewLevelDB("Simulation-2", dir)
require.NoError(t, err)
defer func() {
newDB.Close()
@@ -613,8 +631,16 @@ func BenchmarkInvariants(b *testing.B) {
config := simapp.NewConfigFromFlags()
config.AllInvariants = false
dir, _ := ioutil.TempDir("", "goleveldb-app-invariant-bench")
db, _ := sdk.NewLevelDB("simulation", dir)
dir, err := ioutil.TempDir("", "goleveldb-app-invariant-bench")
if err != nil {
fmt.Println(err)
b.Fail()
}
db, err := sdk.NewLevelDB("simulation", dir)
if err != nil {
fmt.Println(err)
b.Fail()
}
defer func() {
db.Close()
@@ -656,6 +682,7 @@ func BenchmarkInvariants(b *testing.B) {
// NOTE: We use the crisis keeper as it has all the invariants registered with
// their respective metadata which makes it useful for testing/benchmarking.
for _, cr := range gapp.crisisKeeper.Routes() {
cr := cr
b.Run(fmt.Sprintf("%s/%s", cr.ModuleName, cr.Route), func(b *testing.B) {
if res, stop := cr.Invar(ctx); stop {
fmt.Printf("broken invariant at block %d of %d\n%s", ctx.BlockHeight()-1, config.NumBlocks, res)

View File

@@ -45,6 +45,7 @@ const (
)
var (
// nolint:varcheck,deadcode,unused
totalCoins = sdk.NewCoins(
sdk.NewCoin(fee2Denom, sdk.TokensFromConsensusPower(2000000)),
sdk.NewCoin(feeDenom, sdk.TokensFromConsensusPower(2000000)),
@@ -171,7 +172,7 @@ func InitFixtures(t *testing.T) (f *Fixtures) {
f.GenTx(keyFoo)
f.CollectGenTxs()
return
return f
}
// Cleanup is meant to be run at the end of a test to clean up an remaining test state
@@ -757,6 +758,7 @@ func WriteToNewTempFile(t *testing.T, s string) *os.File {
return fp
}
//nolint:deadcode,unused
func marshalStdTx(t *testing.T, stdTx auth.StdTx) []byte {
cdc := app.MakeCodec()
bz, err := cdc.MarshalBinaryBare(stdTx)
@@ -764,6 +766,7 @@ func marshalStdTx(t *testing.T, stdTx auth.StdTx) []byte {
return bz
}
//nolint:deadcode,unused
func unmarshalStdTx(t *testing.T, s string) (stdTx auth.StdTx) {
cdc := app.MakeCodec()
require.Nil(t, cdc.UnmarshalJSON([]byte(s), &stdTx))

View File

@@ -2,6 +2,7 @@ package main
import (
"fmt"
"github.com/snikch/goodman/hooks"
"github.com/snikch/goodman/transaction"
)

View File

@@ -116,7 +116,10 @@ func replayTxs(rootDir string) error {
return err
}
defer func() {
_ = proxyApp.Stop()
err = proxyApp.Stop()
if err != nil {
return
}
}()
state := tmsm.LoadState(tmDB)

View File

@@ -113,6 +113,7 @@ func InitTestnet(cmd *cobra.Command, config *tmconfig.Config, cdc *codec.Codec,
gaiaConfig := srvconfig.DefaultConfig()
gaiaConfig.MinGasPrices = minGasPrices
//nolint:prealloc
var (
genAccounts []authexported.GenesisAccount
genFiles []string

View File

@@ -1,7 +1,6 @@
package main
import (
"encoding/base64"
"encoding/hex"
"fmt"
"os"
@@ -14,7 +13,6 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/viper"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/libs/log"
@@ -26,7 +24,7 @@ import (
func runHackCmd(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("Expected 1 arg")
return fmt.Errorf("expected 1 arg")
}
// ".gaiad"
@@ -88,16 +86,11 @@ func runHackCmd(cmd *cobra.Command, args []string) error {
}
}
func base64ToPub(b64 string) ed25519.PubKeyEd25519 {
data, _ := base64.StdEncoding.DecodeString(b64)
var pubKey ed25519.PubKeyEd25519
copy(pubKey[:], data)
return pubKey
}
func hexToBytes(h string) []byte {
trouble, _ := hex.DecodeString(h)
trouble, err := hex.DecodeString(h)
if err != nil {
return nil
}
return trouble
}

View File

@@ -73,7 +73,7 @@ var rawBytesCmd = &cobra.Command{
func runRawBytesCmd(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("Expected single arg")
return fmt.Errorf("expected single arg")
}
stringBytes := args[0]
stringBytes = strings.Trim(stringBytes, "[")
@@ -94,7 +94,7 @@ func runRawBytesCmd(cmd *cobra.Command, args []string) error {
func runPubKeyCmd(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("Expected single arg")
return fmt.Errorf("expected single arg")
}
pubkeyString := args[0]
@@ -116,7 +116,7 @@ func runPubKeyCmd(cmd *cobra.Command, args []string) error {
var err5 error
pubKeyI, err5 = sdk.GetConsPubKeyBech32(pubkeyString)
if err5 != nil {
return fmt.Errorf(`Expected hex, base64, or bech32. Got errors:
return fmt.Errorf(`expected hex, base64, or bech32. Got errors:
hex: %v,
base64: %v
bech32 Acc: %v
@@ -168,7 +168,7 @@ func runPubKeyCmd(cmd *cobra.Command, args []string) error {
func runAddrCmd(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("Expected single arg")
return fmt.Errorf("expected single arg")
}
addrString := args[0]
@@ -185,7 +185,7 @@ func runAddrCmd(cmd *cobra.Command, args []string) error {
addr, err3 = sdk.ValAddressFromBech32(addrString)
if err3 != nil {
return fmt.Errorf(`Expected hex or bech32. Got errors:
return fmt.Errorf(`expected hex or bech32. Got errors:
hex: %v,
bech32 acc: %v
bech32 val: %v
@@ -207,7 +207,7 @@ func runAddrCmd(cmd *cobra.Command, args []string) error {
func runTxCmd(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("Expected single arg")
return fmt.Errorf("expected single arg")
}
txString := args[0]
@@ -218,7 +218,7 @@ func runTxCmd(cmd *cobra.Command, args []string) error {
var err2 error
txBytes, err2 = base64.StdEncoding.DecodeString(txString)
if err2 != nil {
return fmt.Errorf(`Expected hex or base64. Got errors:
return fmt.Errorf(`expected hex or base64. Got errors:
hex: %v,
base64: %v
`, err, err2)

View File

@@ -134,7 +134,7 @@ func defaultGenesis(config *tmcfg.Config, nValidators int, initAddrs []sdk.AccAd
privVal.Reset()
if nValidators < 1 {
err = errors.New("InitializeLCD must use at least one validator")
err = errors.New("initializeLCD must use at least one validator")
return
}
@@ -150,9 +150,11 @@ func defaultGenesis(config *tmcfg.Config, nValidators int, initAddrs []sdk.AccAd
}
// append any additional (non-proposing) validators
var genTxs []auth.StdTx
var genAccounts []authexported.GenesisAccount
//nolint:prealloc
var (
genTxs []auth.StdTx
genAccounts []authexported.GenesisAccount
)
totalSupply := sdk.ZeroInt()
for i := 0; i < nValidators; i++ {
@@ -280,14 +282,14 @@ func defaultGenesis(config *tmcfg.Config, nValidators int, initAddrs []sdk.AccAd
if !(mintData.Params.InflationMax.Equal(sdk.MustNewDecFromStr("15000.0")) &&
mintData.Minter.Inflation.Equal(sdk.MustNewDecFromStr("10000.0")) &&
mintData.Params.InflationMin.Equal(sdk.MustNewDecFromStr("10000.0"))) {
err = errors.New("Mint parameters does not correspond to their defaults")
err = errors.New("mint parameters does not correspond to their defaults")
return
}
} else {
if !(mintData.Params.InflationMax.Equal(sdk.ZeroDec()) &&
mintData.Minter.Inflation.Equal(sdk.ZeroDec()) &&
mintData.Params.InflationMin.Equal(sdk.ZeroDec())) {
err = errors.New("Mint parameters not equal to decimal 0")
err = errors.New("mint parameters not equal to decimal 0")
return
}
}
@@ -298,7 +300,7 @@ func defaultGenesis(config *tmcfg.Config, nValidators int, initAddrs []sdk.AccAd
}
genDoc.AppState = appState
return
return genDoc, valConsPubKeys, valOperAddrs, privVal, err
}
// startTM creates and starts an in-process Tendermint node with memDB and
@@ -412,7 +414,7 @@ func CreateAddrs(kb crkeys.Keybase, numAddrs int) (addrs []sdk.AccAddress, seeds
passwords = append(passwords, addrSeeds[i].Password)
}
return
return addrs, seeds, names, passwords, errs
}
// AddrSeed combines an Address with the mnemonic of the private key to that address

View File

@@ -1,3 +1,4 @@
//nolint:unused,deadcode,bodyclose
package lcdtest
import (
@@ -115,7 +116,7 @@ func getBlock(t *testing.T, port string, height int, expectFail bool) ctypes.Res
func extractResultFromResponse(t *testing.T, body []byte) []byte {
var resp rest.ResponseWithHeight
require.NoError(t, cdc.UnmarshalJSON([]byte(body), &resp))
require.NoError(t, cdc.UnmarshalJSON(body, &resp))
return resp.Result
}
@@ -155,6 +156,7 @@ func getTransaction(t *testing.T, port string, hash string) sdk.TxResponse {
err := cdc.UnmarshalJSON([]byte(body), &tx)
require.NoError(t, err)
return tx
}
@@ -176,6 +178,7 @@ func getTransactions(t *testing.T, port string, tags ...string) *sdk.SearchTxsRe
require.Equal(t, http.StatusOK, res.StatusCode, body)
err := cdc.UnmarshalJSON([]byte(body), &result)
require.NoError(t, err)
return &result
}
@@ -190,6 +193,7 @@ func getKeys(t *testing.T, port string) []keys.KeyOutput {
var m []keys.KeyOutput
err := cdc.UnmarshalJSON([]byte(body), &m)
require.Nil(t, err)
return m
}
@@ -205,6 +209,7 @@ func doKeysPost(t *testing.T, port, name, password, mnemonic string, account int
var resp keys.KeyOutput
err = cdc.UnmarshalJSON([]byte(body), &resp)
require.Nil(t, err, body)
return resp
}
@@ -212,10 +217,10 @@ func doKeysPost(t *testing.T, port, name, password, mnemonic string, account int
func getKeysSeed(t *testing.T, port string) string {
res, body := Request(t, port, "GET", "/keys/seed", nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
reg, err := regexp.Compile(`([a-z]+ ){12}`)
require.Nil(t, err)
reg := regexp.MustCompile(`([a-z]+ ){12}`)
match := reg.MatchString(body)
require.True(t, match, "Returned seed has wrong format", body)
return body
}
@@ -244,6 +249,7 @@ func getKey(t *testing.T, port, name string) keys.KeyOutput {
var resp keys.KeyOutput
err := cdc.UnmarshalJSON([]byte(body), &resp)
require.Nil(t, err)
return resp
}
@@ -259,6 +265,7 @@ func updateKey(t *testing.T, port, name, oldPassword, newPassword string, fail b
return
}
require.Equal(t, http.StatusOK, res.StatusCode, body)
}
// GET /auth/accounts/{address} Get the account information on blockchain
@@ -1129,10 +1136,6 @@ func doUnjail(
return txResp
}
type unjailReq struct {
BaseReq rest.BaseReq `json:"base_req"`
}
// ICS24 - fee distribution
// POST /distribution/delegators/{delgatorAddr}/rewards Withdraw delegator rewards
@@ -1165,11 +1168,3 @@ func doWithdrawDelegatorAllRewards(
return txResp
}
func mustParseDecCoins(dcstring string) sdk.DecCoins {
dcoins, err := sdk.ParseDecCoins(dcstring)
if err != nil {
panic(err)
}
return dcoins
}

View File

@@ -1,3 +1,4 @@
//nolint:bodyclose
package lcdtest
import (
@@ -269,12 +270,13 @@ func TestEncodeTx(t *testing.T) {
require.NoError(t, err)
defer cleanup()
res, body, _ := doTransferWithGas(t, port, seed, name1, memo, "", addr, "2", 1, false, false, fees)
_, body, _ := doTransferWithGas(t, port, seed, name1, memo, "", addr, "2", 1, false, false, fees)
var tx auth.StdTx
require.Nil(t, cdc.UnmarshalJSON([]byte(body), &tx))
encodedJSON, _ := cdc.MarshalJSON(tx)
res, body = Request(t, port, "POST", "/txs/encode", encodedJSON)
encodedJSON, err := cdc.MarshalJSON(tx)
require.NoError(t, err)
res, body := Request(t, port, "POST", "/txs/encode", encodedJSON)
// Make sure it came back ok, and that we can decode it back to the transaction
// 200 response.
@@ -491,7 +493,6 @@ func TestBonding(t *testing.T) {
//require.Equal(t, rdTokens.ToDec(), delTokensAfterRedelegation)
// verify balance after paying fees
acc = getAccount(t, port, addr)
expectedBalance = expectedBalance.Sub(fees[0])
require.True(t,
expectedBalance.Amount.LT(coins.AmountOf(sdk.DefaultBondDenom)) ||
@@ -820,7 +821,8 @@ func TestUnjail(t *testing.T) {
// NOTE: any less than this and it fails
tests.WaitForHeight(3, port)
pkString, _ := sdk.Bech32ifyConsPub(valPubKeys[0])
pkString, err := sdk.Bech32ifyConsPub(valPubKeys[0])
require.NoError(t, err)
signingInfo := getSigningInfo(t, port, pkString)
tests.WaitForHeight(4, port)
require.Equal(t, true, signingInfo.IndexOffset > 0)