From f9cce282dad1b721b73387d391c42d89ab444063 Mon Sep 17 00:00:00 2001 From: Marko Date: Fri, 2 Aug 2019 08:53:52 +0200 Subject: [PATCH] gocritic (2/2) (#3864) Refs #3262 --- .golangci.yml | 1 - abci/cmd/abci-cli/abci-cli.go | 12 +++++++----- abci/example/kvstore/kvstore_test.go | 2 +- blockchain/v0/pool.go | 7 ++++--- consensus/replay.go | 26 +++++++++++++++----------- consensus/replay_test.go | 3 +-- consensus/state.go | 14 ++++++++------ crypto/merkle/simple_proof.go | 7 ++++--- go.mod | 3 +++ go.sum | 7 +++++++ libs/autofile/group.go | 7 ++++--- libs/common/async_test.go | 14 ++++++++------ libs/common/errors.go | 2 +- libs/log/tmfmt_logger.go | 9 +++++---- mempool/clist_mempool_test.go | 2 +- node/node.go | 7 ++++--- p2p/fuzz.go | 7 ++++--- p2p/netaddress.go | 27 +++++++++++++++------------ p2p/node_info_test.go | 2 +- p2p/switch.go | 3 +-- rpc/lib/client/http_client.go | 7 ++++--- rpc/lib/server/handlers.go | 7 ++++--- state/execution.go | 3 +-- state/txindex/kv/kv.go | 10 +++++----- tools/tm-monitor/monitor/network.go | 7 ++++--- types/validator.go | 14 ++++++++------ 26 files changed, 120 insertions(+), 90 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index b07ec3a46..17d575316 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -15,7 +15,6 @@ linters: - nakedret - lll - gochecknoglobals - - gocritic - gochecknoinits - scopelint - stylecheck diff --git a/abci/cmd/abci-cli/abci-cli.go b/abci/cmd/abci-cli/abci-cli.go index 5f0685107..31721b21b 100644 --- a/abci/cmd/abci-cli/abci-cli.go +++ b/abci/cmd/abci-cli/abci-cli.go @@ -332,16 +332,18 @@ func cmdTest(cmd *cobra.Command, args []string) error { func cmdBatch(cmd *cobra.Command, args []string) error { bufReader := bufio.NewReader(os.Stdin) +LOOP: for { line, more, err := bufReader.ReadLine() - if more { + switch { + case more: return errors.New("Input line is too long") - } else if err == io.EOF { - break - } else if len(line) == 0 { + case err == io.EOF: + break LOOP + case len(line) == 0: continue - } else if err != nil { + case err != nil: return err } diff --git a/abci/example/kvstore/kvstore_test.go b/abci/example/kvstore/kvstore_test.go index 1649d3e84..80b07ff5a 100644 --- a/abci/example/kvstore/kvstore_test.go +++ b/abci/example/kvstore/kvstore_test.go @@ -148,7 +148,7 @@ func TestValUpdates(t *testing.T) { makeApplyBlock(t, kvstore, 2, diff, tx1, tx2, tx3) - vals1 = append(vals[:nInit-2], vals[nInit+1]) + vals1 = append(vals[:nInit-2], vals[nInit+1]) // nolint: gocritic vals2 = kvstore.Validators() valsEqual(t, vals1, vals2) diff --git a/blockchain/v0/pool.go b/blockchain/v0/pool.go index bd570f216..7733dc5ff 100644 --- a/blockchain/v0/pool.go +++ b/blockchain/v0/pool.go @@ -112,17 +112,18 @@ func (pool *BlockPool) makeRequestersRoutine() { } _, numPending, lenRequesters := pool.GetStatus() - if numPending >= maxPendingRequests { + switch { + case numPending >= maxPendingRequests: // sleep for a bit. time.Sleep(requestIntervalMS * time.Millisecond) // check for timed out peers pool.removeTimedoutPeers() - } else if lenRequesters >= maxTotalRequesters { + case lenRequesters >= maxTotalRequesters: // sleep for a bit. time.Sleep(requestIntervalMS * time.Millisecond) // check for timed out peers pool.removeTimedoutPeers() - } else { + default: // request for more blocks. pool.makeNextRequester() } diff --git a/consensus/replay.go b/consensus/replay.go index 433c19407..43ad557f7 100644 --- a/consensus/replay.go +++ b/consensus/replay.go @@ -141,14 +141,16 @@ func (cs *ConsensusState) catchupReplay(csHeight int64) error { var msg *TimedWALMessage dec := WALDecoder{gr} +LOOP: for { msg, err = dec.Decode() - if err == io.EOF { - break - } else if IsDataCorruptionError(err) { + switch { + case err == io.EOF: + break LOOP + case IsDataCorruptionError(err): cs.Logger.Error("data has been corrupted in last height of consensus WAL", "err", err, "height", csHeight) return err - } else if err != nil { + case err != nil: return err } @@ -333,19 +335,20 @@ func (h *Handshaker) ReplayBlocks( } // First handle edge cases and constraints on the storeBlockHeight. - if storeBlockHeight == 0 { + switch { + case storeBlockHeight == 0: assertAppHashEqualsOneFromState(appHash, state) return appHash, nil - } else if storeBlockHeight < appBlockHeight { + case storeBlockHeight < appBlockHeight: // the app should never be ahead of the store (but this is under app's control) return appHash, sm.ErrAppBlockHeightTooHigh{CoreHeight: storeBlockHeight, AppHeight: appBlockHeight} - } else if storeBlockHeight < stateBlockHeight { + case storeBlockHeight < stateBlockHeight: // the state should never be ahead of the store (this is under tendermint's control) panic(fmt.Sprintf("StateBlockHeight (%d) > StoreBlockHeight (%d)", stateBlockHeight, storeBlockHeight)) - } else if storeBlockHeight > stateBlockHeight+1 { + case storeBlockHeight > stateBlockHeight+1: // store should be at most one ahead of the state (this is under tendermint's control) panic(fmt.Sprintf("StoreBlockHeight (%d) > StateBlockHeight + 1 (%d)", storeBlockHeight, stateBlockHeight+1)) } @@ -369,12 +372,13 @@ func (h *Handshaker) ReplayBlocks( } else if storeBlockHeight == stateBlockHeight+1 { // We saved the block in the store but haven't updated the state, // so we'll need to replay a block using the WAL. - if appBlockHeight < stateBlockHeight { + switch { + case appBlockHeight < stateBlockHeight: // the app is further behind than it should be, so replay blocks // but leave the last block to go through the WAL return h.replayBlocks(state, proxyApp, appBlockHeight, storeBlockHeight, true) - } else if appBlockHeight == stateBlockHeight { + case appBlockHeight == stateBlockHeight: // We haven't run Commit (both the state and app are one block behind), // so replayBlock with the real app. // NOTE: We could instead use the cs.WAL on cs.Start, @@ -383,7 +387,7 @@ func (h *Handshaker) ReplayBlocks( state, err = h.replayBlock(state, storeBlockHeight, proxyApp.Consensus()) return state.AppHash, err - } else if appBlockHeight == storeBlockHeight { + case appBlockHeight == storeBlockHeight: // We ran Commit, but didn't save the state, so replayBlock with mock app. abciResponses, err := sm.LoadABCIResponses(h.stateDB, storeBlockHeight) if err != nil { diff --git a/consensus/replay_test.go b/consensus/replay_test.go index 20ecb64d9..5b454248d 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -545,8 +545,7 @@ func TestMockProxyApp(t *testing.T) { abciRes.DeliverTx = make([]*abci.ResponseDeliverTx, len(loadedAbciRes.DeliverTx)) // Execute transactions and get hash. proxyCb := func(req *abci.Request, res *abci.Response) { - switch r := res.Value.(type) { - case *abci.Response_DeliverTx: + if r, ok := res.Value.(*abci.Response_DeliverTx); ok { // TODO: make use of res.Log // TODO: make use of this info // Blocks may include invalid txs. diff --git a/consensus/state.go b/consensus/state.go index fe6fefd42..a53e6b267 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -952,14 +952,15 @@ func (cs *ConsensusState) isProposalComplete() bool { // NOTE: keep it side-effect free for clarity. func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts *types.PartSet) { var commit *types.Commit - if cs.Height == 1 { + switch { + case cs.Height == 1: // We're creating a proposal for the first block. // The commit is empty, but not nil. commit = types.NewCommit(types.BlockID{}, nil) - } else if cs.LastCommit.HasTwoThirdsMajority() { + case cs.LastCommit.HasTwoThirdsMajority(): // Make the commit from LastCommit commit = cs.LastCommit.MakeCommit() - } else { + default: // This shouldn't happen. cs.Logger.Error("enterPropose: Cannot propose anything: No commit for the previous block.") return @@ -1628,17 +1629,18 @@ func (cs *ConsensusState) addVote(vote *types.Vote, peerID p2p.ID) (added bool, } // If +2/3 prevotes for *anything* for future round: - if cs.Round < vote.Round && prevotes.HasTwoThirdsAny() { + switch { + case cs.Round < vote.Round && prevotes.HasTwoThirdsAny(): // Round-skip if there is any 2/3+ of votes ahead of us cs.enterNewRound(height, vote.Round) - } else if cs.Round == vote.Round && cstypes.RoundStepPrevote <= cs.Step { // current round + case cs.Round == vote.Round && cstypes.RoundStepPrevote <= cs.Step: // current round blockID, ok := prevotes.TwoThirdsMajority() if ok && (cs.isProposalComplete() || len(blockID.Hash) == 0) { cs.enterPrecommit(height, vote.Round) } else if prevotes.HasTwoThirdsAny() { cs.enterPrevoteWait(height, vote.Round) } - } else if cs.Proposal != nil && 0 <= cs.Proposal.POLRound && cs.Proposal.POLRound == vote.Round { + case cs.Proposal != nil && 0 <= cs.Proposal.POLRound && cs.Proposal.POLRound == vote.Round: // If the proposal is now complete, enter prevote of cs.Round. if cs.isProposalComplete() { cs.enterPrevote(height, cs.Round) diff --git a/crypto/merkle/simple_proof.go b/crypto/merkle/simple_proof.go index f01dcdca1..d3be5d7ec 100644 --- a/crypto/merkle/simple_proof.go +++ b/crypto/merkle/simple_proof.go @@ -162,11 +162,12 @@ func (spn *SimpleProofNode) FlattenAunts() [][]byte { // Nonrecursive impl. innerHashes := [][]byte{} for spn != nil { - if spn.Left != nil { + switch { + case spn.Left != nil: innerHashes = append(innerHashes, spn.Left.Hash) - } else if spn.Right != nil { + case spn.Right != nil: innerHashes = append(innerHashes, spn.Right.Hash) - } else { + default: break } spn = spn.Parent diff --git a/go.mod b/go.mod index 92a732a89..ffa305e38 100644 --- a/go.mod +++ b/go.mod @@ -14,8 +14,10 @@ require ( github.com/gogo/protobuf v1.2.1 github.com/golang/protobuf v1.3.2 github.com/google/gofuzz v1.0.0 // indirect + github.com/google/pprof v0.0.0-20190723021845-34ac40c74b70 // indirect github.com/gorilla/websocket v1.2.0 github.com/hashicorp/hcl v1.0.0 // indirect + github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515 // indirect github.com/libp2p/go-buffer-pool v0.0.1 @@ -39,6 +41,7 @@ require ( github.com/stretchr/testify v1.3.0 github.com/tendermint/go-amino v0.14.1 github.com/tendermint/tm-db v0.1.1 + golang.org/x/arch v0.0.0-20190312162104-788fe5ffcd8c // indirect golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 golang.org/x/net v0.0.0-20190628185345-da137c7871d7 google.golang.org/grpc v1.22.0 diff --git a/go.sum b/go.sum index 6d748bbf5..c6d506f0b 100644 --- a/go.sum +++ b/go.sum @@ -46,12 +46,16 @@ github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEW github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20190723021845-34ac40c74b70 h1:XTnP8fJpa4Kvpw2qARB4KS9izqxPS0Sd92cDlY3uk+w= +github.com/google/pprof v0.0.0-20190723021845-34ac40c74b70/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/gorilla/websocket v1.2.0 h1:VJtLvh6VQym50czpZzx07z/kw9EgAxI3x1ZB8taTMQQ= github.com/gorilla/websocket v1.2.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6 h1:UDMh68UUwekSh5iP2OMhRRZJiiBccgV7axzUG8vi56c= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= @@ -121,6 +125,8 @@ github.com/tendermint/tm-db v0.1.1 h1:G3Xezy3sOk9+ekhjZ/kjArYIs1SmwV+1OUgNkj7RgV github.com/tendermint/tm-db v0.1.1/go.mod h1:0cPKWu2Mou3IlxecH+MEUSYc1Ch537alLe6CpFrKzgw= go.etcd.io/bbolt v1.3.3 h1:MUGmc65QhB3pIlaQ5bB4LwqSj6GIonVJXpZiaKNyaKk= go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +golang.org/x/arch v0.0.0-20190312162104-788fe5ffcd8c h1:Rx/HTKi09myZ25t1SOlDHmHOy/mKxNAcu0hP1oPX9qM= +golang.org/x/arch v0.0.0-20190312162104-788fe5ffcd8c/go.mod h1:flIaEI6LNU6xOCD5PaJvn9wGP0agmIOqjrtsKGRguv4= golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= @@ -157,3 +163,4 @@ gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWD gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/libs/autofile/group.go b/libs/autofile/group.go index ce73466e4..7cc345478 100644 --- a/libs/autofile/group.go +++ b/libs/autofile/group.go @@ -472,7 +472,8 @@ func (gr *GroupReader) Read(p []byte) (n int, err error) { for { nn, err = gr.curReader.Read(p[n:]) n += nn - if err == io.EOF { + switch { + case err == io.EOF: if n >= lenP { return n, nil } @@ -480,9 +481,9 @@ func (gr *GroupReader) Read(p []byte) (n int, err error) { if err1 := gr.openFile(gr.curIndex + 1); err1 != nil { return n, err1 } - } else if err != nil { + case err != nil: return n, err - } else if nn == 0 { // empty file + case nn == 0: // empty file return n, err } } diff --git a/libs/common/async_test.go b/libs/common/async_test.go index c19ffc86f..9ac5ffe3f 100644 --- a/libs/common/async_test.go +++ b/libs/common/async_test.go @@ -31,13 +31,14 @@ func TestParallel(t *testing.T) { var failedTasks int for i := 0; i < len(tasks); i++ { taskResult, ok := trs.LatestResult(i) - if !ok { + switch { + case !ok: assert.Fail(t, "Task #%v did not complete.", i) failedTasks++ - } else if taskResult.Error != nil { + case taskResult.Error != nil: assert.Fail(t, "Task should not have errored but got %v", taskResult.Error) failedTasks++ - } else if !assert.Equal(t, -1*i, taskResult.Value.(int)) { + case !assert.Equal(t, -1*i, taskResult.Value.(int)): assert.Fail(t, "Task should have returned %v but got %v", -1*i, taskResult.Value.(int)) failedTasks++ } @@ -133,11 +134,12 @@ func checkResult(t *testing.T, taskResultSet *TaskResultSet, index int, val inte taskName := fmt.Sprintf("Task #%v", index) assert.True(t, ok, "TaskResultCh unexpectedly closed for %v", taskName) assert.Equal(t, val, taskResult.Value, taskName) - if err != nil { + switch { + case err != nil: assert.Equal(t, err, taskResult.Error, taskName) - } else if pnk != nil { + case pnk != nil: assert.Equal(t, pnk, taskResult.Error.(Error).Data(), taskName) - } else { + default: assert.Nil(t, taskResult.Error, taskName) } } diff --git a/libs/common/errors.go b/libs/common/errors.go index 24af84267..aacfbe274 100644 --- a/libs/common/errors.go +++ b/libs/common/errors.go @@ -9,7 +9,7 @@ import ( // Convenience method. func ErrorWrap(cause interface{}, format string, args ...interface{}) Error { - if causeCmnError, ok := cause.(*cmnError); ok { + if causeCmnError, ok := cause.(*cmnError); ok { //nolint:gocritic msg := fmt.Sprintf(format, args...) return causeCmnError.Stacktrace().Trace(1, msg) } else if cause == nil { diff --git a/libs/log/tmfmt_logger.go b/libs/log/tmfmt_logger.go index d841263ea..d57f9558e 100644 --- a/libs/log/tmfmt_logger.go +++ b/libs/log/tmfmt_logger.go @@ -60,9 +60,10 @@ func (l tmfmtLogger) Log(keyvals ...interface{}) error { for i := 0; i < len(keyvals)-1; i += 2 { // Extract level - if keyvals[i] == kitlevel.Key() { + switch keyvals[i] { + case kitlevel.Key(): excludeIndexes = append(excludeIndexes, i) - switch keyvals[i+1].(type) { + switch keyvals[i+1].(type) { // nolint:gocritic case string: lvl = keyvals[i+1].(string) case kitlevel.Value: @@ -71,11 +72,11 @@ func (l tmfmtLogger) Log(keyvals ...interface{}) error { panic(fmt.Sprintf("level value of unknown type %T", keyvals[i+1])) } // and message - } else if keyvals[i] == msgKey { + case msgKey: excludeIndexes = append(excludeIndexes, i) msg = keyvals[i+1].(string) // and module (could be multiple keyvals; if such case last keyvalue wins) - } else if keyvals[i] == moduleKey { + case moduleKey: excludeIndexes = append(excludeIndexes, i) module = keyvals[i+1].(string) } diff --git a/mempool/clist_mempool_test.go b/mempool/clist_mempool_test.go index e2ebca925..220bb5cb3 100644 --- a/mempool/clist_mempool_test.go +++ b/mempool/clist_mempool_test.go @@ -244,7 +244,7 @@ func TestTxsAvailable(t *testing.T) { ensureNoFire(t, mempool.TxsAvailable(), timeoutMS) // now call update with all the txs. it should not fire as there are no txs left - committedTxs = append(txs, moreTxs...) + committedTxs = append(txs, moreTxs...) //nolint: gocritic if err := mempool.Update(2, committedTxs, abciResponses(len(committedTxs), abci.CodeTypeOK), nil, nil); err != nil { t.Error(err) } diff --git a/node/node.go b/node/node.go index 2884787dc..18cb0ba3b 100644 --- a/node/node.go +++ b/node/node.go @@ -246,11 +246,12 @@ func createAndStartIndexerService(config *cfg.Config, dbProvider DBProvider, if err != nil { return nil, nil, err } - if config.TxIndex.IndexTags != "" { + switch { + case config.TxIndex.IndexTags != "": txIndexer = kv.NewTxIndex(store, kv.IndexTags(splitAndTrimEmpty(config.TxIndex.IndexTags, ",", " "))) - } else if config.TxIndex.IndexAllTags { + case config.TxIndex.IndexAllTags: txIndexer = kv.NewTxIndex(store, kv.IndexAllTags()) - } else { + default: txIndexer = kv.NewTxIndex(store) } default: diff --git a/p2p/fuzz.go b/p2p/fuzz.go index 80e4fed6a..135155d86 100644 --- a/p2p/fuzz.go +++ b/p2p/fuzz.go @@ -117,14 +117,15 @@ func (fc *FuzzedConnection) fuzz() bool { case config.FuzzModeDrop: // randomly drop the r/w, drop the conn, or sleep r := cmn.RandFloat64() - if r <= fc.config.ProbDropRW { + switch { + case r <= fc.config.ProbDropRW: return true - } else if r < fc.config.ProbDropRW+fc.config.ProbDropConn { + case r < fc.config.ProbDropRW+fc.config.ProbDropConn: // XXX: can't this fail because machine precision? // XXX: do we need an error? fc.Close() // nolint: errcheck, gas return true - } else if r < fc.config.ProbDropRW+fc.config.ProbDropConn+fc.config.ProbSleep { + case r < fc.config.ProbDropRW+fc.config.ProbDropConn+fc.config.ProbSleep: time.Sleep(fc.randomDuration()) } case config.FuzzModeDelay: diff --git a/p2p/netaddress.go b/p2p/netaddress.go index f39a60543..04a2b843f 100644 --- a/p2p/netaddress.go +++ b/p2p/netaddress.go @@ -250,36 +250,39 @@ func (na *NetAddress) ReachabilityTo(o *NetAddress) int { Ipv4 Ipv6_strong ) - if !na.Routable() { + switch { + case !na.Routable(): return Unreachable - } else if na.RFC4380() { - if !o.Routable() { + case na.RFC4380(): + switch { + case !o.Routable(): return Default - } else if o.RFC4380() { + case o.RFC4380(): return Teredo - } else if o.IP.To4() != nil { + case o.IP.To4() != nil: return Ipv4 - } else { // ipv6 + default: // ipv6 return Ipv6_weak } - } else if na.IP.To4() != nil { + case na.IP.To4() != nil: if o.Routable() && o.IP.To4() != nil { return Ipv4 } return Default - } else /* ipv6 */ { + default: /* ipv6 */ var tunnelled bool // Is our v6 is tunnelled? if o.RFC3964() || o.RFC6052() || o.RFC6145() { tunnelled = true } - if !o.Routable() { + switch { + case !o.Routable(): return Default - } else if o.RFC4380() { + case o.RFC4380(): return Teredo - } else if o.IP.To4() != nil { + case o.IP.To4() != nil: return Ipv4 - } else if tunnelled { + case tunnelled: // only prioritise ipv6 if we aren't tunnelling it. return Ipv6_weak } diff --git a/p2p/node_info_test.go b/p2p/node_info_test.go index 9ed80b28b..e90f397cf 100644 --- a/p2p/node_info_test.go +++ b/p2p/node_info_test.go @@ -31,7 +31,7 @@ func TestNodeInfoValidate(t *testing.T) { malleateNodeInfo func(*DefaultNodeInfo) expectErr bool }{ - {"Too Many Channels", func(ni *DefaultNodeInfo) { ni.Channels = append(channels, byte(maxNumChannels)) }, true}, + {"Too Many Channels", func(ni *DefaultNodeInfo) { ni.Channels = append(channels, byte(maxNumChannels)) }, true}, // nolint: gocritic {"Duplicate Channel", func(ni *DefaultNodeInfo) { ni.Channels = dupChannels }, true}, {"Good Channels", func(ni *DefaultNodeInfo) { ni.Channels = ni.Channels[:5] }, false}, diff --git a/p2p/switch.go b/p2p/switch.go index 66c2f9e4a..3681dd942 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -679,8 +679,7 @@ func (sw *Switch) addOutboundPeerWithConfig( metrics: sw.metrics, }) if err != nil { - switch e := err.(type) { - case ErrRejected: + if e, ok := err.(ErrRejected); ok { if e.IsSelf() { // Remove the given address from the address book and add to our addresses // to avoid dialing in the future. diff --git a/rpc/lib/client/http_client.go b/rpc/lib/client/http_client.go index 3b545a5dd..db57c536e 100644 --- a/rpc/lib/client/http_client.go +++ b/rpc/lib/client/http_client.go @@ -42,12 +42,13 @@ func makeHTTPDialer(remoteAddr string) (string, string, func(string, string) (ne parts := strings.SplitN(remoteAddr, "://", 2) var protocol, address string - if len(parts) == 1 { + switch { + case len(parts) == 1: // default to tcp if nothing specified protocol, address = protoTCP, remoteAddr - } else if len(parts) == 2 { + case len(parts) == 2: protocol, address = parts[0], parts[1] - } else { + default: // return a invalid message msg := fmt.Sprintf("Invalid addr: %s", remoteAddr) return clientProtocol, msg, func(_ string, _ string) (net.Conn, error) { diff --git a/rpc/lib/server/handlers.go b/rpc/lib/server/handlers.go index 78bc7b259..5b5c9f8b9 100644 --- a/rpc/lib/server/handlers.go +++ b/rpc/lib/server/handlers.go @@ -339,13 +339,14 @@ func jsonStringToArg(cdc *amino.Codec, rt reflect.Type, arg string) (reflect.Val func nonJSONStringToArg(cdc *amino.Codec, rt reflect.Type, arg string) (reflect.Value, error, bool) { if rt.Kind() == reflect.Ptr { rv_, err, ok := nonJSONStringToArg(cdc, rt.Elem(), arg) - if err != nil { + switch { + case err != nil: return reflect.Value{}, err, false - } else if ok { + case ok: rv := reflect.New(rt.Elem()) rv.Elem().Set(rv_) return rv, nil, true - } else { + default: return reflect.Value{}, nil, false } } else { diff --git a/state/execution.go b/state/execution.go index 600d339b5..2ac2e9689 100644 --- a/state/execution.go +++ b/state/execution.go @@ -249,8 +249,7 @@ func execBlockOnProxyApp( // Execute transactions and get hash. proxyCb := func(req *abci.Request, res *abci.Response) { - switch r := res.Value.(type) { - case *abci.Response_DeliverTx: + if r, ok := res.Value.(*abci.Response_DeliverTx); ok { // TODO: make use of res.Log // TODO: make use of this info // Blocks may include invalid txs. diff --git a/state/txindex/kv/kv.go b/state/txindex/kv/kv.go index 89d8868a0..2695e18a0 100644 --- a/state/txindex/kv/kv.go +++ b/state/txindex/kv/kv.go @@ -379,7 +379,8 @@ func (txi *TxIndex) match(c query.Condition, startKeyBz []byte, filteredHashes m tmpHashes := make(map[string][]byte) - if c.Op == query.OpEqual { + switch { + case c.Op == query.OpEqual: it := dbm.IteratePrefix(txi.store, startKeyBz) defer it.Close() @@ -387,7 +388,7 @@ func (txi *TxIndex) match(c query.Condition, startKeyBz []byte, filteredHashes m tmpHashes[string(it.Value())] = it.Value() } - } else if c.Op == query.OpContains { + case c.Op == query.OpContains: // XXX: startKey does not apply here. // For example, if startKey = "account.owner/an/" and search query = "account.owner CONTAINS an" // we can't iterate with prefix "account.owner/an/" because we might miss keys like "account.owner/Ulan/" @@ -403,7 +404,7 @@ func (txi *TxIndex) match(c query.Condition, startKeyBz []byte, filteredHashes m tmpHashes[string(it.Value())] = it.Value() } } - } else { + default: panic("other operators should be handled already") } @@ -454,8 +455,7 @@ LOOP: continue } - switch r.AnyBound().(type) { - case int64: + if _, ok := r.AnyBound().(int64); ok { v, err := strconv.ParseInt(extractValueFromKey(it.Key()), 10, 64) if err != nil { continue LOOP diff --git a/tools/tm-monitor/monitor/network.go b/tools/tm-monitor/monitor/network.go index bb5dd0baa..4d85d7ed6 100644 --- a/tools/tm-monitor/monitor/network.go +++ b/tools/tm-monitor/monitor/network.go @@ -163,11 +163,12 @@ func (n *Network) updateHealth() { // TODO: make sure they're all at the same height (within a block) // and all proposing (and possibly validating ) Alternatively, just // check there hasn't been a new round in numValidators rounds - if n.NumValidators != 0 && n.NumNodesMonitoredOnline == n.NumValidators { + switch { + case n.NumValidators != 0 && n.NumNodesMonitoredOnline == n.NumValidators: n.Health = FullHealth - } else if n.NumNodesMonitoredOnline > 0 && n.NumNodesMonitoredOnline <= n.NumNodesMonitored { + case n.NumNodesMonitoredOnline > 0 && n.NumNodesMonitoredOnline <= n.NumNodesMonitored: n.Health = ModerateHealth - } else { + default: n.Health = Dead } } diff --git a/types/validator.go b/types/validator.go index a662eb6c0..20069ff9a 100644 --- a/types/validator.go +++ b/types/validator.go @@ -41,17 +41,19 @@ func (v *Validator) CompareProposerPriority(other *Validator) *Validator { if v == nil { return other } - if v.ProposerPriority > other.ProposerPriority { + switch { + case v.ProposerPriority > other.ProposerPriority: return v - } else if v.ProposerPriority < other.ProposerPriority { + case v.ProposerPriority < other.ProposerPriority: return other - } else { + default: result := bytes.Compare(v.Address, other.Address) - if result < 0 { + switch { + case result < 0: return v - } else if result > 0 { + case result > 0: return other - } else { + default: panic("Cannot compare identical validators") } }