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.

1472 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. eventBus *eventbus.EventBus,
  124. waitSync bool,
  125. metrics *Metrics,
  126. ) (*Reactor, error) {
  127. chans := getChannelDescriptors()
  128. stateCh, err := channelCreator(ctx, chans[StateChannel])
  129. if err != nil {
  130. return nil, err
  131. }
  132. dataCh, err := channelCreator(ctx, chans[DataChannel])
  133. if err != nil {
  134. return nil, err
  135. }
  136. voteCh, err := channelCreator(ctx, chans[VoteChannel])
  137. if err != nil {
  138. return nil, err
  139. }
  140. voteSetBitsCh, err := channelCreator(ctx, chans[VoteSetBitsChannel])
  141. if err != nil {
  142. return nil, err
  143. }
  144. r := &Reactor{
  145. logger: logger,
  146. state: cs,
  147. waitSync: waitSync,
  148. peers: make(map[types.NodeID]*PeerState),
  149. eventBus: eventBus,
  150. Metrics: metrics,
  151. stateCh: stateCh,
  152. dataCh: dataCh,
  153. voteCh: voteCh,
  154. voteSetBitsCh: voteSetBitsCh,
  155. peerUpdates: peerUpdates,
  156. readySignal: make(chan struct{}),
  157. }
  158. r.BaseService = *service.NewBaseService(logger, "Consensus", r)
  159. if !r.waitSync {
  160. close(r.readySignal)
  161. }
  162. return r, nil
  163. }
  164. // OnStart starts separate go routines for each p2p Channel and listens for
  165. // envelopes on each. In addition, it also listens for peer updates and handles
  166. // messages on that p2p channel accordingly. The caller must be sure to execute
  167. // OnStop to ensure the outbound p2p Channels are closed.
  168. func (r *Reactor) OnStart(ctx context.Context) error {
  169. r.logger.Debug("consensus wait sync", "wait_sync", r.WaitSync())
  170. // start routine that computes peer statistics for evaluating peer quality
  171. //
  172. // TODO: Evaluate if we need this to be synchronized via WaitGroup as to not
  173. // leak the goroutine when stopping the reactor.
  174. go r.peerStatsRoutine(ctx)
  175. r.subscribeToBroadcastEvents()
  176. if !r.WaitSync() {
  177. if err := r.state.Start(ctx); err != nil {
  178. return err
  179. }
  180. }
  181. go r.processStateCh(ctx)
  182. go r.processDataCh(ctx)
  183. go r.processVoteCh(ctx)
  184. go r.processVoteSetBitsCh(ctx)
  185. go r.processPeerUpdates(ctx)
  186. return nil
  187. }
  188. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  189. // blocking until they all exit, as well as unsubscribing from events and stopping
  190. // state.
  191. func (r *Reactor) OnStop() {
  192. r.state.Stop()
  193. if !r.WaitSync() {
  194. r.state.Wait()
  195. }
  196. }
  197. // WaitSync returns whether the consensus reactor is waiting for state/block sync.
  198. func (r *Reactor) WaitSync() bool {
  199. r.mtx.RLock()
  200. defer r.mtx.RUnlock()
  201. return r.waitSync
  202. }
  203. // SwitchToConsensus switches from block-sync mode to consensus mode. It resets
  204. // the state, turns off block-sync, and starts the consensus state-machine.
  205. func (r *Reactor) SwitchToConsensus(ctx context.Context, state sm.State, skipWAL bool) {
  206. r.logger.Info("switching to consensus")
  207. // we have no votes, so reconstruct LastCommit from SeenCommit
  208. if state.LastBlockHeight > 0 {
  209. r.state.reconstructLastCommit(state)
  210. }
  211. // NOTE: The line below causes broadcastNewRoundStepRoutine() to broadcast a
  212. // NewRoundStepMessage.
  213. r.state.updateToState(ctx, state)
  214. r.mtx.Lock()
  215. r.waitSync = false
  216. close(r.readySignal)
  217. r.mtx.Unlock()
  218. r.Metrics.BlockSyncing.Set(0)
  219. r.Metrics.StateSyncing.Set(0)
  220. if skipWAL {
  221. r.state.doWALCatchup = false
  222. }
  223. if err := r.state.Start(ctx); err != nil {
  224. panic(fmt.Sprintf(`failed to start consensus state: %v
  225. conS:
  226. %+v
  227. conR:
  228. %+v`, err, r.state, r))
  229. }
  230. d := types.EventDataBlockSyncStatus{Complete: true, Height: state.LastBlockHeight}
  231. if err := r.eventBus.PublishEventBlockSyncStatus(ctx, d); err != nil {
  232. r.logger.Error("failed to emit the blocksync complete event", "err", err)
  233. }
  234. }
  235. // String returns a string representation of the Reactor.
  236. //
  237. // NOTE: For now, it is just a hard-coded string to avoid accessing unprotected
  238. // shared variables.
  239. //
  240. // TODO: improve!
  241. func (r *Reactor) String() string {
  242. return "ConsensusReactor"
  243. }
  244. // StringIndented returns an indented string representation of the Reactor.
  245. func (r *Reactor) StringIndented(indent string) string {
  246. r.mtx.RLock()
  247. defer r.mtx.RUnlock()
  248. s := "ConsensusReactor{\n"
  249. s += indent + " " + r.state.StringIndented(indent+" ") + "\n"
  250. for _, ps := range r.peers {
  251. s += indent + " " + ps.StringIndented(indent+" ") + "\n"
  252. }
  253. s += indent + "}"
  254. return s
  255. }
  256. // GetPeerState returns PeerState for a given NodeID.
  257. func (r *Reactor) GetPeerState(peerID types.NodeID) (*PeerState, bool) {
  258. r.mtx.RLock()
  259. defer r.mtx.RUnlock()
  260. ps, ok := r.peers[peerID]
  261. return ps, ok
  262. }
  263. func (r *Reactor) broadcastNewRoundStepMessage(ctx context.Context, rs *cstypes.RoundState) error {
  264. return r.stateCh.Send(ctx, p2p.Envelope{
  265. Broadcast: true,
  266. Message: makeRoundStepMessage(rs),
  267. })
  268. }
  269. func (r *Reactor) broadcastNewValidBlockMessage(ctx context.Context, rs *cstypes.RoundState) error {
  270. psHeader := rs.ProposalBlockParts.Header()
  271. return r.stateCh.Send(ctx, p2p.Envelope{
  272. Broadcast: true,
  273. Message: &tmcons.NewValidBlock{
  274. Height: rs.Height,
  275. Round: rs.Round,
  276. BlockPartSetHeader: psHeader.ToProto(),
  277. BlockParts: rs.ProposalBlockParts.BitArray().ToProto(),
  278. IsCommit: rs.Step == cstypes.RoundStepCommit,
  279. },
  280. })
  281. }
  282. func (r *Reactor) broadcastHasVoteMessage(ctx context.Context, vote *types.Vote) error {
  283. return r.stateCh.Send(ctx, p2p.Envelope{
  284. Broadcast: true,
  285. Message: &tmcons.HasVote{
  286. Height: vote.Height,
  287. Round: vote.Round,
  288. Type: vote.Type,
  289. Index: vote.ValidatorIndex,
  290. },
  291. })
  292. }
  293. // subscribeToBroadcastEvents subscribes for new round steps and votes using the
  294. // internal pubsub defined in the consensus state to broadcast them to peers
  295. // upon receiving.
  296. func (r *Reactor) subscribeToBroadcastEvents() {
  297. onStopCh := r.state.getOnStopCh()
  298. err := r.state.evsw.AddListenerForEvent(
  299. listenerIDConsensus,
  300. types.EventNewRoundStepValue,
  301. func(ctx context.Context, data tmevents.EventData) error {
  302. if err := r.broadcastNewRoundStepMessage(ctx, data.(*cstypes.RoundState)); err != nil {
  303. return err
  304. }
  305. select {
  306. case onStopCh <- data.(*cstypes.RoundState):
  307. return nil
  308. case <-ctx.Done():
  309. return ctx.Err()
  310. default:
  311. return nil
  312. }
  313. },
  314. )
  315. if err != nil {
  316. r.logger.Error("failed to add listener for events", "err", err)
  317. }
  318. err = r.state.evsw.AddListenerForEvent(
  319. listenerIDConsensus,
  320. types.EventValidBlockValue,
  321. func(ctx context.Context, data tmevents.EventData) error {
  322. return r.broadcastNewValidBlockMessage(ctx, data.(*cstypes.RoundState))
  323. },
  324. )
  325. if err != nil {
  326. r.logger.Error("failed to add listener for events", "err", err)
  327. }
  328. err = r.state.evsw.AddListenerForEvent(
  329. listenerIDConsensus,
  330. types.EventVoteValue,
  331. func(ctx context.Context, data tmevents.EventData) error {
  332. return r.broadcastHasVoteMessage(ctx, data.(*types.Vote))
  333. },
  334. )
  335. if err != nil {
  336. r.logger.Error("failed to add listener for events", "err", err)
  337. }
  338. }
  339. func makeRoundStepMessage(rs *cstypes.RoundState) *tmcons.NewRoundStep {
  340. return &tmcons.NewRoundStep{
  341. Height: rs.Height,
  342. Round: rs.Round,
  343. Step: uint32(rs.Step),
  344. SecondsSinceStartTime: int64(time.Since(rs.StartTime).Seconds()),
  345. LastCommitRound: rs.LastCommit.GetRound(),
  346. }
  347. }
  348. func (r *Reactor) sendNewRoundStepMessage(ctx context.Context, peerID types.NodeID) error {
  349. return r.stateCh.Send(ctx, p2p.Envelope{
  350. To: peerID,
  351. Message: makeRoundStepMessage(r.state.GetRoundState()),
  352. })
  353. }
  354. func (r *Reactor) gossipDataForCatchup(ctx context.Context, rs *cstypes.RoundState, prs *cstypes.PeerRoundState, ps *PeerState) {
  355. logger := r.logger.With("height", prs.Height).With("peer", ps.peerID)
  356. if index, ok := prs.ProposalBlockParts.Not().PickRandom(); ok {
  357. // ensure that the peer's PartSetHeader is correct
  358. blockMeta := r.state.blockStore.LoadBlockMeta(prs.Height)
  359. if blockMeta == nil {
  360. logger.Error(
  361. "failed to load block meta",
  362. "our_height", rs.Height,
  363. "blockstore_base", r.state.blockStore.Base(),
  364. "blockstore_height", r.state.blockStore.Height(),
  365. )
  366. time.Sleep(r.state.config.PeerGossipSleepDuration)
  367. return
  368. } else if !blockMeta.BlockID.PartSetHeader.Equals(prs.ProposalBlockPartSetHeader) {
  369. logger.Info(
  370. "peer ProposalBlockPartSetHeader mismatch; sleeping",
  371. "block_part_set_header", blockMeta.BlockID.PartSetHeader,
  372. "peer_block_part_set_header", prs.ProposalBlockPartSetHeader,
  373. )
  374. time.Sleep(r.state.config.PeerGossipSleepDuration)
  375. return
  376. }
  377. part := r.state.blockStore.LoadBlockPart(prs.Height, index)
  378. if part == nil {
  379. logger.Error(
  380. "failed to load block part",
  381. "index", index,
  382. "block_part_set_header", blockMeta.BlockID.PartSetHeader,
  383. "peer_block_part_set_header", prs.ProposalBlockPartSetHeader,
  384. )
  385. time.Sleep(r.state.config.PeerGossipSleepDuration)
  386. return
  387. }
  388. partProto, err := part.ToProto()
  389. if err != nil {
  390. logger.Error("failed to convert block part to proto", "err", err)
  391. time.Sleep(r.state.config.PeerGossipSleepDuration)
  392. return
  393. }
  394. logger.Debug("sending block part for catchup", "round", prs.Round, "index", index)
  395. _ = r.dataCh.Send(ctx, p2p.Envelope{
  396. To: ps.peerID,
  397. Message: &tmcons.BlockPart{
  398. Height: prs.Height, // not our height, so it does not matter.
  399. Round: prs.Round, // not our height, so it does not matter
  400. Part: *partProto,
  401. },
  402. })
  403. return
  404. }
  405. time.Sleep(r.state.config.PeerGossipSleepDuration)
  406. }
  407. func (r *Reactor) gossipDataRoutine(ctx context.Context, ps *PeerState) {
  408. logger := r.logger.With("peer", ps.peerID)
  409. timer := time.NewTimer(0)
  410. defer timer.Stop()
  411. OUTER_LOOP:
  412. for {
  413. if !r.IsRunning() {
  414. return
  415. }
  416. select {
  417. case <-ctx.Done():
  418. return
  419. default:
  420. }
  421. rs := r.state.GetRoundState()
  422. prs := ps.GetRoundState()
  423. // Send proposal Block parts?
  424. if rs.ProposalBlockParts.HasHeader(prs.ProposalBlockPartSetHeader) {
  425. if index, ok := rs.ProposalBlockParts.BitArray().Sub(prs.ProposalBlockParts.Copy()).PickRandom(); ok {
  426. part := rs.ProposalBlockParts.GetPart(index)
  427. partProto, err := part.ToProto()
  428. if err != nil {
  429. logger.Error("failed to convert block part to proto", "err", err)
  430. return
  431. }
  432. logger.Debug("sending block part", "height", prs.Height, "round", prs.Round)
  433. if err := r.dataCh.Send(ctx, p2p.Envelope{
  434. To: ps.peerID,
  435. Message: &tmcons.BlockPart{
  436. Height: rs.Height, // this tells peer that this part applies to us
  437. Round: rs.Round, // this tells peer that this part applies to us
  438. Part: *partProto,
  439. },
  440. }); err != nil {
  441. return
  442. }
  443. ps.SetHasProposalBlockPart(prs.Height, prs.Round, index)
  444. continue OUTER_LOOP
  445. }
  446. }
  447. // if the peer is on a previous height that we have, help catch up
  448. blockStoreBase := r.state.blockStore.Base()
  449. if blockStoreBase > 0 && 0 < prs.Height && prs.Height < rs.Height && prs.Height >= blockStoreBase {
  450. heightLogger := logger.With("height", prs.Height)
  451. // If we never received the commit message from the peer, the block parts
  452. // will not be initialized.
  453. if prs.ProposalBlockParts == nil {
  454. blockMeta := r.state.blockStore.LoadBlockMeta(prs.Height)
  455. if blockMeta == nil {
  456. heightLogger.Error(
  457. "failed to load block meta",
  458. "blockstoreBase", blockStoreBase,
  459. "blockstoreHeight", r.state.blockStore.Height(),
  460. )
  461. timer.Reset(r.state.config.PeerGossipSleepDuration)
  462. select {
  463. case <-timer.C:
  464. case <-ctx.Done():
  465. return
  466. }
  467. } else {
  468. ps.InitProposalBlockParts(blockMeta.BlockID.PartSetHeader)
  469. }
  470. // Continue the loop since prs is a copy and not effected by this
  471. // initialization.
  472. continue OUTER_LOOP
  473. }
  474. r.gossipDataForCatchup(ctx, rs, prs, ps)
  475. continue OUTER_LOOP
  476. }
  477. // if height and round don't match, sleep
  478. if (rs.Height != prs.Height) || (rs.Round != prs.Round) {
  479. timer.Reset(r.state.config.PeerGossipSleepDuration)
  480. select {
  481. case <-timer.C:
  482. case <-ctx.Done():
  483. return
  484. }
  485. continue OUTER_LOOP
  486. }
  487. // By here, height and round match.
  488. // Proposal block parts were already matched and sent if any were wanted.
  489. // (These can match on hash so the round doesn't matter)
  490. // Now consider sending other things, like the Proposal itself.
  491. // Send Proposal && ProposalPOL BitArray?
  492. if rs.Proposal != nil && !prs.Proposal {
  493. // Proposal: share the proposal metadata with peer.
  494. {
  495. propProto := rs.Proposal.ToProto()
  496. logger.Debug("sending proposal", "height", prs.Height, "round", prs.Round)
  497. if err := r.dataCh.Send(ctx, p2p.Envelope{
  498. To: ps.peerID,
  499. Message: &tmcons.Proposal{
  500. Proposal: *propProto,
  501. },
  502. }); err != nil {
  503. return
  504. }
  505. // NOTE: A peer might have received a different proposal message, so
  506. // this Proposal msg will be rejected!
  507. ps.SetHasProposal(rs.Proposal)
  508. }
  509. // ProposalPOL: lets peer know which POL votes we have so far. The peer
  510. // must receive ProposalMessage first. Note, rs.Proposal was validated,
  511. // so rs.Proposal.POLRound <= rs.Round, so we definitely have
  512. // rs.Votes.Prevotes(rs.Proposal.POLRound).
  513. if 0 <= rs.Proposal.POLRound {
  514. pPol := rs.Votes.Prevotes(rs.Proposal.POLRound).BitArray()
  515. pPolProto := pPol.ToProto()
  516. logger.Debug("sending POL", "height", prs.Height, "round", prs.Round)
  517. if err := r.dataCh.Send(ctx, p2p.Envelope{
  518. To: ps.peerID,
  519. Message: &tmcons.ProposalPOL{
  520. Height: rs.Height,
  521. ProposalPolRound: rs.Proposal.POLRound,
  522. ProposalPol: *pPolProto,
  523. },
  524. }); err != nil {
  525. return
  526. }
  527. }
  528. continue OUTER_LOOP
  529. }
  530. // nothing to do -- sleep
  531. timer.Reset(r.state.config.PeerGossipSleepDuration)
  532. select {
  533. case <-timer.C:
  534. case <-ctx.Done():
  535. return
  536. }
  537. continue OUTER_LOOP
  538. }
  539. }
  540. // pickSendVote picks a vote and sends it to the peer. It will return true if
  541. // there is a vote to send and false otherwise.
  542. func (r *Reactor) pickSendVote(ctx context.Context, ps *PeerState, votes types.VoteSetReader) (bool, error) {
  543. vote, ok := ps.PickVoteToSend(votes)
  544. if !ok {
  545. return false, nil
  546. }
  547. r.logger.Debug("sending vote message", "ps", ps, "vote", vote)
  548. if err := r.voteCh.Send(ctx, p2p.Envelope{
  549. To: ps.peerID,
  550. Message: &tmcons.Vote{
  551. Vote: vote.ToProto(),
  552. },
  553. }); err != nil {
  554. return false, err
  555. }
  556. if err := ps.SetHasVote(vote); err != nil {
  557. return false, err
  558. }
  559. return true, nil
  560. }
  561. func (r *Reactor) gossipVotesForHeight(
  562. ctx context.Context,
  563. rs *cstypes.RoundState,
  564. prs *cstypes.PeerRoundState,
  565. ps *PeerState,
  566. ) (bool, error) {
  567. logger := r.logger.With("height", prs.Height).With("peer", ps.peerID)
  568. // if there are lastCommits to send...
  569. if prs.Step == cstypes.RoundStepNewHeight {
  570. if ok, err := r.pickSendVote(ctx, ps, rs.LastCommit); err != nil {
  571. return false, err
  572. } else if ok {
  573. logger.Debug("picked rs.LastCommit to send")
  574. return true, nil
  575. }
  576. }
  577. // if there are POL prevotes to send...
  578. if prs.Step <= cstypes.RoundStepPropose && prs.Round != -1 && prs.Round <= rs.Round && prs.ProposalPOLRound != -1 {
  579. if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil {
  580. if ok, err := r.pickSendVote(ctx, ps, polPrevotes); err != nil {
  581. return false, err
  582. } else if ok {
  583. logger.Debug("picked rs.Prevotes(prs.ProposalPOLRound) to send", "round", prs.ProposalPOLRound)
  584. return true, nil
  585. }
  586. }
  587. }
  588. // if there are prevotes to send...
  589. if prs.Step <= cstypes.RoundStepPrevoteWait && prs.Round != -1 && prs.Round <= rs.Round {
  590. if ok, err := r.pickSendVote(ctx, ps, rs.Votes.Prevotes(prs.Round)); err != nil {
  591. return false, err
  592. } else if ok {
  593. logger.Debug("picked rs.Prevotes(prs.Round) to send", "round", prs.Round)
  594. return true, nil
  595. }
  596. }
  597. // if there are precommits to send...
  598. if prs.Step <= cstypes.RoundStepPrecommitWait && prs.Round != -1 && prs.Round <= rs.Round {
  599. if ok, err := r.pickSendVote(ctx, ps, rs.Votes.Precommits(prs.Round)); err != nil {
  600. return false, err
  601. } else if ok {
  602. logger.Debug("picked rs.Precommits(prs.Round) to send", "round", prs.Round)
  603. return true, nil
  604. }
  605. }
  606. // if there are prevotes to send...(which are needed because of validBlock mechanism)
  607. if prs.Round != -1 && prs.Round <= rs.Round {
  608. if ok, err := r.pickSendVote(ctx, ps, rs.Votes.Prevotes(prs.Round)); err != nil {
  609. return false, err
  610. } else if ok {
  611. logger.Debug("picked rs.Prevotes(prs.Round) to send", "round", prs.Round)
  612. return true, nil
  613. }
  614. }
  615. // if there are POLPrevotes to send...
  616. if prs.ProposalPOLRound != -1 {
  617. if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil {
  618. if ok, err := r.pickSendVote(ctx, ps, polPrevotes); err != nil {
  619. return false, err
  620. } else if ok {
  621. logger.Debug("picked rs.Prevotes(prs.ProposalPOLRound) to send", "round", prs.ProposalPOLRound)
  622. return true, nil
  623. }
  624. }
  625. }
  626. return false, nil
  627. }
  628. func (r *Reactor) gossipVotesRoutine(ctx context.Context, ps *PeerState) {
  629. logger := r.logger.With("peer", ps.peerID)
  630. // XXX: simple hack to throttle logs upon sleep
  631. logThrottle := 0
  632. timer := time.NewTimer(0)
  633. defer timer.Stop()
  634. for {
  635. if !r.IsRunning() {
  636. return
  637. }
  638. select {
  639. case <-ctx.Done():
  640. return
  641. default:
  642. }
  643. rs := r.state.GetRoundState()
  644. prs := ps.GetRoundState()
  645. switch logThrottle {
  646. case 1: // first sleep
  647. logThrottle = 2
  648. case 2: // no more sleep
  649. logThrottle = 0
  650. }
  651. // if height matches, then send LastCommit, Prevotes, and Precommits
  652. if rs.Height == prs.Height {
  653. if ok, err := r.gossipVotesForHeight(ctx, rs, prs, ps); err != nil {
  654. return
  655. } else if ok {
  656. continue
  657. }
  658. }
  659. // special catchup logic -- if peer is lagging by height 1, send LastCommit
  660. if prs.Height != 0 && rs.Height == prs.Height+1 {
  661. if ok, err := r.pickSendVote(ctx, ps, rs.LastCommit); err != nil {
  662. return
  663. } else if ok {
  664. logger.Debug("picked rs.LastCommit to send", "height", prs.Height)
  665. continue
  666. }
  667. }
  668. // catchup logic -- if peer is lagging by more than 1, send Commit
  669. blockStoreBase := r.state.blockStore.Base()
  670. if blockStoreBase > 0 && prs.Height != 0 && rs.Height >= prs.Height+2 && prs.Height >= blockStoreBase {
  671. // Load the block commit for prs.Height, which contains precommit
  672. // signatures for prs.Height.
  673. if commit := r.state.blockStore.LoadBlockCommit(prs.Height); commit != nil {
  674. if ok, err := r.pickSendVote(ctx, ps, commit); err != nil {
  675. return
  676. } else if ok {
  677. logger.Debug("picked Catchup commit to send", "height", prs.Height)
  678. continue
  679. }
  680. }
  681. }
  682. if logThrottle == 0 {
  683. // we sent nothing -- sleep
  684. logThrottle = 1
  685. logger.Debug(
  686. "no votes to send; sleeping",
  687. "rs.Height", rs.Height,
  688. "prs.Height", prs.Height,
  689. "localPV", rs.Votes.Prevotes(rs.Round).BitArray(), "peerPV", prs.Prevotes,
  690. "localPC", rs.Votes.Precommits(rs.Round).BitArray(), "peerPC", prs.Precommits,
  691. )
  692. } else if logThrottle == 2 {
  693. logThrottle = 1
  694. }
  695. timer.Reset(r.state.config.PeerGossipSleepDuration)
  696. select {
  697. case <-ctx.Done():
  698. return
  699. case <-timer.C:
  700. }
  701. }
  702. }
  703. // NOTE: `queryMaj23Routine` has a simple crude design since it only comes
  704. // into play for liveness when there's a signature DDoS attack happening.
  705. func (r *Reactor) queryMaj23Routine(ctx context.Context, ps *PeerState) {
  706. timer := time.NewTimer(0)
  707. defer timer.Stop()
  708. ctx, cancel := context.WithCancel(ctx)
  709. defer cancel()
  710. for {
  711. if !ps.IsRunning() {
  712. return
  713. }
  714. select {
  715. case <-ctx.Done():
  716. return
  717. case <-timer.C:
  718. }
  719. if !ps.IsRunning() {
  720. return
  721. }
  722. rs := r.state.GetRoundState()
  723. prs := ps.GetRoundState()
  724. // TODO create more reliable coppies of these
  725. // structures so the following go routines don't race
  726. wg := &sync.WaitGroup{}
  727. if rs.Height == prs.Height {
  728. wg.Add(1)
  729. go func(rs *cstypes.RoundState, prs *cstypes.PeerRoundState) {
  730. defer wg.Done()
  731. // maybe send Height/Round/Prevotes
  732. if maj23, ok := rs.Votes.Prevotes(prs.Round).TwoThirdsMajority(); ok {
  733. if err := r.stateCh.Send(ctx, p2p.Envelope{
  734. To: ps.peerID,
  735. Message: &tmcons.VoteSetMaj23{
  736. Height: prs.Height,
  737. Round: prs.Round,
  738. Type: tmproto.PrevoteType,
  739. BlockID: maj23.ToProto(),
  740. },
  741. }); err != nil {
  742. cancel()
  743. }
  744. }
  745. }(rs, prs)
  746. if prs.ProposalPOLRound >= 0 {
  747. wg.Add(1)
  748. go func(rs *cstypes.RoundState, prs *cstypes.PeerRoundState) {
  749. defer wg.Done()
  750. // maybe send Height/Round/ProposalPOL
  751. if maj23, ok := rs.Votes.Prevotes(prs.ProposalPOLRound).TwoThirdsMajority(); ok {
  752. if err := r.stateCh.Send(ctx, p2p.Envelope{
  753. To: ps.peerID,
  754. Message: &tmcons.VoteSetMaj23{
  755. Height: prs.Height,
  756. Round: prs.ProposalPOLRound,
  757. Type: tmproto.PrevoteType,
  758. BlockID: maj23.ToProto(),
  759. },
  760. }); err != nil {
  761. cancel()
  762. }
  763. }
  764. }(rs, prs)
  765. }
  766. wg.Add(1)
  767. go func(rs *cstypes.RoundState, prs *cstypes.PeerRoundState) {
  768. defer wg.Done()
  769. // maybe send Height/Round/Precommits
  770. if maj23, ok := rs.Votes.Precommits(prs.Round).TwoThirdsMajority(); ok {
  771. if err := r.stateCh.Send(ctx, p2p.Envelope{
  772. To: ps.peerID,
  773. Message: &tmcons.VoteSetMaj23{
  774. Height: prs.Height,
  775. Round: prs.Round,
  776. Type: tmproto.PrecommitType,
  777. BlockID: maj23.ToProto(),
  778. },
  779. }); err != nil {
  780. cancel()
  781. }
  782. }
  783. }(rs, prs)
  784. }
  785. // Little point sending LastCommitRound/LastCommit, these are fleeting and
  786. // non-blocking.
  787. if prs.CatchupCommitRound != -1 && prs.Height > 0 {
  788. wg.Add(1)
  789. go func(rs *cstypes.RoundState, prs *cstypes.PeerRoundState) {
  790. defer wg.Done()
  791. if prs.Height <= r.state.blockStore.Height() && prs.Height >= r.state.blockStore.Base() {
  792. // maybe send Height/CatchupCommitRound/CatchupCommit
  793. if commit := r.state.LoadCommit(prs.Height); commit != nil {
  794. if err := r.stateCh.Send(ctx, p2p.Envelope{
  795. To: ps.peerID,
  796. Message: &tmcons.VoteSetMaj23{
  797. Height: prs.Height,
  798. Round: commit.Round,
  799. Type: tmproto.PrecommitType,
  800. BlockID: commit.BlockID.ToProto(),
  801. },
  802. }); err != nil {
  803. cancel()
  804. }
  805. }
  806. }
  807. }(rs, prs)
  808. }
  809. waitSignal := make(chan struct{})
  810. go func() { defer close(waitSignal); wg.Wait() }()
  811. select {
  812. case <-waitSignal:
  813. timer.Reset(r.state.config.PeerQueryMaj23SleepDuration)
  814. case <-ctx.Done():
  815. return
  816. }
  817. }
  818. }
  819. // processPeerUpdate process a peer update message. For new or reconnected peers,
  820. // we create a peer state if one does not exist for the peer, which should always
  821. // be the case, and we spawn all the relevant goroutine to broadcast messages to
  822. // the peer. During peer removal, we remove the peer for our set of peers and
  823. // signal to all spawned goroutines to gracefully exit in a non-blocking manner.
  824. func (r *Reactor) processPeerUpdate(ctx context.Context, peerUpdate p2p.PeerUpdate) {
  825. r.logger.Debug("received peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  826. r.mtx.Lock()
  827. defer r.mtx.Unlock()
  828. switch peerUpdate.Status {
  829. case p2p.PeerStatusUp:
  830. // Do not allow starting new broadcasting goroutines after reactor shutdown
  831. // has been initiated. This can happen after we've manually closed all
  832. // peer goroutines, but the router still sends in-flight peer updates.
  833. if !r.IsRunning() {
  834. return
  835. }
  836. ps, ok := r.peers[peerUpdate.NodeID]
  837. if !ok {
  838. ps = NewPeerState(r.logger, peerUpdate.NodeID)
  839. r.peers[peerUpdate.NodeID] = ps
  840. }
  841. if !ps.IsRunning() {
  842. // Set the peer state's closer to signal to all spawned goroutines to exit
  843. // when the peer is removed. We also set the running state to ensure we
  844. // do not spawn multiple instances of the same goroutines and finally we
  845. // set the waitgroup counter so we know when all goroutines have exited.
  846. ps.SetRunning(true)
  847. ctx, ps.cancel = context.WithCancel(ctx)
  848. go func() {
  849. select {
  850. case <-ctx.Done():
  851. return
  852. case <-r.readySignal:
  853. }
  854. // do nothing if the peer has
  855. // stopped while we've been waiting.
  856. if !ps.IsRunning() {
  857. return
  858. }
  859. // start goroutines for this peer
  860. go r.gossipDataRoutine(ctx, ps)
  861. go r.gossipVotesRoutine(ctx, ps)
  862. go r.queryMaj23Routine(ctx, ps)
  863. // Send our state to the peer. If we're block-syncing, broadcast a
  864. // RoundStepMessage later upon SwitchToConsensus().
  865. if !r.WaitSync() {
  866. go func() { _ = r.sendNewRoundStepMessage(ctx, ps.peerID) }()
  867. }
  868. }()
  869. }
  870. case p2p.PeerStatusDown:
  871. ps, ok := r.peers[peerUpdate.NodeID]
  872. if ok && ps.IsRunning() {
  873. // signal to all spawned goroutines for the peer to gracefully exit
  874. go func() {
  875. r.mtx.Lock()
  876. delete(r.peers, peerUpdate.NodeID)
  877. r.mtx.Unlock()
  878. ps.SetRunning(false)
  879. ps.cancel()
  880. }()
  881. }
  882. }
  883. }
  884. // handleStateMessage handles envelopes sent from peers on the StateChannel.
  885. // An error is returned if the message is unrecognized or if validation fails.
  886. // If we fail to find the peer state for the envelope sender, we perform a no-op
  887. // and return. This can happen when we process the envelope after the peer is
  888. // removed.
  889. func (r *Reactor) handleStateMessage(ctx context.Context, envelope *p2p.Envelope, msgI Message) error {
  890. ps, ok := r.GetPeerState(envelope.From)
  891. if !ok || ps == nil {
  892. r.logger.Debug("failed to find peer state", "peer", envelope.From, "ch_id", "StateChannel")
  893. return nil
  894. }
  895. switch msg := envelope.Message.(type) {
  896. case *tmcons.NewRoundStep:
  897. r.state.mtx.RLock()
  898. initialHeight := r.state.state.InitialHeight
  899. r.state.mtx.RUnlock()
  900. if err := msgI.(*NewRoundStepMessage).ValidateHeight(initialHeight); err != nil {
  901. r.logger.Error("peer sent us an invalid msg", "msg", msg, "err", err)
  902. return err
  903. }
  904. ps.ApplyNewRoundStepMessage(msgI.(*NewRoundStepMessage))
  905. case *tmcons.NewValidBlock:
  906. ps.ApplyNewValidBlockMessage(msgI.(*NewValidBlockMessage))
  907. case *tmcons.HasVote:
  908. if err := ps.ApplyHasVoteMessage(msgI.(*HasVoteMessage)); err != nil {
  909. r.logger.Error("applying HasVote message", "msg", msg, "err", err)
  910. return err
  911. }
  912. case *tmcons.VoteSetMaj23:
  913. r.state.mtx.RLock()
  914. height, votes := r.state.Height, r.state.Votes
  915. r.state.mtx.RUnlock()
  916. if height != msg.Height {
  917. return nil
  918. }
  919. vsmMsg := msgI.(*VoteSetMaj23Message)
  920. // peer claims to have a maj23 for some BlockID at <H,R,S>
  921. err := votes.SetPeerMaj23(msg.Round, msg.Type, ps.peerID, vsmMsg.BlockID)
  922. if err != nil {
  923. return err
  924. }
  925. // Respond with a VoteSetBitsMessage showing which votes we have and
  926. // consequently shows which we don't have.
  927. var ourVotes *bits.BitArray
  928. switch vsmMsg.Type {
  929. case tmproto.PrevoteType:
  930. ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(vsmMsg.BlockID)
  931. case tmproto.PrecommitType:
  932. ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(vsmMsg.BlockID)
  933. default:
  934. panic("bad VoteSetBitsMessage field type; forgot to add a check in ValidateBasic?")
  935. }
  936. eMsg := &tmcons.VoteSetBits{
  937. Height: msg.Height,
  938. Round: msg.Round,
  939. Type: msg.Type,
  940. BlockID: msg.BlockID,
  941. }
  942. if votesProto := ourVotes.ToProto(); votesProto != nil {
  943. eMsg.Votes = *votesProto
  944. }
  945. if err := r.voteSetBitsCh.Send(ctx, p2p.Envelope{
  946. To: envelope.From,
  947. Message: eMsg,
  948. }); err != nil {
  949. return err
  950. }
  951. default:
  952. return fmt.Errorf("received unknown message on StateChannel: %T", msg)
  953. }
  954. return nil
  955. }
  956. // handleDataMessage handles envelopes sent from peers on the DataChannel. If we
  957. // fail to find the peer state for the envelope sender, we perform a no-op and
  958. // return. This can happen when we process the envelope after the peer is
  959. // removed.
  960. func (r *Reactor) handleDataMessage(ctx context.Context, envelope *p2p.Envelope, msgI Message) error {
  961. logger := r.logger.With("peer", envelope.From, "ch_id", "DataChannel")
  962. ps, ok := r.GetPeerState(envelope.From)
  963. if !ok || ps == nil {
  964. r.logger.Debug("failed to find peer state")
  965. return nil
  966. }
  967. if r.WaitSync() {
  968. logger.Info("ignoring message received during sync", "msg", fmt.Sprintf("%T", msgI))
  969. return nil
  970. }
  971. switch msg := envelope.Message.(type) {
  972. case *tmcons.Proposal:
  973. pMsg := msgI.(*ProposalMessage)
  974. ps.SetHasProposal(pMsg.Proposal)
  975. select {
  976. case <-ctx.Done():
  977. return ctx.Err()
  978. case r.state.peerMsgQueue <- msgInfo{pMsg, envelope.From, tmtime.Now()}:
  979. }
  980. case *tmcons.ProposalPOL:
  981. ps.ApplyProposalPOLMessage(msgI.(*ProposalPOLMessage))
  982. case *tmcons.BlockPart:
  983. bpMsg := msgI.(*BlockPartMessage)
  984. ps.SetHasProposalBlockPart(bpMsg.Height, bpMsg.Round, int(bpMsg.Part.Index))
  985. r.Metrics.BlockParts.With("peer_id", string(envelope.From)).Add(1)
  986. select {
  987. case r.state.peerMsgQueue <- msgInfo{bpMsg, envelope.From, tmtime.Now()}:
  988. return nil
  989. case <-ctx.Done():
  990. return ctx.Err()
  991. }
  992. default:
  993. return fmt.Errorf("received unknown message on DataChannel: %T", msg)
  994. }
  995. return nil
  996. }
  997. // handleVoteMessage handles envelopes sent from peers on the VoteChannel. If we
  998. // fail to find the peer state for the envelope sender, we perform a no-op and
  999. // return. This can happen when we process the envelope after the peer is
  1000. // removed.
  1001. func (r *Reactor) handleVoteMessage(ctx context.Context, envelope *p2p.Envelope, msgI Message) error {
  1002. logger := r.logger.With("peer", envelope.From, "ch_id", "VoteChannel")
  1003. ps, ok := r.GetPeerState(envelope.From)
  1004. if !ok || ps == nil {
  1005. r.logger.Debug("failed to find peer state")
  1006. return nil
  1007. }
  1008. if r.WaitSync() {
  1009. logger.Info("ignoring message received during sync", "msg", msgI)
  1010. return nil
  1011. }
  1012. switch msg := envelope.Message.(type) {
  1013. case *tmcons.Vote:
  1014. r.state.mtx.RLock()
  1015. height, valSize, lastCommitSize := r.state.Height, r.state.Validators.Size(), r.state.LastCommit.Size()
  1016. r.state.mtx.RUnlock()
  1017. vMsg := msgI.(*VoteMessage)
  1018. ps.EnsureVoteBitArrays(height, valSize)
  1019. ps.EnsureVoteBitArrays(height-1, lastCommitSize)
  1020. if err := ps.SetHasVote(vMsg.Vote); err != nil {
  1021. return err
  1022. }
  1023. select {
  1024. case r.state.peerMsgQueue <- msgInfo{vMsg, envelope.From, tmtime.Now()}:
  1025. return nil
  1026. case <-ctx.Done():
  1027. return ctx.Err()
  1028. }
  1029. default:
  1030. return fmt.Errorf("received unknown message on VoteChannel: %T", msg)
  1031. }
  1032. }
  1033. // handleVoteSetBitsMessage handles envelopes sent from peers on the
  1034. // VoteSetBitsChannel. If we fail to find the peer state for the envelope sender,
  1035. // we perform a no-op and return. This can happen when we process the envelope
  1036. // after the peer is removed.
  1037. func (r *Reactor) handleVoteSetBitsMessage(ctx context.Context, envelope *p2p.Envelope, msgI Message) error {
  1038. logger := r.logger.With("peer", envelope.From, "ch_id", "VoteSetBitsChannel")
  1039. ps, ok := r.GetPeerState(envelope.From)
  1040. if !ok || ps == nil {
  1041. r.logger.Debug("failed to find peer state")
  1042. return nil
  1043. }
  1044. if r.WaitSync() {
  1045. logger.Info("ignoring message received during sync", "msg", msgI)
  1046. return nil
  1047. }
  1048. switch msg := envelope.Message.(type) {
  1049. case *tmcons.VoteSetBits:
  1050. r.state.mtx.RLock()
  1051. height, votes := r.state.Height, r.state.Votes
  1052. r.state.mtx.RUnlock()
  1053. vsbMsg := msgI.(*VoteSetBitsMessage)
  1054. if height == msg.Height {
  1055. var ourVotes *bits.BitArray
  1056. switch msg.Type {
  1057. case tmproto.PrevoteType:
  1058. ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(vsbMsg.BlockID)
  1059. case tmproto.PrecommitType:
  1060. ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(vsbMsg.BlockID)
  1061. default:
  1062. panic("bad VoteSetBitsMessage field type; forgot to add a check in ValidateBasic?")
  1063. }
  1064. ps.ApplyVoteSetBitsMessage(vsbMsg, ourVotes)
  1065. } else {
  1066. ps.ApplyVoteSetBitsMessage(vsbMsg, nil)
  1067. }
  1068. default:
  1069. return fmt.Errorf("received unknown message on VoteSetBitsChannel: %T", msg)
  1070. }
  1071. return nil
  1072. }
  1073. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  1074. // It will handle errors and any possible panics gracefully. A caller can handle
  1075. // any error returned by sending a PeerError on the respective channel.
  1076. //
  1077. // NOTE: We process these messages even when we're block syncing. Messages affect
  1078. // either a peer state or the consensus state. Peer state updates can happen in
  1079. // parallel, but processing of proposals, block parts, and votes are ordered by
  1080. // the p2p channel.
  1081. //
  1082. // NOTE: We block on consensus state for proposals, block parts, and votes.
  1083. func (r *Reactor) handleMessage(ctx context.Context, chID p2p.ChannelID, envelope *p2p.Envelope) (err error) {
  1084. defer func() {
  1085. if e := recover(); e != nil {
  1086. err = fmt.Errorf("panic in processing message: %v", e)
  1087. r.logger.Error(
  1088. "recovering from processing message panic",
  1089. "err", err,
  1090. "stack", string(debug.Stack()),
  1091. )
  1092. }
  1093. }()
  1094. // We wrap the envelope's message in a Proto wire type so we can convert back
  1095. // the domain type that individual channel message handlers can work with. We
  1096. // do this here once to avoid having to do it for each individual message type.
  1097. // and because a large part of the core business logic depends on these
  1098. // domain types opposed to simply working with the Proto types.
  1099. protoMsg := new(tmcons.Message)
  1100. if err := protoMsg.Wrap(envelope.Message); err != nil {
  1101. return err
  1102. }
  1103. msgI, err := MsgFromProto(protoMsg)
  1104. if err != nil {
  1105. return err
  1106. }
  1107. r.logger.Debug("received message", "ch_id", chID, "message", msgI, "peer", envelope.From)
  1108. switch chID {
  1109. case StateChannel:
  1110. err = r.handleStateMessage(ctx, envelope, msgI)
  1111. case DataChannel:
  1112. err = r.handleDataMessage(ctx, envelope, msgI)
  1113. case VoteChannel:
  1114. err = r.handleVoteMessage(ctx, envelope, msgI)
  1115. case VoteSetBitsChannel:
  1116. err = r.handleVoteSetBitsMessage(ctx, envelope, msgI)
  1117. default:
  1118. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  1119. }
  1120. return err
  1121. }
  1122. // processStateCh initiates a blocking process where we listen for and handle
  1123. // envelopes on the StateChannel. Any error encountered during message
  1124. // execution will result in a PeerError being sent on the StateChannel. When
  1125. // the reactor is stopped, we will catch the signal and close the p2p Channel
  1126. // gracefully.
  1127. func (r *Reactor) processStateCh(ctx context.Context) {
  1128. iter := r.stateCh.Receive(ctx)
  1129. for iter.Next(ctx) {
  1130. envelope := iter.Envelope()
  1131. if err := r.handleMessage(ctx, r.stateCh.ID, envelope); err != nil {
  1132. r.logger.Error("failed to process message", "ch_id", r.stateCh.ID, "envelope", envelope, "err", err)
  1133. if serr := r.stateCh.SendError(ctx, p2p.PeerError{
  1134. NodeID: envelope.From,
  1135. Err: err,
  1136. }); serr != nil {
  1137. return
  1138. }
  1139. }
  1140. }
  1141. }
  1142. // processDataCh initiates a blocking process where we listen for and handle
  1143. // envelopes on the DataChannel. Any error encountered during message
  1144. // execution will result in a PeerError being sent on the DataChannel. When
  1145. // the reactor is stopped, we will catch the signal and close the p2p Channel
  1146. // gracefully.
  1147. func (r *Reactor) processDataCh(ctx context.Context) {
  1148. iter := r.dataCh.Receive(ctx)
  1149. for iter.Next(ctx) {
  1150. envelope := iter.Envelope()
  1151. if err := r.handleMessage(ctx, r.dataCh.ID, envelope); err != nil {
  1152. r.logger.Error("failed to process message", "ch_id", r.dataCh.ID, "envelope", envelope, "err", err)
  1153. if serr := r.dataCh.SendError(ctx, p2p.PeerError{
  1154. NodeID: envelope.From,
  1155. Err: err,
  1156. }); serr != nil {
  1157. return
  1158. }
  1159. }
  1160. }
  1161. }
  1162. // processVoteCh initiates a blocking process where we listen for and handle
  1163. // envelopes on the VoteChannel. Any error encountered during message
  1164. // execution will result in a PeerError being sent on the VoteChannel. When
  1165. // the reactor is stopped, we will catch the signal and close the p2p Channel
  1166. // gracefully.
  1167. func (r *Reactor) processVoteCh(ctx context.Context) {
  1168. iter := r.voteCh.Receive(ctx)
  1169. for iter.Next(ctx) {
  1170. envelope := iter.Envelope()
  1171. if err := r.handleMessage(ctx, r.voteCh.ID, envelope); err != nil {
  1172. r.logger.Error("failed to process message", "ch_id", r.voteCh.ID, "envelope", envelope, "err", err)
  1173. if serr := r.voteCh.SendError(ctx, p2p.PeerError{
  1174. NodeID: envelope.From,
  1175. Err: err,
  1176. }); serr != nil {
  1177. return
  1178. }
  1179. }
  1180. }
  1181. }
  1182. // processVoteCh initiates a blocking process where we listen for and handle
  1183. // envelopes on the VoteSetBitsChannel. Any error encountered during message
  1184. // execution will result in a PeerError being sent on the VoteSetBitsChannel.
  1185. // When the reactor is stopped, we will catch the signal and close the p2p
  1186. // Channel gracefully.
  1187. func (r *Reactor) processVoteSetBitsCh(ctx context.Context) {
  1188. iter := r.voteSetBitsCh.Receive(ctx)
  1189. for iter.Next(ctx) {
  1190. envelope := iter.Envelope()
  1191. if err := r.handleMessage(ctx, r.voteSetBitsCh.ID, envelope); err != nil {
  1192. if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
  1193. return
  1194. }
  1195. r.logger.Error("failed to process message", "ch_id", r.voteSetBitsCh.ID, "envelope", envelope, "err", err)
  1196. if serr := r.voteSetBitsCh.SendError(ctx, p2p.PeerError{
  1197. NodeID: envelope.From,
  1198. Err: err,
  1199. }); serr != nil {
  1200. return
  1201. }
  1202. }
  1203. }
  1204. }
  1205. // processPeerUpdates initiates a blocking process where we listen for and handle
  1206. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  1207. // close the p2p PeerUpdatesCh gracefully.
  1208. func (r *Reactor) processPeerUpdates(ctx context.Context) {
  1209. for {
  1210. select {
  1211. case <-ctx.Done():
  1212. return
  1213. case peerUpdate := <-r.peerUpdates.Updates():
  1214. r.processPeerUpdate(ctx, peerUpdate)
  1215. }
  1216. }
  1217. }
  1218. func (r *Reactor) peerStatsRoutine(ctx context.Context) {
  1219. for {
  1220. if !r.IsRunning() {
  1221. r.logger.Info("stopping peerStatsRoutine")
  1222. return
  1223. }
  1224. select {
  1225. case msg := <-r.state.statsMsgQueue:
  1226. ps, ok := r.GetPeerState(msg.PeerID)
  1227. if !ok || ps == nil {
  1228. r.logger.Debug("attempt to update stats for non-existent peer", "peer", msg.PeerID)
  1229. continue
  1230. }
  1231. switch msg.Msg.(type) {
  1232. case *VoteMessage:
  1233. if numVotes := ps.RecordVote(); numVotes%votesToContributeToBecomeGoodPeer == 0 {
  1234. r.peerUpdates.SendUpdate(ctx, p2p.PeerUpdate{
  1235. NodeID: msg.PeerID,
  1236. Status: p2p.PeerStatusGood,
  1237. })
  1238. }
  1239. case *BlockPartMessage:
  1240. if numParts := ps.RecordBlockPart(); numParts%blocksToContributeToBecomeGoodPeer == 0 {
  1241. r.peerUpdates.SendUpdate(ctx, p2p.PeerUpdate{
  1242. NodeID: msg.PeerID,
  1243. Status: p2p.PeerStatusGood,
  1244. })
  1245. }
  1246. }
  1247. case <-ctx.Done():
  1248. return
  1249. }
  1250. }
  1251. }
  1252. func (r *Reactor) GetConsensusState() *State {
  1253. return r.state
  1254. }
  1255. func (r *Reactor) SetStateSyncingMetrics(v float64) {
  1256. r.Metrics.StateSyncing.Set(v)
  1257. }
  1258. func (r *Reactor) SetBlockSyncingMetrics(v float64) {
  1259. r.Metrics.BlockSyncing.Set(v)
  1260. }