diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml index d4d20b204..00c878b47 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yaml @@ -11,7 +11,7 @@ jobs: golangci: name: golangci-lint runs-on: ubuntu-latest - timeout-minutes: 4 + timeout-minutes: 8 steps: - uses: actions/checkout@v2 - uses: technote-space/get-diff-action@v4 @@ -20,10 +20,10 @@ jobs: **/**.go go.mod go.sum - - uses: golangci/golangci-lint-action@v1 + - uses: golangci/golangci-lint-action@v2.3.0 with: # Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version. - version: v1.26.0 + version: v1.31 args: --timeout 10m github-token: ${{ secrets.github_token }} if: env.GIT_DIFF diff --git a/.golangci.yml b/.golangci.yml index 8db13314c..7370e0128 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -10,7 +10,7 @@ linters: # - gochecknoglobals # - gochecknoinits - goconst - - gocritic + # - gocritic # - gocyclo # - godox - gofmt @@ -43,6 +43,9 @@ linters: issues: exclude-rules: + - path: _test\.go + linters: + - gosec - linters: - lll source: "https://" @@ -69,4 +72,4 @@ linters-settings: # - wrapperFunc # - commentFormatting # https://github.com/go-critic/go-critic/issues/755 service: - golangci-lint-version: 1.26.x + golangci-lint-version: 1.31.x diff --git a/abci/example/kvstore/persistent_kvstore.go b/abci/example/kvstore/persistent_kvstore.go index fffc617be..ccebb82e8 100644 --- a/abci/example/kvstore/persistent_kvstore.go +++ b/abci/example/kvstore/persistent_kvstore.go @@ -179,7 +179,7 @@ func isValidatorTx(tx []byte) bool { func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx { tx = tx[len(ValidatorSetChangePrefix):] - //get the pubkey and power + // get the pubkey and power pubKeyAndPower := strings.Split(string(tx), "!") if len(pubKeyAndPower) != 2 { return types.ResponseDeliverTx{ diff --git a/abci/tests/test_app/main.go b/abci/tests/test_app/main.go index ca298d7e2..0b93415b8 100644 --- a/abci/tests/test_app/main.go +++ b/abci/tests/test_app/main.go @@ -63,7 +63,7 @@ func testCounter() { defer cmd.Process.Kill() if err := ensureABCIIsUp(abciType, maxABCIConnectTries); err != nil { - log.Fatalf("echo failed: %v", err) + log.Fatalf("echo failed: %v", err) //nolint:gocritic } client := startClient(abciType) diff --git a/abci/types/util.go b/abci/types/util.go index 3cde88232..f234c0d7b 100644 --- a/abci/types/util.go +++ b/abci/types/util.go @@ -28,7 +28,5 @@ func (v ValidatorUpdates) Less(i, j int) bool { } func (v ValidatorUpdates) Swap(i, j int) { - v1 := v[i] - v[i] = v[j] - v[j] = v1 + v[i], v[j] = v[j], v[i] } diff --git a/blockchain/v0/pool.go b/blockchain/v0/pool.go index bd8165752..2f828cd90 100644 --- a/blockchain/v0/pool.go +++ b/blockchain/v0/pool.go @@ -508,7 +508,7 @@ type bpRequester struct { pool *BlockPool height int64 gotBlockCh chan struct{} - redoCh chan p2p.ID //redo may send multitime, add peerId to identify repeat + redoCh chan p2p.ID // redo may send multitime, add peerId to identify repeat mtx sync.Mutex peerID p2p.ID @@ -600,7 +600,7 @@ OUTER_LOOP: } peer = bpr.pool.pickIncrAvailablePeer(bpr.height) if peer == nil { - //log.Info("No peers available", "height", height) + // log.Info("No peers available", "height", height) time.Sleep(requestIntervalMS * time.Millisecond) continue PICK_PEER_LOOP } diff --git a/blockchain/v0/pool_test.go b/blockchain/v0/pool_test.go index 9a3dd299c..c86f88cbf 100644 --- a/blockchain/v0/pool_test.go +++ b/blockchain/v0/pool_test.go @@ -22,7 +22,7 @@ type testPeer struct { id p2p.ID base int64 height int64 - inputChan chan inputData //make sure each peer's data is sequential + inputChan chan inputData // make sure each peer's data is sequential } type inputData struct { diff --git a/blockchain/v0/reactor.go b/blockchain/v0/reactor.go index 5c13af700..4bdd8f701 100644 --- a/blockchain/v0/reactor.go +++ b/blockchain/v0/reactor.go @@ -299,7 +299,7 @@ FOR_LOOP: // See if there are any blocks to sync. first, second := bcR.pool.PeekTwoBlocks() - //bcR.Logger.Info("TrySync peeked", "first", first, "second", second) + // bcR.Logger.Info("TrySync peeked", "first", first, "second", second) if first == nil || second == nil { // We need both to sync the first block. continue FOR_LOOP diff --git a/blockchain/v0/reactor_test.go b/blockchain/v0/reactor_test.go index a31c9a141..fa2f4a1a1 100644 --- a/blockchain/v0/reactor_test.go +++ b/blockchain/v0/reactor_test.go @@ -227,10 +227,10 @@ func TestBadBlockStopsPeer(t *testing.T) { time.Sleep(1 * time.Second) } - //at this time, reactors[0-3] is the newest + // at this time, reactors[0-3] is the newest assert.Equal(t, 3, reactorPairs[1].reactor.Switch.Peers().Size()) - //mark reactorPairs[3] is an invalid peer + // mark reactorPairs[3] is an invalid peer reactorPairs[3].reactor.store = otherChain.reactor.store lastReactorPair := newBlockchainReactor(log.TestingLogger(), genDoc, privVals, 0) diff --git a/blockchain/v1/reactor.go b/blockchain/v1/reactor.go index 003a03e14..b900c9179 100644 --- a/blockchain/v1/reactor.go +++ b/blockchain/v1/reactor.go @@ -108,7 +108,7 @@ func NewBlockchainReactor(state sm.State, blockExec *sm.BlockExecutor, store *st fsm := NewFSM(startHeight, bcR) bcR.fsm = fsm bcR.BaseReactor = *p2p.NewBaseReactor("BlockchainReactor", bcR) - //bcR.swReporter = behaviour.NewSwitchReporter(bcR.BaseReactor.Switch) + // bcR.swReporter = behaviour.NewSwitchReporter(bcR.BaseReactor.Switch) return bcR } diff --git a/blockchain/v1/reactor_fsm.go b/blockchain/v1/reactor_fsm.go index 33f9a9102..384ea5c28 100644 --- a/blockchain/v1/reactor_fsm.go +++ b/blockchain/v1/reactor_fsm.go @@ -109,7 +109,7 @@ func (msg *bcReactorMessage) String() string { case stateTimeoutEv: dataStr = fmt.Sprintf("state=%v", msg.data.stateName) default: - dataStr = fmt.Sprintf("cannot interpret message data") + dataStr = "cannot interpret message data" } return fmt.Sprintf("%v: %v", msg.event, dataStr) diff --git a/blockchain/v1/reactor_test.go b/blockchain/v1/reactor_test.go index 4696ff546..b4698edf5 100644 --- a/blockchain/v1/reactor_test.go +++ b/blockchain/v1/reactor_test.go @@ -296,10 +296,10 @@ outerFor: break } - //at this time, reactors[0-3] is the newest + // at this time, reactors[0-3] is the newest assert.Equal(t, numNodes-1, reactorPairs[1].bcR.Switch.Peers().Size()) - //mark last reactorPair as an invalid peer + // mark last reactorPair as an invalid peer reactorPairs[numNodes-1].bcR.store = otherChain.bcR.store lastLogger := log.TestingLogger() diff --git a/blockchain/v2/scheduler.go b/blockchain/v2/scheduler.go index 803955b22..f5459936e 100644 --- a/blockchain/v2/scheduler.go +++ b/blockchain/v2/scheduler.go @@ -189,7 +189,7 @@ func newScheduler(initHeight int64, startTime time.Time) *scheduler { receivedBlocks: make(map[int64]p2p.ID), targetPending: 10, // TODO - pass as param peerTimeout: 15 * time.Second, // TODO - pass as param - minRecvRate: 0, //int64(7680), TODO - pass as param + minRecvRate: 0, // int64(7680), TODO - pass as param } return &sc @@ -511,9 +511,7 @@ func (peers PeerByID) Less(i, j int) bool { } func (peers PeerByID) Swap(i, j int) { - it := peers[i] - peers[i] = peers[j] - peers[j] = it + peers[i], peers[j] = peers[j], peers[i] } // Handlers diff --git a/consensus/reactor.go b/consensus/reactor.go index d6dd227e7..58ea93c6b 100644 --- a/consensus/reactor.go +++ b/consensus/reactor.go @@ -626,7 +626,7 @@ OUTER_LOOP: sleeping = 0 } - //logger.Debug("gossipVotesRoutine", "rsHeight", rs.Height, "rsRound", rs.Round, + // logger.Debug("gossipVotesRoutine", "rsHeight", rs.Height, "rsRound", rs.Round, // "prsHeight", prs.Height, "prsRound", prs.Round, "prsStep", prs.Step) // If height matches, then send LastCommit, Prevotes, Precommits. diff --git a/consensus/state.go b/consensus/state.go index 53d021083..7dfbb1764 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -210,7 +210,7 @@ func StateMetrics(metrics *Metrics) StateOption { // String returns a string. func (cs *State) String() string { // better not to access shared variables - return fmt.Sprintf("ConsensusState") //(H:%v R:%v S:%v", cs.Height, cs.Round, cs.Step) + return "ConsensusState" //(H:%v R:%v S:%v", cs.Height, cs.Round, cs.Step) } // GetState returns a copy of the chain state. @@ -1403,13 +1403,13 @@ func (cs *State) finalizeCommit(height int64) { block, blockParts := cs.ProposalBlock, cs.ProposalBlockParts if !ok { - panic(fmt.Sprintf("Cannot finalizeCommit, commit does not have two thirds majority")) + panic("Cannot finalizeCommit, commit does not have two thirds majority") } if !blockParts.HasHeader(blockID.PartsHeader) { - panic(fmt.Sprintf("Expected ProposalBlockParts header to be commit header")) + panic("Expected ProposalBlockParts header to be commit header") } if !block.HashesTo(blockID.Hash) { - panic(fmt.Sprintf("Cannot finalizeCommit, ProposalBlock does not hash to commit hash")) + panic("Cannot finalizeCommit, ProposalBlock does not hash to commit hash") } if err := cs.blockExec.ValidateBlock(cs.state, block); err != nil { panic(fmt.Sprintf("+2/3 committed an invalid block: %v", err)) @@ -1954,12 +1954,12 @@ func (cs *State) voteTime() time.Time { minVoteTime := now // TODO: We should remove next line in case we don't vote for v in case cs.ProposalBlock == nil, // even if cs.LockedBlock != nil. See https://docs.tendermint.com/master/spec/. - timeIotaMs := time.Duration(cs.state.ConsensusParams.Block.TimeIotaMs) * time.Millisecond + timeIota := time.Duration(cs.state.ConsensusParams.Block.TimeIotaMs) * time.Millisecond if cs.LockedBlock != nil { // See the BFT time spec https://docs.tendermint.com/master/spec/consensus/bft-time.html - minVoteTime = cs.LockedBlock.Time.Add(timeIotaMs) + minVoteTime = cs.LockedBlock.Time.Add(timeIota) } else if cs.ProposalBlock != nil { - minVoteTime = cs.ProposalBlock.Time.Add(timeIotaMs) + minVoteTime = cs.ProposalBlock.Time.Add(timeIota) } if now.After(minVoteTime) { diff --git a/crypto/encoding/amino/encode_test.go b/crypto/encoding/amino/encode_test.go index edc54292f..2794df2a3 100644 --- a/crypto/encoding/amino/encode_test.go +++ b/crypto/encoding/amino/encode_test.go @@ -53,7 +53,7 @@ func checkAminoJSON(t *testing.T, src interface{}, dst interface{}, isNil bool) } // ExamplePrintRegisteredTypes refers to unknown identifier: PrintRegisteredTypes -//nolint:govet +// nolint:govet, gocritic func ExamplePrintRegisteredTypes() { cdc.PrintTypes(os.Stdout) // Output: | Type | Name | Prefix | Length | Notes | diff --git a/libs/bech32/bech32.go b/libs/bech32/bech32.go index a4db86d5f..42cd1f8ce 100644 --- a/libs/bech32/bech32.go +++ b/libs/bech32/bech32.go @@ -5,7 +5,7 @@ import ( "github.com/pkg/errors" ) -//ConvertAndEncode converts from a base64 encoded byte string to base32 encoded byte string and then to bech32 +// ConvertAndEncode converts from a base64 encoded byte string to base32 encoded byte string and then to bech32 func ConvertAndEncode(hrp string, data []byte) (string, error) { converted, err := bech32.ConvertBits(data, 8, 5, true) if err != nil { @@ -15,7 +15,7 @@ func ConvertAndEncode(hrp string, data []byte) (string, error) { } -//DecodeAndConvert decodes a bech32 encoded string and converts to base64 encoded bytes +// DecodeAndConvert decodes a bech32 encoded string and converts to base64 encoded bytes func DecodeAndConvert(bech string) (string, []byte, error) { hrp, data, err := bech32.Decode(bech) if err != nil { diff --git a/libs/bytes/bytes.go b/libs/bytes/bytes.go index d7682437b..809049e84 100644 --- a/libs/bytes/bytes.go +++ b/libs/bytes/bytes.go @@ -25,7 +25,7 @@ func (bz HexBytes) MarshalJSON() ([]byte, error) { s := strings.ToUpper(hex.EncodeToString(bz)) jbz := make([]byte, len(s)+2) jbz[0] = '"' - copy(jbz[1:], []byte(s)) + copy(jbz[1:], s) jbz[len(jbz)-1] = '"' return jbz, nil } diff --git a/libs/clist/clist_test.go b/libs/clist/clist_test.go index 14b7e37c0..4a121be60 100644 --- a/libs/clist/clist_test.go +++ b/libs/clist/clist_test.go @@ -33,22 +33,10 @@ func TestSmall(t *testing.T) { t.Error("Expected len 3, got ", l.Len()) } - //fmt.Printf("%p %v\n", el1, el1) - //fmt.Printf("%p %v\n", el2, el2) - //fmt.Printf("%p %v\n", el3, el3) - r1 := l.Remove(el1) - //fmt.Printf("%p %v\n", el1, el1) - //fmt.Printf("%p %v\n", el2, el2) - //fmt.Printf("%p %v\n", el3, el3) - r2 := l.Remove(el2) - //fmt.Printf("%p %v\n", el1, el1) - //fmt.Printf("%p %v\n", el2, el2) - //fmt.Printf("%p %v\n", el3, el3) - r3 := l.Remove(el3) if r1 != 1 { diff --git a/libs/cmap/cmap_test.go b/libs/cmap/cmap_test.go index b1ab85c0c..1819bdfb0 100644 --- a/libs/cmap/cmap_test.go +++ b/libs/cmap/cmap_test.go @@ -22,7 +22,7 @@ func TestIterateKeysWithValues(t *testing.T) { // Iterating Keys, checking for matching Value for _, key := range cmap.Keys() { - val := strings.Replace(key, "key", "value", -1) + val := strings.ReplaceAll(key, "key", "value") assert.Equal(t, val, cmap.Get(key)) } diff --git a/libs/fail/fail.go b/libs/fail/fail.go index 03f4feda0..38cec9a29 100644 --- a/libs/fail/fail.go +++ b/libs/fail/fail.go @@ -23,7 +23,7 @@ func envSet() int { } // Fail when FAIL_TEST_INDEX == callIndex -var callIndex int //indexes Fail calls +var callIndex int // indexes Fail calls func Fail() { callIndexToFail := envSet() diff --git a/libs/log/tracing_logger_test.go b/libs/log/tracing_logger_test.go index 354476755..6d6edc5ca 100644 --- a/libs/log/tracing_logger_test.go +++ b/libs/log/tracing_logger_test.go @@ -22,16 +22,16 @@ func TestTracingLogger(t *testing.T) { err2 := errors.New("it does not matter how slowly you go, so long as you do not stop") logger1.With("err1", err1).Info("foo", "err2", err2) - want := strings.Replace( - strings.Replace( + want := strings.ReplaceAll( + strings.ReplaceAll( `{"_msg":"foo","err1":"`+ fmt.Sprintf("%+v", err1)+ `","err2":"`+ fmt.Sprintf("%+v", err2)+ `","level":"info"}`, - "\t", "", -1, - ), "\n", "", -1) - have := strings.Replace(strings.Replace(strings.TrimSpace(buf.String()), "\\n", "", -1), "\\t", "", -1) + "\t", "", + ), "\n", "") + have := strings.ReplaceAll(strings.ReplaceAll(strings.TrimSpace(buf.String()), "\\n", ""), "\\t", "") if want != have { t.Errorf("\nwant '%s'\nhave '%s'", want, have) } diff --git a/libs/pubsub/pubsub_test.go b/libs/pubsub/pubsub_test.go index 1333faa95..4494768e6 100644 --- a/libs/pubsub/pubsub_test.go +++ b/libs/pubsub/pubsub_test.go @@ -418,9 +418,7 @@ func benchmarkNClientsOneQuery(n int, b *testing.B) { } } -/////////////////////////////////////////////////////////////////////////////// -/// HELPERS -/////////////////////////////////////////////////////////////////////////////// +// HELPERS func assertReceive(t *testing.T, expected interface{}, ch <-chan pubsub.Message, msgAndArgs ...interface{}) { select { diff --git a/lite/proxy/proxy.go b/lite/proxy/proxy.go index b72f863ed..57c079289 100644 --- a/lite/proxy/proxy.go +++ b/lite/proxy/proxy.go @@ -8,7 +8,6 @@ import ( "github.com/tendermint/tendermint/libs/bytes" "github.com/tendermint/tendermint/libs/log" - "github.com/tendermint/tendermint/rpc/client" rpcclient "github.com/tendermint/tendermint/rpc/client" ctypes "github.com/tendermint/tendermint/rpc/core/types" rpcserver "github.com/tendermint/tendermint/rpc/jsonrpc/server" @@ -88,7 +87,7 @@ func RPCRoutes(c rpcclient.Client) map[string]*rpcserver.RPCFunc { } } -func makeStatusFunc(c client.StatusClient) func(ctx *rpctypes.Context) (*ctypes.ResultStatus, error) { +func makeStatusFunc(c rpcclient.StatusClient) func(ctx *rpctypes.Context) (*ctypes.ResultStatus, error) { return func(ctx *rpctypes.Context) (*ctypes.ResultStatus, error) { return c.Status() } diff --git a/lite2/errors.go b/lite2/errors.go index 7bc70f698..12e9d42c3 100644 --- a/lite2/errors.go +++ b/lite2/errors.go @@ -44,5 +44,5 @@ func (e ErrInvalidHeader) Error() string { type errNoWitnesses struct{} func (e errNoWitnesses) Error() string { - return fmt.Sprint("no witnesses connected. please reset light client") + return "no witnesses connected. please reset light client" } diff --git a/lite2/provider/http/http_test.go b/lite2/provider/http/http_test.go index 37a946e52..664ff0e95 100644 --- a/lite2/provider/http/http_test.go +++ b/lite2/provider/http/http_test.go @@ -11,7 +11,6 @@ import ( "github.com/tendermint/tendermint/abci/example/kvstore" "github.com/tendermint/tendermint/lite2/provider" "github.com/tendermint/tendermint/lite2/provider/http" - litehttp "github.com/tendermint/tendermint/lite2/provider/http" rpcclient "github.com/tendermint/tendermint/rpc/client" rpctest "github.com/tendermint/tendermint/rpc/test" "github.com/tendermint/tendermint/types" @@ -52,7 +51,7 @@ func TestProvider(t *testing.T) { } chainID := genDoc.ChainID t.Log("chainID:", chainID) - p, err := litehttp.New(chainID, rpcAddr) + p, err := http.New(chainID, rpcAddr) require.Nil(t, err) require.NotNil(t, p) diff --git a/mempool/clist_mempool.go b/mempool/clist_mempool.go index f55d62329..eeb29afc1 100644 --- a/mempool/clist_mempool.go +++ b/mempool/clist_mempool.go @@ -707,9 +707,9 @@ func (cache *mapTxCache) Push(tx types.Tx) bool { if cache.list.Len() >= cache.size { popped := cache.list.Front() - poppedTxHash := popped.Value.([sha256.Size]byte) - delete(cache.cacheMap, poppedTxHash) if popped != nil { + poppedTxHash := popped.Value.([sha256.Size]byte) + delete(cache.cacheMap, poppedTxHash) cache.list.Remove(popped) } } diff --git a/node/node.go b/node/node.go index 6e60356dc..81c639675 100644 --- a/node/node.go +++ b/node/node.go @@ -23,7 +23,6 @@ import ( bcv1 "github.com/tendermint/tendermint/blockchain/v1" bcv2 "github.com/tendermint/tendermint/blockchain/v2" cfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/consensus" cs "github.com/tendermint/tendermint/consensus" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/evidence" @@ -368,7 +367,7 @@ func createConsensusReactor(config *cfg.Config, csMetrics *cs.Metrics, fastSync bool, eventBus *types.EventBus, - consensusLogger log.Logger) (*consensus.Reactor, *consensus.State) { + consensusLogger log.Logger) (*cs.Reactor, *cs.State) { consensusState := cs.NewState( config.Consensus, @@ -466,7 +465,7 @@ func createSwitch(config *cfg.Config, peerFilters []p2p.PeerFilterFunc, mempoolReactor *mempl.Reactor, bcReactor p2p.Reactor, - consensusReactor *consensus.Reactor, + consensusReactor *cs.Reactor, evidenceReactor *evidence.Reactor, nodeInfo p2p.NodeInfo, nodeKey *p2p.NodeKey, diff --git a/p2p/conn/secret_connection_test.go b/p2p/conn/secret_connection_test.go index 9044d73be..2a310d8f4 100644 --- a/p2p/conn/secret_connection_test.go +++ b/p2p/conn/secret_connection_test.go @@ -431,7 +431,7 @@ func BenchmarkWriteSecretConnection(b *testing.B) { if err := fooSecConn.Close(); err != nil { b.Error(err) } - //barSecConn.Close() race condition + // barSecConn.Close() race condition } func BenchmarkReadSecretConnection(b *testing.B) { diff --git a/p2p/node_info_test.go b/p2p/node_info_test.go index 8896efe1d..319ae0fa5 100644 --- a/p2p/node_info_test.go +++ b/p2p/node_info_test.go @@ -1,7 +1,6 @@ package p2p import ( - "fmt" "testing" "github.com/stretchr/testify/assert" @@ -24,8 +23,8 @@ func TestNodeInfoValidate(t *testing.T) { dupChannels = append(dupChannels, testCh) nonASCII := "¢§µ" - emptyTab := fmt.Sprintf("\t") - emptySpace := fmt.Sprintf(" ") + emptyTab := "\t" + emptySpace := " " testCases := []struct { testName string diff --git a/p2p/pex/pex_reactor.go b/p2p/pex/pex_reactor.go index b719b6218..aea8bb37b 100644 --- a/p2p/pex/pex_reactor.go +++ b/p2p/pex/pex_reactor.go @@ -12,7 +12,6 @@ import ( "github.com/tendermint/tendermint/libs/cmap" tmmath "github.com/tendermint/tendermint/libs/math" - "github.com/tendermint/tendermint/libs/rand" tmrand "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/libs/service" "github.com/tendermint/tendermint/p2p" @@ -409,7 +408,7 @@ func (r *Reactor) SetEnsurePeersPeriod(d time.Duration) { // Ensures that sufficient peers are connected. (continuous) func (r *Reactor) ensurePeersRoutine() { var ( - seed = rand.NewRand() + seed = tmrand.NewRand() jitter = seed.Int63n(r.ensurePeersPeriod.Nanoseconds()) ) @@ -545,8 +544,8 @@ func (r *Reactor) dialPeer(addr *p2p.NetAddress) error { // exponential backoff if it's not our first attempt to dial given address if attempts > 0 { - jitterSeconds := time.Duration(tmrand.Float64() * float64(time.Second)) // 1s == (1e9 ns) - backoffDuration := jitterSeconds + ((1 << uint(attempts)) * time.Second) + jitter := time.Duration(tmrand.Float64() * float64(time.Second)) // 1s == (1e9 ns) + backoffDuration := jitter + ((1 << uint(attempts)) * time.Second) backoffDuration = r.maxBackoffDurationForPeer(addr, backoffDuration) sinceLastDialed := time.Since(lastDialed) if sinceLastDialed < backoffDuration { diff --git a/p2p/upnp/upnp.go b/p2p/upnp/upnp.go index fa99653ea..a755e2769 100644 --- a/p2p/upnp/upnp.go +++ b/p2p/upnp/upnp.go @@ -269,7 +269,7 @@ func soapRequest(url, function, message, domain string) (r *http.Response, err e } req.Header.Set("Content-Type", "text/xml ; charset=\"utf-8\"") req.Header.Set("User-Agent", "Darwin/10.0.0, UPnP/1.0, MiniUPnPc/1.3") - //req.Header.Set("Transfer-Encoding", "chunked") + // req.Header.Set("Transfer-Encoding", "chunked") req.Header.Set("SOAPAction", "\"urn:"+domain+":service:WANIPConnection:1#"+function+"\"") req.Header.Set("Connection", "Close") req.Header.Set("Cache-Control", "no-cache") diff --git a/privval/signer_listener_endpoint_test.go b/privval/signer_listener_endpoint_test.go index 0e22d8e4b..9e9fdd05f 100644 --- a/privval/signer_listener_endpoint_test.go +++ b/privval/signer_listener_endpoint_test.go @@ -131,8 +131,6 @@ func TestRetryConnToRemoteSigner(t *testing.T) { } } -/////////////////////////////////// - func newSignerListenerEndpoint(logger log.Logger, addr string, timeoutReadWrite time.Duration) *SignerListenerEndpoint { proto, address := tmnet.ProtocolAndAddress(addr) diff --git a/proxy/app_conn_test.go b/proxy/app_conn_test.go index ca15f8977..ff3e92590 100644 --- a/proxy/app_conn_test.go +++ b/proxy/app_conn_test.go @@ -115,7 +115,7 @@ func BenchmarkEcho(b *testing.B) { b.StopTimer() // info := proxy.InfoSync(types.RequestInfo{""}) - //b.Log("N: ", b.N, info) + // b.Log("N: ", b.N, info) } func TestInfo(t *testing.T) { diff --git a/rpc/client/examples_test.go b/rpc/client/examples_test.go index 5d87a3a98..75ef04c87 100644 --- a/rpc/client/examples_test.go +++ b/rpc/client/examples_test.go @@ -21,7 +21,7 @@ func ExampleHTTP_simple() { rpcAddr := rpctest.GetConfig().RPC.ListenAddress c, err := rpchttp.New(rpcAddr, "/websocket") if err != nil { - log.Fatal(err) + log.Fatal(err) // nolint: gocritic } // Create a transaction @@ -74,7 +74,7 @@ func ExampleHTTP_batching() { rpcAddr := rpctest.GetConfig().RPC.ListenAddress c, err := rpchttp.New(rpcAddr, "/websocket") if err != nil { - log.Fatal(err) + log.Fatal(err) // nolint: gocritic } // Create our two transactions diff --git a/rpc/client/rpc_test.go b/rpc/client/rpc_test.go index 9d4d6c3c4..b3a8f4276 100644 --- a/rpc/client/rpc_test.go +++ b/rpc/client/rpc_test.go @@ -83,7 +83,7 @@ func TestCustomHTTPClient(t *testing.T) { func TestCorsEnabled(t *testing.T) { origin := rpctest.GetConfig().RPC.CORSAllowedOrigins[0] - remote := strings.Replace(rpctest.GetConfig().RPC.ListenAddress, "tcp", "http", -1) + remote := strings.ReplaceAll(rpctest.GetConfig().RPC.ListenAddress, "tcp", "http") req, err := http.NewRequest("GET", remote, nil) require.Nil(t, err, "%+v", err) @@ -511,14 +511,14 @@ func TestTxSearch(t *testing.T) { require.Len(t, result.Txs, 0) // check sorting - result, err = c.TxSearch(fmt.Sprintf("tx.height >= 1"), false, 1, 30, "asc") + result, err = c.TxSearch("tx.height >= 1", false, 1, 30, "asc") require.Nil(t, err) for k := 0; k < len(result.Txs)-1; k++ { require.LessOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height) require.LessOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index) } - result, err = c.TxSearch(fmt.Sprintf("tx.height >= 1"), false, 1, 30, "desc") + result, err = c.TxSearch("tx.height >= 1", false, 1, 30, "desc") require.Nil(t, err) for k := 0; k < len(result.Txs)-1; k++ { require.GreaterOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height) diff --git a/rpc/jsonrpc/client/http_json_client.go b/rpc/jsonrpc/client/http_json_client.go index 2fab11502..b4d0c3914 100644 --- a/rpc/jsonrpc/client/http_json_client.go +++ b/rpc/jsonrpc/client/http_json_client.go @@ -68,7 +68,7 @@ func (u parsedURL) GetHostWithPath() string { // Get a trimmed address - useful for WS connections func (u parsedURL) GetTrimmedHostWithPath() string { // replace / with . for http requests (kvstore domain) - return strings.Replace(u.GetHostWithPath(), "/", ".", -1) + return strings.ReplaceAll(u.GetHostWithPath(), "/", ".") } // Get a trimmed address with protocol - useful as address in RPC connections diff --git a/rpc/jsonrpc/client/ws_client.go b/rpc/jsonrpc/client/ws_client.go index a46d3a55b..2f6a24d83 100644 --- a/rpc/jsonrpc/client/ws_client.go +++ b/rpc/jsonrpc/client/ws_client.go @@ -255,7 +255,6 @@ func (c *WSClient) CallWithArrayParams(ctx context.Context, method string, param func (c *WSClient) Codec() *amino.Codec { return c.cdc } func (c *WSClient) SetCodec(cdc *amino.Codec) { c.cdc = cdc } -/////////////////////////////////////////////////////////////////////////////// // Private methods func (c *WSClient) nextRequestID() types.JSONRPCIntID { @@ -295,8 +294,8 @@ func (c *WSClient) reconnect() error { }() for { - jitterSeconds := time.Duration(tmrand.Float64() * float64(time.Second)) // 1s == (1e9 ns) - backoffDuration := jitterSeconds + ((1 << uint(attempt)) * time.Second) + jitter := time.Duration(tmrand.Float64() * float64(time.Second)) // 1s == (1e9 ns) + backoffDuration := jitter + ((1 << uint(attempt)) * time.Second) c.Logger.Info("reconnecting", "attempt", attempt+1, "backoff_duration", backoffDuration) time.Sleep(backoffDuration) @@ -525,7 +524,6 @@ func (c *WSClient) readRoutine() { } } -/////////////////////////////////////////////////////////////////////////////// // Predefined methods // Subscribe to a query. Note the server must have a "subscribe" route diff --git a/rpc/jsonrpc/jsonrpc_test.go b/rpc/jsonrpc/jsonrpc_test.go index 9f7b49480..d6a9fd2f1 100644 --- a/rpc/jsonrpc/jsonrpc_test.go +++ b/rpc/jsonrpc/jsonrpc_test.go @@ -384,5 +384,5 @@ func randBytes(t *testing.T) []byte { buf := make([]byte, n) _, err := crand.Read(buf) require.Nil(t, err) - return bytes.Replace(buf, []byte("="), []byte{100}, -1) + return bytes.ReplaceAll(buf, []byte("="), []byte{100}) } diff --git a/rpc/jsonrpc/server/http_json_handler.go b/rpc/jsonrpc/server/http_json_handler.go index ab4e21ae4..26afc28b7 100644 --- a/rpc/jsonrpc/server/http_json_handler.go +++ b/rpc/jsonrpc/server/http_json_handler.go @@ -17,9 +17,7 @@ import ( types "github.com/tendermint/tendermint/rpc/jsonrpc/types" ) -/////////////////////////////////////////////////////////////////////////////// // HTTP + JSON handler -/////////////////////////////////////////////////////////////////////////////// // jsonrpc calls grab the given method's function info and runs reflect.Call func makeJSONRPCHandler(funcMap map[string]*RPCFunc, cdc *amino.Codec, logger log.Logger) http.HandlerFunc { diff --git a/rpc/jsonrpc/server/http_uri_handler.go b/rpc/jsonrpc/server/http_uri_handler.go index 13a7764bc..b837e8069 100644 --- a/rpc/jsonrpc/server/http_uri_handler.go +++ b/rpc/jsonrpc/server/http_uri_handler.go @@ -15,9 +15,7 @@ import ( types "github.com/tendermint/tendermint/rpc/jsonrpc/types" ) -/////////////////////////////////////////////////////////////////////////////// // HTTP + URI handler -/////////////////////////////////////////////////////////////////////////////// var reInt = regexp.MustCompile(`^-?[0-9]+$`) diff --git a/rpc/jsonrpc/server/rpc_func.go b/rpc/jsonrpc/server/rpc_func.go index 56b3c8389..305643b6f 100644 --- a/rpc/jsonrpc/server/rpc_func.go +++ b/rpc/jsonrpc/server/rpc_func.go @@ -26,9 +26,7 @@ func RegisterRPCFuncs(mux *http.ServeMux, funcMap map[string]*RPCFunc, cdc *amin mux.HandleFunc("/", handleInvalidJSONRPCPaths(makeJSONRPCHandler(funcMap, cdc, logger))) } -/////////////////////////////////////////////////////////////////////////////// // Function introspection -/////////////////////////////////////////////////////////////////////////////// // RPCFunc contains the introspected type information for a function type RPCFunc struct { diff --git a/rpc/jsonrpc/server/ws_handler.go b/rpc/jsonrpc/server/ws_handler.go index 61dc6bdac..508f9c26a 100644 --- a/rpc/jsonrpc/server/ws_handler.go +++ b/rpc/jsonrpc/server/ws_handler.go @@ -19,9 +19,7 @@ import ( types "github.com/tendermint/tendermint/rpc/jsonrpc/types" ) -/////////////////////////////////////////////////////////////////////////////// // WebSocket handler -/////////////////////////////////////////////////////////////////////////////// const ( defaultWSWriteChanCapacity = 1000 @@ -103,9 +101,7 @@ func (wm *WebsocketManager) WebsocketHandler(w http.ResponseWriter, r *http.Requ con.Stop() } -/////////////////////////////////////////////////////////////////////////////// // WebSocket connection -/////////////////////////////////////////////////////////////////////////////// // A single websocket connection contains listener id, underlying ws // connection, and the event switch for subscribing to events. diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go index 82d3ced24..baf1c9fcd 100644 --- a/rpc/test/helpers.go +++ b/rpc/test/helpers.go @@ -73,7 +73,7 @@ func makePathname() string { } // fmt.Println(p) sep := string(filepath.Separator) - return strings.Replace(p, sep, "_", -1) + return strings.ReplaceAll(p, sep, "_") } func randPort() int { diff --git a/scripts/wal2json/main.go b/scripts/wal2json/main.go index 181f40c75..d5616263a 100644 --- a/scripts/wal2json/main.go +++ b/scripts/wal2json/main.go @@ -63,7 +63,7 @@ func main() { } if err != nil { fmt.Println("Failed to write message", err) - os.Exit(1) + os.Exit(1) // nolint: gocritic } } } diff --git a/state/state_test.go b/state/state_test.go index 746f7837c..1fdc67daa 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -18,7 +18,6 @@ import ( cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/libs/kv" - "github.com/tendermint/tendermint/libs/rand" tmrand "github.com/tendermint/tendermint/libs/rand" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" @@ -347,7 +346,7 @@ func genValSetWithPowers(powers []int64) *types.ValidatorSet { for i := 0; i < size; i++ { totalVotePower += powers[i] val := types.NewValidator(ed25519.GenPrivKey().PubKey(), powers[i]) - val.ProposerPriority = rand.Int64() + val.ProposerPriority = tmrand.Int64() vals[i] = val } valSet := types.NewValidatorSet(vals) diff --git a/state/txindex/kv/kv.go b/state/txindex/kv/kv.go index c5ba99ca3..c96d5a356 100644 --- a/state/txindex/kv/kv.go +++ b/state/txindex/kv/kv.go @@ -583,7 +583,6 @@ LOOP: return filteredHashes } -/////////////////////////////////////////////////////////////////////////////// // Keys func isTagKey(key []byte) bool { diff --git a/store/store.go b/store/store.go index c971a9a15..15b5484bb 100644 --- a/store/store.go +++ b/store/store.go @@ -7,7 +7,6 @@ import ( "github.com/pkg/errors" - db "github.com/tendermint/tm-db" dbm "github.com/tendermint/tm-db" "github.com/tendermint/tendermint/types" @@ -213,7 +212,7 @@ func (bs *BlockStore) PruneBlocks(height int64) (uint64, error) { pruned := uint64(0) batch := bs.db.NewBatch() defer batch.Close() - flush := func(batch db.Batch, base int64) error { + flush := func(batch dbm.Batch, base int64) error { // We can't trust batches to be atomic, so update base first to make sure noone // tries to access missing blocks. bs.mtx.Lock() @@ -279,7 +278,7 @@ func (bs *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, s panic(fmt.Sprintf("BlockStore can only save contiguous blocks. Wanted %v, got %v", w, g)) } if !blockParts.IsComplete() { - panic(fmt.Sprintf("BlockStore can only save complete block part sets")) + panic("BlockStore can only save complete block part sets") } // Save block meta diff --git a/store/store_test.go b/store/store_test.go index 3b61604e1..5c8a92de6 100644 --- a/store/store_test.go +++ b/store/store_test.go @@ -13,7 +13,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" db "github.com/tendermint/tm-db" - dbm "github.com/tendermint/tm-db" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/libs/log" @@ -54,8 +53,8 @@ func makeStateAndBlockStore(logger log.Logger) (sm.State, *BlockStore, cleanupFu config := cfg.ResetTestRoot("blockchain_reactor_test") // blockDB := dbm.NewDebugDB("blockDB", dbm.NewMemDB()) // stateDB := dbm.NewDebugDB("stateDB", dbm.NewMemDB()) - blockDB := dbm.NewMemDB() - stateDB := dbm.NewMemDB() + blockDB := db.NewMemDB() + stateDB := db.NewMemDB() state, err := sm.LoadStateFromDBOrGenesisFile(stateDB, config.GenesisFile()) if err != nil { panic(errors.Wrap(err, "error constructing state from genesis file")) @@ -389,9 +388,9 @@ func TestLoadBlockPart(t *testing.T) { func TestPruneBlocks(t *testing.T) { config := cfg.ResetTestRoot("blockchain_reactor_test") defer os.RemoveAll(config.RootDir) - state, err := sm.LoadStateFromDBOrGenesisFile(dbm.NewMemDB(), config.GenesisFile()) + state, err := sm.LoadStateFromDBOrGenesisFile(db.NewMemDB(), config.GenesisFile()) require.NoError(t, err) - db := dbm.NewMemDB() + db := db.NewMemDB() bs := NewBlockStore(db) assert.EqualValues(t, 0, bs.Base()) assert.EqualValues(t, 0, bs.Height()) diff --git a/types/events.go b/types/events.go index c257ba328..7d62f6799 100644 --- a/types/events.go +++ b/types/events.go @@ -38,9 +38,7 @@ const ( EventVote = "Vote" ) -/////////////////////////////////////////////////////////////////////////////// // ENCODING / DECODING -/////////////////////////////////////////////////////////////////////////////// // TMEventData implements events.EventData. type TMEventData interface { @@ -121,9 +119,7 @@ type EventDataValidatorSetUpdates struct { ValidatorUpdates []*Validator `json:"validator_updates"` } -/////////////////////////////////////////////////////////////////////////////// // PUBSUB -/////////////////////////////////////////////////////////////////////////////// const ( // EventTypeKey is a reserved composite key for event name. diff --git a/types/priv_validator.go b/types/priv_validator.go index fbe8cebf0..7034ce4bd 100644 --- a/types/priv_validator.go +++ b/types/priv_validator.go @@ -41,9 +41,7 @@ func (pvs PrivValidatorsByAddress) Less(i, j int) bool { } func (pvs PrivValidatorsByAddress) Swap(i, j int) { - it := pvs[i] - pvs[i] = pvs[j] - pvs[j] = it + pvs[i], pvs[j] = pvs[j], pvs[i] } //---------------------------------------- diff --git a/types/validator_set.go b/types/validator_set.go index f4f11fcc6..a10f4d94b 100644 --- a/types/validator_set.go +++ b/types/validator_set.go @@ -676,9 +676,7 @@ func (vals *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, return nil } -/////////////////////////////////////////////////////////////////////////////// // LIGHT CLIENT VERIFICATION METHODS -/////////////////////////////////////////////////////////////////////////////// // VerifyCommitLight verifies +2/3 of the set had signed the given commit. // @@ -952,9 +950,7 @@ func (valz ValidatorsByAddress) Less(i, j int) bool { } func (valz ValidatorsByAddress) Swap(i, j int) { - it := valz[i] - valz[i] = valz[j] - valz[j] = it + valz[i], valz[j] = valz[j], valz[i] } // ToProto converts ValidatorSet to protobuf @@ -1034,7 +1030,6 @@ func RandValidatorSet(numValidators int, votingPower int64) (*ValidatorSet, []Pr return vals, privValidators } -/////////////////////////////////////////////////////////////////////////////// // safe addition/subtraction/multiplication func safeAdd(a, b int64) (int64, bool) { diff --git a/types/validator_set_test.go b/types/validator_set_test.go index 059d043df..6a4808482 100644 --- a/types/validator_set_test.go +++ b/types/validator_set_test.go @@ -1553,9 +1553,7 @@ func (valz validatorsByPriority) Less(i, j int) bool { } func (valz validatorsByPriority) Swap(i, j int) { - it := valz[i] - valz[i] = valz[j] - valz[j] = it + valz[i], valz[j] = valz[j], valz[i] } //------------------------------------- @@ -1571,9 +1569,7 @@ func (tvals testValsByAddress) Less(i, j int) bool { } func (tvals testValsByAddress) Swap(i, j int) { - it := tvals[i] - tvals[i] = tvals[j] - tvals[j] = it + tvals[i], tvals[j] = tvals[j], tvals[i] } //------------------------------------- diff --git a/types/vote.go b/types/vote.go index 533cf7d5f..5bf0fb32c 100644 --- a/types/vote.go +++ b/types/vote.go @@ -192,7 +192,7 @@ func (vote *Vote) ToProto() *tmproto.Vote { } } -//FromProto converts a proto generetad type to a handwritten type +// FromProto converts a proto generetad type to a handwritten type // return type, nil if everything converts safely, otherwise nil, error func VoteFromProto(pv *tmproto.Vote) (*Vote, error) { if pv == nil {