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.

427 lines
13 KiB

blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
8 years ago
7 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
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
7 years ago
7 years ago
8 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
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
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
8 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
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
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
  1. package v0
  2. import (
  3. "fmt"
  4. "reflect"
  5. "time"
  6. bc "github.com/tendermint/tendermint/blockchain"
  7. "github.com/tendermint/tendermint/libs/log"
  8. "github.com/tendermint/tendermint/p2p"
  9. bcproto "github.com/tendermint/tendermint/proto/tendermint/blockchain"
  10. sm "github.com/tendermint/tendermint/state"
  11. "github.com/tendermint/tendermint/store"
  12. "github.com/tendermint/tendermint/types"
  13. )
  14. const (
  15. // BlockchainChannel is a channel for blocks and status updates (`BlockStore` height)
  16. BlockchainChannel = byte(0x40)
  17. trySyncIntervalMS = 10
  18. // stop syncing when last block's time is
  19. // within this much of the system time.
  20. // stopSyncingDurationMinutes = 10
  21. // ask for best height every 10s
  22. statusUpdateIntervalSeconds = 10
  23. // check if we should switch to consensus reactor
  24. switchToConsensusIntervalSeconds = 1
  25. )
  26. type consensusReactor interface {
  27. // for when we switch from blockchain reactor and fast sync to
  28. // the consensus machine
  29. SwitchToConsensus(state sm.State, skipWAL bool)
  30. }
  31. type peerError struct {
  32. err error
  33. peerID p2p.ID
  34. }
  35. func (e peerError) Error() string {
  36. return fmt.Sprintf("error with peer %v: %s", e.peerID, e.err.Error())
  37. }
  38. // BlockchainReactor handles long-term catchup syncing.
  39. type BlockchainReactor struct {
  40. p2p.BaseReactor
  41. // immutable
  42. initialState sm.State
  43. blockExec *sm.BlockExecutor
  44. store *store.BlockStore
  45. pool *BlockPool
  46. fastSync bool
  47. requestsCh <-chan BlockRequest
  48. errorsCh <-chan peerError
  49. }
  50. // NewBlockchainReactor returns new reactor instance.
  51. func NewBlockchainReactor(state sm.State, blockExec *sm.BlockExecutor, store *store.BlockStore,
  52. fastSync bool) *BlockchainReactor {
  53. if state.LastBlockHeight != store.Height() {
  54. panic(fmt.Sprintf("state (%v) and store (%v) height mismatch", state.LastBlockHeight,
  55. store.Height()))
  56. }
  57. requestsCh := make(chan BlockRequest, maxTotalRequesters)
  58. const capacity = 1000 // must be bigger than peers count
  59. errorsCh := make(chan peerError, capacity) // so we don't block in #Receive#pool.AddBlock
  60. startHeight := store.Height() + 1
  61. if startHeight == 1 {
  62. startHeight = state.InitialHeight
  63. }
  64. pool := NewBlockPool(startHeight, requestsCh, errorsCh)
  65. bcR := &BlockchainReactor{
  66. initialState: state,
  67. blockExec: blockExec,
  68. store: store,
  69. pool: pool,
  70. fastSync: fastSync,
  71. requestsCh: requestsCh,
  72. errorsCh: errorsCh,
  73. }
  74. bcR.BaseReactor = *p2p.NewBaseReactor("BlockchainReactor", bcR)
  75. return bcR
  76. }
  77. // SetLogger implements service.Service by setting the logger on reactor and pool.
  78. func (bcR *BlockchainReactor) SetLogger(l log.Logger) {
  79. bcR.BaseService.Logger = l
  80. bcR.pool.Logger = l
  81. }
  82. // OnStart implements service.Service.
  83. func (bcR *BlockchainReactor) OnStart() error {
  84. if bcR.fastSync {
  85. err := bcR.pool.Start()
  86. if err != nil {
  87. return err
  88. }
  89. go bcR.poolRoutine(false)
  90. }
  91. return nil
  92. }
  93. // SwitchToFastSync is called by the state sync reactor when switching to fast sync.
  94. func (bcR *BlockchainReactor) SwitchToFastSync(state sm.State) error {
  95. bcR.fastSync = true
  96. bcR.initialState = state
  97. bcR.pool.height = state.LastBlockHeight + 1
  98. err := bcR.pool.Start()
  99. if err != nil {
  100. return err
  101. }
  102. go bcR.poolRoutine(true)
  103. return nil
  104. }
  105. // OnStop implements service.Service.
  106. func (bcR *BlockchainReactor) OnStop() {
  107. if bcR.fastSync {
  108. if err := bcR.pool.Stop(); err != nil {
  109. bcR.Logger.Error("Error stopping pool", "err", err)
  110. }
  111. }
  112. }
  113. // GetChannels implements Reactor
  114. func (bcR *BlockchainReactor) GetChannels() []*p2p.ChannelDescriptor {
  115. return []*p2p.ChannelDescriptor{
  116. {
  117. ID: BlockchainChannel,
  118. Priority: 10,
  119. SendQueueCapacity: 1000,
  120. RecvBufferCapacity: 50 * 4096,
  121. RecvMessageCapacity: bc.MaxMsgSize,
  122. },
  123. }
  124. }
  125. // AddPeer implements Reactor by sending our state to peer.
  126. func (bcR *BlockchainReactor) AddPeer(peer p2p.Peer) {
  127. msgBytes, err := bc.EncodeMsg(&bcproto.StatusResponse{
  128. Base: bcR.store.Base(),
  129. Height: bcR.store.Height()})
  130. if err != nil {
  131. bcR.Logger.Error("could not convert msg to protobuf", "err", err)
  132. return
  133. }
  134. peer.Send(BlockchainChannel, msgBytes)
  135. // it's OK if send fails. will try later in poolRoutine
  136. // peer is added to the pool once we receive the first
  137. // bcStatusResponseMessage from the peer and call pool.SetPeerRange
  138. }
  139. // RemovePeer implements Reactor by removing peer from the pool.
  140. func (bcR *BlockchainReactor) RemovePeer(peer p2p.Peer, reason interface{}) {
  141. bcR.pool.RemovePeer(peer.ID())
  142. }
  143. // respondToPeer loads a block and sends it to the requesting peer,
  144. // if we have it. Otherwise, we'll respond saying we don't have it.
  145. func (bcR *BlockchainReactor) respondToPeer(msg *bcproto.BlockRequest,
  146. src p2p.Peer) (queued bool) {
  147. block := bcR.store.LoadBlock(msg.Height)
  148. if block != nil {
  149. bl, err := block.ToProto()
  150. if err != nil {
  151. bcR.Logger.Error("could not convert msg to protobuf", "err", err)
  152. return false
  153. }
  154. msgBytes, err := bc.EncodeMsg(&bcproto.BlockResponse{Block: bl})
  155. if err != nil {
  156. bcR.Logger.Error("could not marshal msg", "err", err)
  157. return false
  158. }
  159. return src.TrySend(BlockchainChannel, msgBytes)
  160. }
  161. bcR.Logger.Info("Peer asking for a block we don't have", "src", src, "height", msg.Height)
  162. msgBytes, err := bc.EncodeMsg(&bcproto.NoBlockResponse{Height: msg.Height})
  163. if err != nil {
  164. bcR.Logger.Error("could not convert msg to protobuf", "err", err)
  165. return false
  166. }
  167. return src.TrySend(BlockchainChannel, msgBytes)
  168. }
  169. // Receive implements Reactor by handling 4 types of messages (look below).
  170. func (bcR *BlockchainReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) {
  171. msg, err := bc.DecodeMsg(msgBytes)
  172. if err != nil {
  173. bcR.Logger.Error("Error decoding message", "src", src, "chId", chID, "msg", msg, "err", err, "bytes", msgBytes)
  174. bcR.Switch.StopPeerForError(src, err)
  175. return
  176. }
  177. if err = bc.ValidateMsg(msg); err != nil {
  178. bcR.Logger.Error("Peer sent us invalid msg", "peer", src, "msg", msg, "err", err)
  179. bcR.Switch.StopPeerForError(src, err)
  180. return
  181. }
  182. bcR.Logger.Debug("Receive", "src", src, "chID", chID, "msg", msg)
  183. switch msg := msg.(type) {
  184. case *bcproto.BlockRequest:
  185. bcR.respondToPeer(msg, src)
  186. case *bcproto.BlockResponse:
  187. bi, err := types.BlockFromProto(msg.Block)
  188. if err != nil {
  189. bcR.Logger.Error("Block content is invalid", "err", err)
  190. bcR.Switch.StopPeerForError(src, err)
  191. return
  192. }
  193. bcR.pool.AddBlock(src.ID(), bi, len(msgBytes))
  194. case *bcproto.StatusRequest:
  195. // Send peer our state.
  196. msgBytes, err := bc.EncodeMsg(&bcproto.StatusResponse{
  197. Height: bcR.store.Height(),
  198. Base: bcR.store.Base(),
  199. })
  200. if err != nil {
  201. bcR.Logger.Error("could not convert msg to protobut", "err", err)
  202. return
  203. }
  204. src.TrySend(BlockchainChannel, msgBytes)
  205. case *bcproto.StatusResponse:
  206. // Got a peer status. Unverified.
  207. bcR.pool.SetPeerRange(src.ID(), msg.Base, msg.Height)
  208. case *bcproto.NoBlockResponse:
  209. bcR.Logger.Debug("Peer does not have requested block", "peer", src, "height", msg.Height)
  210. default:
  211. bcR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg)))
  212. }
  213. }
  214. // Handle messages from the poolReactor telling the reactor what to do.
  215. // NOTE: Don't sleep in the FOR_LOOP or otherwise slow it down!
  216. func (bcR *BlockchainReactor) poolRoutine(stateSynced bool) {
  217. trySyncTicker := time.NewTicker(trySyncIntervalMS * time.Millisecond)
  218. statusUpdateTicker := time.NewTicker(statusUpdateIntervalSeconds * time.Second)
  219. switchToConsensusTicker := time.NewTicker(switchToConsensusIntervalSeconds * time.Second)
  220. blocksSynced := uint64(0)
  221. chainID := bcR.initialState.ChainID
  222. state := bcR.initialState
  223. lastHundred := time.Now()
  224. lastRate := 0.0
  225. didProcessCh := make(chan struct{}, 1)
  226. go func() {
  227. for {
  228. select {
  229. case <-bcR.Quit():
  230. return
  231. case <-bcR.pool.Quit():
  232. return
  233. case request := <-bcR.requestsCh:
  234. peer := bcR.Switch.Peers().Get(request.PeerID)
  235. if peer == nil {
  236. continue
  237. }
  238. msgBytes, err := bc.EncodeMsg(&bcproto.BlockRequest{Height: request.Height})
  239. if err != nil {
  240. bcR.Logger.Error("could not convert msg to proto", "err", err)
  241. continue
  242. }
  243. queued := peer.TrySend(BlockchainChannel, msgBytes)
  244. if !queued {
  245. bcR.Logger.Debug("Send queue is full, drop block request", "peer", peer.ID(), "height", request.Height)
  246. }
  247. case err := <-bcR.errorsCh:
  248. peer := bcR.Switch.Peers().Get(err.peerID)
  249. if peer != nil {
  250. bcR.Switch.StopPeerForError(peer, err)
  251. }
  252. case <-statusUpdateTicker.C:
  253. // ask for status updates
  254. go bcR.BroadcastStatusRequest() // nolint: errcheck
  255. }
  256. }
  257. }()
  258. FOR_LOOP:
  259. for {
  260. select {
  261. case <-switchToConsensusTicker.C:
  262. height, numPending, lenRequesters := bcR.pool.GetStatus()
  263. outbound, inbound, _ := bcR.Switch.NumPeers()
  264. bcR.Logger.Debug("Consensus ticker", "numPending", numPending, "total", lenRequesters,
  265. "outbound", outbound, "inbound", inbound)
  266. if bcR.pool.IsCaughtUp() {
  267. bcR.Logger.Info("Time to switch to consensus reactor!", "height", height)
  268. if err := bcR.pool.Stop(); err != nil {
  269. bcR.Logger.Error("Error stopping pool", "err", err)
  270. }
  271. conR, ok := bcR.Switch.Reactor("CONSENSUS").(consensusReactor)
  272. if ok {
  273. conR.SwitchToConsensus(state, blocksSynced > 0 || stateSynced)
  274. }
  275. // else {
  276. // should only happen during testing
  277. // }
  278. break FOR_LOOP
  279. }
  280. case <-trySyncTicker.C: // chan time
  281. select {
  282. case didProcessCh <- struct{}{}:
  283. default:
  284. }
  285. case <-didProcessCh:
  286. // NOTE: It is a subtle mistake to process more than a single block
  287. // at a time (e.g. 10) here, because we only TrySend 1 request per
  288. // loop. The ratio mismatch can result in starving of blocks, a
  289. // sudden burst of requests and responses, and repeat.
  290. // Consequently, it is better to split these routines rather than
  291. // coupling them as it's written here. TODO uncouple from request
  292. // routine.
  293. // See if there are any blocks to sync.
  294. first, second := bcR.pool.PeekTwoBlocks()
  295. // bcR.Logger.Info("TrySync peeked", "first", first, "second", second)
  296. if first == nil || second == nil {
  297. // We need both to sync the first block.
  298. continue FOR_LOOP
  299. } else {
  300. // Try again quickly next loop.
  301. didProcessCh <- struct{}{}
  302. }
  303. firstParts := first.MakePartSet(types.BlockPartSizeBytes)
  304. firstPartSetHeader := firstParts.Header()
  305. firstID := types.BlockID{Hash: first.Hash(), PartSetHeader: firstPartSetHeader}
  306. // Finally, verify the first block using the second's commit
  307. // NOTE: we can probably make this more efficient, but note that calling
  308. // first.Hash() doesn't verify the tx contents, so MakePartSet() is
  309. // currently necessary.
  310. err := state.Validators.VerifyCommitLight(
  311. chainID, firstID, first.Height, second.LastCommit)
  312. if err != nil {
  313. bcR.Logger.Error("Error in validation", "err", err)
  314. peerID := bcR.pool.RedoRequest(first.Height)
  315. peer := bcR.Switch.Peers().Get(peerID)
  316. if peer != nil {
  317. // NOTE: we've already removed the peer's request, but we
  318. // still need to clean up the rest.
  319. bcR.Switch.StopPeerForError(peer, fmt.Errorf("blockchainReactor validation error: %v", err))
  320. }
  321. peerID2 := bcR.pool.RedoRequest(second.Height)
  322. peer2 := bcR.Switch.Peers().Get(peerID2)
  323. if peer2 != nil && peer2 != peer {
  324. // NOTE: we've already removed the peer's request, but we
  325. // still need to clean up the rest.
  326. bcR.Switch.StopPeerForError(peer2, fmt.Errorf("blockchainReactor validation error: %v", err))
  327. }
  328. continue FOR_LOOP
  329. } else {
  330. bcR.pool.PopRequest()
  331. // TODO: batch saves so we dont persist to disk every block
  332. bcR.store.SaveBlock(first, firstParts, second.LastCommit)
  333. // TODO: same thing for app - but we would need a way to
  334. // get the hash without persisting the state
  335. var err error
  336. state, _, err = bcR.blockExec.ApplyBlock(state, firstID, first)
  337. if err != nil {
  338. // TODO This is bad, are we zombie?
  339. panic(fmt.Sprintf("Failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err))
  340. }
  341. blocksSynced++
  342. if blocksSynced%100 == 0 {
  343. lastRate = 0.9*lastRate + 0.1*(100/time.Since(lastHundred).Seconds())
  344. bcR.Logger.Info("Fast Sync Rate", "height", bcR.pool.height,
  345. "max_peer_height", bcR.pool.MaxPeerHeight(), "blocks/s", lastRate)
  346. lastHundred = time.Now()
  347. }
  348. }
  349. continue FOR_LOOP
  350. case <-bcR.Quit():
  351. break FOR_LOOP
  352. }
  353. }
  354. }
  355. // BroadcastStatusRequest broadcasts `BlockStore` base and height.
  356. func (bcR *BlockchainReactor) BroadcastStatusRequest() error {
  357. bm, err := bc.EncodeMsg(&bcproto.StatusRequest{})
  358. if err != nil {
  359. bcR.Logger.Error("could not convert msg to proto", "err", err)
  360. return fmt.Errorf("could not convert msg to proto: %w", err)
  361. }
  362. bcR.Switch.Broadcast(BlockchainChannel, bm)
  363. return nil
  364. }