Browse Source

fix lint failures with 1.31 (#5489)

pull/5561/head
Marko 4 years ago
committed by Erik Grinaker
parent
commit
9379bc92fd
58 changed files with 98 additions and 144 deletions
  1. +1
    -1
      .github/workflows/lint.yaml
  2. +1
    -1
      abci/example/kvstore/persistent_kvstore.go
  3. +1
    -1
      abci/tests/test_app/main.go
  4. +1
    -3
      abci/types/util.go
  5. +2
    -2
      blockchain/v0/pool.go
  6. +1
    -1
      blockchain/v0/pool_test.go
  7. +1
    -1
      blockchain/v0/reactor.go
  8. +1
    -1
      blockchain/v0/reactor_test.go
  9. +1
    -1
      blockchain/v1/reactor.go
  10. +2
    -2
      blockchain/v1/reactor_test.go
  11. +2
    -4
      blockchain/v2/scheduler.go
  12. +2
    -2
      consensus/byzantine_test.go
  13. +2
    -2
      consensus/common_test.go
  14. +6
    -5
      consensus/reactor.go
  15. +1
    -1
      consensus/reactor_test.go
  16. +1
    -1
      consensus/replay.go
  17. +11
    -21
      consensus/replay_test.go
  18. +3
    -3
      consensus/state.go
  19. +2
    -2
      consensus/state_test.go
  20. +1
    -5
      consensus/wal.go
  21. +1
    -3
      consensus/wal_generator.go
  22. +1
    -1
      consensus/wal_test.go
  23. +1
    -1
      libs/bytes/bytes.go
  24. +13
    -13
      libs/clist/clist_test.go
  25. +1
    -1
      libs/cmap/cmap_test.go
  26. +1
    -1
      libs/fail/fail.go
  27. +5
    -5
      libs/log/tracing_logger_test.go
  28. +1
    -1
      libs/math/fraction.go
  29. +3
    -3
      libs/protoio/io_test.go
  30. +1
    -3
      libs/pubsub/pubsub_test.go
  31. +1
    -1
      node/id.go
  32. +1
    -2
      p2p/conn/secret_connection_test.go
  33. +1
    -1
      p2p/switch_test.go
  34. +1
    -1
      p2p/upnp/upnp.go
  35. +0
    -2
      privval/signer_listener_endpoint_test.go
  36. +1
    -1
      proxy/app_conn_test.go
  37. +4
    -3
      rpc/client/examples_test.go
  38. +1
    -1
      rpc/client/rpc_test.go
  39. +1
    -1
      rpc/jsonrpc/client/http_json_client.go
  40. +0
    -2
      rpc/jsonrpc/client/ws_client.go
  41. +1
    -1
      rpc/jsonrpc/jsonrpc_test.go
  42. +0
    -2
      rpc/jsonrpc/server/http_json_handler.go
  43. +0
    -2
      rpc/jsonrpc/server/http_uri_handler.go
  44. +0
    -2
      rpc/jsonrpc/server/rpc_func.go
  45. +0
    -4
      rpc/jsonrpc/server/ws_handler.go
  46. +1
    -1
      rpc/test/helpers.go
  47. +4
    -1
      scripts/wal2json/main.go
  48. +1
    -1
      state/state.go
  49. +1
    -1
      state/state_test.go
  50. +2
    -2
      state/store.go
  51. +0
    -1
      state/txindex/kv/kv.go
  52. +1
    -1
      store/store.go
  53. +0
    -4
      types/events.go
  54. +1
    -1
      types/part_set_test.go
  55. +1
    -3
      types/priv_validator.go
  56. +0
    -3
      types/validator_set.go
  57. +2
    -6
      types/validator_set_test.go
  58. +1
    -1
      types/vote.go

+ 1
- 1
.github/workflows/lint.yaml View File

@ -23,7 +23,7 @@ jobs:
- uses: golangci/golangci-lint-action@v2.2.1 - uses: golangci/golangci-lint-action@v2.2.1
with: with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version. # Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: v1.30
version: v1.31
args: --timeout 10m args: --timeout 10m
github-token: ${{ secrets.github_token }} github-token: ${{ secrets.github_token }}
if: env.GIT_DIFF if: env.GIT_DIFF

+ 1
- 1
abci/example/kvstore/persistent_kvstore.go View File

@ -212,7 +212,7 @@ func isValidatorTx(tx []byte) bool {
func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx { func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx {
tx = tx[len(ValidatorSetChangePrefix):] tx = tx[len(ValidatorSetChangePrefix):]
//get the pubkey and power
// get the pubkey and power
pubKeyAndPower := strings.Split(string(tx), "!") pubKeyAndPower := strings.Split(string(tx), "!")
if len(pubKeyAndPower) != 2 { if len(pubKeyAndPower) != 2 {
return types.ResponseDeliverTx{ return types.ResponseDeliverTx{


+ 1
- 1
abci/tests/test_app/main.go View File

@ -69,7 +69,7 @@ func testCounter() {
}() }()
if err := ensureABCIIsUp(abciType, maxABCIConnectTries); err != nil { if err := ensureABCIIsUp(abciType, maxABCIConnectTries); err != nil {
log.Fatalf("echo failed: %v", err)
log.Fatalf("echo failed: %v", err) //nolint:gocritic
} }
client := startClient(abciType) client := startClient(abciType)


+ 1
- 3
abci/types/util.go View File

@ -27,7 +27,5 @@ func (v ValidatorUpdates) Less(i, j int) bool {
} }
func (v ValidatorUpdates) Swap(i, j int) { 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]
} }

+ 2
- 2
blockchain/v0/pool.go View File

@ -509,7 +509,7 @@ type bpRequester struct {
pool *BlockPool pool *BlockPool
height int64 height int64
gotBlockCh chan struct{} 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 tmsync.Mutex mtx tmsync.Mutex
peerID p2p.ID peerID p2p.ID
@ -601,7 +601,7 @@ OUTER_LOOP:
} }
peer = bpr.pool.pickIncrAvailablePeer(bpr.height) peer = bpr.pool.pickIncrAvailablePeer(bpr.height)
if peer == nil { if peer == nil {
//log.Info("No peers available", "height", height)
// log.Info("No peers available", "height", height)
time.Sleep(requestIntervalMS * time.Millisecond) time.Sleep(requestIntervalMS * time.Millisecond)
continue PICK_PEER_LOOP continue PICK_PEER_LOOP
} }


+ 1
- 1
blockchain/v0/pool_test.go View File

@ -22,7 +22,7 @@ type testPeer struct {
id p2p.ID id p2p.ID
base int64 base int64
height 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 { type inputData struct {


+ 1
- 1
blockchain/v0/reactor.go View File

@ -346,7 +346,7 @@ FOR_LOOP:
// See if there are any blocks to sync. // See if there are any blocks to sync.
first, second := bcR.pool.PeekTwoBlocks() 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 { if first == nil || second == nil {
// We need both to sync the first block. // We need both to sync the first block.
continue FOR_LOOP continue FOR_LOOP


+ 1
- 1
blockchain/v0/reactor_test.go View File

@ -247,7 +247,7 @@ func TestBadBlockStopsPeer(t *testing.T) {
} }
} }
//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()) assert.Equal(t, 3, reactorPairs[1].reactor.Switch.Peers().Size())
// Mark reactorPairs[3] as an invalid peer. Fiddling with .store without a mutex is a data // Mark reactorPairs[3] as an invalid peer. Fiddling with .store without a mutex is a data


+ 1
- 1
blockchain/v1/reactor.go View File

@ -100,7 +100,7 @@ func NewBlockchainReactor(state sm.State, blockExec *sm.BlockExecutor, store *st
fsm := NewFSM(startHeight, bcR) fsm := NewFSM(startHeight, bcR)
bcR.fsm = fsm bcR.fsm = fsm
bcR.BaseReactor = *p2p.NewBaseReactor("BlockchainReactor", bcR) bcR.BaseReactor = *p2p.NewBaseReactor("BlockchainReactor", bcR)
//bcR.swReporter = behaviour.NewSwitchReporter(bcR.BaseReactor.Switch)
// bcR.swReporter = behaviour.NewSwitchReporter(bcR.BaseReactor.Switch)
return bcR return bcR
} }


+ 2
- 2
blockchain/v1/reactor_test.go View File

@ -305,10 +305,10 @@ outerFor:
break 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()) 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 reactorPairs[numNodes-1].bcR.store = otherChain.bcR.store
lastLogger := log.TestingLogger() lastLogger := log.TestingLogger()


+ 2
- 4
blockchain/v2/scheduler.go View File

@ -210,7 +210,7 @@ func newScheduler(initHeight int64, startTime time.Time) *scheduler {
receivedBlocks: make(map[int64]p2p.ID), receivedBlocks: make(map[int64]p2p.ID),
targetPending: 10, // TODO - pass as param targetPending: 10, // TODO - pass as param
peerTimeout: 15 * time.Second, // 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 return &sc
@ -532,9 +532,7 @@ func (peers PeerByID) Less(i, j int) bool {
} }
func (peers PeerByID) Swap(i, j int) { 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 // Handlers


+ 2
- 2
consensus/byzantine_test.go View File

@ -112,7 +112,7 @@ func TestByzantinePrevoteEquivocation(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
blocksSubs = append(blocksSubs, blocksSub) blocksSubs = append(blocksSubs, blocksSub)
if css[i].state.LastBlockHeight == 0 { //simulate handle initChain in handshake
if css[i].state.LastBlockHeight == 0 { // simulate handle initChain in handshake
err = css[i].blockExec.Store().Save(css[i].state) err = css[i].blockExec.Store().Save(css[i].state)
require.NoError(t, err) require.NoError(t, err)
} }
@ -276,7 +276,7 @@ func TestByzantineConflictingProposalsWithPartition(t *testing.T) {
} }
reactors[i] = conRI reactors[i] = conRI
err = css[i].blockExec.Store().Save(css[i].state) //for save height 1's validators info
err = css[i].blockExec.Store().Save(css[i].state) // for save height 1's validators info
require.NoError(t, err) require.NoError(t, err)
} }


+ 2
- 2
consensus/common_test.go View File

@ -391,7 +391,7 @@ func newStateWithConfigAndBlockStore(
// Make State // Make State
stateDB := blockDB stateDB := blockDB
stateStore := sm.NewStore(stateDB) stateStore := sm.NewStore(stateDB)
if err := stateStore.Save(state); err != nil { //for save height 1's validators info
if err := stateStore.Save(state); err != nil { // for save height 1's validators info
panic(err) panic(err)
} }
@ -749,7 +749,7 @@ func randConsensusNetWithPeers(
state.Version.Consensus.App = kvstore.ProtocolVersion state.Version.Consensus.App = kvstore.ProtocolVersion
} }
app.InitChain(abci.RequestInitChain{Validators: vals}) app.InitChain(abci.RequestInitChain{Validators: vals})
//sm.SaveState(stateDB,state) //height 1's validatorsInfo already saved in LoadStateFromDBOrGenesisDoc above
// sm.SaveState(stateDB,state) //height 1's validatorsInfo already saved in LoadStateFromDBOrGenesisDoc above
css[i] = newStateWithConfig(thisConfig, state, privVal, app) css[i] = newStateWithConfig(thisConfig, state, privVal, app)
css[i].SetTimeoutTicker(tickerFunc()) css[i].SetTimeoutTicker(tickerFunc())


+ 6
- 5
consensus/reactor.go View File

@ -540,7 +540,8 @@ OUTER_LOOP:
// If height and round don't match, sleep. // If height and round don't match, sleep.
if (rs.Height != prs.Height) || (rs.Round != prs.Round) { if (rs.Height != prs.Height) || (rs.Round != prs.Round) {
//logger.Info("Peer Height|Round mismatch, sleeping", "peerHeight", prs.Height, "peerRound", prs.Round, "peer", peer)
// logger.Info("Peer Height|Round mismatch, sleeping",
// "peerHeight", prs.Height, "peerRound", prs.Round, "peer", peer)
time.Sleep(conR.conS.config.PeerGossipSleepDuration) time.Sleep(conR.conS.config.PeerGossipSleepDuration)
continue OUTER_LOOP continue OUTER_LOOP
} }
@ -622,7 +623,7 @@ func (conR *Reactor) gossipDataForCatchup(logger log.Logger, rs *cstypes.RoundSt
} }
return return
} }
//logger.Info("No parts to send in catch-up, sleeping")
// logger.Info("No parts to send in catch-up, sleeping")
time.Sleep(conR.conS.config.PeerGossipSleepDuration) time.Sleep(conR.conS.config.PeerGossipSleepDuration)
} }
@ -649,8 +650,8 @@ OUTER_LOOP:
sleeping = 0 sleeping = 0
} }
//logger.Debug("gossipVotesRoutine", "rsHeight", rs.Height, "rsRound", rs.Round,
// "prsHeight", prs.Height, "prsRound", prs.Round, "prsStep", prs.Step)
// 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. // If height matches, then send LastCommit, Prevotes, Precommits.
if rs.Height == prs.Height { if rs.Height == prs.Height {
@ -1488,7 +1489,7 @@ func (m *NewRoundStepMessage) String() string {
//------------------------------------- //-------------------------------------
// NewValidBlockMessage is sent when a validator observes a valid block B in some round r, // NewValidBlockMessage is sent when a validator observes a valid block B in some round r,
//i.e., there is a Proposal for block B and 2/3+ prevotes for the block B in the round r.
// i.e., there is a Proposal for block B and 2/3+ prevotes for the block B in the round r.
// In case the block is also committed, then IsCommit flag is set to true. // In case the block is also committed, then IsCommit flag is set to true.
type NewValidBlockMessage struct { type NewValidBlockMessage struct {
Height int64 Height int64


+ 1
- 1
consensus/reactor_test.go View File

@ -65,7 +65,7 @@ func startConsensusNet(t *testing.T, css []*State, n int) (
require.NoError(t, err) require.NoError(t, err)
blocksSubs = append(blocksSubs, blocksSub) blocksSubs = append(blocksSubs, blocksSub)
if css[i].state.LastBlockHeight == 0 { //simulate handle initChain in handshake
if css[i].state.LastBlockHeight == 0 { // simulate handle initChain in handshake
if err := css[i].blockExec.Store().Save(css[i].state); err != nil { if err := css[i].blockExec.Store().Save(css[i].state); err != nil {
t.Error(err) t.Error(err)
} }


+ 1
- 1
consensus/replay.go View File

@ -323,7 +323,7 @@ func (h *Handshaker) ReplayBlocks(
appHash = res.AppHash appHash = res.AppHash
if stateBlockHeight == 0 { //we only update state when we are in initial state
if stateBlockHeight == 0 { // we only update state when we are in initial state
// If the app did not return an app hash, we keep the one set from the genesis doc in // If the app did not return an app hash, we keep the one set from the genesis doc in
// the state. We don't set appHash since we don't want the genesis doc app hash // the state. We don't set appHash since we don't want the genesis doc app hash
// recorded in the genesis block. We should probably just remove GenesisDoc.AppHash. // recorded in the genesis block. We should probably just remove GenesisDoc.AppHash.


+ 11
- 21
consensus/replay_test.go View File

@ -353,9 +353,7 @@ func TestSimulateValidatorsChange(t *testing.T) {
signAddVotes(css[0], tmproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vss[1:nVals]...) signAddVotes(css[0], tmproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vss[1:nVals]...)
ensureNewRound(newRoundCh, height+1, 0) ensureNewRound(newRoundCh, height+1, 0)
/////////////////////////////////////////////////////////////////////////////
// HEIGHT 2 // HEIGHT 2
/////////////////////////////////////////////////////////////////////////////
height++ height++
incrementHeight(vss...) incrementHeight(vss...)
newValidatorPubKey1, err := css[nVals].privValidator.GetPubKey() newValidatorPubKey1, err := css[nVals].privValidator.GetPubKey()
@ -365,7 +363,7 @@ func TestSimulateValidatorsChange(t *testing.T) {
newValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower) newValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower)
err = assertMempool(css[0].txNotifier).CheckTx(newValidatorTx1, nil, mempl.TxInfo{}) err = assertMempool(css[0].txNotifier).CheckTx(newValidatorTx1, nil, mempl.TxInfo{})
assert.Nil(t, err) assert.Nil(t, err)
propBlock, _ := css[0].createProposalBlock() //changeProposer(t, cs1, vs2)
propBlock, _ := css[0].createProposalBlock() // changeProposer(t, cs1, vs2)
propBlockParts := propBlock.MakePartSet(partSize) propBlockParts := propBlock.MakePartSet(partSize)
blockID := types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()} blockID := types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()}
@ -385,9 +383,7 @@ func TestSimulateValidatorsChange(t *testing.T) {
signAddVotes(css[0], tmproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vss[1:nVals]...) signAddVotes(css[0], tmproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vss[1:nVals]...)
ensureNewRound(newRoundCh, height+1, 0) ensureNewRound(newRoundCh, height+1, 0)
/////////////////////////////////////////////////////////////////////////////
// HEIGHT 3 // HEIGHT 3
/////////////////////////////////////////////////////////////////////////////
height++ height++
incrementHeight(vss...) incrementHeight(vss...)
updateValidatorPubKey1, err := css[nVals].privValidator.GetPubKey() updateValidatorPubKey1, err := css[nVals].privValidator.GetPubKey()
@ -397,7 +393,7 @@ func TestSimulateValidatorsChange(t *testing.T) {
updateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25) updateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25)
err = assertMempool(css[0].txNotifier).CheckTx(updateValidatorTx1, nil, mempl.TxInfo{}) err = assertMempool(css[0].txNotifier).CheckTx(updateValidatorTx1, nil, mempl.TxInfo{})
assert.Nil(t, err) assert.Nil(t, err)
propBlock, _ = css[0].createProposalBlock() //changeProposer(t, cs1, vs2)
propBlock, _ = css[0].createProposalBlock() // changeProposer(t, cs1, vs2)
propBlockParts = propBlock.MakePartSet(partSize) propBlockParts = propBlock.MakePartSet(partSize)
blockID = types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()} blockID = types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()}
@ -417,9 +413,7 @@ func TestSimulateValidatorsChange(t *testing.T) {
signAddVotes(css[0], tmproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vss[1:nVals]...) signAddVotes(css[0], tmproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vss[1:nVals]...)
ensureNewRound(newRoundCh, height+1, 0) ensureNewRound(newRoundCh, height+1, 0)
/////////////////////////////////////////////////////////////////////////////
// HEIGHT 4 // HEIGHT 4
/////////////////////////////////////////////////////////////////////////////
height++ height++
incrementHeight(vss...) incrementHeight(vss...)
newValidatorPubKey2, err := css[nVals+1].privValidator.GetPubKey() newValidatorPubKey2, err := css[nVals+1].privValidator.GetPubKey()
@ -436,7 +430,7 @@ func TestSimulateValidatorsChange(t *testing.T) {
newValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower) newValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower)
err = assertMempool(css[0].txNotifier).CheckTx(newValidatorTx3, nil, mempl.TxInfo{}) err = assertMempool(css[0].txNotifier).CheckTx(newValidatorTx3, nil, mempl.TxInfo{})
assert.Nil(t, err) assert.Nil(t, err)
propBlock, _ = css[0].createProposalBlock() //changeProposer(t, cs1, vs2)
propBlock, _ = css[0].createProposalBlock() // changeProposer(t, cs1, vs2)
propBlockParts = propBlock.MakePartSet(partSize) propBlockParts = propBlock.MakePartSet(partSize)
blockID = types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()} blockID = types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()}
newVss := make([]*validatorStub, nVals+1) newVss := make([]*validatorStub, nVals+1)
@ -487,9 +481,7 @@ func TestSimulateValidatorsChange(t *testing.T) {
ensureNewRound(newRoundCh, height+1, 0) ensureNewRound(newRoundCh, height+1, 0)
/////////////////////////////////////////////////////////////////////////////
// HEIGHT 5 // HEIGHT 5
/////////////////////////////////////////////////////////////////////////////
height++ height++
incrementHeight(vss...) incrementHeight(vss...)
// Reflect the changes to vss[nVals] at height 3 and resort newVss. // Reflect the changes to vss[nVals] at height 3 and resort newVss.
@ -507,15 +499,13 @@ func TestSimulateValidatorsChange(t *testing.T) {
} }
ensureNewRound(newRoundCh, height+1, 0) ensureNewRound(newRoundCh, height+1, 0)
/////////////////////////////////////////////////////////////////////////////
// HEIGHT 6 // HEIGHT 6
/////////////////////////////////////////////////////////////////////////////
height++ height++
incrementHeight(vss...) incrementHeight(vss...)
removeValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, 0) removeValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, 0)
err = assertMempool(css[0].txNotifier).CheckTx(removeValidatorTx3, nil, mempl.TxInfo{}) err = assertMempool(css[0].txNotifier).CheckTx(removeValidatorTx3, nil, mempl.TxInfo{})
assert.Nil(t, err) assert.Nil(t, err)
propBlock, _ = css[0].createProposalBlock() //changeProposer(t, cs1, vs2)
propBlock, _ = css[0].createProposalBlock() // changeProposer(t, cs1, vs2)
propBlockParts = propBlock.MakePartSet(partSize) propBlockParts = propBlock.MakePartSet(partSize)
blockID = types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()} blockID = types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()}
newVss = make([]*validatorStub, nVals+3) newVss = make([]*validatorStub, nVals+3)
@ -594,7 +584,7 @@ func TestHandshakeReplayNone(t *testing.T) {
// Test mockProxyApp should not panic when app return ABCIResponses with some empty ResponseDeliverTx // Test mockProxyApp should not panic when app return ABCIResponses with some empty ResponseDeliverTx
func TestMockProxyApp(t *testing.T) { func TestMockProxyApp(t *testing.T) {
sim.CleanupFunc() //clean the test env created in TestSimulateValidatorsChange
sim.CleanupFunc() // clean the test env created in TestSimulateValidatorsChange
logger := log.TestingLogger() logger := log.TestingLogger()
var validTxs, invalidTxs = 0, 0 var validTxs, invalidTxs = 0, 0
txIndex := 0 txIndex := 0
@ -676,7 +666,7 @@ func testHandshakeReplay(t *testing.T, config *cfg.Config, nBlocks int, mode uin
chain = append([]*types.Block{}, sim.Chain...) // copy chain chain = append([]*types.Block{}, sim.Chain...) // copy chain
commits = sim.Commits commits = sim.Commits
store = newMockBlockStore(config, genesisState.ConsensusParams) store = newMockBlockStore(config, genesisState.ConsensusParams)
} else { //test single node
} else { // test single node
testConfig := ResetConfig(fmt.Sprintf("%s_%v_s", t.Name(), mode)) testConfig := ResetConfig(fmt.Sprintf("%s_%v_s", t.Name(), mode))
defer os.RemoveAll(testConfig.RootDir) defer os.RemoveAll(testConfig.RootDir)
walBody, err := WALWithNBlocks(t, numBlocks) walBody, err := WALWithNBlocks(t, numBlocks)
@ -805,14 +795,14 @@ func buildAppStateFromChain(proxyApp proxy.AppConns, stateStore sm.Store,
} }
defer proxyApp.Stop() //nolint:errcheck // ignore defer proxyApp.Stop() //nolint:errcheck // ignore
state.Version.Consensus.App = kvstore.ProtocolVersion //simulate handshake, receive app version
state.Version.Consensus.App = kvstore.ProtocolVersion // simulate handshake, receive app version
validators := types.TM2PB.ValidatorUpdates(state.Validators) validators := types.TM2PB.ValidatorUpdates(state.Validators)
if _, err := proxyApp.Consensus().InitChainSync(abci.RequestInitChain{ if _, err := proxyApp.Consensus().InitChainSync(abci.RequestInitChain{
Validators: validators, Validators: validators,
}); err != nil { }); err != nil {
panic(err) panic(err)
} }
if err := stateStore.Save(state); err != nil { //save height 1's validatorsInfo
if err := stateStore.Save(state); err != nil { // save height 1's validatorsInfo
panic(err) panic(err)
} }
switch mode { switch mode {
@ -853,16 +843,16 @@ func buildTMStateFromChain(
if err := proxyApp.Start(); err != nil { if err := proxyApp.Start(); err != nil {
panic(err) panic(err)
} }
defer proxyApp.Stop() //nolint:errcheck //ignore
defer proxyApp.Stop() //nolint:errcheck
state.Version.Consensus.App = kvstore.ProtocolVersion //simulate handshake, receive app version
state.Version.Consensus.App = kvstore.ProtocolVersion // simulate handshake, receive app version
validators := types.TM2PB.ValidatorUpdates(state.Validators) validators := types.TM2PB.ValidatorUpdates(state.Validators)
if _, err := proxyApp.Consensus().InitChainSync(abci.RequestInitChain{ if _, err := proxyApp.Consensus().InitChainSync(abci.RequestInitChain{
Validators: validators, Validators: validators,
}); err != nil { }); err != nil {
panic(err) panic(err)
} }
if err := stateStore.Save(state); err != nil { //save height 1's validatorsInfo
if err := stateStore.Save(state); err != nil { // save height 1's validatorsInfo
panic(err) panic(err)
} }
switch mode { switch mode {


+ 3
- 3
consensus/state.go View File

@ -520,7 +520,7 @@ func (cs *State) updateRoundStep(round int32, step cstypes.RoundStepType) {
// enterNewRound(height, 0) at cs.StartTime. // enterNewRound(height, 0) at cs.StartTime.
func (cs *State) scheduleRound0(rs *cstypes.RoundState) { func (cs *State) scheduleRound0(rs *cstypes.RoundState) {
//cs.Logger.Info("scheduleRound0", "now", tmtime.Now(), "startTime", cs.StartTime)
// cs.Logger.Info("scheduleRound0", "now", tmtime.Now(), "startTime", cs.StartTime)
sleepDuration := rs.StartTime.Sub(tmtime.Now()) sleepDuration := rs.StartTime.Sub(tmtime.Now())
cs.scheduleTimeout(sleepDuration, rs.Height, 0, cstypes.RoundStepNewHeight) cs.scheduleTimeout(sleepDuration, rs.Height, 0, cstypes.RoundStepNewHeight)
} }
@ -2137,9 +2137,9 @@ func (cs *State) signAddVote(msgType tmproto.SignedMsgType, hash []byte, header
cs.Logger.Info("Signed and pushed vote", "height", cs.Height, "round", cs.Round, "vote", vote, "err", err) cs.Logger.Info("Signed and pushed vote", "height", cs.Height, "round", cs.Round, "vote", vote, "err", err)
return vote return vote
} }
//if !cs.replayMode {
// if !cs.replayMode {
cs.Logger.Error("Error signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "err", err) cs.Logger.Error("Error signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "err", err)
//}
// }
return nil return nil
} }


+ 2
- 2
consensus/state_test.go View File

@ -191,7 +191,7 @@ func TestStateBadProposal(t *testing.T) {
proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal) proposalCh := subscribe(cs1.eventBus, types.EventQueryCompleteProposal)
voteCh := subscribe(cs1.eventBus, types.EventQueryVote) voteCh := subscribe(cs1.eventBus, types.EventQueryVote)
propBlock, _ := cs1.createProposalBlock() //changeProposer(t, cs1, vs2)
propBlock, _ := cs1.createProposalBlock() // changeProposer(t, cs1, vs2)
// make the second validator the proposer by incrementing round // make the second validator the proposer by incrementing round
round++ round++
@ -380,7 +380,7 @@ func TestStateFullRound2(t *testing.T) {
signAddVotes(cs1, tmproto.PrevoteType, propBlockHash, propPartSetHeader, vs2) signAddVotes(cs1, tmproto.PrevoteType, propBlockHash, propPartSetHeader, vs2)
ensurePrevote(voteCh, height, round) // prevote ensurePrevote(voteCh, height, round) // prevote
ensurePrecommit(voteCh, height, round) //precommit
ensurePrecommit(voteCh, height, round) // precommit
// the proposed block should now be locked and our precommit added // the proposed block should now be locked and our precommit added
validatePrecommit(t, cs1, 0, 0, vss[0], propBlockHash, propBlockHash) validatePrecommit(t, cs1, 0, 0, vss[0], propBlockHash, propBlockHash)


+ 1
- 5
consensus/wal.go View File

@ -208,7 +208,7 @@ func (wal *BaseWAL) WriteSync(msg WALMessage) error {
} }
if err := wal.FlushAndSync(); err != nil { if err := wal.FlushAndSync(); err != nil {
wal.Logger.Error(`WriteSync failed to flush consensus wal.
wal.Logger.Error(`WriteSync failed to flush consensus wal.
WARNING: may result in creating alternative proposals / votes for the current height iff the node restarted`, WARNING: may result in creating alternative proposals / votes for the current height iff the node restarted`,
"err", err) "err", err)
return err return err
@ -282,8 +282,6 @@ func (wal *BaseWAL) SearchForEndHeight(
return nil, false, nil return nil, false, nil
} }
///////////////////////////////////////////////////////////////////////////////
// A WALEncoder writes custom-encoded WAL messages to an output stream. // A WALEncoder writes custom-encoded WAL messages to an output stream.
// //
// Format: 4 bytes CRC sum + 4 bytes length + arbitrary-length value // Format: 4 bytes CRC sum + 4 bytes length + arbitrary-length value
@ -330,8 +328,6 @@ func (enc *WALEncoder) Encode(v *TimedWALMessage) error {
return err return err
} }
///////////////////////////////////////////////////////////////////////////////
// IsDataCorruptionError returns true if data has been corrupted inside WAL. // IsDataCorruptionError returns true if data has been corrupted inside WAL.
func IsDataCorruptionError(err error) bool { func IsDataCorruptionError(err error) bool {
_, ok := err.(DataCorruptionError) _, ok := err.(DataCorruptionError)


+ 1
- 3
consensus/wal_generator.go View File

@ -35,7 +35,6 @@ func WALGenerateNBlocks(t *testing.T, wr io.Writer, numBlocks int) (err error) {
logger := log.TestingLogger().With("wal_generator", "wal_generator") logger := log.TestingLogger().With("wal_generator", "wal_generator")
logger.Info("generating WAL (last height msg excluded)", "numBlocks", numBlocks) logger.Info("generating WAL (last height msg excluded)", "numBlocks", numBlocks)
/////////////////////////////////////////////////////////////////////////////
// COPY PASTE FROM node.go WITH A FEW MODIFICATIONS // COPY PASTE FROM node.go WITH A FEW MODIFICATIONS
// NOTE: we can't import node package because of circular dependency. // NOTE: we can't import node package because of circular dependency.
// NOTE: we don't do handshake so need to set state.Version.Consensus.App directly. // NOTE: we don't do handshake so need to set state.Version.Consensus.App directly.
@ -91,7 +90,6 @@ func WALGenerateNBlocks(t *testing.T, wr io.Writer, numBlocks int) (err error) {
consensusState.SetPrivValidator(privValidator) consensusState.SetPrivValidator(privValidator)
} }
// END OF COPY PASTE // END OF COPY PASTE
/////////////////////////////////////////////////////////////////////////////
// set consensus wal to buffered WAL, which will write all incoming msgs to buffer // set consensus wal to buffered WAL, which will write all incoming msgs to buffer
numBlocksWritten := make(chan struct{}) numBlocksWritten := make(chan struct{})
@ -121,7 +119,7 @@ func WALGenerateNBlocks(t *testing.T, wr io.Writer, numBlocks int) (err error) {
} }
} }
//WALWithNBlocks returns a WAL content with numBlocks.
// WALWithNBlocks returns a WAL content with numBlocks.
func WALWithNBlocks(t *testing.T, numBlocks int) (data []byte, err error) { func WALWithNBlocks(t *testing.T, numBlocks int) (data []byte, err error) {
var b bytes.Buffer var b bytes.Buffer
wr := bufio.NewWriter(&b) wr := bufio.NewWriter(&b)


+ 1
- 1
consensus/wal_test.go View File

@ -60,7 +60,7 @@ func TestWALTruncate(t *testing.T) {
err = WALGenerateNBlocks(t, wal.Group(), 60) err = WALGenerateNBlocks(t, wal.Group(), 60)
require.NoError(t, err) require.NoError(t, err)
time.Sleep(1 * time.Millisecond) //wait groupCheckDuration, make sure RotateFile run
time.Sleep(1 * time.Millisecond) // wait groupCheckDuration, make sure RotateFile run
if err := wal.FlushAndSync(); err != nil { if err := wal.FlushAndSync(); err != nil {
t.Error(err) t.Error(err)


+ 1
- 1
libs/bytes/bytes.go View File

@ -25,7 +25,7 @@ func (bz HexBytes) MarshalJSON() ([]byte, error) {
s := strings.ToUpper(hex.EncodeToString(bz)) s := strings.ToUpper(hex.EncodeToString(bz))
jbz := make([]byte, len(s)+2) jbz := make([]byte, len(s)+2)
jbz[0] = '"' jbz[0] = '"'
copy(jbz[1:], []byte(s))
copy(jbz[1:], s)
jbz[len(jbz)-1] = '"' jbz[len(jbz)-1] = '"'
return jbz, nil return jbz, nil
} }


+ 13
- 13
libs/clist/clist_test.go View File

@ -33,21 +33,21 @@ func TestSmall(t *testing.T) {
t.Error("Expected len 3, got ", l.Len()) 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)
// 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) 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)
// 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) 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)
// 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) r3 := l.Remove(el3)
@ -97,10 +97,10 @@ func _TestGCFifo(t *testing.T) {
for el := l.Front(); el != nil; { for el := l.Front(); el != nil; {
l.Remove(el) l.Remove(el)
//oldEl := el
// oldEl := el
el = el.Next() el = el.Next()
//oldEl.DetachPrev()
//oldEl.DetachNext()
// oldEl.DetachPrev()
// oldEl.DetachNext()
} }
runtime.GC() runtime.GC()
@ -211,7 +211,7 @@ func TestScanRightDeleteRandom(t *testing.T) {
// Remove it // Remove it
l.Remove(rmEl) l.Remove(rmEl)
//fmt.Print(".")
// fmt.Print(".")
// Insert a new element // Insert a new element
newEl := l.PushBack(-1*i - 1) newEl := l.PushBack(-1*i - 1)


+ 1
- 1
libs/cmap/cmap_test.go View File

@ -22,7 +22,7 @@ func TestIterateKeysWithValues(t *testing.T) {
// Iterating Keys, checking for matching Value // Iterating Keys, checking for matching Value
for _, key := range cmap.Keys() { 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)) assert.Equal(t, val, cmap.Get(key))
} }


+ 1
- 1
libs/fail/fail.go View File

@ -23,7 +23,7 @@ func envSet() int {
} }
// Fail when FAIL_TEST_INDEX == callIndex // Fail when FAIL_TEST_INDEX == callIndex
var callIndex int //indexes Fail calls
var callIndex int // indexes Fail calls
func Fail() { func Fail() {
callIndexToFail := envSet() callIndexToFail := envSet()


+ 5
- 5
libs/log/tracing_logger_test.go 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") 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) logger1.With("err1", err1).Info("foo", "err2", err2)
want := strings.Replace(
strings.Replace(
want := strings.ReplaceAll(
strings.ReplaceAll(
`{"_msg":"foo","err1":"`+ `{"_msg":"foo","err1":"`+
fmt.Sprintf("%+v", err1)+ fmt.Sprintf("%+v", err1)+
`","err2":"`+ `","err2":"`+
fmt.Sprintf("%+v", err2)+ fmt.Sprintf("%+v", err2)+
`","level":"info"}`, `","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 { if want != have {
t.Errorf("\nwant '%s'\nhave '%s'", want, have) t.Errorf("\nwant '%s'\nhave '%s'", want, have)
} }


+ 1
- 1
libs/math/fraction.go View File

@ -25,7 +25,7 @@ func (fr Fraction) String() string {
// to the equivalent fraction else returns an error. The format of the string must be // to the equivalent fraction else returns an error. The format of the string must be
// one number followed by a slash (/) and then the other number. // one number followed by a slash (/) and then the other number.
func ParseFraction(f string) (Fraction, error) { func ParseFraction(f string) (Fraction, error) {
o := strings.SplitN(f, "/", -1)
o := strings.Split(f, "/")
if len(o) != 2 { if len(o) != 2 {
return Fraction{}, errors.New("incorrect formating: should be like \"1/3\"") return Fraction{}, errors.New("incorrect formating: should be like \"1/3\"")
} }


+ 3
- 3
libs/protoio/io_test.go View File

@ -50,11 +50,11 @@ func iotest(writer protoio.WriteCloser, reader protoio.ReadCloser) error {
r := rand.New(rand.NewSource(time.Now().UnixNano())) r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := range msgs { for i := range msgs {
msgs[i] = test.NewPopulatedNinOptNative(r, true) msgs[i] = test.NewPopulatedNinOptNative(r, true)
//issue 31
// issue 31
if i == 5 { if i == 5 {
msgs[i] = &test.NinOptNative{} msgs[i] = &test.NinOptNative{}
} }
//issue 31
// issue 31
if i == 999 { if i == 999 {
msgs[i] = &test.NinOptNative{} msgs[i] = &test.NinOptNative{}
} }
@ -133,7 +133,7 @@ func TestVarintNoClose(t *testing.T) {
} }
} }
//issue 32
// issue 32
func TestVarintMaxSize(t *testing.T) { func TestVarintMaxSize(t *testing.T) {
buf := newBuffer() buf := newBuffer()
writer := protoio.NewDelimitedWriter(buf) writer := protoio.NewDelimitedWriter(buf)


+ 1
- 3
libs/pubsub/pubsub_test.go View File

@ -488,9 +488,7 @@ func benchmarkNClientsOneQuery(n int, b *testing.B) {
} }
} }
///////////////////////////////////////////////////////////////////////////////
/// HELPERS
///////////////////////////////////////////////////////////////////////////////
// HELPERS
func assertReceive(t *testing.T, expected interface{}, ch <-chan pubsub.Message, msgAndArgs ...interface{}) { func assertReceive(t *testing.T, expected interface{}, ch <-chan pubsub.Message, msgAndArgs ...interface{}) {
select { select {


+ 1
- 1
node/id.go View File

@ -30,6 +30,6 @@ type SignedNodeGreeting struct {
} }
func (pnid *PrivNodeID) SignGreeting() *SignedNodeGreeting { func (pnid *PrivNodeID) SignGreeting() *SignedNodeGreeting {
//greeting := NodeGreeting{}
// greeting := NodeGreeting{}
return nil return nil
} }

+ 1
- 2
p2p/conn/secret_connection_test.go View File

@ -380,7 +380,6 @@ func makeSecretConnPair(tb testing.TB) (fooSecConn, barSecConn *SecretConnection
return fooSecConn, barSecConn return fooSecConn, barSecConn
} }
///////////////////////////////////////////////////////////////////////////////
// Benchmarks // Benchmarks
func BenchmarkWriteSecretConnection(b *testing.B) { func BenchmarkWriteSecretConnection(b *testing.B) {
@ -428,7 +427,7 @@ func BenchmarkWriteSecretConnection(b *testing.B) {
if err := fooSecConn.Close(); err != nil { if err := fooSecConn.Close(); err != nil {
b.Error(err) b.Error(err)
} }
//barSecConn.Close() race condition
// barSecConn.Close() race condition
} }
func BenchmarkReadSecretConnection(b *testing.B) { func BenchmarkReadSecretConnection(b *testing.B) {


+ 1
- 1
p2p/switch_test.go View File

@ -75,7 +75,7 @@ func (tr *TestReactor) Receive(chID byte, peer Peer, msgBytes []byte) {
if tr.logMessages { if tr.logMessages {
tr.mtx.Lock() tr.mtx.Lock()
defer tr.mtx.Unlock() defer tr.mtx.Unlock()
//fmt.Printf("Received: %X, %X\n", chID, msgBytes)
// fmt.Printf("Received: %X, %X\n", chID, msgBytes)
tr.msgsReceived[chID] = append(tr.msgsReceived[chID], PeerMessage{peer.ID(), msgBytes, tr.msgsCounter}) tr.msgsReceived[chID] = append(tr.msgsReceived[chID], PeerMessage{peer.ID(), msgBytes, tr.msgsCounter})
tr.msgsCounter++ tr.msgsCounter++
} }


+ 1
- 1
p2p/upnp/upnp.go 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("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("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("SOAPAction", "\"urn:"+domain+":service:WANIPConnection:1#"+function+"\"")
req.Header.Set("Connection", "Close") req.Header.Set("Connection", "Close")
req.Header.Set("Cache-Control", "no-cache") req.Header.Set("Cache-Control", "no-cache")


+ 0
- 2
privval/signer_listener_endpoint_test.go View File

@ -145,8 +145,6 @@ func TestRetryConnToRemoteSigner(t *testing.T) {
} }
} }
///////////////////////////////////
func newSignerListenerEndpoint(logger log.Logger, addr string, timeoutReadWrite time.Duration) *SignerListenerEndpoint { func newSignerListenerEndpoint(logger log.Logger, addr string, timeoutReadWrite time.Duration) *SignerListenerEndpoint {
proto, address := tmnet.ProtocolAndAddress(addr) proto, address := tmnet.ProtocolAndAddress(addr)


+ 1
- 1
proxy/app_conn_test.go View File

@ -123,7 +123,7 @@ func BenchmarkEcho(b *testing.B) {
b.StopTimer() b.StopTimer()
// info := proxy.InfoSync(types.RequestInfo{""}) // info := proxy.InfoSync(types.RequestInfo{""})
//b.Log("N: ", b.N, info)
// b.Log("N: ", b.N, info)
} }
func TestInfo(t *testing.T) { func TestInfo(t *testing.T) {


+ 4
- 3
rpc/client/examples_test.go View File

@ -22,7 +22,7 @@ func ExampleHTTP_simple() {
rpcAddr := rpctest.GetConfig().RPC.ListenAddress rpcAddr := rpctest.GetConfig().RPC.ListenAddress
c, err := rpchttp.New(rpcAddr, "/websocket") c, err := rpchttp.New(rpcAddr, "/websocket")
if err != nil { if err != nil {
log.Fatal(err)
log.Fatal(err) //nolint:gocritic
} }
// Create a transaction // Create a transaction
@ -69,7 +69,6 @@ func ExampleHTTP_batching() {
// Start a tendermint node (and kvstore) in the background to test against // Start a tendermint node (and kvstore) in the background to test against
app := kvstore.NewApplication() app := kvstore.NewApplication()
node := rpctest.StartTendermint(app, rpctest.SuppressStdout, rpctest.RecreateConfig) node := rpctest.StartTendermint(app, rpctest.SuppressStdout, rpctest.RecreateConfig)
defer rpctest.StopTendermint(node)
// Create our RPC client // Create our RPC client
rpcAddr := rpctest.GetConfig().RPC.ListenAddress rpcAddr := rpctest.GetConfig().RPC.ListenAddress
@ -78,6 +77,8 @@ func ExampleHTTP_batching() {
log.Fatal(err) log.Fatal(err)
} }
defer rpctest.StopTendermint(node)
// Create our two transactions // Create our two transactions
k1 := []byte("firstName") k1 := []byte("firstName")
v1 := []byte("satoshi") v1 := []byte("satoshi")
@ -97,7 +98,7 @@ func ExampleHTTP_batching() {
// Broadcast the transaction and wait for it to commit (rather use // Broadcast the transaction and wait for it to commit (rather use
// c.BroadcastTxSync though in production). // c.BroadcastTxSync though in production).
if _, err := batch.BroadcastTxCommit(context.Background(), tx); err != nil { if _, err := batch.BroadcastTxCommit(context.Background(), tx); err != nil {
log.Fatal(err)
log.Fatal(err) //nolint:gocritic
} }
} }


+ 1
- 1
rpc/client/rpc_test.go View File

@ -82,7 +82,7 @@ func TestCustomHTTPClient(t *testing.T) {
func TestCorsEnabled(t *testing.T) { func TestCorsEnabled(t *testing.T) {
origin := rpctest.GetConfig().RPC.CORSAllowedOrigins[0] 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) req, err := http.NewRequest("GET", remote, nil)
require.Nil(t, err, "%+v", err) require.Nil(t, err, "%+v", err)


+ 1
- 1
rpc/jsonrpc/client/http_json_client.go View File

@ -66,7 +66,7 @@ func (u parsedURL) GetHostWithPath() string {
// Get a trimmed address - useful for WS connections // Get a trimmed address - useful for WS connections
func (u parsedURL) GetTrimmedHostWithPath() string { func (u parsedURL) GetTrimmedHostWithPath() string {
// replace / with . for http requests (kvstore domain) // 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 // Get a trimmed address with protocol - useful as address in RPC connections


+ 0
- 2
rpc/jsonrpc/client/ws_client.go View File

@ -248,7 +248,6 @@ func (c *WSClient) CallWithArrayParams(ctx context.Context, method string, param
return c.Send(ctx, request) return c.Send(ctx, request)
} }
///////////////////////////////////////////////////////////////////////////////
// Private methods // Private methods
func (c *WSClient) nextRequestID() types.JSONRPCIntID { func (c *WSClient) nextRequestID() types.JSONRPCIntID {
@ -521,7 +520,6 @@ func (c *WSClient) readRoutine() {
} }
} }
///////////////////////////////////////////////////////////////////////////////
// Predefined methods // Predefined methods
// Subscribe to a query. Note the server must have a "subscribe" route // Subscribe to a query. Note the server must have a "subscribe" route


+ 1
- 1
rpc/jsonrpc/jsonrpc_test.go View File

@ -404,5 +404,5 @@ func randBytes(t *testing.T) []byte {
buf := make([]byte, n) buf := make([]byte, n)
_, err := crand.Read(buf) _, err := crand.Read(buf)
require.Nil(t, err) require.Nil(t, err)
return bytes.Replace(buf, []byte("="), []byte{100}, -1)
return bytes.ReplaceAll(buf, []byte("="), []byte{100})
} }

+ 0
- 2
rpc/jsonrpc/server/http_json_handler.go View File

@ -14,9 +14,7 @@ import (
types "github.com/tendermint/tendermint/rpc/jsonrpc/types" types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
) )
///////////////////////////////////////////////////////////////////////////////
// HTTP + JSON handler // HTTP + JSON handler
///////////////////////////////////////////////////////////////////////////////
// jsonrpc calls grab the given method's function info and runs reflect.Call // jsonrpc calls grab the given method's function info and runs reflect.Call
func makeJSONRPCHandler(funcMap map[string]*RPCFunc, logger log.Logger) http.HandlerFunc { func makeJSONRPCHandler(funcMap map[string]*RPCFunc, logger log.Logger) http.HandlerFunc {


+ 0
- 2
rpc/jsonrpc/server/http_uri_handler.go View File

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


+ 0
- 2
rpc/jsonrpc/server/rpc_func.go View File

@ -23,9 +23,7 @@ func RegisterRPCFuncs(mux *http.ServeMux, funcMap map[string]*RPCFunc, logger lo
mux.HandleFunc("/", handleInvalidJSONRPCPaths(makeJSONRPCHandler(funcMap, logger))) mux.HandleFunc("/", handleInvalidJSONRPCPaths(makeJSONRPCHandler(funcMap, logger)))
} }
///////////////////////////////////////////////////////////////////////////////
// Function introspection // Function introspection
///////////////////////////////////////////////////////////////////////////////
// RPCFunc contains the introspected type information for a function // RPCFunc contains the introspected type information for a function
type RPCFunc struct { type RPCFunc struct {


+ 0
- 4
rpc/jsonrpc/server/ws_handler.go View File

@ -17,9 +17,7 @@ import (
types "github.com/tendermint/tendermint/rpc/jsonrpc/types" types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
) )
///////////////////////////////////////////////////////////////////////////////
// WebSocket handler // WebSocket handler
///////////////////////////////////////////////////////////////////////////////
const ( const (
defaultWSWriteChanCapacity = 100 defaultWSWriteChanCapacity = 100
@ -100,9 +98,7 @@ func (wm *WebsocketManager) WebsocketHandler(w http.ResponseWriter, r *http.Requ
} }
} }
///////////////////////////////////////////////////////////////////////////////
// WebSocket connection // WebSocket connection
///////////////////////////////////////////////////////////////////////////////
// A single websocket connection contains listener id, underlying ws // A single websocket connection contains listener id, underlying ws
// connection, and the event switch for subscribing to events. // connection, and the event switch for subscribing to events.


+ 1
- 1
rpc/test/helpers.go View File

@ -72,7 +72,7 @@ func makePathname() string {
} }
// fmt.Println(p) // fmt.Println(p)
sep := string(filepath.Separator) sep := string(filepath.Separator)
return strings.Replace(p, sep, "_", -1)
return strings.ReplaceAll(p, sep, "_")
} }
func randPort() int { func randPort() int {


+ 4
- 1
scripts/wal2json/main.go View File

@ -46,14 +46,17 @@ func main() {
if err == nil { if err == nil {
_, err = os.Stdout.Write([]byte("\n")) _, err = os.Stdout.Write([]byte("\n"))
} }
if err == nil { if err == nil {
if endMsg, ok := msg.Msg.(cs.EndHeightMessage); ok { if endMsg, ok := msg.Msg.(cs.EndHeightMessage); ok {
_, err = os.Stdout.Write([]byte(fmt.Sprintf("ENDHEIGHT %d\n", endMsg.Height))) _, err = os.Stdout.Write([]byte(fmt.Sprintf("ENDHEIGHT %d\n", endMsg.Height)))
} }
} }
if err != nil { if err != nil {
fmt.Println("Failed to write message", err) fmt.Println("Failed to write message", err)
os.Exit(1)
os.Exit(1) //nolint:gocritic
} }
} }
} }

+ 1
- 1
state/state.go View File

@ -131,7 +131,7 @@ func (state State) IsEmpty() bool {
return state.Validators == nil // XXX can't compare to Empty return state.Validators == nil // XXX can't compare to Empty
} }
//ToProto takes the local state type and returns the equivalent proto type
// ToProto takes the local state type and returns the equivalent proto type
func (state *State) ToProto() (*tmstate.State, error) { func (state *State) ToProto() (*tmstate.State, error) {
if state == nil { if state == nil {
return nil, errors.New("state is nil") return nil, errors.New("state is nil")


+ 1
- 1
state/state_test.go View File

@ -59,7 +59,7 @@ func TestStateCopy(t *testing.T) {
%v`, state)) %v`, state))
} }
//TestMakeGenesisStateNilValidators tests state's consistency when genesis file's validators field is nil.
// TestMakeGenesisStateNilValidators tests state's consistency when genesis file's validators field is nil.
func TestMakeGenesisStateNilValidators(t *testing.T) { func TestMakeGenesisStateNilValidators(t *testing.T) {
doc := types.GenesisDoc{ doc := types.GenesisDoc{
ChainID: "dummy", ChainID: "dummy",


+ 2
- 2
state/store.go View File

@ -70,7 +70,7 @@ type Store interface {
PruneStates(int64, int64) error PruneStates(int64, int64) error
} }
//dbStore wraps a db (github.com/tendermint/tm-db)
// dbStore wraps a db (github.com/tendermint/tm-db)
type dbStore struct { type dbStore struct {
db dbm.DB db dbm.DB
} }
@ -390,7 +390,7 @@ func (store dbStore) LoadABCIResponses(height int64) (*tmstate.ABCIResponses, er
// Exposed for testing. // Exposed for testing.
func (store dbStore) SaveABCIResponses(height int64, abciResponses *tmstate.ABCIResponses) error { func (store dbStore) SaveABCIResponses(height int64, abciResponses *tmstate.ABCIResponses) error {
var dtxs []*abci.ResponseDeliverTx var dtxs []*abci.ResponseDeliverTx
//strip nil values,
// strip nil values,
for _, tx := range abciResponses.DeliverTxs { for _, tx := range abciResponses.DeliverTxs {
if tx != nil { if tx != nil {
dtxs = append(dtxs, tx) dtxs = append(dtxs, tx)


+ 0
- 1
state/txindex/kv/kv.go View File

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


+ 1
- 1
store/store.go View File

@ -488,7 +488,7 @@ func LoadBlockStoreState(db dbm.DB) tmstore.BlockStoreState {
return bsj return bsj
} }
//mustEncode proto encodes a proto.message and panics if fails
// mustEncode proto encodes a proto.message and panics if fails
func mustEncode(pb proto.Message) []byte { func mustEncode(pb proto.Message) []byte {
bz, err := proto.Marshal(pb) bz, err := proto.Marshal(pb)
if err != nil { if err != nil {


+ 0
- 4
types/events.go View File

@ -38,9 +38,7 @@ const (
EventVote = "Vote" EventVote = "Vote"
) )
///////////////////////////////////////////////////////////////////////////////
// ENCODING / DECODING // ENCODING / DECODING
///////////////////////////////////////////////////////////////////////////////
// TMEventData implements events.EventData. // TMEventData implements events.EventData.
type TMEventData interface { type TMEventData interface {
@ -127,9 +125,7 @@ type EventDataValidatorSetUpdates struct {
ValidatorUpdates []*Validator `json:"validator_updates"` ValidatorUpdates []*Validator `json:"validator_updates"`
} }
///////////////////////////////////////////////////////////////////////////////
// PUBSUB // PUBSUB
///////////////////////////////////////////////////////////////////////////////
const ( const (
// EventTypeKey is a reserved composite key for event name. // EventTypeKey is a reserved composite key for event name.


+ 1
- 1
types/part_set_test.go View File

@ -35,7 +35,7 @@ func TestBasicPartSet(t *testing.T) {
assert.True(t, partSet2.HasHeader(partSet.Header())) assert.True(t, partSet2.HasHeader(partSet.Header()))
for i := 0; i < int(partSet.Total()); i++ { for i := 0; i < int(partSet.Total()); i++ {
part := partSet.GetPart(i) part := partSet.GetPart(i)
//t.Logf("\n%v", part)
// t.Logf("\n%v", part)
added, err := partSet2.AddPart(part) added, err := partSet2.AddPart(part)
if !added || err != nil { if !added || err != nil {
t.Errorf("failed to add part %v, error: %v", i, err) t.Errorf("failed to add part %v, error: %v", i, err)


+ 1
- 3
types/priv_validator.go View File

@ -39,9 +39,7 @@ func (pvs PrivValidatorsByAddress) Less(i, j int) bool {
} }
func (pvs PrivValidatorsByAddress) Swap(i, j int) { 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]
} }
//---------------------------------------- //----------------------------------------


+ 0
- 3
types/validator_set.go View File

@ -708,9 +708,7 @@ func (vals *ValidatorSet) VerifyCommit(chainID string, blockID BlockID,
return nil return nil
} }
///////////////////////////////////////////////////////////////////////////////
// LIGHT CLIENT VERIFICATION METHODS // LIGHT CLIENT VERIFICATION METHODS
///////////////////////////////////////////////////////////////////////////////
// VerifyCommitLight verifies +2/3 of the set had signed the given commit. // VerifyCommitLight verifies +2/3 of the set had signed the given commit.
// //
@ -1026,7 +1024,6 @@ func RandValidatorSet(numValidators int, votingPower int64) (*ValidatorSet, []Pr
return NewValidatorSet(valz), privValidators return NewValidatorSet(valz), privValidators
} }
///////////////////////////////////////////////////////////////////////////////
// safe addition/subtraction/multiplication // safe addition/subtraction/multiplication
func safeAdd(a, b int64) (int64, bool) { func safeAdd(a, b int64) (int64, bool) {


+ 2
- 6
types/validator_set_test.go View File

@ -1658,9 +1658,7 @@ func (valz validatorsByPriority) Less(i, j int) bool {
} }
func (valz validatorsByPriority) Swap(i, j int) { 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]
} }
//------------------------------------- //-------------------------------------
@ -1679,9 +1677,7 @@ func (tvals testValsByVotingPower) Less(i, j int) bool {
} }
func (tvals testValsByVotingPower) Swap(i, j int) { func (tvals testValsByVotingPower) Swap(i, j int) {
it := tvals[i]
tvals[i] = tvals[j]
tvals[j] = it
tvals[i], tvals[j] = tvals[j], tvals[i]
} }
//------------------------------------- //-------------------------------------


+ 1
- 1
types/vote.go View File

@ -220,7 +220,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 // return type, nil if everything converts safely, otherwise nil, error
func VoteFromProto(pv *tmproto.Vote) (*Vote, error) { func VoteFromProto(pv *tmproto.Vote) (*Vote, error) {
if pv == nil { if pv == nil {


Loading…
Cancel
Save