Browse Source

Fix lint errors (#1390)

* use increment and decrement operators.

* remove unnecessary else branches.

* fix package comment with leading space.

* fix receiver names.

* fix error strings.

* remove omittable code.

* remove redundant return statement.

* Revert changes (code is generated.)

* use cfg as receiver name for all config-related types.

* use lsi as the receiver name for the LastSignedInfo type.
pull/1378/head
Thomas Corbière 7 years ago
committed by Anton Kaliaev
parent
commit
2644a529f0
40 changed files with 262 additions and 299 deletions
  1. +1
    -2
      cmd/tendermint/commands/run_node.go
  2. +36
    -36
      config/config.go
  3. +2
    -2
      consensus/common_test.go
  4. +5
    -6
      consensus/mempool_test.go
  5. +4
    -6
      consensus/reactor.go
  6. +1
    -1
      consensus/reactor_test.go
  7. +6
    -6
      consensus/replay.go
  8. +8
    -9
      consensus/replay_file.go
  9. +3
    -3
      consensus/replay_test.go
  10. +9
    -10
      consensus/state.go
  11. +6
    -7
      node/node.go
  12. +4
    -4
      p2p/base_reactor.go
  13. +1
    -2
      p2p/conn/connection.go
  14. +3
    -4
      p2p/conn/secret_connection.go
  15. +1
    -1
      p2p/conn/secret_connection_test.go
  16. +2
    -3
      p2p/key.go
  17. +2
    -2
      p2p/netaddress.go
  18. +1
    -2
      p2p/peer_set.go
  19. +1
    -1
      p2p/peer_set_test.go
  20. +1
    -1
      p2p/pex/known_address.go
  21. +1
    -2
      p2p/pex/pex_reactor.go
  22. +1
    -1
      p2p/test_util.go
  23. +1
    -1
      p2p/upnp/upnp.go
  24. +2
    -2
      rpc/core/tx.go
  25. +13
    -13
      rpc/lib/client/ws_client.go
  26. +1
    -2
      rpc/lib/types/types.go
  27. +1
    -0
      scripts/wal2json/main.go
  28. +2
    -2
      state/state_test.go
  29. +1
    -2
      state/txindex/kv/kv.go
  30. +1
    -1
      state/txindex/kv/kv_test.go
  31. +1
    -2
      types/block.go
  32. +1
    -1
      types/block_test.go
  33. +1
    -1
      types/evidence.go
  34. +1
    -2
      types/genesis.go
  35. +13
    -17
      types/part_set.go
  36. +60
    -60
      types/priv_validator.go
  37. +23
    -23
      types/priv_validator/sign_info.go
  38. +21
    -28
      types/validator_set.go
  39. +1
    -1
      types/validator_set_test.go
  40. +19
    -30
      types/vote_set.go

+ 1
- 2
cmd/tendermint/commands/run_node.go View File

@ -57,9 +57,8 @@ func NewRunNodeCmd(nodeProvider nm.NodeProvider) *cobra.Command {
if err := n.Start(); err != nil { if err := n.Start(); err != nil {
return fmt.Errorf("Failed to start node: %v", err) return fmt.Errorf("Failed to start node: %v", err)
} else {
logger.Info("Started node", "nodeInfo", n.Switch().NodeInfo())
} }
logger.Info("Started node", "nodeInfo", n.Switch().NodeInfo())
// Trap signal, run forever. // Trap signal, run forever.
n.RunForever() n.RunForever()


+ 36
- 36
config/config.go View File

@ -165,28 +165,28 @@ func TestBaseConfig() BaseConfig {
return cfg return cfg
} }
func (b BaseConfig) ChainID() string {
return b.chainID
func (cfg BaseConfig) ChainID() string {
return cfg.chainID
} }
// GenesisFile returns the full path to the genesis.json file // GenesisFile returns the full path to the genesis.json file
func (b BaseConfig) GenesisFile() string {
return rootify(b.Genesis, b.RootDir)
func (cfg BaseConfig) GenesisFile() string {
return rootify(cfg.Genesis, cfg.RootDir)
} }
// PrivValidatorFile returns the full path to the priv_validator.json file // PrivValidatorFile returns the full path to the priv_validator.json file
func (b BaseConfig) PrivValidatorFile() string {
return rootify(b.PrivValidator, b.RootDir)
func (cfg BaseConfig) PrivValidatorFile() string {
return rootify(cfg.PrivValidator, cfg.RootDir)
} }
// NodeKeyFile returns the full path to the node_key.json file // NodeKeyFile returns the full path to the node_key.json file
func (b BaseConfig) NodeKeyFile() string {
return rootify(b.NodeKey, b.RootDir)
func (cfg BaseConfig) NodeKeyFile() string {
return rootify(cfg.NodeKey, cfg.RootDir)
} }
// DBDir returns the full path to the database directory // DBDir returns the full path to the database directory
func (b BaseConfig) DBDir() string {
return rootify(b.DBPath, b.RootDir)
func (cfg BaseConfig) DBDir() string {
return rootify(cfg.DBPath, cfg.RootDir)
} }
// DefaultLogLevel returns a default log level of "error" // DefaultLogLevel returns a default log level of "error"
@ -321,8 +321,8 @@ func TestP2PConfig() *P2PConfig {
} }
// AddrBookFile returns the full path to the address book // AddrBookFile returns the full path to the address book
func (p *P2PConfig) AddrBookFile() string {
return rootify(p.AddrBook, p.RootDir)
func (cfg *P2PConfig) AddrBookFile() string {
return rootify(cfg.AddrBook, cfg.RootDir)
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -357,8 +357,8 @@ func TestMempoolConfig() *MempoolConfig {
} }
// WalDir returns the full path to the mempool's write-ahead log // WalDir returns the full path to the mempool's write-ahead log
func (m *MempoolConfig) WalDir() string {
return rootify(m.WalPath, m.RootDir)
func (cfg *MempoolConfig) WalDir() string {
return rootify(cfg.WalPath, cfg.RootDir)
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -436,56 +436,56 @@ func TestConsensusConfig() *ConsensusConfig {
} }
// WaitForTxs returns true if the consensus should wait for transactions before entering the propose step // WaitForTxs returns true if the consensus should wait for transactions before entering the propose step
func (c *ConsensusConfig) WaitForTxs() bool {
return !c.CreateEmptyBlocks || c.CreateEmptyBlocksInterval > 0
func (cfg *ConsensusConfig) WaitForTxs() bool {
return !cfg.CreateEmptyBlocks || cfg.CreateEmptyBlocksInterval > 0
} }
// EmptyBlocks returns the amount of time to wait before proposing an empty block or starting the propose timer if there are no txs available // EmptyBlocks returns the amount of time to wait before proposing an empty block or starting the propose timer if there are no txs available
func (c *ConsensusConfig) EmptyBlocksInterval() time.Duration {
return time.Duration(c.CreateEmptyBlocksInterval) * time.Second
func (cfg *ConsensusConfig) EmptyBlocksInterval() time.Duration {
return time.Duration(cfg.CreateEmptyBlocksInterval) * time.Second
} }
// Propose returns the amount of time to wait for a proposal // Propose returns the amount of time to wait for a proposal
func (c *ConsensusConfig) Propose(round int) time.Duration {
return time.Duration(c.TimeoutPropose+c.TimeoutProposeDelta*round) * time.Millisecond
func (cfg *ConsensusConfig) Propose(round int) time.Duration {
return time.Duration(cfg.TimeoutPropose+cfg.TimeoutProposeDelta*round) * time.Millisecond
} }
// Prevote returns the amount of time to wait for straggler votes after receiving any +2/3 prevotes // Prevote returns the amount of time to wait for straggler votes after receiving any +2/3 prevotes
func (c *ConsensusConfig) Prevote(round int) time.Duration {
return time.Duration(c.TimeoutPrevote+c.TimeoutPrevoteDelta*round) * time.Millisecond
func (cfg *ConsensusConfig) Prevote(round int) time.Duration {
return time.Duration(cfg.TimeoutPrevote+cfg.TimeoutPrevoteDelta*round) * time.Millisecond
} }
// Precommit returns the amount of time to wait for straggler votes after receiving any +2/3 precommits // Precommit returns the amount of time to wait for straggler votes after receiving any +2/3 precommits
func (c *ConsensusConfig) Precommit(round int) time.Duration {
return time.Duration(c.TimeoutPrecommit+c.TimeoutPrecommitDelta*round) * time.Millisecond
func (cfg *ConsensusConfig) Precommit(round int) time.Duration {
return time.Duration(cfg.TimeoutPrecommit+cfg.TimeoutPrecommitDelta*round) * time.Millisecond
} }
// Commit returns the amount of time to wait for straggler votes after receiving +2/3 precommits for a single block (ie. a commit). // Commit returns the amount of time to wait for straggler votes after receiving +2/3 precommits for a single block (ie. a commit).
func (c *ConsensusConfig) Commit(t time.Time) time.Time {
return t.Add(time.Duration(c.TimeoutCommit) * time.Millisecond)
func (cfg *ConsensusConfig) Commit(t time.Time) time.Time {
return t.Add(time.Duration(cfg.TimeoutCommit) * time.Millisecond)
} }
// PeerGossipSleep returns the amount of time to sleep if there is nothing to send from the ConsensusReactor // PeerGossipSleep returns the amount of time to sleep if there is nothing to send from the ConsensusReactor
func (c *ConsensusConfig) PeerGossipSleep() time.Duration {
return time.Duration(c.PeerGossipSleepDuration) * time.Millisecond
func (cfg *ConsensusConfig) PeerGossipSleep() time.Duration {
return time.Duration(cfg.PeerGossipSleepDuration) * time.Millisecond
} }
// PeerQueryMaj23Sleep returns the amount of time to sleep after each VoteSetMaj23Message is sent in the ConsensusReactor // PeerQueryMaj23Sleep returns the amount of time to sleep after each VoteSetMaj23Message is sent in the ConsensusReactor
func (c *ConsensusConfig) PeerQueryMaj23Sleep() time.Duration {
return time.Duration(c.PeerQueryMaj23SleepDuration) * time.Millisecond
func (cfg *ConsensusConfig) PeerQueryMaj23Sleep() time.Duration {
return time.Duration(cfg.PeerQueryMaj23SleepDuration) * time.Millisecond
} }
// WalFile returns the full path to the write-ahead log file // WalFile returns the full path to the write-ahead log file
func (c *ConsensusConfig) WalFile() string {
if c.walFile != "" {
return c.walFile
func (cfg *ConsensusConfig) WalFile() string {
if cfg.walFile != "" {
return cfg.walFile
} }
return rootify(c.WalPath, c.RootDir)
return rootify(cfg.WalPath, cfg.RootDir)
} }
// SetWalFile sets the path to the write-ahead log file // SetWalFile sets the path to the write-ahead log file
func (c *ConsensusConfig) SetWalFile(walFile string) {
c.walFile = walFile
func (cfg *ConsensusConfig) SetWalFile(walFile string) {
cfg.walFile = walFile
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------


+ 2
- 2
consensus/common_test.go View File

@ -101,13 +101,13 @@ func signVotes(voteType byte, hash []byte, header types.PartSetHeader, vss ...*v
func incrementHeight(vss ...*validatorStub) { func incrementHeight(vss ...*validatorStub) {
for _, vs := range vss { for _, vs := range vss {
vs.Height += 1
vs.Height++
} }
} }
func incrementRound(vss ...*validatorStub) { func incrementRound(vss ...*validatorStub) {
for _, vs := range vss { for _, vs := range vss {
vs.Round += 1
vs.Round++
} }
} }


+ 5
- 6
consensus/mempool_test.go View File

@ -200,7 +200,7 @@ func (app *CounterApplication) DeliverTx(tx []byte) abci.ResponseDeliverTx {
Code: code.CodeTypeBadNonce, Code: code.CodeTypeBadNonce,
Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.txCount, txValue)} Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.txCount, txValue)}
} }
app.txCount += 1
app.txCount++
return abci.ResponseDeliverTx{Code: code.CodeTypeOK} return abci.ResponseDeliverTx{Code: code.CodeTypeOK}
} }
@ -211,7 +211,7 @@ func (app *CounterApplication) CheckTx(tx []byte) abci.ResponseCheckTx {
Code: code.CodeTypeBadNonce, Code: code.CodeTypeBadNonce,
Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.mempoolTxCount, txValue)} Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.mempoolTxCount, txValue)}
} }
app.mempoolTxCount += 1
app.mempoolTxCount++
return abci.ResponseCheckTx{Code: code.CodeTypeOK} return abci.ResponseCheckTx{Code: code.CodeTypeOK}
} }
@ -225,9 +225,8 @@ func (app *CounterApplication) Commit() abci.ResponseCommit {
app.mempoolTxCount = app.txCount app.mempoolTxCount = app.txCount
if app.txCount == 0 { if app.txCount == 0 {
return abci.ResponseCommit{} return abci.ResponseCommit{}
} else {
hash := make([]byte, 8)
binary.BigEndian.PutUint64(hash, uint64(app.txCount))
return abci.ResponseCommit{Data: hash}
} }
hash := make([]byte, 8)
binary.BigEndian.PutUint64(hash, uint64(app.txCount))
return abci.ResponseCommit{Data: hash}
} }

+ 4
- 6
consensus/reactor.go View File

@ -602,11 +602,9 @@ func (conR *ConsensusReactor) gossipDataForCatchup(logger log.Logger, rs *cstype
logger.Debug("Sending block part for catchup failed") logger.Debug("Sending block part for catchup failed")
} }
return return
} else {
//logger.Info("No parts to send in catch-up, sleeping")
time.Sleep(conR.conS.config.PeerGossipSleep())
return
} }
//logger.Info("No parts to send in catch-up, sleeping")
time.Sleep(conR.conS.config.PeerGossipSleep())
} }
func (conR *ConsensusReactor) gossipVotesRoutine(peer p2p.Peer, ps *PeerState) { func (conR *ConsensusReactor) gossipVotesRoutine(peer p2p.Peer, ps *PeerState) {
@ -1087,7 +1085,7 @@ func (ps *PeerState) RecordVote(vote *types.Vote) int {
return ps.stats.votes return ps.stats.votes
} }
ps.stats.lastVoteHeight = vote.Height ps.stats.lastVoteHeight = vote.Height
ps.stats.votes += 1
ps.stats.votes++
return ps.stats.votes return ps.stats.votes
} }
@ -1106,7 +1104,7 @@ func (ps *PeerState) RecordBlockPart(bp *BlockPartMessage) int {
} }
ps.stats.lastBlockPartHeight = bp.Height ps.stats.lastBlockPartHeight = bp.Height
ps.stats.blockParts += 1
ps.stats.blockParts++
return ps.stats.blockParts return ps.stats.blockParts
} }


+ 1
- 1
consensus/reactor_test.go View File

@ -441,7 +441,7 @@ func waitForAndValidateBlockWithTx(t *testing.T, n int, activeVals map[string]st
// but they should be in order. // but they should be in order.
for _, tx := range newBlock.Data.Txs { for _, tx := range newBlock.Data.Txs {
assert.EqualValues(t, txs[ntxs], tx) assert.EqualValues(t, txs[ntxs], tx)
ntxs += 1
ntxs++
} }
if ntxs == len(txs) { if ntxs == len(txs) {


+ 6
- 6
consensus/replay.go View File

@ -112,7 +112,7 @@ func (cs *ConsensusState) catchupReplay(csHeight int64) error {
} }
} }
if found { if found {
return fmt.Errorf("WAL should not contain #ENDHEIGHT %d.", csHeight)
return fmt.Errorf("WAL should not contain #ENDHEIGHT %d", csHeight)
} }
// Search for last height marker // Search for last height marker
@ -125,7 +125,7 @@ func (cs *ConsensusState) catchupReplay(csHeight int64) error {
return err return err
} }
if !found { if !found {
return fmt.Errorf("Cannot replay height %d. WAL does not contain #ENDHEIGHT for %d.", csHeight, csHeight-1)
return fmt.Errorf("Cannot replay height %d. WAL does not contain #ENDHEIGHT for %d", csHeight, csHeight-1)
} }
defer gr.Close() // nolint: errcheck defer gr.Close() // nolint: errcheck
@ -352,7 +352,7 @@ func (h *Handshaker) replayBlocks(state sm.State, proxyApp proxy.AppConns, appBl
var err error var err error
finalBlock := storeBlockHeight finalBlock := storeBlockHeight
if mutateState { if mutateState {
finalBlock -= 1
finalBlock--
} }
for i := appBlockHeight + 1; i <= finalBlock; i++ { for i := appBlockHeight + 1; i <= finalBlock; i++ {
h.logger.Info("Applying block", "height", i) h.logger.Info("Applying block", "height", i)
@ -362,7 +362,7 @@ func (h *Handshaker) replayBlocks(state sm.State, proxyApp proxy.AppConns, appBl
return nil, err return nil, err
} }
h.nBlocks += 1
h.nBlocks++
} }
if mutateState { if mutateState {
@ -390,7 +390,7 @@ func (h *Handshaker) replayBlock(state sm.State, height int64, proxyApp proxy.Ap
return sm.State{}, err return sm.State{}, err
} }
h.nBlocks += 1
h.nBlocks++
return state, nil return state, nil
} }
@ -429,7 +429,7 @@ type mockProxyApp struct {
func (mock *mockProxyApp) DeliverTx(tx []byte) abci.ResponseDeliverTx { func (mock *mockProxyApp) DeliverTx(tx []byte) abci.ResponseDeliverTx {
r := mock.abciResponses.DeliverTx[mock.txCount] r := mock.abciResponses.DeliverTx[mock.txCount]
mock.txCount += 1
mock.txCount++
return *r return *r
} }


+ 8
- 9
consensus/replay_file.go View File

@ -87,9 +87,9 @@ func (cs *ConsensusState) ReplayFile(file string, console bool) error {
} }
if nextN > 0 { if nextN > 0 {
nextN -= 1
nextN--
} }
pb.count += 1
pb.count++
} }
return nil return nil
} }
@ -153,7 +153,7 @@ func (pb *playback) replayReset(count int, newStepCh chan interface{}) error {
if err := pb.cs.readReplayMessage(msg, newStepCh); err != nil { if err := pb.cs.readReplayMessage(msg, newStepCh); err != nil {
return err return err
} }
pb.count += 1
pb.count++
} }
return nil return nil
} }
@ -197,13 +197,12 @@ func (pb *playback) replayConsoleLoop() int {
if len(tokens) == 1 { if len(tokens) == 1 {
return 0 return 0
}
i, err := strconv.Atoi(tokens[1])
if err != nil {
fmt.Println("next takes an integer argument")
} else { } else {
i, err := strconv.Atoi(tokens[1])
if err != nil {
fmt.Println("next takes an integer argument")
} else {
return i
}
return i
} }
case "back": case "back":


+ 3
- 3
consensus/replay_test.go View File

@ -382,9 +382,9 @@ func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) {
expectedBlocksToSync := NUM_BLOCKS - nBlocks expectedBlocksToSync := NUM_BLOCKS - nBlocks
if nBlocks == NUM_BLOCKS && mode > 0 { if nBlocks == NUM_BLOCKS && mode > 0 {
expectedBlocksToSync += 1
expectedBlocksToSync++
} else if nBlocks > 0 && mode == 1 { } else if nBlocks > 0 && mode == 1 {
expectedBlocksToSync += 1
expectedBlocksToSync++
} }
if handshaker.NBlocks() != expectedBlocksToSync { if handshaker.NBlocks() != expectedBlocksToSync {
@ -533,7 +533,7 @@ func makeBlockchainFromWAL(wal WAL) ([]*types.Block, []*types.Commit, error) {
} }
blocks = append(blocks, block) blocks = append(blocks, block)
commits = append(commits, thisBlockCommit) commits = append(commits, thisBlockCommit)
height += 1
height++
} }
case *types.PartSetHeader: case *types.PartSetHeader:
thisBlockParts = types.NewPartSetFromHeader(*p) thisBlockParts = types.NewPartSetFromHeader(*p)


+ 9
- 10
consensus/state.go View File

@ -494,7 +494,7 @@ func (cs *ConsensusState) updateToState(state sm.State) {
func (cs *ConsensusState) newStep() { func (cs *ConsensusState) newStep() {
rs := cs.RoundStateEvent() rs := cs.RoundStateEvent()
cs.wal.Save(rs) cs.wal.Save(rs)
cs.nSteps += 1
cs.nSteps++
// newStep is called by updateToStep in NewConsensusState before the eventBus is set! // newStep is called by updateToStep in NewConsensusState before the eventBus is set!
if cs.eventBus != nil { if cs.eventBus != nil {
cs.eventBus.PublishEventNewRoundStep(rs) cs.eventBus.PublishEventNewRoundStep(rs)
@ -741,7 +741,7 @@ func (cs *ConsensusState) proposalHeartbeat(height int64, round int) {
} }
cs.privValidator.SignHeartbeat(chainID, heartbeat) cs.privValidator.SignHeartbeat(chainID, heartbeat)
cs.eventBus.PublishEventProposalHeartbeat(types.EventDataProposalHeartbeat{heartbeat}) cs.eventBus.PublishEventProposalHeartbeat(types.EventDataProposalHeartbeat{heartbeat})
counter += 1
counter++
time.Sleep(proposalHeartbeatIntervalSeconds * time.Second) time.Sleep(proposalHeartbeatIntervalSeconds * time.Second)
} }
} }
@ -852,10 +852,10 @@ func (cs *ConsensusState) isProposalComplete() bool {
// make sure we have the prevotes from it too // make sure we have the prevotes from it too
if cs.Proposal.POLRound < 0 { if cs.Proposal.POLRound < 0 {
return true return true
} else {
// if this is false the proposer is lying or we haven't received the POL yet
return cs.Votes.Prevotes(cs.Proposal.POLRound).HasTwoThirdsMajority()
} }
// if this is false the proposer is lying or we haven't received the POL yet
return cs.Votes.Prevotes(cs.Proposal.POLRound).HasTwoThirdsMajority()
} }
// Create the next block to propose and return it. // Create the next block to propose and return it.
@ -1498,12 +1498,11 @@ func (cs *ConsensusState) signAddVote(type_ byte, hash []byte, header types.Part
cs.sendInternalMessage(msgInfo{&VoteMessage{vote}, ""}) cs.sendInternalMessage(msgInfo{&VoteMessage{vote}, ""})
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
} else {
//if !cs.replayMode {
cs.Logger.Error("Error signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "err", err)
//}
return nil
} }
//if !cs.replayMode {
cs.Logger.Error("Error signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "err", err)
//}
return nil
} }
//--------------------------------------------------------- //---------------------------------------------------------


+ 6
- 7
node/node.go View File

@ -643,14 +643,13 @@ func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
bytes := db.Get(genesisDocKey) bytes := db.Get(genesisDocKey)
if len(bytes) == 0 { if len(bytes) == 0 {
return nil, errors.New("Genesis doc not found") return nil, errors.New("Genesis doc not found")
} else {
var genDoc *types.GenesisDoc
err := json.Unmarshal(bytes, &genDoc)
if err != nil {
cmn.PanicCrisis(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, bytes))
}
return genDoc, nil
} }
var genDoc *types.GenesisDoc
err := json.Unmarshal(bytes, &genDoc)
if err != nil {
cmn.PanicCrisis(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, bytes))
}
return genDoc, nil
} }
// panics if failed to marshal the given genesis document // panics if failed to marshal the given genesis document


+ 4
- 4
p2p/base_reactor.go View File

@ -47,7 +47,7 @@ func NewBaseReactor(name string, impl Reactor) *BaseReactor {
func (br *BaseReactor) SetSwitch(sw *Switch) { func (br *BaseReactor) SetSwitch(sw *Switch) {
br.Switch = sw br.Switch = sw
} }
func (_ *BaseReactor) GetChannels() []*conn.ChannelDescriptor { return nil }
func (_ *BaseReactor) AddPeer(peer Peer) {}
func (_ *BaseReactor) RemovePeer(peer Peer, reason interface{}) {}
func (_ *BaseReactor) Receive(chID byte, peer Peer, msgBytes []byte) {}
func (*BaseReactor) GetChannels() []*conn.ChannelDescriptor { return nil }
func (*BaseReactor) AddPeer(peer Peer) {}
func (*BaseReactor) RemovePeer(peer Peer, reason interface{}) {}
func (*BaseReactor) Receive(chID byte, peer Peer, msgBytes []byte) {}

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

@ -422,9 +422,8 @@ func (c *MConnection) sendMsgPacket() bool {
// Nothing to send? // Nothing to send?
if leastChannel == nil { if leastChannel == nil {
return true return true
} else {
// c.Logger.Info("Found a msgPacket to send")
} }
// c.Logger.Info("Found a msgPacket to send")
// Make & send a msgPacket from this channel // Make & send a msgPacket from this channel
n, err := leastChannel.writeMsgPacketTo(c.bufWriter) n, err := leastChannel.writeMsgPacketTo(c.bufWriter)


+ 3
- 4
p2p/conn/secret_connection.go View File

@ -113,7 +113,7 @@ func (sc *SecretConnection) RemotePubKey() crypto.PubKey {
// CONTRACT: data smaller than dataMaxSize is read atomically. // CONTRACT: data smaller than dataMaxSize is read atomically.
func (sc *SecretConnection) Write(data []byte) (n int, err error) { func (sc *SecretConnection) Write(data []byte) (n int, err error) {
for 0 < len(data) { for 0 < len(data) {
var frame []byte = make([]byte, totalFrameSize)
var frame = make([]byte, totalFrameSize)
var chunk []byte var chunk []byte
if dataMaxSize < len(data) { if dataMaxSize < len(data) {
chunk = data[:dataMaxSize] chunk = data[:dataMaxSize]
@ -136,9 +136,8 @@ func (sc *SecretConnection) Write(data []byte) (n int, err error) {
_, err := sc.conn.Write(sealedFrame) _, err := sc.conn.Write(sealedFrame)
if err != nil { if err != nil {
return n, err return n, err
} else {
n += len(chunk)
} }
n += len(chunk)
} }
return return
} }
@ -347,7 +346,7 @@ func incr2Nonce(nonce *[24]byte) {
// increment nonce big-endian by 1 with wraparound. // increment nonce big-endian by 1 with wraparound.
func incrNonce(nonce *[24]byte) { func incrNonce(nonce *[24]byte) {
for i := 23; 0 <= i; i-- { for i := 23; 0 <= i; i-- {
nonce[i] += 1
nonce[i]++
if nonce[i] != 0 { if nonce[i] != 0 {
return return
} }


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

@ -180,7 +180,7 @@ func TestSecretConnectionReadWrite(t *testing.T) {
var readCount = 0 var readCount = 0
for _, readChunk := range reads { for _, readChunk := range reads {
read += readChunk read += readChunk
readCount += 1
readCount++
if len(write) <= len(read) { if len(write) <= len(read) {
break break
} }


+ 2
- 3
p2p/key.go View File

@ -53,9 +53,8 @@ func LoadOrGenNodeKey(filePath string) (*NodeKey, error) {
return nil, err return nil, err
} }
return nodeKey, nil return nodeKey, nil
} else {
return genNodeKey(filePath)
} }
return genNodeKey(filePath)
} }
func loadNodeKey(filePath string) (*NodeKey, error) { func loadNodeKey(filePath string) (*NodeKey, error) {
@ -66,7 +65,7 @@ func loadNodeKey(filePath string) (*NodeKey, error) {
nodeKey := new(NodeKey) nodeKey := new(NodeKey)
err = json.Unmarshal(jsonBytes, nodeKey) err = json.Unmarshal(jsonBytes, nodeKey)
if err != nil { if err != nil {
return nil, fmt.Errorf("Error reading NodeKey from %v: %v\n", filePath, err)
return nil, fmt.Errorf("Error reading NodeKey from %v: %v", filePath, err)
} }
return nodeKey, nil return nodeKey, nil
} }


+ 2
- 2
p2p/netaddress.go View File

@ -294,7 +294,7 @@ func (na *NetAddress) RFC6145() bool { return rfc6145.Contains(na.IP) }
func removeProtocolIfDefined(addr string) string { func removeProtocolIfDefined(addr string) string {
if strings.Contains(addr, "://") { if strings.Contains(addr, "://") {
return strings.Split(addr, "://")[1] return strings.Split(addr, "://")[1]
} else {
return addr
} }
return addr
} }

+ 1
- 2
p2p/peer_set.go View File

@ -68,9 +68,8 @@ func (ps *PeerSet) Get(peerKey ID) Peer {
item, ok := ps.lookup[peerKey] item, ok := ps.lookup[peerKey]
if ok { if ok {
return item.peer return item.peer
} else {
return nil
} }
return nil
} }
// Remove discards peer by its Key, if the peer was previously memoized. // Remove discards peer by its Key, if the peer was previously memoized.


+ 1
- 1
p2p/peer_set_test.go View File

@ -115,7 +115,7 @@ func TestPeerSetAddDuplicate(t *testing.T) {
errsTally := make(map[error]int) errsTally := make(map[error]int)
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
err := <-errsChan err := <-errsChan
errsTally[err] += 1
errsTally[err]++
} }
// Our next procedure is to ensure that only one addition // Our next procedure is to ensure that only one addition


+ 1
- 1
p2p/pex/known_address.go View File

@ -56,7 +56,7 @@ func (ka *knownAddress) isNew() bool {
func (ka *knownAddress) markAttempt() { func (ka *knownAddress) markAttempt() {
now := time.Now() now := time.Now()
ka.LastAttempt = now ka.LastAttempt = now
ka.Attempts += 1
ka.Attempts++
} }
func (ka *knownAddress) markGood() { func (ka *knownAddress) markGood() {


+ 1
- 2
p2p/pex/pex_reactor.go View File

@ -467,9 +467,8 @@ func (r *PEXReactor) AttemptsToDial(addr *p2p.NetAddress) int {
lAttempts, attempted := r.attemptsToDial.Load(addr.DialString()) lAttempts, attempted := r.attemptsToDial.Load(addr.DialString())
if attempted { if attempted {
return lAttempts.(_attemptsToDial).number return lAttempts.(_attemptsToDial).number
} else {
return 0
} }
return 0
} }
//---------------------------------------------------------- //----------------------------------------------------------


+ 1
- 1
p2p/test_util.go View File

@ -143,7 +143,7 @@ func MakeSwitch(cfg *cfg.P2PConfig, i int, network, version string, initSwitch f
Version: version, Version: version,
ListenAddr: cmn.Fmt("%v:%v", network, rand.Intn(64512)+1023), ListenAddr: cmn.Fmt("%v:%v", network, rand.Intn(64512)+1023),
} }
for ch, _ := range sw.reactorsByCh {
for ch := range sw.reactorsByCh {
ni.Channels = append(ni.Channels, ch) ni.Channels = append(ni.Channels, ch)
} }
sw.SetNodeInfo(ni) sw.SetNodeInfo(ni)


+ 1
- 1
p2p/upnp/upnp.go View File

@ -103,7 +103,7 @@ func Discover() (nat NAT, err error) {
return return
} }
} }
err = errors.New("UPnP port discovery failed.")
err = errors.New("UPnP port discovery failed")
return return
} }


+ 2
- 2
rpc/core/tx.go View File

@ -73,7 +73,7 @@ func Tx(hash []byte, prove bool) (*ctypes.ResultTx, error) {
// if index is disabled, return error // if index is disabled, return error
if _, ok := txIndexer.(*null.TxIndex); ok { if _, ok := txIndexer.(*null.TxIndex); ok {
return nil, fmt.Errorf("Transaction indexing is disabled.")
return nil, fmt.Errorf("Transaction indexing is disabled")
} }
r, err := txIndexer.Get(hash) r, err := txIndexer.Get(hash)
@ -169,7 +169,7 @@ func Tx(hash []byte, prove bool) (*ctypes.ResultTx, error) {
func TxSearch(query string, prove bool) ([]*ctypes.ResultTx, error) { func TxSearch(query string, prove bool) ([]*ctypes.ResultTx, error) {
// if index is disabled, return error // if index is disabled, return error
if _, ok := txIndexer.(*null.TxIndex); ok { if _, ok := txIndexer.(*null.TxIndex); ok {
return nil, fmt.Errorf("Transaction indexing is disabled.")
return nil, fmt.Errorf("Transaction indexing is disabled")
} }
q, err := tmquery.New(query) q, err := tmquery.New(query)


+ 13
- 13
rpc/lib/client/ws_client.go View File

@ -318,21 +318,21 @@ func (c *WSClient) reconnectRoutine() {
c.Logger.Error("failed to reconnect", "err", err, "original_err", originalError) c.Logger.Error("failed to reconnect", "err", err, "original_err", originalError)
c.Stop() c.Stop()
return return
} else {
// drain reconnectAfter
LOOP:
for {
select {
case <-c.reconnectAfter:
default:
break LOOP
}
}
err = c.processBacklog()
if err == nil {
c.startReadWriteRoutines()
}
// drain reconnectAfter
LOOP:
for {
select {
case <-c.reconnectAfter:
default:
break LOOP
} }
} }
err := c.processBacklog()
if err == nil {
c.startReadWriteRoutines()
}
case <-c.Quit(): case <-c.Quit():
return return
} }


+ 1
- 2
rpc/lib/types/types.go View File

@ -101,9 +101,8 @@ func NewRPCErrorResponse(id string, code int, msg string, data string) RPCRespon
func (resp RPCResponse) String() string { func (resp RPCResponse) String() string {
if resp.Error == nil { if resp.Error == nil {
return fmt.Sprintf("[%s %v]", resp.ID, resp.Result) return fmt.Sprintf("[%s %v]", resp.ID, resp.Result)
} else {
return fmt.Sprintf("[%s %s]", resp.ID, resp.Error)
} }
return fmt.Sprintf("[%s %s]", resp.ID, resp.Error)
} }
func RPCParseError(id string, err error) RPCResponse { func RPCParseError(id string, err error) RPCResponse {


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

@ -4,6 +4,7 @@
Usage: Usage:
wal2json <path-to-wal> wal2json <path-to-wal>
*/ */
package main package main
import ( import (


+ 2
- 2
state/state_test.go View File

@ -222,7 +222,7 @@ func TestOneValidatorChangesSaveLoad(t *testing.T) {
// use the next pubkey // use the next pubkey
if changeIndex < len(changeHeights) && i == changeHeights[changeIndex] { if changeIndex < len(changeHeights) && i == changeHeights[changeIndex] {
changeIndex++ changeIndex++
power += 1
power++
} }
header, blockID, responses := makeHeaderPartsResponsesValPowerChange(state, i, power) header, blockID, responses := makeHeaderPartsResponsesValPowerChange(state, i, power)
state, err = updateState(state, blockID, header, responses) state, err = updateState(state, blockID, header, responses)
@ -240,7 +240,7 @@ func TestOneValidatorChangesSaveLoad(t *testing.T) {
// use the next pubkey (note our counter starts at 0 this time) // use the next pubkey (note our counter starts at 0 this time)
if changeIndex < len(changeHeights) && i == changeHeights[changeIndex]+1 { if changeIndex < len(changeHeights) && i == changeHeights[changeIndex]+1 {
changeIndex++ changeIndex++
power += 1
power++
} }
testCases[i-1] = power testCases[i-1] = power
} }


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

@ -148,9 +148,8 @@ func (txi *TxIndex) Search(q *query.Query) ([]*types.TxResult, error) {
res, err := txi.Get(hash) res, err := txi.Get(hash)
if res == nil { if res == nil {
return []*types.TxResult{}, nil return []*types.TxResult{}, nil
} else {
return []*types.TxResult{res}, errors.Wrap(err, "error while retrieving the result")
} }
return []*types.TxResult{res}, errors.Wrap(err, "error while retrieving the result")
} }
// conditions to skip because they're handled before "everything else" // conditions to skip because they're handled before "everything else"


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

@ -196,7 +196,7 @@ func benchmarkTxIndex(txsCount int, b *testing.B) {
if err := batch.Add(txResult); err != nil { if err := batch.Add(txResult); err != nil {
b.Fatal(err) b.Fatal(err)
} }
txResult.Index += 1
txResult.Index++
} }
b.ResetTimer() b.ResetTimer()


+ 1
- 2
types/block.go View File

@ -141,9 +141,8 @@ func (b *Block) StringIndented(indent string) string {
func (b *Block) StringShort() string { func (b *Block) StringShort() string {
if b == nil { if b == nil {
return "nil-Block" return "nil-Block"
} else {
return fmt.Sprintf("Block#%v", b.Hash())
} }
return fmt.Sprintf("Block#%v", b.Hash())
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------


+ 1
- 1
types/block_test.go View File

@ -29,7 +29,7 @@ func TestValidateBlock(t *testing.T) {
// tamper with NumTxs // tamper with NumTxs
block = MakeBlock(h, txs, commit) block = MakeBlock(h, txs, commit)
block.NumTxs += 1
block.NumTxs++
err = block.ValidateBasic() err = block.ValidateBasic()
require.Error(t, err) require.Error(t, err)


+ 1
- 1
types/evidence.go View File

@ -144,7 +144,7 @@ func (dve *DuplicateVoteEvidence) Verify(chainID string) error {
// BlockIDs must be different // BlockIDs must be different
if dve.VoteA.BlockID.Equals(dve.VoteB.BlockID) { if dve.VoteA.BlockID.Equals(dve.VoteB.BlockID) {
return fmt.Errorf("DuplicateVoteEvidence Error: BlockIDs are the same (%v) - not a real duplicate vote!", dve.VoteA.BlockID)
return fmt.Errorf("DuplicateVoteEvidence Error: BlockIDs are the same (%v) - not a real duplicate vote", dve.VoteA.BlockID)
} }
// Signatures must be valid // Signatures must be valid


+ 1
- 2
types/genesis.go View File

@ -37,9 +37,8 @@ type GenesisDoc struct {
func (genDoc *GenesisDoc) AppState() json.RawMessage { func (genDoc *GenesisDoc) AppState() json.RawMessage {
if len(genDoc.AppOptions) > 0 { if len(genDoc.AppOptions) > 0 {
return genDoc.AppOptions return genDoc.AppOptions
} else {
return genDoc.AppStateJSON
} }
return genDoc.AppStateJSON
} }
// SaveAs is a utility method for saving GenensisDoc as a JSON file. // SaveAs is a utility method for saving GenensisDoc as a JSON file.


+ 13
- 17
types/part_set.go View File

@ -30,12 +30,11 @@ type Part struct {
func (part *Part) Hash() []byte { func (part *Part) Hash() []byte {
if part.hash != nil { if part.hash != nil {
return part.hash return part.hash
} else {
hasher := ripemd160.New()
hasher.Write(part.Bytes) // nolint: errcheck, gas
part.hash = hasher.Sum(nil)
return part.hash
} }
hasher := ripemd160.New()
hasher.Write(part.Bytes) // nolint: errcheck, gas
part.hash = hasher.Sum(nil)
return part.hash
} }
func (part *Part) String() string { func (part *Part) String() string {
@ -129,20 +128,18 @@ func NewPartSetFromHeader(header PartSetHeader) *PartSet {
func (ps *PartSet) Header() PartSetHeader { func (ps *PartSet) Header() PartSetHeader {
if ps == nil { if ps == nil {
return PartSetHeader{} return PartSetHeader{}
} else {
return PartSetHeader{
Total: ps.total,
Hash: ps.hash,
}
}
return PartSetHeader{
Total: ps.total,
Hash: ps.hash,
} }
} }
func (ps *PartSet) HasHeader(header PartSetHeader) bool { func (ps *PartSet) HasHeader(header PartSetHeader) bool {
if ps == nil { if ps == nil {
return false return false
} else {
return ps.Header().Equals(header)
} }
return ps.Header().Equals(header)
} }
func (ps *PartSet) BitArray() *cmn.BitArray { func (ps *PartSet) BitArray() *cmn.BitArray {
@ -251,7 +248,7 @@ func (psr *PartSetReader) Read(p []byte) (n int, err error) {
return n1 + n2, err return n1 + n2, err
} }
psr.i += 1
psr.i++
if psr.i >= len(psr.parts) { if psr.i >= len(psr.parts) {
return 0, io.EOF return 0, io.EOF
} }
@ -262,9 +259,8 @@ func (psr *PartSetReader) Read(p []byte) (n int, err error) {
func (ps *PartSet) StringShort() string { func (ps *PartSet) StringShort() string {
if ps == nil { if ps == nil {
return "nil-PartSet" return "nil-PartSet"
} else {
ps.mtx.Lock()
defer ps.mtx.Unlock()
return fmt.Sprintf("(%v of %v)", ps.Count(), ps.Total())
} }
ps.mtx.Lock()
defer ps.mtx.Unlock()
return fmt.Sprintf("(%v of %v)", ps.Count(), ps.Total())
} }

+ 60
- 60
types/priv_validator.go View File

@ -211,18 +211,18 @@ func LoadPrivValidatorFSWithSigner(filePath string, signerFunc func(PrivValidato
} }
// Save persists the PrivValidatorFS to disk. // Save persists the PrivValidatorFS to disk.
func (privVal *PrivValidatorFS) Save() {
privVal.mtx.Lock()
defer privVal.mtx.Unlock()
privVal.save()
func (pv *PrivValidatorFS) Save() {
pv.mtx.Lock()
defer pv.mtx.Unlock()
pv.save()
} }
func (privVal *PrivValidatorFS) save() {
outFile := privVal.filePath
func (pv *PrivValidatorFS) save() {
outFile := pv.filePath
if outFile == "" { if outFile == "" {
panic("Cannot save PrivValidator: filePath not set") panic("Cannot save PrivValidator: filePath not set")
} }
jsonBytes, err := json.Marshal(privVal)
jsonBytes, err := json.Marshal(pv)
if err != nil { if err != nil {
panic(err) panic(err)
} }
@ -234,22 +234,22 @@ func (privVal *PrivValidatorFS) save() {
// Reset resets all fields in the PrivValidatorFS. // Reset resets all fields in the PrivValidatorFS.
// NOTE: Unsafe! // NOTE: Unsafe!
func (privVal *PrivValidatorFS) Reset() {
func (pv *PrivValidatorFS) Reset() {
var sig crypto.Signature var sig crypto.Signature
privVal.LastHeight = 0
privVal.LastRound = 0
privVal.LastStep = 0
privVal.LastSignature = sig
privVal.LastSignBytes = nil
privVal.Save()
pv.LastHeight = 0
pv.LastRound = 0
pv.LastStep = 0
pv.LastSignature = sig
pv.LastSignBytes = nil
pv.Save()
} }
// SignVote signs a canonical representation of the vote, along with the // SignVote signs a canonical representation of the vote, along with the
// chainID. Implements PrivValidator. // chainID. Implements PrivValidator.
func (privVal *PrivValidatorFS) SignVote(chainID string, vote *Vote) error {
privVal.mtx.Lock()
defer privVal.mtx.Unlock()
if err := privVal.signVote(chainID, vote); err != nil {
func (pv *PrivValidatorFS) SignVote(chainID string, vote *Vote) error {
pv.mtx.Lock()
defer pv.mtx.Unlock()
if err := pv.signVote(chainID, vote); err != nil {
return errors.New(cmn.Fmt("Error signing vote: %v", err)) return errors.New(cmn.Fmt("Error signing vote: %v", err))
} }
return nil return nil
@ -257,32 +257,32 @@ func (privVal *PrivValidatorFS) SignVote(chainID string, vote *Vote) error {
// SignProposal signs a canonical representation of the proposal, along with // SignProposal signs a canonical representation of the proposal, along with
// the chainID. Implements PrivValidator. // the chainID. Implements PrivValidator.
func (privVal *PrivValidatorFS) SignProposal(chainID string, proposal *Proposal) error {
privVal.mtx.Lock()
defer privVal.mtx.Unlock()
if err := privVal.signProposal(chainID, proposal); err != nil {
func (pv *PrivValidatorFS) SignProposal(chainID string, proposal *Proposal) error {
pv.mtx.Lock()
defer pv.mtx.Unlock()
if err := pv.signProposal(chainID, proposal); err != nil {
return fmt.Errorf("Error signing proposal: %v", err) return fmt.Errorf("Error signing proposal: %v", err)
} }
return nil return nil
} }
// returns error if HRS regression or no LastSignBytes. returns true if HRS is unchanged // returns error if HRS regression or no LastSignBytes. returns true if HRS is unchanged
func (privVal *PrivValidatorFS) checkHRS(height int64, round int, step int8) (bool, error) {
if privVal.LastHeight > height {
func (pv *PrivValidatorFS) checkHRS(height int64, round int, step int8) (bool, error) {
if pv.LastHeight > height {
return false, errors.New("Height regression") return false, errors.New("Height regression")
} }
if privVal.LastHeight == height {
if privVal.LastRound > round {
if pv.LastHeight == height {
if pv.LastRound > round {
return false, errors.New("Round regression") return false, errors.New("Round regression")
} }
if privVal.LastRound == round {
if privVal.LastStep > step {
if pv.LastRound == round {
if pv.LastStep > step {
return false, errors.New("Step regression") return false, errors.New("Step regression")
} else if privVal.LastStep == step {
if privVal.LastSignBytes != nil {
if privVal.LastSignature.Empty() {
} else if pv.LastStep == step {
if pv.LastSignBytes != nil {
if pv.LastSignature.Empty() {
panic("privVal: LastSignature is nil but LastSignBytes is not!") panic("privVal: LastSignature is nil but LastSignBytes is not!")
} }
return true, nil return true, nil
@ -297,11 +297,11 @@ func (privVal *PrivValidatorFS) checkHRS(height int64, round int, step int8) (bo
// signVote checks if the vote is good to sign and sets the vote signature. // signVote checks if the vote is good to sign and sets the vote signature.
// It may need to set the timestamp as well if the vote is otherwise the same as // It may need to set the timestamp as well if the vote is otherwise the same as
// a previously signed vote (ie. we crashed after signing but before the vote hit the WAL). // a previously signed vote (ie. we crashed after signing but before the vote hit the WAL).
func (privVal *PrivValidatorFS) signVote(chainID string, vote *Vote) error {
func (pv *PrivValidatorFS) signVote(chainID string, vote *Vote) error {
height, round, step := vote.Height, vote.Round, voteToStep(vote) height, round, step := vote.Height, vote.Round, voteToStep(vote)
signBytes := vote.SignBytes(chainID) signBytes := vote.SignBytes(chainID)
sameHRS, err := privVal.checkHRS(height, round, step)
sameHRS, err := pv.checkHRS(height, round, step)
if err != nil { if err != nil {
return err return err
} }
@ -312,11 +312,11 @@ func (privVal *PrivValidatorFS) signVote(chainID string, vote *Vote) error {
// If they only differ by timestamp, use last timestamp and signature // If they only differ by timestamp, use last timestamp and signature
// Otherwise, return error // Otherwise, return error
if sameHRS { if sameHRS {
if bytes.Equal(signBytes, privVal.LastSignBytes) {
vote.Signature = privVal.LastSignature
} else if timestamp, ok := checkVotesOnlyDifferByTimestamp(privVal.LastSignBytes, signBytes); ok {
if bytes.Equal(signBytes, pv.LastSignBytes) {
vote.Signature = pv.LastSignature
} else if timestamp, ok := checkVotesOnlyDifferByTimestamp(pv.LastSignBytes, signBytes); ok {
vote.Timestamp = timestamp vote.Timestamp = timestamp
vote.Signature = privVal.LastSignature
vote.Signature = pv.LastSignature
} else { } else {
err = fmt.Errorf("Conflicting data") err = fmt.Errorf("Conflicting data")
} }
@ -324,11 +324,11 @@ func (privVal *PrivValidatorFS) signVote(chainID string, vote *Vote) error {
} }
// It passed the checks. Sign the vote // It passed the checks. Sign the vote
sig, err := privVal.Sign(signBytes)
sig, err := pv.Sign(signBytes)
if err != nil { if err != nil {
return err return err
} }
privVal.saveSigned(height, round, step, signBytes, sig)
pv.saveSigned(height, round, step, signBytes, sig)
vote.Signature = sig vote.Signature = sig
return nil return nil
} }
@ -336,11 +336,11 @@ func (privVal *PrivValidatorFS) signVote(chainID string, vote *Vote) error {
// signProposal checks if the proposal is good to sign and sets the proposal signature. // signProposal checks if the proposal is good to sign and sets the proposal signature.
// It may need to set the timestamp as well if the proposal is otherwise the same as // It may need to set the timestamp as well if the proposal is otherwise the same as
// a previously signed proposal ie. we crashed after signing but before the proposal hit the WAL). // a previously signed proposal ie. we crashed after signing but before the proposal hit the WAL).
func (privVal *PrivValidatorFS) signProposal(chainID string, proposal *Proposal) error {
func (pv *PrivValidatorFS) signProposal(chainID string, proposal *Proposal) error {
height, round, step := proposal.Height, proposal.Round, stepPropose height, round, step := proposal.Height, proposal.Round, stepPropose
signBytes := proposal.SignBytes(chainID) signBytes := proposal.SignBytes(chainID)
sameHRS, err := privVal.checkHRS(height, round, step)
sameHRS, err := pv.checkHRS(height, round, step)
if err != nil { if err != nil {
return err return err
} }
@ -351,11 +351,11 @@ func (privVal *PrivValidatorFS) signProposal(chainID string, proposal *Proposal)
// If they only differ by timestamp, use last timestamp and signature // If they only differ by timestamp, use last timestamp and signature
// Otherwise, return error // Otherwise, return error
if sameHRS { if sameHRS {
if bytes.Equal(signBytes, privVal.LastSignBytes) {
proposal.Signature = privVal.LastSignature
} else if timestamp, ok := checkProposalsOnlyDifferByTimestamp(privVal.LastSignBytes, signBytes); ok {
if bytes.Equal(signBytes, pv.LastSignBytes) {
proposal.Signature = pv.LastSignature
} else if timestamp, ok := checkProposalsOnlyDifferByTimestamp(pv.LastSignBytes, signBytes); ok {
proposal.Timestamp = timestamp proposal.Timestamp = timestamp
proposal.Signature = privVal.LastSignature
proposal.Signature = pv.LastSignature
} else { } else {
err = fmt.Errorf("Conflicting data") err = fmt.Errorf("Conflicting data")
} }
@ -363,40 +363,40 @@ func (privVal *PrivValidatorFS) signProposal(chainID string, proposal *Proposal)
} }
// It passed the checks. Sign the proposal // It passed the checks. Sign the proposal
sig, err := privVal.Sign(signBytes)
sig, err := pv.Sign(signBytes)
if err != nil { if err != nil {
return err return err
} }
privVal.saveSigned(height, round, step, signBytes, sig)
pv.saveSigned(height, round, step, signBytes, sig)
proposal.Signature = sig proposal.Signature = sig
return nil return nil
} }
// Persist height/round/step and signature // Persist height/round/step and signature
func (privVal *PrivValidatorFS) saveSigned(height int64, round int, step int8,
func (pv *PrivValidatorFS) saveSigned(height int64, round int, step int8,
signBytes []byte, sig crypto.Signature) { signBytes []byte, sig crypto.Signature) {
privVal.LastHeight = height
privVal.LastRound = round
privVal.LastStep = step
privVal.LastSignature = sig
privVal.LastSignBytes = signBytes
privVal.save()
pv.LastHeight = height
pv.LastRound = round
pv.LastStep = step
pv.LastSignature = sig
pv.LastSignBytes = signBytes
pv.save()
} }
// SignHeartbeat signs a canonical representation of the heartbeat, along with the chainID. // SignHeartbeat signs a canonical representation of the heartbeat, along with the chainID.
// Implements PrivValidator. // Implements PrivValidator.
func (privVal *PrivValidatorFS) SignHeartbeat(chainID string, heartbeat *Heartbeat) error {
privVal.mtx.Lock()
defer privVal.mtx.Unlock()
func (pv *PrivValidatorFS) SignHeartbeat(chainID string, heartbeat *Heartbeat) error {
pv.mtx.Lock()
defer pv.mtx.Unlock()
var err error var err error
heartbeat.Signature, err = privVal.Sign(heartbeat.SignBytes(chainID))
heartbeat.Signature, err = pv.Sign(heartbeat.SignBytes(chainID))
return err return err
} }
// String returns a string representation of the PrivValidatorFS. // String returns a string representation of the PrivValidatorFS.
func (privVal *PrivValidatorFS) String() string {
return fmt.Sprintf("PrivValidator{%v LH:%v, LR:%v, LS:%v}", privVal.GetAddress(), privVal.LastHeight, privVal.LastRound, privVal.LastStep)
func (pv *PrivValidatorFS) String() string {
return fmt.Sprintf("PrivValidator{%v LH:%v, LR:%v, LS:%v}", pv.GetAddress(), pv.LastHeight, pv.LastRound, pv.LastStep)
} }
//------------------------------------- //-------------------------------------


+ 23
- 23
types/priv_validator/sign_info.go View File

@ -49,30 +49,30 @@ func NewLastSignedInfo() *LastSignedInfo {
} }
} }
func (info *LastSignedInfo) String() string {
return fmt.Sprintf("LH:%v, LR:%v, LS:%v", info.Height, info.Round, info.Step)
func (lsi *LastSignedInfo) String() string {
return fmt.Sprintf("LH:%v, LR:%v, LS:%v", lsi.Height, lsi.Round, lsi.Step)
} }
// Verify returns an error if there is a height/round/step regression // Verify returns an error if there is a height/round/step regression
// or if the HRS matches but there are no LastSignBytes. // or if the HRS matches but there are no LastSignBytes.
// It returns true if HRS matches exactly and the LastSignature exists. // It returns true if HRS matches exactly and the LastSignature exists.
// It panics if the HRS matches, the LastSignBytes are not empty, but the LastSignature is empty. // It panics if the HRS matches, the LastSignBytes are not empty, but the LastSignature is empty.
func (info LastSignedInfo) Verify(height int64, round int, step int8) (bool, error) {
if info.Height > height {
func (lsi LastSignedInfo) Verify(height int64, round int, step int8) (bool, error) {
if lsi.Height > height {
return false, errors.New("Height regression") return false, errors.New("Height regression")
} }
if info.Height == height {
if info.Round > round {
if lsi.Height == height {
if lsi.Round > round {
return false, errors.New("Round regression") return false, errors.New("Round regression")
} }
if info.Round == round {
if info.Step > step {
if lsi.Round == round {
if lsi.Step > step {
return false, errors.New("Step regression") return false, errors.New("Step regression")
} else if info.Step == step {
if info.SignBytes != nil {
if info.Signature.Empty() {
} else if lsi.Step == step {
if lsi.SignBytes != nil {
if lsi.Signature.Empty() {
panic("info: LastSignature is nil but LastSignBytes is not!") panic("info: LastSignature is nil but LastSignBytes is not!")
} }
return true, nil return true, nil
@ -85,24 +85,24 @@ func (info LastSignedInfo) Verify(height int64, round int, step int8) (bool, err
} }
// Set height/round/step and signature on the info // Set height/round/step and signature on the info
func (info *LastSignedInfo) Set(height int64, round int, step int8,
func (lsi *LastSignedInfo) Set(height int64, round int, step int8,
signBytes []byte, sig crypto.Signature) { signBytes []byte, sig crypto.Signature) {
info.Height = height
info.Round = round
info.Step = step
info.Signature = sig
info.SignBytes = signBytes
lsi.Height = height
lsi.Round = round
lsi.Step = step
lsi.Signature = sig
lsi.SignBytes = signBytes
} }
// Reset resets all the values. // Reset resets all the values.
// XXX: Unsafe. // XXX: Unsafe.
func (info *LastSignedInfo) Reset() {
info.Height = 0
info.Round = 0
info.Step = 0
info.Signature = crypto.Signature{}
info.SignBytes = nil
func (lsi *LastSignedInfo) Reset() {
lsi.Height = 0
lsi.Round = 0
lsi.Step = 0
lsi.Signature = crypto.Signature{}
lsi.SignBytes = nil
} }
// SignVote checks the height/round/step (HRS) are greater than the latest state of the LastSignedInfo. // SignVote checks the height/round/step (HRS) are greater than the latest state of the LastSignedInfo.


+ 21
- 28
types/validator_set.go View File

@ -96,9 +96,8 @@ func (valSet *ValidatorSet) GetByAddress(address []byte) (index int, val *Valida
}) })
if idx != len(valSet.Validators) && bytes.Equal(valSet.Validators[idx].Address, address) { if idx != len(valSet.Validators) && bytes.Equal(valSet.Validators[idx].Address, address) {
return idx, valSet.Validators[idx].Copy() return idx, valSet.Validators[idx].Copy()
} else {
return 0, nil
} }
return 0, nil
} }
// GetByIndex returns the validator by index. // GetByIndex returns the validator by index.
@ -187,13 +186,12 @@ func (valSet *ValidatorSet) Update(val *Validator) (updated bool) {
index, sameVal := valSet.GetByAddress(val.Address) index, sameVal := valSet.GetByAddress(val.Address)
if sameVal == nil { if sameVal == nil {
return false return false
} else {
valSet.Validators[index] = val.Copy()
// Invalidate cache
valSet.Proposer = nil
valSet.totalVotingPower = 0
return true
} }
valSet.Validators[index] = val.Copy()
// Invalidate cache
valSet.Proposer = nil
valSet.totalVotingPower = 0
return true
} }
func (valSet *ValidatorSet) Remove(address []byte) (val *Validator, removed bool) { func (valSet *ValidatorSet) Remove(address []byte) (val *Validator, removed bool) {
@ -202,18 +200,17 @@ func (valSet *ValidatorSet) Remove(address []byte) (val *Validator, removed bool
}) })
if idx == len(valSet.Validators) || !bytes.Equal(valSet.Validators[idx].Address, address) { if idx == len(valSet.Validators) || !bytes.Equal(valSet.Validators[idx].Address, address) {
return nil, false return nil, false
} else {
removedVal := valSet.Validators[idx]
newValidators := valSet.Validators[:idx]
if idx+1 < len(valSet.Validators) {
newValidators = append(newValidators, valSet.Validators[idx+1:]...)
}
valSet.Validators = newValidators
// Invalidate cache
valSet.Proposer = nil
valSet.totalVotingPower = 0
return removedVal, true
} }
removedVal := valSet.Validators[idx]
newValidators := valSet.Validators[:idx]
if idx+1 < len(valSet.Validators) {
newValidators = append(newValidators, valSet.Validators[idx+1:]...)
}
valSet.Validators = newValidators
// Invalidate cache
valSet.Proposer = nil
valSet.totalVotingPower = 0
return removedVal, true
} }
func (valSet *ValidatorSet) Iterate(fn func(index int, val *Validator) bool) { func (valSet *ValidatorSet) Iterate(fn func(index int, val *Validator) bool) {
@ -266,10 +263,9 @@ func (valSet *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, height
if talliedVotingPower > valSet.TotalVotingPower()*2/3 { if talliedVotingPower > valSet.TotalVotingPower()*2/3 {
return nil return nil
} else {
return fmt.Errorf("Invalid commit -- insufficient voting power: got %v, needed %v",
talliedVotingPower, (valSet.TotalVotingPower()*2/3 + 1))
} }
return fmt.Errorf("Invalid commit -- insufficient voting power: got %v, needed %v",
talliedVotingPower, (valSet.TotalVotingPower()*2/3 + 1))
} }
// VerifyCommitAny will check to see if the set would // VerifyCommitAny will check to see if the set would
@ -472,9 +468,8 @@ func safeMulClip(a, b int64) int64 {
if overflow { if overflow {
if (a < 0 || b < 0) && !(a < 0 && b < 0) { if (a < 0 || b < 0) && !(a < 0 && b < 0) {
return math.MinInt64 return math.MinInt64
} else {
return math.MaxInt64
} }
return math.MaxInt64
} }
return c return c
} }
@ -484,9 +479,8 @@ func safeAddClip(a, b int64) int64 {
if overflow { if overflow {
if b < 0 { if b < 0 {
return math.MinInt64 return math.MinInt64
} else {
return math.MaxInt64
} }
return math.MaxInt64
} }
return c return c
} }
@ -496,9 +490,8 @@ func safeSubClip(a, b int64) int64 {
if overflow { if overflow {
if b > 0 { if b > 0 {
return math.MinInt64 return math.MinInt64
} else {
return math.MaxInt64
} }
return math.MaxInt64
} }
return c return c
} }

+ 1
- 1
types/validator_set_test.go View File

@ -127,7 +127,7 @@ func TestProposerSelection2(t *testing.T) {
for i := 0; i < 120*N; i++ { for i := 0; i < 120*N; i++ {
prop := vals.GetProposer() prop := vals.GetProposer()
ii := prop.Address[19] ii := prop.Address[19]
propCount[ii] += 1
propCount[ii]++
vals.IncrementAccum(1) vals.IncrementAccum(1)
} }


+ 19
- 30
types/vote_set.go View File

@ -94,33 +94,29 @@ func (voteSet *VoteSet) ChainID() string {
func (voteSet *VoteSet) Height() int64 { func (voteSet *VoteSet) Height() int64 {
if voteSet == nil { if voteSet == nil {
return 0 return 0
} else {
return voteSet.height
} }
return voteSet.height
} }
func (voteSet *VoteSet) Round() int { func (voteSet *VoteSet) Round() int {
if voteSet == nil { if voteSet == nil {
return -1 return -1
} else {
return voteSet.round
} }
return voteSet.round
} }
func (voteSet *VoteSet) Type() byte { func (voteSet *VoteSet) Type() byte {
if voteSet == nil { if voteSet == nil {
return 0x00 return 0x00
} else {
return voteSet.type_
} }
return voteSet.type_
} }
func (voteSet *VoteSet) Size() int { func (voteSet *VoteSet) Size() int {
if voteSet == nil { if voteSet == nil {
return 0 return 0
} else {
return voteSet.valSet.Size()
} }
return voteSet.valSet.Size()
} }
// Returns added=true if vote is valid and new. // Returns added=true if vote is valid and new.
@ -185,9 +181,8 @@ func (voteSet *VoteSet) addVote(vote *Vote) (added bool, err error) {
if existing, ok := voteSet.getVote(valIndex, blockKey); ok { if existing, ok := voteSet.getVote(valIndex, blockKey); ok {
if existing.Signature.Equals(vote.Signature) { if existing.Signature.Equals(vote.Signature) {
return false, nil // duplicate return false, nil // duplicate
} else {
return false, errors.Wrapf(ErrVoteNonDeterministicSignature, "Existing vote: %v; New vote: %v", existing, vote)
} }
return false, errors.Wrapf(ErrVoteNonDeterministicSignature, "Existing vote: %v; New vote: %v", existing, vote)
} }
// Check signature. // Check signature.
@ -199,13 +194,11 @@ func (voteSet *VoteSet) addVote(vote *Vote) (added bool, err error) {
added, conflicting := voteSet.addVerifiedVote(vote, blockKey, val.VotingPower) added, conflicting := voteSet.addVerifiedVote(vote, blockKey, val.VotingPower)
if conflicting != nil { if conflicting != nil {
return added, NewConflictingVoteError(val, conflicting, vote) return added, NewConflictingVoteError(val, conflicting, vote)
} else {
if !added {
cmn.PanicSanity("Expected to add non-conflicting vote")
}
return added, nil
} }
if !added {
cmn.PanicSanity("Expected to add non-conflicting vote")
}
return added, nil
} }
// Returns (vote, true) if vote exists for valIndex and blockKey // Returns (vote, true) if vote exists for valIndex and blockKey
@ -257,13 +250,12 @@ func (voteSet *VoteSet) addVerifiedVote(vote *Vote, blockKey string, votingPower
// ... and there's a conflicting vote. // ... and there's a conflicting vote.
// We're not even tracking this blockKey, so just forget it. // We're not even tracking this blockKey, so just forget it.
return false, conflicting return false, conflicting
} else {
// ... and there's no conflicting vote.
// Start tracking this blockKey
votesByBlock = newBlockVotes(false, voteSet.valSet.Size())
voteSet.votesByBlock[blockKey] = votesByBlock
// We'll add the vote in a bit.
} }
// ... and there's no conflicting vote.
// Start tracking this blockKey
votesByBlock = newBlockVotes(false, voteSet.valSet.Size())
voteSet.votesByBlock[blockKey] = votesByBlock
// We'll add the vote in a bit.
} }
// Before adding to votesByBlock, see if we'll exceed quorum // Before adding to votesByBlock, see if we'll exceed quorum
@ -309,10 +301,9 @@ func (voteSet *VoteSet) SetPeerMaj23(peerID P2PID, blockID BlockID) error {
if existing, ok := voteSet.peerMaj23s[peerID]; ok { if existing, ok := voteSet.peerMaj23s[peerID]; ok {
if existing.Equals(blockID) { if existing.Equals(blockID) {
return nil // Nothing to do return nil // Nothing to do
} else {
return fmt.Errorf("SetPeerMaj23: Received conflicting blockID from peer %v. Got %v, expected %v",
peerID, blockID, existing)
} }
return fmt.Errorf("SetPeerMaj23: Received conflicting blockID from peer %v. Got %v, expected %v",
peerID, blockID, existing)
} }
voteSet.peerMaj23s[peerID] = blockID voteSet.peerMaj23s[peerID] = blockID
@ -321,10 +312,9 @@ func (voteSet *VoteSet) SetPeerMaj23(peerID P2PID, blockID BlockID) error {
if ok { if ok {
if votesByBlock.peerMaj23 { if votesByBlock.peerMaj23 {
return nil // Nothing to do return nil // Nothing to do
} else {
votesByBlock.peerMaj23 = true
// No need to copy votes, already there.
} }
votesByBlock.peerMaj23 = true
// No need to copy votes, already there.
} else { } else {
votesByBlock = newBlockVotes(true, voteSet.valSet.Size()) votesByBlock = newBlockVotes(true, voteSet.valSet.Size())
voteSet.votesByBlock[blockKey] = votesByBlock voteSet.votesByBlock[blockKey] = votesByBlock
@ -422,9 +412,8 @@ func (voteSet *VoteSet) TwoThirdsMajority() (blockID BlockID, ok bool) {
defer voteSet.mtx.Unlock() defer voteSet.mtx.Unlock()
if voteSet.maj23 != nil { if voteSet.maj23 != nil {
return *voteSet.maj23, true return *voteSet.maj23, true
} else {
return BlockID{}, false
} }
return BlockID{}, false
} }
func (voteSet *VoteSet) String() string { func (voteSet *VoteSet) String() string {


Loading…
Cancel
Save