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.

211 lines
6.0 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
6 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
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
6 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
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
6 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
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
6 years ago
  1. package v1
  2. import (
  3. "fmt"
  4. "math"
  5. "time"
  6. flow "github.com/tendermint/tendermint/libs/flowrate"
  7. "github.com/tendermint/tendermint/libs/log"
  8. "github.com/tendermint/tendermint/p2p"
  9. "github.com/tendermint/tendermint/types"
  10. )
  11. //--------
  12. // Peer
  13. // BpPeerParams stores the peer parameters that are used when creating a peer.
  14. type BpPeerParams struct {
  15. timeout time.Duration
  16. minRecvRate int64
  17. sampleRate time.Duration
  18. windowSize time.Duration
  19. }
  20. // BpPeer is the datastructure associated with a fast sync peer.
  21. type BpPeer struct {
  22. logger log.Logger
  23. ID p2p.ID
  24. Base int64 // the peer reported base
  25. Height int64 // the peer reported height
  26. NumPendingBlockRequests int // number of requests still waiting for block responses
  27. blocks map[int64]*types.Block // blocks received or expected to be received from this peer
  28. blockResponseTimer *time.Timer
  29. recvMonitor *flow.Monitor
  30. params *BpPeerParams // parameters for timer and monitor
  31. onErr func(err error, peerID p2p.ID) // function to call on error
  32. }
  33. // NewBpPeer creates a new peer.
  34. func NewBpPeer(peerID p2p.ID, base int64, height int64,
  35. onErr func(err error, peerID p2p.ID), params *BpPeerParams) *BpPeer {
  36. if params == nil {
  37. params = BpPeerDefaultParams()
  38. }
  39. return &BpPeer{
  40. ID: peerID,
  41. Base: base,
  42. Height: height,
  43. blocks: make(map[int64]*types.Block, maxRequestsPerPeer),
  44. logger: log.NewNopLogger(),
  45. onErr: onErr,
  46. params: params,
  47. }
  48. }
  49. // String returns a string representation of a peer.
  50. func (peer *BpPeer) String() string {
  51. return fmt.Sprintf("peer: %v height: %v pending: %v", peer.ID, peer.Height, peer.NumPendingBlockRequests)
  52. }
  53. // SetLogger sets the logger of the peer.
  54. func (peer *BpPeer) SetLogger(l log.Logger) {
  55. peer.logger = l
  56. }
  57. // Cleanup performs cleanup of the peer, removes blocks, requests, stops timer and monitor.
  58. func (peer *BpPeer) Cleanup() {
  59. if peer.blockResponseTimer != nil {
  60. peer.blockResponseTimer.Stop()
  61. }
  62. if peer.NumPendingBlockRequests != 0 {
  63. peer.logger.Info("peer with pending requests is being cleaned", "peer", peer.ID)
  64. }
  65. if len(peer.blocks)-peer.NumPendingBlockRequests != 0 {
  66. peer.logger.Info("peer with pending blocks is being cleaned", "peer", peer.ID)
  67. }
  68. for h := range peer.blocks {
  69. delete(peer.blocks, h)
  70. }
  71. peer.NumPendingBlockRequests = 0
  72. peer.recvMonitor = nil
  73. }
  74. // BlockAtHeight returns the block at a given height if available and errMissingBlock otherwise.
  75. func (peer *BpPeer) BlockAtHeight(height int64) (*types.Block, error) {
  76. block, ok := peer.blocks[height]
  77. if !ok {
  78. return nil, errMissingBlock
  79. }
  80. if block == nil {
  81. return nil, errMissingBlock
  82. }
  83. return peer.blocks[height], nil
  84. }
  85. // AddBlock adds a block at peer level. Block must be non-nil and recvSize a positive integer
  86. // The peer must have a pending request for this block.
  87. func (peer *BpPeer) AddBlock(block *types.Block, recvSize int) error {
  88. if block == nil || recvSize < 0 {
  89. panic("bad parameters")
  90. }
  91. existingBlock, ok := peer.blocks[block.Height]
  92. if !ok {
  93. peer.logger.Error("unsolicited block", "blockHeight", block.Height, "peer", peer.ID)
  94. return errMissingBlock
  95. }
  96. if existingBlock != nil {
  97. peer.logger.Error("already have a block for height", "height", block.Height)
  98. return errDuplicateBlock
  99. }
  100. if peer.NumPendingBlockRequests == 0 {
  101. panic("peer does not have pending requests")
  102. }
  103. peer.blocks[block.Height] = block
  104. peer.NumPendingBlockRequests--
  105. if peer.NumPendingBlockRequests == 0 {
  106. peer.stopMonitor()
  107. peer.stopBlockResponseTimer()
  108. } else {
  109. peer.recvMonitor.Update(recvSize)
  110. peer.resetBlockResponseTimer()
  111. }
  112. return nil
  113. }
  114. // RemoveBlock removes the block of given height
  115. func (peer *BpPeer) RemoveBlock(height int64) {
  116. delete(peer.blocks, height)
  117. }
  118. // RequestSent records that a request was sent, and starts the peer timer and monitor if needed.
  119. func (peer *BpPeer) RequestSent(height int64) {
  120. peer.blocks[height] = nil
  121. if peer.NumPendingBlockRequests == 0 {
  122. peer.startMonitor()
  123. peer.resetBlockResponseTimer()
  124. }
  125. peer.NumPendingBlockRequests++
  126. }
  127. // CheckRate verifies that the response rate of the peer is acceptable (higher than the minimum allowed).
  128. func (peer *BpPeer) CheckRate() error {
  129. if peer.NumPendingBlockRequests == 0 {
  130. return nil
  131. }
  132. curRate := peer.recvMonitor.Status().CurRate
  133. // curRate can be 0 on start
  134. if curRate != 0 && curRate < peer.params.minRecvRate {
  135. err := errSlowPeer
  136. peer.logger.Error("SendTimeout", "peer", peer,
  137. "reason", err,
  138. "curRate", fmt.Sprintf("%d KB/s", curRate/1024),
  139. "minRate", fmt.Sprintf("%d KB/s", peer.params.minRecvRate/1024))
  140. return err
  141. }
  142. return nil
  143. }
  144. func (peer *BpPeer) onTimeout() {
  145. peer.onErr(errNoPeerResponse, peer.ID)
  146. }
  147. func (peer *BpPeer) stopMonitor() {
  148. peer.recvMonitor.Done()
  149. peer.recvMonitor = nil
  150. }
  151. func (peer *BpPeer) startMonitor() {
  152. peer.recvMonitor = flow.New(peer.params.sampleRate, peer.params.windowSize)
  153. initialValue := float64(peer.params.minRecvRate) * math.E
  154. peer.recvMonitor.SetREMA(initialValue)
  155. }
  156. func (peer *BpPeer) resetBlockResponseTimer() {
  157. if peer.blockResponseTimer == nil {
  158. peer.blockResponseTimer = time.AfterFunc(peer.params.timeout, peer.onTimeout)
  159. } else {
  160. peer.blockResponseTimer.Reset(peer.params.timeout)
  161. }
  162. }
  163. func (peer *BpPeer) stopBlockResponseTimer() bool {
  164. if peer.blockResponseTimer == nil {
  165. return false
  166. }
  167. return peer.blockResponseTimer.Stop()
  168. }
  169. // BpPeerDefaultParams returns the default peer parameters.
  170. func BpPeerDefaultParams() *BpPeerParams {
  171. return &BpPeerParams{
  172. // Timeout for a peer to respond to a block request.
  173. timeout: 15 * time.Second,
  174. // Minimum recv rate to ensure we're receiving blocks from a peer fast
  175. // enough. If a peer is not sending data at at least that rate, we
  176. // consider them to have timedout and we disconnect.
  177. //
  178. // Assuming a DSL connection (not a good choice) 128 Kbps (upload) ~ 15 KB/s,
  179. // sending data across atlantic ~ 7.5 KB/s.
  180. minRecvRate: int64(7680),
  181. // Monitor parameters
  182. sampleRate: time.Second,
  183. windowSize: 40 * time.Second,
  184. }
  185. }