lint: update and appease the linter (#6101)

Closes: #5775
This commit is contained in:
Callum Waters
2021-02-16 09:41:36 +01:00
committed by GitHub
parent 2e406e0d78
commit 84904ecef1
54 changed files with 81 additions and 134 deletions

View File

@@ -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

View File

@@ -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

View File

@@ -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{

View File

@@ -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)

View File

@@ -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]
}

View File

@@ -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
}

View File

@@ -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 {

View File

@@ -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

View File

@@ -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)

View File

@@ -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
}

View File

@@ -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)

View File

@@ -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()

View File

@@ -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

View File

@@ -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.

View File

@@ -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) {

View File

@@ -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 |

View File

@@ -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 {

View File

@@ -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
}

View File

@@ -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 {

View File

@@ -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))
}

View File

@@ -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()

View File

@@ -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)
}

View File

@@ -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 {

View File

@@ -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()
}

View File

@@ -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"
}

View File

@@ -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)

View File

@@ -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)
}
}

View File

@@ -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,

View File

@@ -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) {

View File

@@ -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

View File

@@ -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 {

View File

@@ -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")

View File

@@ -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)

View File

@@ -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) {

View File

@@ -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

View File

@@ -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)

View File

@@ -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

View File

@@ -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

View File

@@ -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})
}

View File

@@ -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 {

View File

@@ -15,9 +15,7 @@ import (
types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
)
///////////////////////////////////////////////////////////////////////////////
// HTTP + URI handler
///////////////////////////////////////////////////////////////////////////////
var reInt = regexp.MustCompile(`^-?[0-9]+$`)

View File

@@ -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 {

View File

@@ -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.

View File

@@ -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 {

View File

@@ -63,7 +63,7 @@ func main() {
}
if err != nil {
fmt.Println("Failed to write message", err)
os.Exit(1)
os.Exit(1) // nolint: gocritic
}
}
}

View File

@@ -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)

View File

@@ -583,7 +583,6 @@ LOOP:
return filteredHashes
}
///////////////////////////////////////////////////////////////////////////////
// Keys
func isTagKey(key []byte) bool {

View File

@@ -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

View File

@@ -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())

View File

@@ -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.

View File

@@ -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]
}
//----------------------------------------

View File

@@ -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) {

View File

@@ -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]
}
//-------------------------------------

View File

@@ -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 {