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.

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