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.

422 lines
12 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
7 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>
4 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>
4 years ago
7 years ago
7 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>
4 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>
4 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>
4 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>
4 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>
4 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>
4 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. bcR.pool.Stop()
  109. }
  110. }
  111. // GetChannels implements Reactor
  112. func (bcR *BlockchainReactor) GetChannels() []*p2p.ChannelDescriptor {
  113. return []*p2p.ChannelDescriptor{
  114. {
  115. ID: BlockchainChannel,
  116. Priority: 10,
  117. SendQueueCapacity: 1000,
  118. RecvBufferCapacity: 50 * 4096,
  119. RecvMessageCapacity: bc.MaxMsgSize,
  120. },
  121. }
  122. }
  123. // AddPeer implements Reactor by sending our state to peer.
  124. func (bcR *BlockchainReactor) AddPeer(peer p2p.Peer) {
  125. msgBytes, err := bc.EncodeMsg(&bcproto.StatusResponse{
  126. Base: bcR.store.Base(),
  127. Height: bcR.store.Height()})
  128. if err != nil {
  129. bcR.Logger.Error("could not convert msg to protobuf", "err", err)
  130. return
  131. }
  132. peer.Send(BlockchainChannel, msgBytes)
  133. // it's OK if send fails. will try later in poolRoutine
  134. // peer is added to the pool once we receive the first
  135. // bcStatusResponseMessage from the peer and call pool.SetPeerRange
  136. }
  137. // RemovePeer implements Reactor by removing peer from the pool.
  138. func (bcR *BlockchainReactor) RemovePeer(peer p2p.Peer, reason interface{}) {
  139. bcR.pool.RemovePeer(peer.ID())
  140. }
  141. // respondToPeer loads a block and sends it to the requesting peer,
  142. // if we have it. Otherwise, we'll respond saying we don't have it.
  143. func (bcR *BlockchainReactor) respondToPeer(msg *bcproto.BlockRequest,
  144. src p2p.Peer) (queued bool) {
  145. block := bcR.store.LoadBlock(msg.Height)
  146. if block != nil {
  147. bl, err := block.ToProto()
  148. if err != nil {
  149. bcR.Logger.Error("could not convert msg to protobuf", "err", err)
  150. return false
  151. }
  152. msgBytes, err := bc.EncodeMsg(&bcproto.BlockResponse{Block: bl})
  153. if err != nil {
  154. bcR.Logger.Error("could not marshal msg", "err", err)
  155. return false
  156. }
  157. return src.TrySend(BlockchainChannel, msgBytes)
  158. }
  159. bcR.Logger.Info("Peer asking for a block we don't have", "src", src, "height", msg.Height)
  160. msgBytes, err := bc.EncodeMsg(&bcproto.NoBlockResponse{Height: msg.Height})
  161. if err != nil {
  162. bcR.Logger.Error("could not convert msg to protobuf", "err", err)
  163. return false
  164. }
  165. return src.TrySend(BlockchainChannel, msgBytes)
  166. }
  167. // Receive implements Reactor by handling 4 types of messages (look below).
  168. func (bcR *BlockchainReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) {
  169. msg, err := bc.DecodeMsg(msgBytes)
  170. if err != nil {
  171. bcR.Logger.Error("Error decoding message", "src", src, "chId", chID, "msg", msg, "err", err, "bytes", msgBytes)
  172. bcR.Switch.StopPeerForError(src, err)
  173. return
  174. }
  175. if err = bc.ValidateMsg(msg); err != nil {
  176. bcR.Logger.Error("Peer sent us invalid msg", "peer", src, "msg", msg, "err", err)
  177. bcR.Switch.StopPeerForError(src, err)
  178. return
  179. }
  180. bcR.Logger.Debug("Receive", "src", src, "chID", chID, "msg", msg)
  181. switch msg := msg.(type) {
  182. case *bcproto.BlockRequest:
  183. bcR.respondToPeer(msg, src)
  184. case *bcproto.BlockResponse:
  185. bi, err := types.BlockFromProto(msg.Block)
  186. if err != nil {
  187. bcR.Logger.Error("Block content is invalid", "err", err)
  188. return
  189. }
  190. bcR.pool.AddBlock(src.ID(), bi, len(msgBytes))
  191. case *bcproto.StatusRequest:
  192. // Send peer our state.
  193. msgBytes, err := bc.EncodeMsg(&bcproto.StatusResponse{
  194. Height: bcR.store.Height(),
  195. Base: bcR.store.Base(),
  196. })
  197. if err != nil {
  198. bcR.Logger.Error("could not convert msg to protobut", "err", err)
  199. return
  200. }
  201. src.TrySend(BlockchainChannel, msgBytes)
  202. case *bcproto.StatusResponse:
  203. // Got a peer status. Unverified.
  204. bcR.pool.SetPeerRange(src.ID(), msg.Base, msg.Height)
  205. case *bcproto.NoBlockResponse:
  206. bcR.Logger.Debug("Peer does not have requested block", "peer", src, "height", msg.Height)
  207. default:
  208. bcR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg)))
  209. }
  210. }
  211. // Handle messages from the poolReactor telling the reactor what to do.
  212. // NOTE: Don't sleep in the FOR_LOOP or otherwise slow it down!
  213. func (bcR *BlockchainReactor) poolRoutine(stateSynced bool) {
  214. trySyncTicker := time.NewTicker(trySyncIntervalMS * time.Millisecond)
  215. statusUpdateTicker := time.NewTicker(statusUpdateIntervalSeconds * time.Second)
  216. switchToConsensusTicker := time.NewTicker(switchToConsensusIntervalSeconds * time.Second)
  217. blocksSynced := uint64(0)
  218. chainID := bcR.initialState.ChainID
  219. state := bcR.initialState
  220. lastHundred := time.Now()
  221. lastRate := 0.0
  222. didProcessCh := make(chan struct{}, 1)
  223. go func() {
  224. for {
  225. select {
  226. case <-bcR.Quit():
  227. return
  228. case <-bcR.pool.Quit():
  229. return
  230. case request := <-bcR.requestsCh:
  231. peer := bcR.Switch.Peers().Get(request.PeerID)
  232. if peer == nil {
  233. continue
  234. }
  235. msgBytes, err := bc.EncodeMsg(&bcproto.BlockRequest{Height: request.Height})
  236. if err != nil {
  237. bcR.Logger.Error("could not convert msg to proto", "err", err)
  238. continue
  239. }
  240. queued := peer.TrySend(BlockchainChannel, msgBytes)
  241. if !queued {
  242. bcR.Logger.Debug("Send queue is full, drop block request", "peer", peer.ID(), "height", request.Height)
  243. }
  244. case err := <-bcR.errorsCh:
  245. peer := bcR.Switch.Peers().Get(err.peerID)
  246. if peer != nil {
  247. bcR.Switch.StopPeerForError(peer, err)
  248. }
  249. case <-statusUpdateTicker.C:
  250. // ask for status updates
  251. go bcR.BroadcastStatusRequest() // nolint: errcheck
  252. }
  253. }
  254. }()
  255. FOR_LOOP:
  256. for {
  257. select {
  258. case <-switchToConsensusTicker.C:
  259. height, numPending, lenRequesters := bcR.pool.GetStatus()
  260. outbound, inbound, _ := bcR.Switch.NumPeers()
  261. bcR.Logger.Debug("Consensus ticker", "numPending", numPending, "total", lenRequesters,
  262. "outbound", outbound, "inbound", inbound)
  263. if bcR.pool.IsCaughtUp() {
  264. bcR.Logger.Info("Time to switch to consensus reactor!", "height", height)
  265. bcR.pool.Stop()
  266. conR, ok := bcR.Switch.Reactor("CONSENSUS").(consensusReactor)
  267. if ok {
  268. conR.SwitchToConsensus(state, blocksSynced > 0 || stateSynced)
  269. }
  270. // else {
  271. // should only happen during testing
  272. // }
  273. break FOR_LOOP
  274. }
  275. case <-trySyncTicker.C: // chan time
  276. select {
  277. case didProcessCh <- struct{}{}:
  278. default:
  279. }
  280. case <-didProcessCh:
  281. // NOTE: It is a subtle mistake to process more than a single block
  282. // at a time (e.g. 10) here, because we only TrySend 1 request per
  283. // loop. The ratio mismatch can result in starving of blocks, a
  284. // sudden burst of requests and responses, and repeat.
  285. // Consequently, it is better to split these routines rather than
  286. // coupling them as it's written here. TODO uncouple from request
  287. // routine.
  288. // See if there are any blocks to sync.
  289. first, second := bcR.pool.PeekTwoBlocks()
  290. //bcR.Logger.Info("TrySync peeked", "first", first, "second", second)
  291. if first == nil || second == nil {
  292. // We need both to sync the first block.
  293. continue FOR_LOOP
  294. } else {
  295. // Try again quickly next loop.
  296. didProcessCh <- struct{}{}
  297. }
  298. firstParts := first.MakePartSet(types.BlockPartSizeBytes)
  299. firstPartSetHeader := firstParts.Header()
  300. firstID := types.BlockID{Hash: first.Hash(), PartSetHeader: firstPartSetHeader}
  301. // Finally, verify the first block using the second's commit
  302. // NOTE: we can probably make this more efficient, but note that calling
  303. // first.Hash() doesn't verify the tx contents, so MakePartSet() is
  304. // currently necessary.
  305. err := state.Validators.VerifyCommit(
  306. chainID, firstID, first.Height, second.LastCommit)
  307. if err != nil {
  308. bcR.Logger.Error("Error in validation", "err", err)
  309. peerID := bcR.pool.RedoRequest(first.Height)
  310. peer := bcR.Switch.Peers().Get(peerID)
  311. if peer != nil {
  312. // NOTE: we've already removed the peer's request, but we
  313. // still need to clean up the rest.
  314. bcR.Switch.StopPeerForError(peer, fmt.Errorf("blockchainReactor validation error: %v", err))
  315. }
  316. peerID2 := bcR.pool.RedoRequest(second.Height)
  317. peer2 := bcR.Switch.Peers().Get(peerID2)
  318. if peer2 != nil && peer2 != peer {
  319. // NOTE: we've already removed the peer's request, but we
  320. // still need to clean up the rest.
  321. bcR.Switch.StopPeerForError(peer2, fmt.Errorf("blockchainReactor validation error: %v", err))
  322. }
  323. continue FOR_LOOP
  324. } else {
  325. bcR.pool.PopRequest()
  326. // TODO: batch saves so we dont persist to disk every block
  327. bcR.store.SaveBlock(first, firstParts, second.LastCommit)
  328. // TODO: same thing for app - but we would need a way to
  329. // get the hash without persisting the state
  330. var err error
  331. state, _, err = bcR.blockExec.ApplyBlock(state, firstID, first)
  332. if err != nil {
  333. // TODO This is bad, are we zombie?
  334. panic(fmt.Sprintf("Failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err))
  335. }
  336. blocksSynced++
  337. if blocksSynced%100 == 0 {
  338. lastRate = 0.9*lastRate + 0.1*(100/time.Since(lastHundred).Seconds())
  339. bcR.Logger.Info("Fast Sync Rate", "height", bcR.pool.height,
  340. "max_peer_height", bcR.pool.MaxPeerHeight(), "blocks/s", lastRate)
  341. lastHundred = time.Now()
  342. }
  343. }
  344. continue FOR_LOOP
  345. case <-bcR.Quit():
  346. break FOR_LOOP
  347. }
  348. }
  349. }
  350. // BroadcastStatusRequest broadcasts `BlockStore` base and height.
  351. func (bcR *BlockchainReactor) BroadcastStatusRequest() error {
  352. bm, err := bc.EncodeMsg(&bcproto.StatusRequest{})
  353. if err != nil {
  354. bcR.Logger.Error("could not convert msg to proto", "err", err)
  355. return fmt.Errorf("could not convert msg to proto: %w", err)
  356. }
  357. bcR.Switch.Broadcast(BlockchainChannel, bm)
  358. return nil
  359. }