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.

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