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.

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