From 41bf54a906fe63ff41088d1c85ea9d6f758a22fc Mon Sep 17 00:00:00 2001 From: Marko Date: Tue, 30 Jul 2019 16:13:35 +0200 Subject: [PATCH] gocritic (1/2) (#3836) Add gocritic as a linter The linting is not complete, but should i complete in this PR or in a following. 23 files have been touched so it may be better to do in a following PR Commits: * Add gocritic to linting - Added gocritic to linting Signed-off-by: Marko Baricevic * gocritic * pr comments * remove switch in cmdBatch --- abci/cmd/abci-cli/abci-cli.go | 50 +++++--------------- abci/example/kvstore/persistent_kvstore.go | 3 +- abci/server/socket_server.go | 7 +-- cmd/tendermint/commands/root_test.go | 2 +- consensus/mempool_test.go | 4 +- consensus/reactor_test.go | 12 ++--- consensus/replay.go | 6 +-- consensus/replay_file.go | 6 +-- consensus/state.go | 6 +-- consensus/state_test.go | 36 +++++++------- crypto/ed25519/ed25519.go | 4 +- crypto/internal/benchmarking/bench.go | 4 +- crypto/secp256k1/internal/secp256k1/curve.go | 1 + libs/cli/helper.go | 2 +- libs/common/random_test.go | 8 ++-- libs/common/string.go | 7 +-- mempool/reactor_test.go | 8 ++-- p2p/node_info_test.go | 2 +- p2p/pex/addrbook.go | 6 +-- rpc/lib/server/handlers.go | 10 ++-- state/state_test.go | 18 +++---- types/genesis.go | 6 +-- types/validator_set.go | 4 +- 23 files changed, 89 insertions(+), 123 deletions(-) diff --git a/abci/cmd/abci-cli/abci-cli.go b/abci/cmd/abci-cli/abci-cli.go index cd0a6fd1f..5f0685107 100644 --- a/abci/cmd/abci-cli/abci-cli.go +++ b/abci/cmd/abci-cli/abci-cli.go @@ -174,9 +174,7 @@ where example.file looks something like: info `, Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - return cmdBatch(cmd, args) - }, + RunE: cmdBatch, } var consoleCmd = &cobra.Command{ @@ -189,9 +187,7 @@ without opening a new connection each time `, Args: cobra.ExactArgs(0), ValidArgs: []string{"echo", "info", "set_option", "deliver_tx", "check_tx", "commit", "query"}, - RunE: func(cmd *cobra.Command, args []string) error { - return cmdConsole(cmd, args) - }, + RunE: cmdConsole, } var echoCmd = &cobra.Command{ @@ -199,27 +195,21 @@ var echoCmd = &cobra.Command{ Short: "have the application echo a message", Long: "have the application echo a message", Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - return cmdEcho(cmd, args) - }, + RunE: cmdEcho, } var infoCmd = &cobra.Command{ Use: "info", Short: "get some info about the application", Long: "get some info about the application", Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - return cmdInfo(cmd, args) - }, + RunE: cmdInfo, } var setOptionCmd = &cobra.Command{ Use: "set_option", Short: "set an option on the application", Long: "set an option on the application", Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - return cmdSetOption(cmd, args) - }, + RunE: cmdSetOption, } var deliverTxCmd = &cobra.Command{ @@ -227,9 +217,7 @@ var deliverTxCmd = &cobra.Command{ Short: "deliver a new transaction to the application", Long: "deliver a new transaction to the application", Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - return cmdDeliverTx(cmd, args) - }, + RunE: cmdDeliverTx, } var checkTxCmd = &cobra.Command{ @@ -237,9 +225,7 @@ var checkTxCmd = &cobra.Command{ Short: "validate a transaction", Long: "validate a transaction", Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - return cmdCheckTx(cmd, args) - }, + RunE: cmdCheckTx, } var commitCmd = &cobra.Command{ @@ -247,9 +233,7 @@ var commitCmd = &cobra.Command{ Short: "commit the application state and return the Merkle root hash", Long: "commit the application state and return the Merkle root hash", Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - return cmdCommit(cmd, args) - }, + RunE: cmdCommit, } var versionCmd = &cobra.Command{ @@ -268,9 +252,7 @@ var queryCmd = &cobra.Command{ Short: "query the application state", Long: "query the application state", Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - return cmdQuery(cmd, args) - }, + RunE: cmdQuery, } var counterCmd = &cobra.Command{ @@ -278,9 +260,7 @@ var counterCmd = &cobra.Command{ Short: "ABCI demo example", Long: "ABCI demo example", Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - return cmdCounter(cmd, args) - }, + RunE: cmdCounter, } var kvstoreCmd = &cobra.Command{ @@ -288,9 +268,7 @@ var kvstoreCmd = &cobra.Command{ Short: "ABCI demo example", Long: "ABCI demo example", Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - return cmdKVStore(cmd, args) - }, + RunE: cmdKVStore, } var testCmd = &cobra.Command{ @@ -298,9 +276,7 @@ var testCmd = &cobra.Command{ Short: "run integration tests", Long: "run integration tests", Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - return cmdTest(cmd, args) - }, + RunE: cmdTest, } // Generates new Args array based off of previous call args to maintain flag persistence @@ -419,7 +395,7 @@ func muxOnCommands(cmd *cobra.Command, pArgs []string) error { } // otherwise, we need to skip the next one too - i += 1 + i++ continue } diff --git a/abci/example/kvstore/persistent_kvstore.go b/abci/example/kvstore/persistent_kvstore.go index 308100b6a..4f84cd3e9 100644 --- a/abci/example/kvstore/persistent_kvstore.go +++ b/abci/example/kvstore/persistent_kvstore.go @@ -121,8 +121,7 @@ func (app *PersistentKVStoreApplication) BeginBlock(req types.RequestBeginBlock) app.ValUpdates = make([]types.ValidatorUpdate, 0) for _, ev := range req.ByzantineValidators { - switch ev.Type { - case tmtypes.ABCIEvidenceTypeDuplicateVote: + if ev.Type == tmtypes.ABCIEvidenceTypeDuplicateVote { // decrease voting power by 1 if ev.TotalVotingPower == 0 { continue diff --git a/abci/server/socket_server.go b/abci/server/socket_server.go index 82ce610ed..3e1d775d7 100644 --- a/abci/server/socket_server.go +++ b/abci/server/socket_server.go @@ -127,11 +127,12 @@ func (s *SocketServer) acceptConnectionsRoutine() { func (s *SocketServer) waitForClose(closeConn chan error, connID int) { err := <-closeConn - if err == io.EOF { + switch { + case err == io.EOF: s.Logger.Error("Connection was closed by client") - } else if err != nil { + case err != nil: s.Logger.Error("Connection error", "error", err) - } else { + default: // never happens s.Logger.Error("Connection was closed.") } diff --git a/cmd/tendermint/commands/root_test.go b/cmd/tendermint/commands/root_test.go index 892a49b74..229385af9 100644 --- a/cmd/tendermint/commands/root_test.go +++ b/cmd/tendermint/commands/root_test.go @@ -165,7 +165,7 @@ func TestRootConfig(t *testing.T) { func WriteConfigVals(dir string, vals map[string]string) error { data := "" for k, v := range vals { - data = data + fmt.Sprintf("%s = \"%s\"\n", k, v) + data += fmt.Sprintf("%s = \"%s\"\n", k, v) } cfile := filepath.Join(dir, "config.toml") return ioutil.WriteFile(cfile, []byte(data), 0666) diff --git a/consensus/mempool_test.go b/consensus/mempool_test.go index 94f7340c2..f4df1aca1 100644 --- a/consensus/mempool_test.go +++ b/consensus/mempool_test.go @@ -82,14 +82,14 @@ func TestMempoolProgressInHigherRound(t *testing.T) { ensureNewRound(newRoundCh, height, round) // first round at first height ensureNewEventOnChannel(newBlockCh) // first block gets committed - height = height + 1 // moving to the next height + height++ // moving to the next height round = 0 ensureNewRound(newRoundCh, height, round) // first round at next height deliverTxsRange(cs, 0, 1) // we deliver txs, but dont set a proposal so we get the next round ensureNewTimeout(timeoutCh, height, round, cs.config.TimeoutPropose.Nanoseconds()) - round = round + 1 // moving to the next round + round++ // moving to the next round ensureNewRound(newRoundCh, height, round) // wait for the next round ensureNewEventOnChannel(newBlockCh) // now we can commit the block } diff --git a/consensus/reactor_test.go b/consensus/reactor_test.go index af6a62568..6697efdb8 100644 --- a/consensus/reactor_test.go +++ b/consensus/reactor_test.go @@ -31,15 +31,15 @@ import ( //---------------------------------------------- // in-process testnets -func startConsensusNet(t *testing.T, css []*ConsensusState, N int) ( +func startConsensusNet(t *testing.T, css []*ConsensusState, n int) ( []*ConsensusReactor, []types.Subscription, []*types.EventBus, ) { - reactors := make([]*ConsensusReactor, N) + reactors := make([]*ConsensusReactor, n) blocksSubs := make([]types.Subscription, 0) - eventBuses := make([]*types.EventBus, N) - for i := 0; i < N; i++ { + eventBuses := make([]*types.EventBus, n) + for i := 0; i < n; i++ { /*logger, err := tmflags.ParseLogLevel("consensus:info,*:error", logger, "info") if err != nil { t.Fatal(err)}*/ reactors[i] = NewConsensusReactor(css[i], true) // so we dont start the consensus states @@ -58,7 +58,7 @@ func startConsensusNet(t *testing.T, css []*ConsensusState, N int) ( } } // make connected switches and start all reactors - p2p.MakeConnectedSwitches(config.P2P, N, func(i int, s *p2p.Switch) *p2p.Switch { + p2p.MakeConnectedSwitches(config.P2P, n, func(i int, s *p2p.Switch) *p2p.Switch { s.AddReactor("CONSENSUS", reactors[i]) s.SetLogger(reactors[i].conS.Logger.With("module", "p2p")) return s @@ -68,7 +68,7 @@ func startConsensusNet(t *testing.T, css []*ConsensusState, N int) ( // If we started the state machines before everyone was connected, // we'd block when the cs fires NewBlockEvent and the peers are trying to start their reactors // TODO: is this still true with new pubsub? - for i := 0; i < N; i++ { + for i := 0; i < n; i++ { s := reactors[i].conS.GetState() reactors[i].SwitchToConsensus(s, 0) } diff --git a/consensus/replay.go b/consensus/replay.go index a55fd80c5..797593585 100644 --- a/consensus/replay.go +++ b/consensus/replay.go @@ -320,11 +320,9 @@ func (h *Handshaker) ReplayBlocks( } state.Validators = types.NewValidatorSet(vals) state.NextValidators = types.NewValidatorSet(vals) - } else { + } else if len(h.genDoc.Validators) == 0 { // If validator set is not set in genesis and still empty after InitChain, exit. - if len(h.genDoc.Validators) == 0 { - return nil, fmt.Errorf("validator set is nil in genesis and still empty after InitChain") - } + return nil, fmt.Errorf("validator set is nil in genesis and still empty after InitChain") } if res.ConsensusParams != nil { diff --git a/consensus/replay_file.go b/consensus/replay_file.go index e686262d6..00a18c218 100644 --- a/consensus/replay_file.go +++ b/consensus/replay_file.go @@ -231,10 +231,8 @@ func (pb *playback) replayConsoleLoop() int { fmt.Println("back takes an integer argument") } else if i > pb.count { fmt.Printf("argument to back must not be larger than the current count (%d)\n", pb.count) - } else { - if err := pb.replayReset(i, newStepSub); err != nil { - pb.cs.Logger.Error("Replay reset error", "err", err) - } + } else if err := pb.replayReset(i, newStepSub); err != nil { + pb.cs.Logger.Error("Replay reset error", "err", err) } } diff --git a/consensus/state.go b/consensus/state.go index 0a48b0525..fe6fefd42 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -924,10 +924,8 @@ func (cs *ConsensusState) defaultDecideProposal(height int64, round int) { } cs.Logger.Info("Signed proposal", "height", height, "round", round, "proposal", proposal) cs.Logger.Debug(fmt.Sprintf("Signed proposal block: %v", block)) - } else { - if !cs.replayMode { - cs.Logger.Error("enterPropose: Error signing proposal", "height", height, "round", round, "err", err) - } + } else if !cs.replayMode { + cs.Logger.Error("enterPropose: Error signing proposal", "height", height, "round", round, "err", err) } } diff --git a/consensus/state_test.go b/consensus/state_test.go index 1888e4057..8409f2235 100644 --- a/consensus/state_test.go +++ b/consensus/state_test.go @@ -181,7 +181,7 @@ func TestStateBadProposal(t *testing.T) { propBlock, _ := cs1.createProposalBlock() //changeProposer(t, cs1, vs2) // make the second validator the proposer by incrementing round - round = round + 1 + round++ incrementRound(vss[1:]...) // make the block bad by tampering with statehash @@ -374,7 +374,7 @@ func TestStateLockNoPOL(t *testing.T) { /// - round = round + 1 // moving to the next round + round++ // moving to the next round ensureNewRound(newRoundCh, height, round) t.Log("#### ONTO ROUND 1") /* @@ -418,7 +418,7 @@ func TestStateLockNoPOL(t *testing.T) { // then we enterPrecommitWait and timeout into NewRound ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) - round = round + 1 // entering new round + round++ // entering new round ensureNewRound(newRoundCh, height, round) t.Log("#### ONTO ROUND 2") /* @@ -460,7 +460,7 @@ func TestStateLockNoPOL(t *testing.T) { incrementRound(vs2) - round = round + 1 // entering new round + round++ // entering new round ensureNewRound(newRoundCh, height, round) t.Log("#### ONTO ROUND 3") /* @@ -544,7 +544,7 @@ func TestStateLockPOLRelock(t *testing.T) { // timeout to new round ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) - round = round + 1 // moving to the next round + round++ // moving to the next round //XXX: this isnt guaranteed to get there before the timeoutPropose ... if err := cs1.SetProposalAndBlock(prop, propBlock, propBlockParts, "some peer"); err != nil { t.Fatal(err) @@ -635,7 +635,7 @@ func TestStateLockPOLUnlock(t *testing.T) { lockedBlockHash := rs.LockedBlock.Hash() incrementRound(vs2, vs3, vs4) - round = round + 1 // moving to the next round + round++ // moving to the next round ensureNewRound(newRoundCh, height, round) t.Log("#### ONTO ROUND 1") @@ -718,7 +718,7 @@ func TestStateLockPOLSafety1(t *testing.T) { incrementRound(vs2, vs3, vs4) - round = round + 1 // moving to the next round + round++ // moving to the next round ensureNewRound(newRoundCh, height, round) //XXX: this isnt guaranteed to get there before the timeoutPropose ... @@ -755,7 +755,7 @@ func TestStateLockPOLSafety1(t *testing.T) { ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) incrementRound(vs2, vs3, vs4) - round = round + 1 // moving to the next round + round++ // moving to the next round ensureNewRound(newRoundCh, height, round) @@ -821,7 +821,7 @@ func TestStateLockPOLSafety2(t *testing.T) { incrementRound(vs2, vs3, vs4) - round = round + 1 // moving to the next round + round++ // moving to the next round t.Log("### ONTO Round 1") // jump in at round 1 startTestRound(cs1, height, round) @@ -850,7 +850,7 @@ func TestStateLockPOLSafety2(t *testing.T) { // timeout of precommit wait to new round ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) - round = round + 1 // moving to the next round + round++ // moving to the next round // in round 2 we see the polkad block from round 0 newProp := types.NewProposal(height, round, 0, propBlockID0) if err := vs3.SignProposal(config.ChainID(), newProp); err != nil { @@ -920,7 +920,7 @@ func TestProposeValidBlock(t *testing.T) { ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) incrementRound(vs2, vs3, vs4) - round = round + 1 // moving to the next round + round++ // moving to the next round ensureNewRound(newRoundCh, height, round) @@ -945,14 +945,14 @@ func TestProposeValidBlock(t *testing.T) { signAddVotes(cs1, types.PrecommitType, nil, types.PartSetHeader{}, vs2, vs3, vs4) - round = round + 2 // moving to the next round + round += 2 // moving to the next round ensureNewRound(newRoundCh, height, round) t.Log("### ONTO ROUND 3") ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) - round = round + 1 // moving to the next round + round++ // moving to the next round ensureNewRound(newRoundCh, height, round) @@ -1044,7 +1044,7 @@ func TestSetValidBlockOnDelayedProposal(t *testing.T) { voteCh := subscribeToVoter(cs1, addr) proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) - round = round + 1 // move to round in which P0 is not proposer + round++ // move to round in which P0 is not proposer incrementRound(vs2, vs3, vs4) startTestRound(cs1, cs1.Height, round) @@ -1123,7 +1123,7 @@ func TestWaitingTimeoutProposeOnNewRound(t *testing.T) { incrementRound(vss[1:]...) signAddVotes(cs1, types.PrevoteType, nil, types.PartSetHeader{}, vs2, vs3, vs4) - round = round + 1 // moving to the next round + round++ // moving to the next round ensureNewRound(newRoundCh, height, round) rs := cs1.GetRoundState() @@ -1157,7 +1157,7 @@ func TestRoundSkipOnNilPolkaFromHigherRound(t *testing.T) { incrementRound(vss[1:]...) signAddVotes(cs1, types.PrecommitType, nil, types.PartSetHeader{}, vs2, vs3, vs4) - round = round + 1 // moving to the next round + round++ // moving to the next round ensureNewRound(newRoundCh, height, round) ensurePrecommit(voteCh, height, round) @@ -1165,7 +1165,7 @@ func TestRoundSkipOnNilPolkaFromHigherRound(t *testing.T) { ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) - round = round + 1 // moving to the next round + round++ // moving to the next round ensureNewRound(newRoundCh, height, round) } @@ -1511,7 +1511,7 @@ func TestStateHalt1(t *testing.T) { // timeout to new round ensureNewTimeout(timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds()) - round = round + 1 // moving to the next round + round++ // moving to the next round ensureNewRound(newRoundCh, height, round) rs = cs1.GetRoundState() diff --git a/crypto/ed25519/ed25519.go b/crypto/ed25519/ed25519.go index bc60838d5..8947608ae 100644 --- a/crypto/ed25519/ed25519.go +++ b/crypto/ed25519/ed25519.go @@ -54,7 +54,7 @@ func (privKey PrivKeyEd25519) Bytes() []byte { // incorrect signature. func (privKey PrivKeyEd25519) Sign(msg []byte) ([]byte, error) { signatureBytes := ed25519.Sign(privKey[:], msg) - return signatureBytes[:], nil + return signatureBytes, nil } // PubKey gets the corresponding public key from the private key. @@ -100,7 +100,7 @@ func GenPrivKey() PrivKeyEd25519 { // genPrivKey generates a new ed25519 private key using the provided reader. func genPrivKey(rand io.Reader) PrivKeyEd25519 { seed := make([]byte, 32) - _, err := io.ReadFull(rand, seed[:]) + _, err := io.ReadFull(rand, seed) if err != nil { panic(err) } diff --git a/crypto/internal/benchmarking/bench.go b/crypto/internal/benchmarking/bench.go index c988de48e..43ab312f0 100644 --- a/crypto/internal/benchmarking/bench.go +++ b/crypto/internal/benchmarking/bench.go @@ -24,10 +24,10 @@ func (zeroReader) Read(buf []byte) (int, error) { // BenchmarkKeyGeneration benchmarks the given key generation algorithm using // a dummy reader. -func BenchmarkKeyGeneration(b *testing.B, GenerateKey func(reader io.Reader) crypto.PrivKey) { +func BenchmarkKeyGeneration(b *testing.B, generateKey func(reader io.Reader) crypto.PrivKey) { var zero zeroReader for i := 0; i < b.N; i++ { - GenerateKey(zero) + generateKey(zero) } } diff --git a/crypto/secp256k1/internal/secp256k1/curve.go b/crypto/secp256k1/internal/secp256k1/curve.go index 5409ee1d2..df87200f2 100644 --- a/crypto/secp256k1/internal/secp256k1/curve.go +++ b/crypto/secp256k1/internal/secp256k1/curve.go @@ -30,6 +30,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// nolint:gocritic package secp256k1 import ( diff --git a/libs/cli/helper.go b/libs/cli/helper.go index 878cf26e5..6bf23750c 100644 --- a/libs/cli/helper.go +++ b/libs/cli/helper.go @@ -14,7 +14,7 @@ import ( func WriteConfigVals(dir string, vals map[string]string) error { data := "" for k, v := range vals { - data = data + fmt.Sprintf("%s = \"%s\"\n", k, v) + data += fmt.Sprintf("%s = \"%s\"\n", k, v) } cfile := filepath.Join(dir, "config.toml") return ioutil.WriteFile(cfile, []byte(data), 0666) diff --git a/libs/common/random_test.go b/libs/common/random_test.go index c59a577b8..74dcc04b4 100644 --- a/libs/common/random_test.go +++ b/libs/common/random_test.go @@ -45,11 +45,9 @@ func TestDeterminism(t *testing.T) { output := testThemAll() if i == 0 { firstOutput = output - } else { - if firstOutput != output { - t.Errorf("Run #%d's output was different from first run.\nfirst: %v\nlast: %v", - i, firstOutput, output) - } + } else if firstOutput != output { + t.Errorf("Run #%d's output was different from first run.\nfirst: %v\nlast: %v", + i, firstOutput, output) } } } diff --git a/libs/common/string.go b/libs/common/string.go index ddf350b10..4f8a8f20d 100644 --- a/libs/common/string.go +++ b/libs/common/string.go @@ -51,11 +51,12 @@ func IsASCIIText(s string) bool { func ASCIITrim(s string) string { r := make([]byte, 0, len(s)) for _, b := range []byte(s) { - if b == 32 { + switch { + case b == 32: continue // skip space - } else if 32 < b && b <= 126 { + case 32 < b && b <= 126: r = append(r, b) - } else { + default: panic(fmt.Sprintf("non-ASCII (non-tab) char 0x%X", b)) } } diff --git a/mempool/reactor_test.go b/mempool/reactor_test.go index 94c0d1900..dff4c0d68 100644 --- a/mempool/reactor_test.go +++ b/mempool/reactor_test.go @@ -42,10 +42,10 @@ func mempoolLogger() log.Logger { } // connect N mempool reactors through N switches -func makeAndConnectReactors(config *cfg.Config, N int) []*Reactor { - reactors := make([]*Reactor, N) +func makeAndConnectReactors(config *cfg.Config, n int) []*Reactor { + reactors := make([]*Reactor, n) logger := mempoolLogger() - for i := 0; i < N; i++ { + for i := 0; i < n; i++ { app := kvstore.NewKVStoreApplication() cc := proxy.NewLocalClientCreator(app) mempool, cleanup := newMempoolWithApp(cc) @@ -55,7 +55,7 @@ func makeAndConnectReactors(config *cfg.Config, N int) []*Reactor { reactors[i].SetLogger(logger.With("validator", i)) } - p2p.MakeConnectedSwitches(config.P2P, N, func(i int, s *p2p.Switch) *p2p.Switch { + p2p.MakeConnectedSwitches(config.P2P, n, func(i int, s *p2p.Switch) *p2p.Switch { s.AddReactor("MEMPOOL", reactors[i]) return s diff --git a/p2p/node_info_test.go b/p2p/node_info_test.go index 19567d2bf..9ed80b28b 100644 --- a/p2p/node_info_test.go +++ b/p2p/node_info_test.go @@ -19,7 +19,7 @@ func TestNodeInfoValidate(t *testing.T) { channels[i] = byte(i) } dupChannels := make([]byte, 5) - copy(dupChannels[:], channels[:5]) + copy(dupChannels, channels[:5]) dupChannels = append(dupChannels, testCh) nonAscii := "¢§µ" diff --git a/p2p/pex/addrbook.go b/p2p/pex/addrbook.go index cfe2569ba..27bcef9e8 100644 --- a/p2p/pex/addrbook.go +++ b/p2p/pex/addrbook.go @@ -178,11 +178,11 @@ func (a *addrBook) OurAddress(addr *p2p.NetAddress) bool { return ok } -func (a *addrBook) AddPrivateIDs(IDs []string) { +func (a *addrBook) AddPrivateIDs(ids []string) { a.mtx.Lock() defer a.mtx.Unlock() - for _, id := range IDs { + for _, id := range ids { a.privateIDs[p2p.ID(id)] = struct{}{} } } @@ -643,7 +643,7 @@ func (a *addrBook) randomPickAddresses(bucketType byte, num int) []*p2p.NetAddre } total := 0 for _, bucket := range buckets { - total = total + len(bucket) + total += len(bucket) } addresses := make([]*knownAddress, 0, total) for _, bucket := range buckets { diff --git a/rpc/lib/server/handlers.go b/rpc/lib/server/handlers.go index 434ee8916..78bc7b259 100644 --- a/rpc/lib/server/handlers.go +++ b/rpc/lib/server/handlers.go @@ -735,12 +735,10 @@ func (wsc *wsConnection) writeRoutine() { jsonBytes, err := json.MarshalIndent(msg, "", " ") if err != nil { wsc.Logger.Error("Failed to marshal RPCResponse to JSON", "err", err) - } else { - if err = wsc.writeMessageWithDeadline(websocket.TextMessage, jsonBytes); err != nil { - wsc.Logger.Error("Failed to write response", "err", err) - wsc.Stop() - return - } + } else if err = wsc.writeMessageWithDeadline(websocket.TextMessage, jsonBytes); err != nil { + wsc.Logger.Error("Failed to write response", "err", err) + wsc.Stop() + return } case <-wsc.Quit(): return diff --git a/state/state_test.go b/state/state_test.go index 0512fbf38..ac3b4db9f 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -440,13 +440,13 @@ func TestProposerPriorityDoesNotGetResetToZero(t *testing.T) { // 3. Center - with avg, resulting val2:-61, val1:62 avg := big.NewInt(0).Add(big.NewInt(wantVal1Prio), big.NewInt(wantVal2Prio)) avg.Div(avg, big.NewInt(2)) - wantVal2Prio = wantVal2Prio - avg.Int64() // -61 - wantVal1Prio = wantVal1Prio - avg.Int64() // 62 + wantVal2Prio -= avg.Int64() // -61 + wantVal1Prio -= avg.Int64() // 62 // 4. Steps from IncrementProposerPriority - wantVal1Prio = wantVal1Prio + val1VotingPower // 72 - wantVal2Prio = wantVal2Prio + val2VotingPower // 39 - wantVal1Prio = wantVal1Prio - totalPowerAfter // -38 as val1 is proposer + wantVal1Prio += val1VotingPower // 72 + wantVal2Prio += val2VotingPower // 39 + wantVal1Prio -= totalPowerAfter // -38 as val1 is proposer assert.Equal(t, wantVal1Prio, updatedVal1.ProposerPriority) assert.Equal(t, wantVal2Prio, addedVal2.ProposerPriority) @@ -563,9 +563,9 @@ func TestProposerPriorityProposerAlternates(t *testing.T) { expectedVal2Prio := v2PrioWhenAddedVal2 - avg.Int64() // -11 expectedVal1Prio := oldVal1.ProposerPriority - avg.Int64() // 11 // 4. Increment - expectedVal2Prio = expectedVal2Prio + val2VotingPower // -11 + 10 = -1 - expectedVal1Prio = expectedVal1Prio + val1VotingPower // 11 + 10 == 21 - expectedVal1Prio = expectedVal1Prio - totalPower // 1, val1 proposer + expectedVal2Prio += val2VotingPower // -11 + 10 = -1 + expectedVal1Prio += val1VotingPower // 11 + 10 == 21 + expectedVal1Prio -= totalPower // 1, val1 proposer assert.EqualValues(t, expectedVal1Prio, updatedVal1.ProposerPriority) assert.EqualValues(t, expectedVal2Prio, updatedVal2.ProposerPriority, "unexpected proposer priority for validator: %v", updatedVal2) @@ -589,7 +589,7 @@ func TestProposerPriorityProposerAlternates(t *testing.T) { // Increment expectedVal2Prio2 := expectedVal2Prio + val2VotingPower // -1 + 10 = 9 expectedVal1Prio2 := expectedVal1Prio + val1VotingPower // 1 + 10 == 11 - expectedVal1Prio2 = expectedVal1Prio2 - totalPower // -9, val1 proposer + expectedVal1Prio2 -= totalPower // -9, val1 proposer assert.EqualValues(t, expectedVal1Prio2, updatedVal1.ProposerPriority, "unexpected proposer priority for validator: %v", updatedVal2) assert.EqualValues(t, expectedVal2Prio2, updatedVal2.ProposerPriority, "unexpected proposer priority for validator: %v", updatedVal2) diff --git a/types/genesis.go b/types/genesis.go index 54b81e9e2..de59fc87e 100644 --- a/types/genesis.go +++ b/types/genesis.go @@ -72,10 +72,8 @@ func (genDoc *GenesisDoc) ValidateAndComplete() error { if genDoc.ConsensusParams == nil { genDoc.ConsensusParams = DefaultConsensusParams() - } else { - if err := genDoc.ConsensusParams.Validate(); err != nil { - return err - } + } else if err := genDoc.ConsensusParams.Validate(); err != nil { + return err } for i, v := range genDoc.Validators { diff --git a/types/validator_set.go b/types/validator_set.go index 2078e7a95..33636d092 100644 --- a/types/validator_set.go +++ b/types/validator_set.go @@ -121,7 +121,7 @@ func (vals *ValidatorSet) RescalePriorities(diffMax int64) { ratio := (diff + diffMax - 1) / diffMax if diff > diffMax { for _, val := range vals.Validators { - val.ProposerPriority = val.ProposerPriority / ratio + val.ProposerPriority /= ratio } } } @@ -525,7 +525,7 @@ func (vals *ValidatorSet) applyRemovals(deletes []*Validator) { // The 'allowDeletes' flag is set to false by NewValidatorSet() and to true by UpdateWithChangeSet(). func (vals *ValidatorSet) updateWithChangeSet(changes []*Validator, allowDeletes bool) error { - if len(changes) <= 0 { + if len(changes) == 0 { return nil }