You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1480 lines
42 KiB

lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
10 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
fix data race Closes #1442 ``` WARNING: DATA RACE Write at 0x00c4209de7c8 by goroutine 23: github.com/tendermint/tendermint/types.(*Block).fillHeader() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:88 +0x157 github.com/tendermint/tendermint/types.(*Block).Hash() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:104 +0x121 github.com/tendermint/tendermint/types.(*Block).HashesTo() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:135 +0x4f github.com/tendermint/tendermint/consensus.(*ConsensusState).enterPrecommit() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1037 +0x182d github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1425 +0x1a6c github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1318 +0x77 github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:581 +0x7a9 github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:539 +0x6c3 Previous read at 0x00c4209de7c8 by goroutine 47: github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*HexBytes).MarshalJSON() <autogenerated>:1 +0x52 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.invokeMarshalJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:433 +0x88 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:82 +0x8d2 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).MarshalJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/amino.go:296 +0x182 github.com/tendermint/tendermint/rpc/lib/types.NewRPCSuccessResponse() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/types/types.go:100 +0x12c github.com/tendermint/tendermint/rpc/lib/server.makeJSONRPCHandler.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/handlers.go:152 +0xab7 net/http.HandlerFunc.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:1918 +0x51 net/http.(*ServeMux).ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:2254 +0xa2 github.com/tendermint/tendermint/rpc/lib/server.RecoverAndLogHandler.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:138 +0x4fa net/http.HandlerFunc.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:1918 +0x51 net/http.serverHandler.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:2619 +0xbc net/http.(*conn).serve() /usr/lib/go-1.9/src/net/http/server.go:1801 +0x83b Goroutine 23 (running) created at: github.com/tendermint/tendermint/consensus.(*ConsensusState).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:250 +0x35b github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/consensus.(*ConsensusReactor).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/reactor.go:69 +0x1b4 github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/consensus.(*ConsensusReactor).Start() <autogenerated>:1 +0x43 github.com/tendermint/tendermint/p2p.(*Switch).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch.go:177 +0x124 github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/node.(*Node).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/node/node.go:416 +0xa1b github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/rpc/test.StartTendermint() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/test/helpers.go:100 +0x5b github.com/tendermint/tendermint/rpc/client_test.TestMain() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/client/main_test.go:17 +0x4c main.main() github.com/tendermint/tendermint/rpc/client/_test/_testmain.go:76 +0x1cd Goroutine 47 (running) created at: net/http.(*Server).Serve() /usr/lib/go-1.9/src/net/http/server.go:2720 +0x37c net/http.Serve() /usr/lib/go-1.9/src/net/http/server.go:2323 +0xe2 github.com/tendermint/tendermint/rpc/lib/server.StartHTTPServer.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:35 +0xb3 ```
7 years ago
protect Record* peerStateStats functions by mutex Fixes #1414 DATA RACE: ``` Read at 0x00c4214ee940 by goroutine 146: github.com/tendermint/tendermint/consensus.(*peerStateStats).String() <autogenerated>:1 +0x57 fmt.(*pp).handleMethods() /usr/local/go/src/fmt/print.go:596 +0x3f4 fmt.(*pp).printArg() /usr/local/go/src/fmt/print.go:679 +0x11f fmt.(*pp).doPrintf() /usr/local/go/src/fmt/print.go:996 +0x319 fmt.Sprintf() /usr/local/go/src/fmt/print.go:196 +0x73 github.com/tendermint/tendermint/consensus.(*PeerState).StringIndented() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:1426 +0x573 github.com/tendermint/tendermint/consensus.(*PeerState).String() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:1419 +0x66 github.com/go-logfmt/logfmt.safeString() /home/ubuntu/go/src/github.com/go-logfmt/logfmt/encode.go:299 +0x9d github.com/go-logfmt/logfmt.writeValue() /home/ubuntu/go/src/github.com/go-logfmt/logfmt/encode.go:217 +0x5a0 github.com/go-logfmt/logfmt.(*Encoder).EncodeKeyval() /home/ubuntu/go/src/github.com/go-logfmt/logfmt/encode.go:61 +0x1dd github.com/tendermint/tmlibs/log.tmfmtLogger.Log() /home/ubuntu/go/src/github.com/tendermint/tmlibs/log/tmfmt_logger.go:107 +0x1001 github.com/tendermint/tmlibs/log.(*tmfmtLogger).Log() <autogenerated>:1 +0x93 github.com/go-kit/kit/log.(*context).Log() /home/ubuntu/go/src/github.com/go-kit/kit/log/log.go:124 +0x248 github.com/tendermint/tmlibs/log.(*tmLogger).Debug() /home/ubuntu/go/src/github.com/tendermint/tmlibs/log/tm_logger.go:64 +0x1d0 github.com/tendermint/tendermint/consensus.(*PeerState).PickSendVote() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:1059 +0x242 github.com/tendermint/tendermint/consensus.(*ConsensusReactor).gossipVotesForHeight() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:789 +0x6ef github.com/tendermint/tendermint/consensus.(*ConsensusReactor).gossipVotesRoutine() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:723 +0x1039 Previous write at 0x00c4214ee940 by goroutine 21: github.com/tendermint/tendermint/consensus.(*PeerState).RecordVote() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:1242 +0x15a github.com/tendermint/tendermint/consensus.(*ConsensusReactor).Receive() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:309 +0x32e6 github.com/tendermint/tendermint/p2p.createMConnection.func1() /home/ubuntu/go/src/github.com/tendermint/tendermint/p2p/peer.go:365 +0xea github.com/tendermint/tendermint/p2p/conn.(*MConnection).recvRoutine() /home/ubuntu/go/src/github.com/tendermint/tendermint/p2p/conn/connection.go:531 +0x779 ```
7 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package consensus
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "runtime/debug"
  7. "sync"
  8. "time"
  9. cstypes "github.com/tendermint/tendermint/internal/consensus/types"
  10. "github.com/tendermint/tendermint/internal/eventbus"
  11. "github.com/tendermint/tendermint/internal/p2p"
  12. sm "github.com/tendermint/tendermint/internal/state"
  13. "github.com/tendermint/tendermint/libs/bits"
  14. tmevents "github.com/tendermint/tendermint/libs/events"
  15. "github.com/tendermint/tendermint/libs/log"
  16. "github.com/tendermint/tendermint/libs/service"
  17. tmtime "github.com/tendermint/tendermint/libs/time"
  18. tmcons "github.com/tendermint/tendermint/proto/tendermint/consensus"
  19. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  20. "github.com/tendermint/tendermint/types"
  21. )
  22. var (
  23. _ service.Service = (*Reactor)(nil)
  24. _ p2p.Wrapper = (*tmcons.Message)(nil)
  25. )
  26. // GetChannelDescriptor produces an instance of a descriptor for this
  27. // package's required channels.
  28. func getChannelDescriptors() map[p2p.ChannelID]*p2p.ChannelDescriptor {
  29. return map[p2p.ChannelID]*p2p.ChannelDescriptor{
  30. StateChannel: {
  31. ID: StateChannel,
  32. MessageType: new(tmcons.Message),
  33. Priority: 8,
  34. SendQueueCapacity: 64,
  35. RecvMessageCapacity: maxMsgSize,
  36. RecvBufferCapacity: 128,
  37. },
  38. DataChannel: {
  39. // TODO: Consider a split between gossiping current block and catchup
  40. // stuff. Once we gossip the whole block there is nothing left to send
  41. // until next height or round.
  42. ID: DataChannel,
  43. MessageType: new(tmcons.Message),
  44. Priority: 12,
  45. SendQueueCapacity: 64,
  46. RecvBufferCapacity: 512,
  47. RecvMessageCapacity: maxMsgSize,
  48. },
  49. VoteChannel: {
  50. ID: VoteChannel,
  51. MessageType: new(tmcons.Message),
  52. Priority: 10,
  53. SendQueueCapacity: 64,
  54. RecvBufferCapacity: 128,
  55. RecvMessageCapacity: maxMsgSize,
  56. },
  57. VoteSetBitsChannel: {
  58. ID: VoteSetBitsChannel,
  59. MessageType: new(tmcons.Message),
  60. Priority: 5,
  61. SendQueueCapacity: 8,
  62. RecvBufferCapacity: 128,
  63. RecvMessageCapacity: maxMsgSize,
  64. },
  65. }
  66. }
  67. const (
  68. StateChannel = p2p.ChannelID(0x20)
  69. DataChannel = p2p.ChannelID(0x21)
  70. VoteChannel = p2p.ChannelID(0x22)
  71. VoteSetBitsChannel = p2p.ChannelID(0x23)
  72. maxMsgSize = 1048576 // 1MB; NOTE: keep in sync with types.PartSet sizes.
  73. blocksToContributeToBecomeGoodPeer = 10000
  74. votesToContributeToBecomeGoodPeer = 10000
  75. listenerIDConsensus = "consensus-reactor"
  76. )
  77. // NOTE: Temporary interface for switching to block sync, we should get rid of v0.
  78. // See: https://github.com/tendermint/tendermint/issues/4595
  79. type BlockSyncReactor interface {
  80. SwitchToBlockSync(context.Context, sm.State) error
  81. GetMaxPeerBlockHeight() int64
  82. // GetTotalSyncedTime returns the time duration since the blocksync starting.
  83. GetTotalSyncedTime() time.Duration
  84. // GetRemainingSyncTime returns the estimating time the node will be fully synced,
  85. // if will return 0 if the blocksync does not perform or the number of block synced is
  86. // too small (less than 100).
  87. GetRemainingSyncTime() time.Duration
  88. }
  89. //go:generate ../../scripts/mockery_generate.sh ConsSyncReactor
  90. // ConsSyncReactor defines an interface used for testing abilities of node.startStateSync.
  91. type ConsSyncReactor interface {
  92. SwitchToConsensus(sm.State, bool)
  93. SetStateSyncingMetrics(float64)
  94. SetBlockSyncingMetrics(float64)
  95. }
  96. // Reactor defines a reactor for the consensus service.
  97. type Reactor struct {
  98. service.BaseService
  99. logger log.Logger
  100. state *State
  101. eventBus *eventbus.EventBus
  102. Metrics *Metrics
  103. mtx sync.RWMutex
  104. peers map[types.NodeID]*PeerState
  105. waitSync bool
  106. readySignal chan struct{} // closed when the node is ready to start consensus
  107. stateCh *p2p.Channel
  108. dataCh *p2p.Channel
  109. voteCh *p2p.Channel
  110. voteSetBitsCh *p2p.Channel
  111. peerUpdates *p2p.PeerUpdates
  112. }
  113. // NewReactor returns a reference to a new consensus reactor, which implements
  114. // the service.Service interface. It accepts a logger, consensus state, references
  115. // to relevant p2p Channels and a channel to listen for peer updates on. The
  116. // reactor will close all p2p Channels when stopping.
  117. func NewReactor(
  118. ctx context.Context,
  119. logger log.Logger,
  120. cs *State,
  121. channelCreator p2p.ChannelCreator,
  122. peerUpdates *p2p.PeerUpdates,
  123. waitSync bool,
  124. metrics *Metrics,
  125. ) (*Reactor, error) {
  126. chans := getChannelDescriptors()
  127. stateCh, err := channelCreator(ctx, chans[StateChannel])
  128. if err != nil {
  129. return nil, err
  130. }
  131. dataCh, err := channelCreator(ctx, chans[DataChannel])
  132. if err != nil {
  133. return nil, err
  134. }
  135. voteCh, err := channelCreator(ctx, chans[VoteChannel])
  136. if err != nil {
  137. return nil, err
  138. }
  139. voteSetBitsCh, err := channelCreator(ctx, chans[VoteSetBitsChannel])
  140. if err != nil {
  141. return nil, err
  142. }
  143. r := &Reactor{
  144. logger: logger,
  145. state: cs,
  146. waitSync: waitSync,
  147. peers: make(map[types.NodeID]*PeerState),
  148. Metrics: metrics,
  149. stateCh: stateCh,
  150. dataCh: dataCh,
  151. voteCh: voteCh,
  152. voteSetBitsCh: voteSetBitsCh,
  153. peerUpdates: peerUpdates,
  154. readySignal: make(chan struct{}),
  155. }
  156. r.BaseService = *service.NewBaseService(logger, "Consensus", r)
  157. if !r.waitSync {
  158. close(r.readySignal)
  159. }
  160. return r, nil
  161. }
  162. // OnStart starts separate go routines for each p2p Channel and listens for
  163. // envelopes on each. In addition, it also listens for peer updates and handles
  164. // messages on that p2p channel accordingly. The caller must be sure to execute
  165. // OnStop to ensure the outbound p2p Channels are closed.
  166. func (r *Reactor) OnStart(ctx context.Context) error {
  167. r.logger.Debug("consensus wait sync", "wait_sync", r.WaitSync())
  168. // start routine that computes peer statistics for evaluating peer quality
  169. //
  170. // TODO: Evaluate if we need this to be synchronized via WaitGroup as to not
  171. // leak the goroutine when stopping the reactor.
  172. go r.peerStatsRoutine(ctx)
  173. r.subscribeToBroadcastEvents()
  174. if !r.WaitSync() {
  175. if err := r.state.Start(ctx); err != nil {
  176. return err
  177. }
  178. }
  179. go r.processStateCh(ctx)
  180. go r.processDataCh(ctx)
  181. go r.processVoteCh(ctx)
  182. go r.processVoteSetBitsCh(ctx)
  183. go r.processPeerUpdates(ctx)
  184. return nil
  185. }
  186. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  187. // blocking until they all exit, as well as unsubscribing from events and stopping
  188. // state.
  189. func (r *Reactor) OnStop() {
  190. r.unsubscribeFromBroadcastEvents()
  191. r.state.Stop()
  192. if !r.WaitSync() {
  193. r.state.Wait()
  194. }
  195. }
  196. // SetEventBus sets the reactor's event bus.
  197. func (r *Reactor) SetEventBus(b *eventbus.EventBus) {
  198. r.eventBus = b
  199. r.state.SetEventBus(b)
  200. }
  201. // WaitSync returns whether the consensus reactor is waiting for state/block sync.
  202. func (r *Reactor) WaitSync() bool {
  203. r.mtx.RLock()
  204. defer r.mtx.RUnlock()
  205. return r.waitSync
  206. }
  207. // SwitchToConsensus switches from block-sync mode to consensus mode. It resets
  208. // the state, turns off block-sync, and starts the consensus state-machine.
  209. func (r *Reactor) SwitchToConsensus(ctx context.Context, state sm.State, skipWAL bool) {
  210. r.logger.Info("switching to consensus")
  211. // we have no votes, so reconstruct LastCommit from SeenCommit
  212. if state.LastBlockHeight > 0 {
  213. r.state.reconstructLastCommit(state)
  214. }
  215. // NOTE: The line below causes broadcastNewRoundStepRoutine() to broadcast a
  216. // NewRoundStepMessage.
  217. r.state.updateToState(ctx, state)
  218. r.mtx.Lock()
  219. r.waitSync = false
  220. close(r.readySignal)
  221. r.mtx.Unlock()
  222. r.Metrics.BlockSyncing.Set(0)
  223. r.Metrics.StateSyncing.Set(0)
  224. if skipWAL {
  225. r.state.doWALCatchup = false
  226. }
  227. if err := r.state.Start(ctx); err != nil {
  228. panic(fmt.Sprintf(`failed to start consensus state: %v
  229. conS:
  230. %+v
  231. conR:
  232. %+v`, err, r.state, r))
  233. }
  234. d := types.EventDataBlockSyncStatus{Complete: true, Height: state.LastBlockHeight}
  235. if err := r.eventBus.PublishEventBlockSyncStatus(ctx, d); err != nil {
  236. r.logger.Error("failed to emit the blocksync complete event", "err", err)
  237. }
  238. }
  239. // String returns a string representation of the Reactor.
  240. //
  241. // NOTE: For now, it is just a hard-coded string to avoid accessing unprotected
  242. // shared variables.
  243. //
  244. // TODO: improve!
  245. func (r *Reactor) String() string {
  246. return "ConsensusReactor"
  247. }
  248. // StringIndented returns an indented string representation of the Reactor.
  249. func (r *Reactor) StringIndented(indent string) string {
  250. r.mtx.RLock()
  251. defer r.mtx.RUnlock()
  252. s := "ConsensusReactor{\n"
  253. s += indent + " " + r.state.StringIndented(indent+" ") + "\n"
  254. for _, ps := range r.peers {
  255. s += indent + " " + ps.StringIndented(indent+" ") + "\n"
  256. }
  257. s += indent + "}"
  258. return s
  259. }
  260. // GetPeerState returns PeerState for a given NodeID.
  261. func (r *Reactor) GetPeerState(peerID types.NodeID) (*PeerState, bool) {
  262. r.mtx.RLock()
  263. defer r.mtx.RUnlock()
  264. ps, ok := r.peers[peerID]
  265. return ps, ok
  266. }
  267. func (r *Reactor) broadcastNewRoundStepMessage(ctx context.Context, rs *cstypes.RoundState) error {
  268. return r.stateCh.Send(ctx, p2p.Envelope{
  269. Broadcast: true,
  270. Message: makeRoundStepMessage(rs),
  271. })
  272. }
  273. func (r *Reactor) broadcastNewValidBlockMessage(ctx context.Context, rs *cstypes.RoundState) error {
  274. psHeader := rs.ProposalBlockParts.Header()
  275. return r.stateCh.Send(ctx, p2p.Envelope{
  276. Broadcast: true,
  277. Message: &tmcons.NewValidBlock{
  278. Height: rs.Height,
  279. Round: rs.Round,
  280. BlockPartSetHeader: psHeader.ToProto(),
  281. BlockParts: rs.ProposalBlockParts.BitArray().ToProto(),
  282. IsCommit: rs.Step == cstypes.RoundStepCommit,
  283. },
  284. })
  285. }
  286. func (r *Reactor) broadcastHasVoteMessage(ctx context.Context, vote *types.Vote) error {
  287. return r.stateCh.Send(ctx, p2p.Envelope{
  288. Broadcast: true,
  289. Message: &tmcons.HasVote{
  290. Height: vote.Height,
  291. Round: vote.Round,
  292. Type: vote.Type,
  293. Index: vote.ValidatorIndex,
  294. },
  295. })
  296. }
  297. // subscribeToBroadcastEvents subscribes for new round steps and votes using the
  298. // internal pubsub defined in the consensus state to broadcast them to peers
  299. // upon receiving.
  300. func (r *Reactor) subscribeToBroadcastEvents() {
  301. err := r.state.evsw.AddListenerForEvent(
  302. listenerIDConsensus,
  303. types.EventNewRoundStepValue,
  304. func(ctx context.Context, data tmevents.EventData) error {
  305. if err := r.broadcastNewRoundStepMessage(ctx, data.(*cstypes.RoundState)); err != nil {
  306. return err
  307. }
  308. select {
  309. case r.state.onStopCh <- data.(*cstypes.RoundState):
  310. return nil
  311. case <-ctx.Done():
  312. return ctx.Err()
  313. default:
  314. return nil
  315. }
  316. },
  317. )
  318. if err != nil {
  319. r.logger.Error("failed to add listener for events", "err", err)
  320. }
  321. err = r.state.evsw.AddListenerForEvent(
  322. listenerIDConsensus,
  323. types.EventValidBlockValue,
  324. func(ctx context.Context, data tmevents.EventData) error {
  325. return r.broadcastNewValidBlockMessage(ctx, data.(*cstypes.RoundState))
  326. },
  327. )
  328. if err != nil {
  329. r.logger.Error("failed to add listener for events", "err", err)
  330. }
  331. err = r.state.evsw.AddListenerForEvent(
  332. listenerIDConsensus,
  333. types.EventVoteValue,
  334. func(ctx context.Context, data tmevents.EventData) error {
  335. return r.broadcastHasVoteMessage(ctx, data.(*types.Vote))
  336. },
  337. )
  338. if err != nil {
  339. r.logger.Error("failed to add listener for events", "err", err)
  340. }
  341. }
  342. func (r *Reactor) unsubscribeFromBroadcastEvents() {
  343. r.state.evsw.RemoveListener(listenerIDConsensus)
  344. }
  345. func makeRoundStepMessage(rs *cstypes.RoundState) *tmcons.NewRoundStep {
  346. return &tmcons.NewRoundStep{
  347. Height: rs.Height,
  348. Round: rs.Round,
  349. Step: uint32(rs.Step),
  350. SecondsSinceStartTime: int64(time.Since(rs.StartTime).Seconds()),
  351. LastCommitRound: rs.LastCommit.GetRound(),
  352. }
  353. }
  354. func (r *Reactor) sendNewRoundStepMessage(ctx context.Context, peerID types.NodeID) error {
  355. return r.stateCh.Send(ctx, p2p.Envelope{
  356. To: peerID,
  357. Message: makeRoundStepMessage(r.state.GetRoundState()),
  358. })
  359. }
  360. func (r *Reactor) gossipDataForCatchup(ctx context.Context, rs *cstypes.RoundState, prs *cstypes.PeerRoundState, ps *PeerState) {
  361. logger := r.logger.With("height", prs.Height).With("peer", ps.peerID)
  362. if index, ok := prs.ProposalBlockParts.Not().PickRandom(); ok {
  363. // ensure that the peer's PartSetHeader is correct
  364. blockMeta := r.state.blockStore.LoadBlockMeta(prs.Height)
  365. if blockMeta == nil {
  366. logger.Error(
  367. "failed to load block meta",
  368. "our_height", rs.Height,
  369. "blockstore_base", r.state.blockStore.Base(),
  370. "blockstore_height", r.state.blockStore.Height(),
  371. )
  372. time.Sleep(r.state.config.PeerGossipSleepDuration)
  373. return
  374. } else if !blockMeta.BlockID.PartSetHeader.Equals(prs.ProposalBlockPartSetHeader) {
  375. logger.Info(
  376. "peer ProposalBlockPartSetHeader mismatch; sleeping",
  377. "block_part_set_header", blockMeta.BlockID.PartSetHeader,
  378. "peer_block_part_set_header", prs.ProposalBlockPartSetHeader,
  379. )
  380. time.Sleep(r.state.config.PeerGossipSleepDuration)
  381. return
  382. }
  383. part := r.state.blockStore.LoadBlockPart(prs.Height, index)
  384. if part == nil {
  385. logger.Error(
  386. "failed to load block part",
  387. "index", index,
  388. "block_part_set_header", blockMeta.BlockID.PartSetHeader,
  389. "peer_block_part_set_header", prs.ProposalBlockPartSetHeader,
  390. )
  391. time.Sleep(r.state.config.PeerGossipSleepDuration)
  392. return
  393. }
  394. partProto, err := part.ToProto()
  395. if err != nil {
  396. logger.Error("failed to convert block part to proto", "err", err)
  397. time.Sleep(r.state.config.PeerGossipSleepDuration)
  398. return
  399. }
  400. logger.Debug("sending block part for catchup", "round", prs.Round, "index", index)
  401. _ = r.dataCh.Send(ctx, p2p.Envelope{
  402. To: ps.peerID,
  403. Message: &tmcons.BlockPart{
  404. Height: prs.Height, // not our height, so it does not matter.
  405. Round: prs.Round, // not our height, so it does not matter
  406. Part: *partProto,
  407. },
  408. })
  409. return
  410. }
  411. time.Sleep(r.state.config.PeerGossipSleepDuration)
  412. }
  413. func (r *Reactor) gossipDataRoutine(ctx context.Context, ps *PeerState) {
  414. logger := r.logger.With("peer", ps.peerID)
  415. timer := time.NewTimer(0)
  416. defer timer.Stop()
  417. OUTER_LOOP:
  418. for {
  419. if !r.IsRunning() {
  420. return
  421. }
  422. select {
  423. case <-ctx.Done():
  424. return
  425. default:
  426. }
  427. rs := r.state.GetRoundState()
  428. prs := ps.GetRoundState()
  429. // Send proposal Block parts?
  430. if rs.ProposalBlockParts.HasHeader(prs.ProposalBlockPartSetHeader) {
  431. if index, ok := rs.ProposalBlockParts.BitArray().Sub(prs.ProposalBlockParts.Copy()).PickRandom(); ok {
  432. part := rs.ProposalBlockParts.GetPart(index)
  433. partProto, err := part.ToProto()
  434. if err != nil {
  435. logger.Error("failed to convert block part to proto", "err", err)
  436. return
  437. }
  438. logger.Debug("sending block part", "height", prs.Height, "round", prs.Round)
  439. if err := r.dataCh.Send(ctx, p2p.Envelope{
  440. To: ps.peerID,
  441. Message: &tmcons.BlockPart{
  442. Height: rs.Height, // this tells peer that this part applies to us
  443. Round: rs.Round, // this tells peer that this part applies to us
  444. Part: *partProto,
  445. },
  446. }); err != nil {
  447. return
  448. }
  449. ps.SetHasProposalBlockPart(prs.Height, prs.Round, index)
  450. continue OUTER_LOOP
  451. }
  452. }
  453. // if the peer is on a previous height that we have, help catch up
  454. blockStoreBase := r.state.blockStore.Base()
  455. if blockStoreBase > 0 && 0 < prs.Height && prs.Height < rs.Height && prs.Height >= blockStoreBase {
  456. heightLogger := logger.With("height", prs.Height)
  457. // If we never received the commit message from the peer, the block parts
  458. // will not be initialized.
  459. if prs.ProposalBlockParts == nil {
  460. blockMeta := r.state.blockStore.LoadBlockMeta(prs.Height)
  461. if blockMeta == nil {
  462. heightLogger.Error(
  463. "failed to load block meta",
  464. "blockstoreBase", blockStoreBase,
  465. "blockstoreHeight", r.state.blockStore.Height(),
  466. )
  467. timer.Reset(r.state.config.PeerGossipSleepDuration)
  468. select {
  469. case <-timer.C:
  470. case <-ctx.Done():
  471. return
  472. }
  473. } else {
  474. ps.InitProposalBlockParts(blockMeta.BlockID.PartSetHeader)
  475. }
  476. // Continue the loop since prs is a copy and not effected by this
  477. // initialization.
  478. continue OUTER_LOOP
  479. }
  480. r.gossipDataForCatchup(ctx, rs, prs, ps)
  481. continue OUTER_LOOP
  482. }
  483. // if height and round don't match, sleep
  484. if (rs.Height != prs.Height) || (rs.Round != prs.Round) {
  485. timer.Reset(r.state.config.PeerGossipSleepDuration)
  486. select {
  487. case <-timer.C:
  488. case <-ctx.Done():
  489. return
  490. }
  491. continue OUTER_LOOP
  492. }
  493. // By here, height and round match.
  494. // Proposal block parts were already matched and sent if any were wanted.
  495. // (These can match on hash so the round doesn't matter)
  496. // Now consider sending other things, like the Proposal itself.
  497. // Send Proposal && ProposalPOL BitArray?
  498. if rs.Proposal != nil && !prs.Proposal {
  499. // Proposal: share the proposal metadata with peer.
  500. {
  501. propProto := rs.Proposal.ToProto()
  502. logger.Debug("sending proposal", "height", prs.Height, "round", prs.Round)
  503. if err := r.dataCh.Send(ctx, p2p.Envelope{
  504. To: ps.peerID,
  505. Message: &tmcons.Proposal{
  506. Proposal: *propProto,
  507. },
  508. }); err != nil {
  509. return
  510. }
  511. // NOTE: A peer might have received a different proposal message, so
  512. // this Proposal msg will be rejected!
  513. ps.SetHasProposal(rs.Proposal)
  514. }
  515. // ProposalPOL: lets peer know which POL votes we have so far. The peer
  516. // must receive ProposalMessage first. Note, rs.Proposal was validated,
  517. // so rs.Proposal.POLRound <= rs.Round, so we definitely have
  518. // rs.Votes.Prevotes(rs.Proposal.POLRound).
  519. if 0 <= rs.Proposal.POLRound {
  520. pPol := rs.Votes.Prevotes(rs.Proposal.POLRound).BitArray()
  521. pPolProto := pPol.ToProto()
  522. logger.Debug("sending POL", "height", prs.Height, "round", prs.Round)
  523. if err := r.dataCh.Send(ctx, p2p.Envelope{
  524. To: ps.peerID,
  525. Message: &tmcons.ProposalPOL{
  526. Height: rs.Height,
  527. ProposalPolRound: rs.Proposal.POLRound,
  528. ProposalPol: *pPolProto,
  529. },
  530. }); err != nil {
  531. return
  532. }
  533. }
  534. continue OUTER_LOOP
  535. }
  536. // nothing to do -- sleep
  537. timer.Reset(r.state.config.PeerGossipSleepDuration)
  538. select {
  539. case <-timer.C:
  540. case <-ctx.Done():
  541. return
  542. }
  543. continue OUTER_LOOP
  544. }
  545. }
  546. // pickSendVote picks a vote and sends it to the peer. It will return true if
  547. // there is a vote to send and false otherwise.
  548. func (r *Reactor) pickSendVote(ctx context.Context, ps *PeerState, votes types.VoteSetReader) (bool, error) {
  549. vote, ok := ps.PickVoteToSend(votes)
  550. if !ok {
  551. return false, nil
  552. }
  553. r.logger.Debug("sending vote message", "ps", ps, "vote", vote)
  554. if err := r.voteCh.Send(ctx, p2p.Envelope{
  555. To: ps.peerID,
  556. Message: &tmcons.Vote{
  557. Vote: vote.ToProto(),
  558. },
  559. }); err != nil {
  560. return false, err
  561. }
  562. if err := ps.SetHasVote(vote); err != nil {
  563. return false, err
  564. }
  565. return true, nil
  566. }
  567. func (r *Reactor) gossipVotesForHeight(
  568. ctx context.Context,
  569. rs *cstypes.RoundState,
  570. prs *cstypes.PeerRoundState,
  571. ps *PeerState,
  572. ) (bool, error) {
  573. logger := r.logger.With("height", prs.Height).With("peer", ps.peerID)
  574. // if there are lastCommits to send...
  575. if prs.Step == cstypes.RoundStepNewHeight {
  576. if ok, err := r.pickSendVote(ctx, ps, rs.LastCommit); err != nil {
  577. return false, err
  578. } else if ok {
  579. logger.Debug("picked rs.LastCommit to send")
  580. return true, nil
  581. }
  582. }
  583. // if there are POL prevotes to send...
  584. if prs.Step <= cstypes.RoundStepPropose && prs.Round != -1 && prs.Round <= rs.Round && prs.ProposalPOLRound != -1 {
  585. if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil {
  586. if ok, err := r.pickSendVote(ctx, ps, polPrevotes); err != nil {
  587. return false, err
  588. } else if ok {
  589. logger.Debug("picked rs.Prevotes(prs.ProposalPOLRound) to send", "round", prs.ProposalPOLRound)
  590. return true, nil
  591. }
  592. }
  593. }
  594. // if there are prevotes to send...
  595. if prs.Step <= cstypes.RoundStepPrevoteWait && prs.Round != -1 && prs.Round <= rs.Round {
  596. if ok, err := r.pickSendVote(ctx, ps, rs.Votes.Prevotes(prs.Round)); err != nil {
  597. return false, err
  598. } else if ok {
  599. logger.Debug("picked rs.Prevotes(prs.Round) to send", "round", prs.Round)
  600. return true, nil
  601. }
  602. }
  603. // if there are precommits to send...
  604. if prs.Step <= cstypes.RoundStepPrecommitWait && prs.Round != -1 && prs.Round <= rs.Round {
  605. if ok, err := r.pickSendVote(ctx, ps, rs.Votes.Precommits(prs.Round)); err != nil {
  606. return false, err
  607. } else if ok {
  608. logger.Debug("picked rs.Precommits(prs.Round) to send", "round", prs.Round)
  609. return true, nil
  610. }
  611. }
  612. // if there are prevotes to send...(which are needed because of validBlock mechanism)
  613. if prs.Round != -1 && prs.Round <= rs.Round {
  614. if ok, err := r.pickSendVote(ctx, ps, rs.Votes.Prevotes(prs.Round)); err != nil {
  615. return false, err
  616. } else if ok {
  617. logger.Debug("picked rs.Prevotes(prs.Round) to send", "round", prs.Round)
  618. return true, nil
  619. }
  620. }
  621. // if there are POLPrevotes to send...
  622. if prs.ProposalPOLRound != -1 {
  623. if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil {
  624. if ok, err := r.pickSendVote(ctx, ps, polPrevotes); err != nil {
  625. return false, err
  626. } else if ok {
  627. logger.Debug("picked rs.Prevotes(prs.ProposalPOLRound) to send", "round", prs.ProposalPOLRound)
  628. return true, nil
  629. }
  630. }
  631. }
  632. return false, nil
  633. }
  634. func (r *Reactor) gossipVotesRoutine(ctx context.Context, ps *PeerState) {
  635. logger := r.logger.With("peer", ps.peerID)
  636. // XXX: simple hack to throttle logs upon sleep
  637. logThrottle := 0
  638. timer := time.NewTimer(0)
  639. defer timer.Stop()
  640. for {
  641. if !r.IsRunning() {
  642. return
  643. }
  644. select {
  645. case <-ctx.Done():
  646. return
  647. default:
  648. }
  649. rs := r.state.GetRoundState()
  650. prs := ps.GetRoundState()
  651. switch logThrottle {
  652. case 1: // first sleep
  653. logThrottle = 2
  654. case 2: // no more sleep
  655. logThrottle = 0
  656. }
  657. // if height matches, then send LastCommit, Prevotes, and Precommits
  658. if rs.Height == prs.Height {
  659. if ok, err := r.gossipVotesForHeight(ctx, rs, prs, ps); err != nil {
  660. return
  661. } else if ok {
  662. continue
  663. }
  664. }
  665. // special catchup logic -- if peer is lagging by height 1, send LastCommit
  666. if prs.Height != 0 && rs.Height == prs.Height+1 {
  667. if ok, err := r.pickSendVote(ctx, ps, rs.LastCommit); err != nil {
  668. return
  669. } else if ok {
  670. logger.Debug("picked rs.LastCommit to send", "height", prs.Height)
  671. continue
  672. }
  673. }
  674. // catchup logic -- if peer is lagging by more than 1, send Commit
  675. blockStoreBase := r.state.blockStore.Base()
  676. if blockStoreBase > 0 && prs.Height != 0 && rs.Height >= prs.Height+2 && prs.Height >= blockStoreBase {
  677. // Load the block commit for prs.Height, which contains precommit
  678. // signatures for prs.Height.
  679. if commit := r.state.blockStore.LoadBlockCommit(prs.Height); commit != nil {
  680. if ok, err := r.pickSendVote(ctx, ps, commit); err != nil {
  681. return
  682. } else if ok {
  683. logger.Debug("picked Catchup commit to send", "height", prs.Height)
  684. continue
  685. }
  686. }
  687. }
  688. if logThrottle == 0 {
  689. // we sent nothing -- sleep
  690. logThrottle = 1
  691. logger.Debug(
  692. "no votes to send; sleeping",
  693. "rs.Height", rs.Height,
  694. "prs.Height", prs.Height,
  695. "localPV", rs.Votes.Prevotes(rs.Round).BitArray(), "peerPV", prs.Prevotes,
  696. "localPC", rs.Votes.Precommits(rs.Round).BitArray(), "peerPC", prs.Precommits,
  697. )
  698. } else if logThrottle == 2 {
  699. logThrottle = 1
  700. }
  701. timer.Reset(r.state.config.PeerGossipSleepDuration)
  702. select {
  703. case <-ctx.Done():
  704. return
  705. case <-timer.C:
  706. }
  707. }
  708. }
  709. // NOTE: `queryMaj23Routine` has a simple crude design since it only comes
  710. // into play for liveness when there's a signature DDoS attack happening.
  711. func (r *Reactor) queryMaj23Routine(ctx context.Context, ps *PeerState) {
  712. timer := time.NewTimer(0)
  713. defer timer.Stop()
  714. ctx, cancel := context.WithCancel(ctx)
  715. defer cancel()
  716. for {
  717. if !ps.IsRunning() {
  718. return
  719. }
  720. select {
  721. case <-ctx.Done():
  722. return
  723. case <-timer.C:
  724. }
  725. if !ps.IsRunning() {
  726. return
  727. }
  728. rs := r.state.GetRoundState()
  729. prs := ps.GetRoundState()
  730. // TODO create more reliable coppies of these
  731. // structures so the following go routines don't race
  732. wg := &sync.WaitGroup{}
  733. if rs.Height == prs.Height {
  734. wg.Add(1)
  735. go func(rs *cstypes.RoundState, prs *cstypes.PeerRoundState) {
  736. defer wg.Done()
  737. // maybe send Height/Round/Prevotes
  738. if maj23, ok := rs.Votes.Prevotes(prs.Round).TwoThirdsMajority(); ok {
  739. if err := r.stateCh.Send(ctx, p2p.Envelope{
  740. To: ps.peerID,
  741. Message: &tmcons.VoteSetMaj23{
  742. Height: prs.Height,
  743. Round: prs.Round,
  744. Type: tmproto.PrevoteType,
  745. BlockID: maj23.ToProto(),
  746. },
  747. }); err != nil {
  748. cancel()
  749. }
  750. }
  751. }(rs, prs)
  752. if prs.ProposalPOLRound >= 0 {
  753. wg.Add(1)
  754. go func(rs *cstypes.RoundState, prs *cstypes.PeerRoundState) {
  755. defer wg.Done()
  756. // maybe send Height/Round/ProposalPOL
  757. if maj23, ok := rs.Votes.Prevotes(prs.ProposalPOLRound).TwoThirdsMajority(); ok {
  758. if err := r.stateCh.Send(ctx, p2p.Envelope{
  759. To: ps.peerID,
  760. Message: &tmcons.VoteSetMaj23{
  761. Height: prs.Height,
  762. Round: prs.ProposalPOLRound,
  763. Type: tmproto.PrevoteType,
  764. BlockID: maj23.ToProto(),
  765. },
  766. }); err != nil {
  767. cancel()
  768. }
  769. }
  770. }(rs, prs)
  771. }
  772. wg.Add(1)
  773. go func(rs *cstypes.RoundState, prs *cstypes.PeerRoundState) {
  774. defer wg.Done()
  775. // maybe send Height/Round/Precommits
  776. if maj23, ok := rs.Votes.Precommits(prs.Round).TwoThirdsMajority(); ok {
  777. if err := r.stateCh.Send(ctx, p2p.Envelope{
  778. To: ps.peerID,
  779. Message: &tmcons.VoteSetMaj23{
  780. Height: prs.Height,
  781. Round: prs.Round,
  782. Type: tmproto.PrecommitType,
  783. BlockID: maj23.ToProto(),
  784. },
  785. }); err != nil {
  786. cancel()
  787. }
  788. }
  789. }(rs, prs)
  790. }
  791. // Little point sending LastCommitRound/LastCommit, these are fleeting and
  792. // non-blocking.
  793. if prs.CatchupCommitRound != -1 && prs.Height > 0 {
  794. wg.Add(1)
  795. go func(rs *cstypes.RoundState, prs *cstypes.PeerRoundState) {
  796. defer wg.Done()
  797. if prs.Height <= r.state.blockStore.Height() && prs.Height >= r.state.blockStore.Base() {
  798. // maybe send Height/CatchupCommitRound/CatchupCommit
  799. if commit := r.state.LoadCommit(prs.Height); commit != nil {
  800. if err := r.stateCh.Send(ctx, p2p.Envelope{
  801. To: ps.peerID,
  802. Message: &tmcons.VoteSetMaj23{
  803. Height: prs.Height,
  804. Round: commit.Round,
  805. Type: tmproto.PrecommitType,
  806. BlockID: commit.BlockID.ToProto(),
  807. },
  808. }); err != nil {
  809. cancel()
  810. }
  811. }
  812. }
  813. }(rs, prs)
  814. }
  815. waitSignal := make(chan struct{})
  816. go func() { defer close(waitSignal); wg.Wait() }()
  817. select {
  818. case <-waitSignal:
  819. timer.Reset(r.state.config.PeerQueryMaj23SleepDuration)
  820. case <-ctx.Done():
  821. return
  822. }
  823. }
  824. }
  825. // processPeerUpdate process a peer update message. For new or reconnected peers,
  826. // we create a peer state if one does not exist for the peer, which should always
  827. // be the case, and we spawn all the relevant goroutine to broadcast messages to
  828. // the peer. During peer removal, we remove the peer for our set of peers and
  829. // signal to all spawned goroutines to gracefully exit in a non-blocking manner.
  830. func (r *Reactor) processPeerUpdate(ctx context.Context, peerUpdate p2p.PeerUpdate) {
  831. r.logger.Debug("received peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  832. r.mtx.Lock()
  833. defer r.mtx.Unlock()
  834. switch peerUpdate.Status {
  835. case p2p.PeerStatusUp:
  836. // Do not allow starting new broadcasting goroutines after reactor shutdown
  837. // has been initiated. This can happen after we've manually closed all
  838. // peer goroutines, but the router still sends in-flight peer updates.
  839. if !r.IsRunning() {
  840. return
  841. }
  842. ps, ok := r.peers[peerUpdate.NodeID]
  843. if !ok {
  844. ps = NewPeerState(r.logger, peerUpdate.NodeID)
  845. r.peers[peerUpdate.NodeID] = ps
  846. }
  847. if !ps.IsRunning() {
  848. // Set the peer state's closer to signal to all spawned goroutines to exit
  849. // when the peer is removed. We also set the running state to ensure we
  850. // do not spawn multiple instances of the same goroutines and finally we
  851. // set the waitgroup counter so we know when all goroutines have exited.
  852. ps.SetRunning(true)
  853. ctx, ps.cancel = context.WithCancel(ctx)
  854. go func() {
  855. select {
  856. case <-ctx.Done():
  857. return
  858. case <-r.readySignal:
  859. }
  860. // do nothing if the peer has
  861. // stopped while we've been waiting.
  862. if !ps.IsRunning() {
  863. return
  864. }
  865. // start goroutines for this peer
  866. go r.gossipDataRoutine(ctx, ps)
  867. go r.gossipVotesRoutine(ctx, ps)
  868. go r.queryMaj23Routine(ctx, ps)
  869. // Send our state to the peer. If we're block-syncing, broadcast a
  870. // RoundStepMessage later upon SwitchToConsensus().
  871. if !r.WaitSync() {
  872. go func() { _ = r.sendNewRoundStepMessage(ctx, ps.peerID) }()
  873. }
  874. }()
  875. }
  876. case p2p.PeerStatusDown:
  877. ps, ok := r.peers[peerUpdate.NodeID]
  878. if ok && ps.IsRunning() {
  879. // signal to all spawned goroutines for the peer to gracefully exit
  880. go func() {
  881. r.mtx.Lock()
  882. delete(r.peers, peerUpdate.NodeID)
  883. r.mtx.Unlock()
  884. ps.SetRunning(false)
  885. ps.cancel()
  886. }()
  887. }
  888. }
  889. }
  890. // handleStateMessage handles envelopes sent from peers on the StateChannel.
  891. // An error is returned if the message is unrecognized or if validation fails.
  892. // If we fail to find the peer state for the envelope sender, we perform a no-op
  893. // and return. This can happen when we process the envelope after the peer is
  894. // removed.
  895. func (r *Reactor) handleStateMessage(ctx context.Context, envelope *p2p.Envelope, msgI Message) error {
  896. ps, ok := r.GetPeerState(envelope.From)
  897. if !ok || ps == nil {
  898. r.logger.Debug("failed to find peer state", "peer", envelope.From, "ch_id", "StateChannel")
  899. return nil
  900. }
  901. switch msg := envelope.Message.(type) {
  902. case *tmcons.NewRoundStep:
  903. r.state.mtx.RLock()
  904. initialHeight := r.state.state.InitialHeight
  905. r.state.mtx.RUnlock()
  906. if err := msgI.(*NewRoundStepMessage).ValidateHeight(initialHeight); err != nil {
  907. r.logger.Error("peer sent us an invalid msg", "msg", msg, "err", err)
  908. return err
  909. }
  910. ps.ApplyNewRoundStepMessage(msgI.(*NewRoundStepMessage))
  911. case *tmcons.NewValidBlock:
  912. ps.ApplyNewValidBlockMessage(msgI.(*NewValidBlockMessage))
  913. case *tmcons.HasVote:
  914. if err := ps.ApplyHasVoteMessage(msgI.(*HasVoteMessage)); err != nil {
  915. r.logger.Error("applying HasVote message", "msg", msg, "err", err)
  916. return err
  917. }
  918. case *tmcons.VoteSetMaj23:
  919. r.state.mtx.RLock()
  920. height, votes := r.state.Height, r.state.Votes
  921. r.state.mtx.RUnlock()
  922. if height != msg.Height {
  923. return nil
  924. }
  925. vsmMsg := msgI.(*VoteSetMaj23Message)
  926. // peer claims to have a maj23 for some BlockID at <H,R,S>
  927. err := votes.SetPeerMaj23(msg.Round, msg.Type, ps.peerID, vsmMsg.BlockID)
  928. if err != nil {
  929. return err
  930. }
  931. // Respond with a VoteSetBitsMessage showing which votes we have and
  932. // consequently shows which we don't have.
  933. var ourVotes *bits.BitArray
  934. switch vsmMsg.Type {
  935. case tmproto.PrevoteType:
  936. ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(vsmMsg.BlockID)
  937. case tmproto.PrecommitType:
  938. ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(vsmMsg.BlockID)
  939. default:
  940. panic("bad VoteSetBitsMessage field type; forgot to add a check in ValidateBasic?")
  941. }
  942. eMsg := &tmcons.VoteSetBits{
  943. Height: msg.Height,
  944. Round: msg.Round,
  945. Type: msg.Type,
  946. BlockID: msg.BlockID,
  947. }
  948. if votesProto := ourVotes.ToProto(); votesProto != nil {
  949. eMsg.Votes = *votesProto
  950. }
  951. if err := r.voteSetBitsCh.Send(ctx, p2p.Envelope{
  952. To: envelope.From,
  953. Message: eMsg,
  954. }); err != nil {
  955. return err
  956. }
  957. default:
  958. return fmt.Errorf("received unknown message on StateChannel: %T", msg)
  959. }
  960. return nil
  961. }
  962. // handleDataMessage handles envelopes sent from peers on the DataChannel. If we
  963. // fail to find the peer state for the envelope sender, we perform a no-op and
  964. // return. This can happen when we process the envelope after the peer is
  965. // removed.
  966. func (r *Reactor) handleDataMessage(ctx context.Context, envelope *p2p.Envelope, msgI Message) error {
  967. logger := r.logger.With("peer", envelope.From, "ch_id", "DataChannel")
  968. ps, ok := r.GetPeerState(envelope.From)
  969. if !ok || ps == nil {
  970. r.logger.Debug("failed to find peer state")
  971. return nil
  972. }
  973. if r.WaitSync() {
  974. logger.Info("ignoring message received during sync", "msg", fmt.Sprintf("%T", msgI))
  975. return nil
  976. }
  977. switch msg := envelope.Message.(type) {
  978. case *tmcons.Proposal:
  979. pMsg := msgI.(*ProposalMessage)
  980. ps.SetHasProposal(pMsg.Proposal)
  981. select {
  982. case <-ctx.Done():
  983. return ctx.Err()
  984. case r.state.peerMsgQueue <- msgInfo{pMsg, envelope.From, tmtime.Now()}:
  985. }
  986. case *tmcons.ProposalPOL:
  987. ps.ApplyProposalPOLMessage(msgI.(*ProposalPOLMessage))
  988. case *tmcons.BlockPart:
  989. bpMsg := msgI.(*BlockPartMessage)
  990. ps.SetHasProposalBlockPart(bpMsg.Height, bpMsg.Round, int(bpMsg.Part.Index))
  991. r.Metrics.BlockParts.With("peer_id", string(envelope.From)).Add(1)
  992. select {
  993. case r.state.peerMsgQueue <- msgInfo{bpMsg, envelope.From, tmtime.Now()}:
  994. return nil
  995. case <-ctx.Done():
  996. return ctx.Err()
  997. }
  998. default:
  999. return fmt.Errorf("received unknown message on DataChannel: %T", msg)
  1000. }
  1001. return nil
  1002. }
  1003. // handleVoteMessage handles envelopes sent from peers on the VoteChannel. If we
  1004. // fail to find the peer state for the envelope sender, we perform a no-op and
  1005. // return. This can happen when we process the envelope after the peer is
  1006. // removed.
  1007. func (r *Reactor) handleVoteMessage(ctx context.Context, envelope *p2p.Envelope, msgI Message) error {
  1008. logger := r.logger.With("peer", envelope.From, "ch_id", "VoteChannel")
  1009. ps, ok := r.GetPeerState(envelope.From)
  1010. if !ok || ps == nil {
  1011. r.logger.Debug("failed to find peer state")
  1012. return nil
  1013. }
  1014. if r.WaitSync() {
  1015. logger.Info("ignoring message received during sync", "msg", msgI)
  1016. return nil
  1017. }
  1018. switch msg := envelope.Message.(type) {
  1019. case *tmcons.Vote:
  1020. r.state.mtx.RLock()
  1021. height, valSize, lastCommitSize := r.state.Height, r.state.Validators.Size(), r.state.LastCommit.Size()
  1022. r.state.mtx.RUnlock()
  1023. vMsg := msgI.(*VoteMessage)
  1024. ps.EnsureVoteBitArrays(height, valSize)
  1025. ps.EnsureVoteBitArrays(height-1, lastCommitSize)
  1026. if err := ps.SetHasVote(vMsg.Vote); err != nil {
  1027. return err
  1028. }
  1029. select {
  1030. case r.state.peerMsgQueue <- msgInfo{vMsg, envelope.From, tmtime.Now()}:
  1031. return nil
  1032. case <-ctx.Done():
  1033. return ctx.Err()
  1034. }
  1035. default:
  1036. return fmt.Errorf("received unknown message on VoteChannel: %T", msg)
  1037. }
  1038. }
  1039. // handleVoteSetBitsMessage handles envelopes sent from peers on the
  1040. // VoteSetBitsChannel. If we fail to find the peer state for the envelope sender,
  1041. // we perform a no-op and return. This can happen when we process the envelope
  1042. // after the peer is removed.
  1043. func (r *Reactor) handleVoteSetBitsMessage(ctx context.Context, envelope *p2p.Envelope, msgI Message) error {
  1044. logger := r.logger.With("peer", envelope.From, "ch_id", "VoteSetBitsChannel")
  1045. ps, ok := r.GetPeerState(envelope.From)
  1046. if !ok || ps == nil {
  1047. r.logger.Debug("failed to find peer state")
  1048. return nil
  1049. }
  1050. if r.WaitSync() {
  1051. logger.Info("ignoring message received during sync", "msg", msgI)
  1052. return nil
  1053. }
  1054. switch msg := envelope.Message.(type) {
  1055. case *tmcons.VoteSetBits:
  1056. r.state.mtx.RLock()
  1057. height, votes := r.state.Height, r.state.Votes
  1058. r.state.mtx.RUnlock()
  1059. vsbMsg := msgI.(*VoteSetBitsMessage)
  1060. if height == msg.Height {
  1061. var ourVotes *bits.BitArray
  1062. switch msg.Type {
  1063. case tmproto.PrevoteType:
  1064. ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(vsbMsg.BlockID)
  1065. case tmproto.PrecommitType:
  1066. ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(vsbMsg.BlockID)
  1067. default:
  1068. panic("bad VoteSetBitsMessage field type; forgot to add a check in ValidateBasic?")
  1069. }
  1070. ps.ApplyVoteSetBitsMessage(vsbMsg, ourVotes)
  1071. } else {
  1072. ps.ApplyVoteSetBitsMessage(vsbMsg, nil)
  1073. }
  1074. default:
  1075. return fmt.Errorf("received unknown message on VoteSetBitsChannel: %T", msg)
  1076. }
  1077. return nil
  1078. }
  1079. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  1080. // It will handle errors and any possible panics gracefully. A caller can handle
  1081. // any error returned by sending a PeerError on the respective channel.
  1082. //
  1083. // NOTE: We process these messages even when we're block syncing. Messages affect
  1084. // either a peer state or the consensus state. Peer state updates can happen in
  1085. // parallel, but processing of proposals, block parts, and votes are ordered by
  1086. // the p2p channel.
  1087. //
  1088. // NOTE: We block on consensus state for proposals, block parts, and votes.
  1089. func (r *Reactor) handleMessage(ctx context.Context, chID p2p.ChannelID, envelope *p2p.Envelope) (err error) {
  1090. defer func() {
  1091. if e := recover(); e != nil {
  1092. err = fmt.Errorf("panic in processing message: %v", e)
  1093. r.logger.Error(
  1094. "recovering from processing message panic",
  1095. "err", err,
  1096. "stack", string(debug.Stack()),
  1097. )
  1098. }
  1099. }()
  1100. // We wrap the envelope's message in a Proto wire type so we can convert back
  1101. // the domain type that individual channel message handlers can work with. We
  1102. // do this here once to avoid having to do it for each individual message type.
  1103. // and because a large part of the core business logic depends on these
  1104. // domain types opposed to simply working with the Proto types.
  1105. protoMsg := new(tmcons.Message)
  1106. if err := protoMsg.Wrap(envelope.Message); err != nil {
  1107. return err
  1108. }
  1109. msgI, err := MsgFromProto(protoMsg)
  1110. if err != nil {
  1111. return err
  1112. }
  1113. r.logger.Debug("received message", "ch_id", chID, "message", msgI, "peer", envelope.From)
  1114. switch chID {
  1115. case StateChannel:
  1116. err = r.handleStateMessage(ctx, envelope, msgI)
  1117. case DataChannel:
  1118. err = r.handleDataMessage(ctx, envelope, msgI)
  1119. case VoteChannel:
  1120. err = r.handleVoteMessage(ctx, envelope, msgI)
  1121. case VoteSetBitsChannel:
  1122. err = r.handleVoteSetBitsMessage(ctx, envelope, msgI)
  1123. default:
  1124. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  1125. }
  1126. return err
  1127. }
  1128. // processStateCh initiates a blocking process where we listen for and handle
  1129. // envelopes on the StateChannel. Any error encountered during message
  1130. // execution will result in a PeerError being sent on the StateChannel. When
  1131. // the reactor is stopped, we will catch the signal and close the p2p Channel
  1132. // gracefully.
  1133. func (r *Reactor) processStateCh(ctx context.Context) {
  1134. iter := r.stateCh.Receive(ctx)
  1135. for iter.Next(ctx) {
  1136. envelope := iter.Envelope()
  1137. if err := r.handleMessage(ctx, r.stateCh.ID, envelope); err != nil {
  1138. r.logger.Error("failed to process message", "ch_id", r.stateCh.ID, "envelope", envelope, "err", err)
  1139. if serr := r.stateCh.SendError(ctx, p2p.PeerError{
  1140. NodeID: envelope.From,
  1141. Err: err,
  1142. }); serr != nil {
  1143. return
  1144. }
  1145. }
  1146. }
  1147. }
  1148. // processDataCh initiates a blocking process where we listen for and handle
  1149. // envelopes on the DataChannel. Any error encountered during message
  1150. // execution will result in a PeerError being sent on the DataChannel. When
  1151. // the reactor is stopped, we will catch the signal and close the p2p Channel
  1152. // gracefully.
  1153. func (r *Reactor) processDataCh(ctx context.Context) {
  1154. iter := r.dataCh.Receive(ctx)
  1155. for iter.Next(ctx) {
  1156. envelope := iter.Envelope()
  1157. if err := r.handleMessage(ctx, r.dataCh.ID, envelope); err != nil {
  1158. r.logger.Error("failed to process message", "ch_id", r.dataCh.ID, "envelope", envelope, "err", err)
  1159. if serr := r.dataCh.SendError(ctx, p2p.PeerError{
  1160. NodeID: envelope.From,
  1161. Err: err,
  1162. }); serr != nil {
  1163. return
  1164. }
  1165. }
  1166. }
  1167. }
  1168. // processVoteCh initiates a blocking process where we listen for and handle
  1169. // envelopes on the VoteChannel. Any error encountered during message
  1170. // execution will result in a PeerError being sent on the VoteChannel. When
  1171. // the reactor is stopped, we will catch the signal and close the p2p Channel
  1172. // gracefully.
  1173. func (r *Reactor) processVoteCh(ctx context.Context) {
  1174. iter := r.voteCh.Receive(ctx)
  1175. for iter.Next(ctx) {
  1176. envelope := iter.Envelope()
  1177. if err := r.handleMessage(ctx, r.voteCh.ID, envelope); err != nil {
  1178. r.logger.Error("failed to process message", "ch_id", r.voteCh.ID, "envelope", envelope, "err", err)
  1179. if serr := r.voteCh.SendError(ctx, p2p.PeerError{
  1180. NodeID: envelope.From,
  1181. Err: err,
  1182. }); serr != nil {
  1183. return
  1184. }
  1185. }
  1186. }
  1187. }
  1188. // processVoteCh initiates a blocking process where we listen for and handle
  1189. // envelopes on the VoteSetBitsChannel. Any error encountered during message
  1190. // execution will result in a PeerError being sent on the VoteSetBitsChannel.
  1191. // When the reactor is stopped, we will catch the signal and close the p2p
  1192. // Channel gracefully.
  1193. func (r *Reactor) processVoteSetBitsCh(ctx context.Context) {
  1194. iter := r.voteSetBitsCh.Receive(ctx)
  1195. for iter.Next(ctx) {
  1196. envelope := iter.Envelope()
  1197. if err := r.handleMessage(ctx, r.voteSetBitsCh.ID, envelope); err != nil {
  1198. if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
  1199. return
  1200. }
  1201. r.logger.Error("failed to process message", "ch_id", r.voteSetBitsCh.ID, "envelope", envelope, "err", err)
  1202. if serr := r.voteSetBitsCh.SendError(ctx, p2p.PeerError{
  1203. NodeID: envelope.From,
  1204. Err: err,
  1205. }); serr != nil {
  1206. return
  1207. }
  1208. }
  1209. }
  1210. }
  1211. // processPeerUpdates initiates a blocking process where we listen for and handle
  1212. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  1213. // close the p2p PeerUpdatesCh gracefully.
  1214. func (r *Reactor) processPeerUpdates(ctx context.Context) {
  1215. for {
  1216. select {
  1217. case <-ctx.Done():
  1218. return
  1219. case peerUpdate := <-r.peerUpdates.Updates():
  1220. r.processPeerUpdate(ctx, peerUpdate)
  1221. }
  1222. }
  1223. }
  1224. func (r *Reactor) peerStatsRoutine(ctx context.Context) {
  1225. for {
  1226. if !r.IsRunning() {
  1227. r.logger.Info("stopping peerStatsRoutine")
  1228. return
  1229. }
  1230. select {
  1231. case msg := <-r.state.statsMsgQueue:
  1232. ps, ok := r.GetPeerState(msg.PeerID)
  1233. if !ok || ps == nil {
  1234. r.logger.Debug("attempt to update stats for non-existent peer", "peer", msg.PeerID)
  1235. continue
  1236. }
  1237. switch msg.Msg.(type) {
  1238. case *VoteMessage:
  1239. if numVotes := ps.RecordVote(); numVotes%votesToContributeToBecomeGoodPeer == 0 {
  1240. r.peerUpdates.SendUpdate(ctx, p2p.PeerUpdate{
  1241. NodeID: msg.PeerID,
  1242. Status: p2p.PeerStatusGood,
  1243. })
  1244. }
  1245. case *BlockPartMessage:
  1246. if numParts := ps.RecordBlockPart(); numParts%blocksToContributeToBecomeGoodPeer == 0 {
  1247. r.peerUpdates.SendUpdate(ctx, p2p.PeerUpdate{
  1248. NodeID: msg.PeerID,
  1249. Status: p2p.PeerStatusGood,
  1250. })
  1251. }
  1252. }
  1253. case <-ctx.Done():
  1254. return
  1255. }
  1256. }
  1257. }
  1258. func (r *Reactor) GetConsensusState() *State {
  1259. return r.state
  1260. }
  1261. func (r *Reactor) SetStateSyncingMetrics(v float64) {
  1262. r.Metrics.StateSyncing.Set(v)
  1263. }
  1264. func (r *Reactor) SetBlockSyncingMetrics(v float64) {
  1265. r.Metrics.BlockSyncing.Set(v)
  1266. }