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.

633 lines
16 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
10 years ago
8 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
8 years ago
9 years ago
10 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
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
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
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
fix invalid memory address or nil pointer dereference error (Refs #762) https://github.com/tendermint/tendermint/issues/762#issuecomment-338276055 ``` E[10-19|04:52:38.969] Stopping peer for error module=p2p peer="Peer{MConn{178.62.46.14:46656} B14916FAF38A out}" err="Error: runtime error: invalid memory address or nil pointer dereference\nStack: goroutine 529485 [running]:\nruntime/debug.Stack(0xc4355cfb38, 0xb463e0, 0x11b1c30)\n\t/usr/local/go/src/runtime/debug/stack.go:24 +0xa7\ngithub.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/p2p.(*MConnection)._recover(0xc439a28870)\n\t/home/ubuntu/go/src/github.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/p2p/connection.go:206 +0x6e\npanic(0xb463e0, 0x11b1c30)\n\t/usr/local/go/src/runtime/panic.go:491 +0x283\ngithub.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/blockchain.(*bpPeer).decrPending(0x0, 0x381)\n\t/home/ubuntu/go/src/github.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/blockchain/pool.go:376 +0x22\ngithub.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/blockchain.(*BlockPool).AddBlock(0xc4200e4000, 0xc4266d1f00, 0x40, 0xc432ac9640, 0x381)\n\t/home/ubuntu/go/src/github.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/blockchain/pool.go:215 +0x139\ngithub.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/blockchain.(*BlockchainReactor).Receive(0xc42050a780, 0xc420257740, 0x1171be0, 0xc42ff302d0, 0xc4384b2000, 0x381, 0x1000)\n\t/home/ubuntu/go/src/github.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/blockchain/reactor.go:160 +0x712\ngithub.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/p2p.createMConnection.func1(0x11e5040, 0xc4384b2000, 0x381, 0x1000)\n\t/home/ubuntu/go/src/github.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/p2p/peer.go:334 +0xbd\ngithub.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/p2p.(*MConnection).recvRoutine(0xc439a28870)\n\t/home/ubuntu/go/src/github.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/p2p/connection.go:475 +0x4a3\ncreated by github.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/p2p.(*MConnection).OnStart\n\t/home/ubuntu/go/src/github.com/cosmos/gaia/vendor/github.com/tendermint/tendermint/p2p/connection.go:170 +0x187\n" ```
7 years ago
8 years ago
8 years ago
8 years ago
8 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
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
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 v0
  2. import (
  3. "errors"
  4. "fmt"
  5. "math"
  6. "sync"
  7. "sync/atomic"
  8. "time"
  9. cmn "github.com/tendermint/tendermint/libs/common"
  10. flow "github.com/tendermint/tendermint/libs/flowrate"
  11. "github.com/tendermint/tendermint/libs/log"
  12. "github.com/tendermint/tendermint/p2p"
  13. "github.com/tendermint/tendermint/types"
  14. )
  15. /*
  16. eg, L = latency = 0.1s
  17. P = num peers = 10
  18. FN = num full nodes
  19. BS = 1kB block size
  20. CB = 1 Mbit/s = 128 kB/s
  21. CB/P = 12.8 kB
  22. B/S = CB/P/BS = 12.8 blocks/s
  23. 12.8 * 0.1 = 1.28 blocks on conn
  24. */
  25. const (
  26. requestIntervalMS = 2
  27. maxTotalRequesters = 600
  28. maxPendingRequests = maxTotalRequesters
  29. maxPendingRequestsPerPeer = 20
  30. // Minimum recv rate to ensure we're receiving blocks from a peer fast
  31. // enough. If a peer is not sending us data at at least that rate, we
  32. // consider them to have timedout and we disconnect.
  33. //
  34. // Assuming a DSL connection (not a good choice) 128 Kbps (upload) ~ 15 KB/s,
  35. // sending data across atlantic ~ 7.5 KB/s.
  36. minRecvRate = 7680
  37. // Maximum difference between current and new block's height.
  38. maxDiffBetweenCurrentAndReceivedBlockHeight = 100
  39. )
  40. var peerTimeout = 15 * time.Second // not const so we can override with tests
  41. /*
  42. Peers self report their heights when we join the block pool.
  43. Starting from our latest pool.height, we request blocks
  44. in sequence from peers that reported higher heights than ours.
  45. Every so often we ask peers what height they're on so we can keep going.
  46. Requests are continuously made for blocks of higher heights until
  47. the limit is reached. If most of the requests have no available peers, and we
  48. are not at peer limits, we can probably switch to consensus reactor
  49. */
  50. // BlockPool keeps track of the fast sync peers, block requests and block responses.
  51. type BlockPool struct {
  52. cmn.BaseService
  53. startTime time.Time
  54. mtx sync.Mutex
  55. // block requests
  56. requesters map[int64]*bpRequester
  57. height int64 // the lowest key in requesters.
  58. // peers
  59. peers map[p2p.ID]*bpPeer
  60. maxPeerHeight int64 // the biggest reported height
  61. // atomic
  62. numPending int32 // number of requests pending assignment or block response
  63. requestsCh chan<- BlockRequest
  64. errorsCh chan<- peerError
  65. }
  66. // NewBlockPool returns a new BlockPool with the height equal to start. Block
  67. // requests and errors will be sent to requestsCh and errorsCh accordingly.
  68. func NewBlockPool(start int64, requestsCh chan<- BlockRequest, errorsCh chan<- peerError) *BlockPool {
  69. bp := &BlockPool{
  70. peers: make(map[p2p.ID]*bpPeer),
  71. requesters: make(map[int64]*bpRequester),
  72. height: start,
  73. numPending: 0,
  74. requestsCh: requestsCh,
  75. errorsCh: errorsCh,
  76. }
  77. bp.BaseService = *cmn.NewBaseService(nil, "BlockPool", bp)
  78. return bp
  79. }
  80. // OnStart implements cmn.Service by spawning requesters routine and recording
  81. // pool's start time.
  82. func (pool *BlockPool) OnStart() error {
  83. go pool.makeRequestersRoutine()
  84. pool.startTime = time.Now()
  85. return nil
  86. }
  87. // spawns requesters as needed
  88. func (pool *BlockPool) makeRequestersRoutine() {
  89. for {
  90. if !pool.IsRunning() {
  91. break
  92. }
  93. _, numPending, lenRequesters := pool.GetStatus()
  94. if numPending >= maxPendingRequests {
  95. // sleep for a bit.
  96. time.Sleep(requestIntervalMS * time.Millisecond)
  97. // check for timed out peers
  98. pool.removeTimedoutPeers()
  99. } else if lenRequesters >= maxTotalRequesters {
  100. // sleep for a bit.
  101. time.Sleep(requestIntervalMS * time.Millisecond)
  102. // check for timed out peers
  103. pool.removeTimedoutPeers()
  104. } else {
  105. // request for more blocks.
  106. pool.makeNextRequester()
  107. }
  108. }
  109. }
  110. func (pool *BlockPool) removeTimedoutPeers() {
  111. pool.mtx.Lock()
  112. defer pool.mtx.Unlock()
  113. for _, peer := range pool.peers {
  114. if !peer.didTimeout && peer.numPending > 0 {
  115. curRate := peer.recvMonitor.Status().CurRate
  116. // curRate can be 0 on start
  117. if curRate != 0 && curRate < minRecvRate {
  118. err := errors.New("peer is not sending us data fast enough")
  119. pool.sendError(err, peer.id)
  120. pool.Logger.Error("SendTimeout", "peer", peer.id,
  121. "reason", err,
  122. "curRate", fmt.Sprintf("%d KB/s", curRate/1024),
  123. "minRate", fmt.Sprintf("%d KB/s", minRecvRate/1024))
  124. peer.didTimeout = true
  125. }
  126. }
  127. if peer.didTimeout {
  128. pool.removePeer(peer.id)
  129. }
  130. }
  131. }
  132. // GetStatus returns pool's height, numPending requests and the number of
  133. // requesters.
  134. func (pool *BlockPool) GetStatus() (height int64, numPending int32, lenRequesters int) {
  135. pool.mtx.Lock()
  136. defer pool.mtx.Unlock()
  137. return pool.height, atomic.LoadInt32(&pool.numPending), len(pool.requesters)
  138. }
  139. // IsCaughtUp returns true if this node is caught up, false - otherwise.
  140. // TODO: relax conditions, prevent abuse.
  141. func (pool *BlockPool) IsCaughtUp() bool {
  142. pool.mtx.Lock()
  143. defer pool.mtx.Unlock()
  144. // Need at least 1 peer to be considered caught up.
  145. if len(pool.peers) == 0 {
  146. pool.Logger.Debug("Blockpool has no peers")
  147. return false
  148. }
  149. // Some conditions to determine if we're caught up.
  150. // Ensures we've either received a block or waited some amount of time,
  151. // and that we're synced to the highest known height.
  152. // Note we use maxPeerHeight - 1 because to sync block H requires block H+1
  153. // to verify the LastCommit.
  154. receivedBlockOrTimedOut := pool.height > 0 || time.Since(pool.startTime) > 5*time.Second
  155. ourChainIsLongestAmongPeers := pool.maxPeerHeight == 0 || pool.height >= (pool.maxPeerHeight-1)
  156. isCaughtUp := receivedBlockOrTimedOut && ourChainIsLongestAmongPeers
  157. return isCaughtUp
  158. }
  159. // PeekTwoBlocks returns blocks at pool.height and pool.height+1.
  160. // We need to see the second block's Commit to validate the first block.
  161. // So we peek two blocks at a time.
  162. // The caller will verify the commit.
  163. func (pool *BlockPool) PeekTwoBlocks() (first *types.Block, second *types.Block) {
  164. pool.mtx.Lock()
  165. defer pool.mtx.Unlock()
  166. if r := pool.requesters[pool.height]; r != nil {
  167. first = r.getBlock()
  168. }
  169. if r := pool.requesters[pool.height+1]; r != nil {
  170. second = r.getBlock()
  171. }
  172. return
  173. }
  174. // PopRequest pops the first block at pool.height.
  175. // It must have been validated by 'second'.Commit from PeekTwoBlocks().
  176. func (pool *BlockPool) PopRequest() {
  177. pool.mtx.Lock()
  178. defer pool.mtx.Unlock()
  179. if r := pool.requesters[pool.height]; r != nil {
  180. /* The block can disappear at any time, due to removePeer().
  181. if r := pool.requesters[pool.height]; r == nil || r.block == nil {
  182. PanicSanity("PopRequest() requires a valid block")
  183. }
  184. */
  185. r.Stop()
  186. delete(pool.requesters, pool.height)
  187. pool.height++
  188. } else {
  189. panic(fmt.Sprintf("Expected requester to pop, got nothing at height %v", pool.height))
  190. }
  191. }
  192. // RedoRequest invalidates the block at pool.height,
  193. // Remove the peer and redo request from others.
  194. // Returns the ID of the removed peer.
  195. func (pool *BlockPool) RedoRequest(height int64) p2p.ID {
  196. pool.mtx.Lock()
  197. defer pool.mtx.Unlock()
  198. request := pool.requesters[height]
  199. peerID := request.getPeerID()
  200. if peerID != p2p.ID("") {
  201. // RemovePeer will redo all requesters associated with this peer.
  202. pool.removePeer(peerID)
  203. }
  204. return peerID
  205. }
  206. // AddBlock validates that the block comes from the peer it was expected from and calls the requester to store it.
  207. // TODO: ensure that blocks come in order for each peer.
  208. func (pool *BlockPool) AddBlock(peerID p2p.ID, block *types.Block, blockSize int) {
  209. pool.mtx.Lock()
  210. defer pool.mtx.Unlock()
  211. requester := pool.requesters[block.Height]
  212. if requester == nil {
  213. pool.Logger.Info("peer sent us a block we didn't expect", "peer", peerID, "curHeight", pool.height, "blockHeight", block.Height)
  214. diff := pool.height - block.Height
  215. if diff < 0 {
  216. diff *= -1
  217. }
  218. if diff > maxDiffBetweenCurrentAndReceivedBlockHeight {
  219. pool.sendError(errors.New("peer sent us a block we didn't expect with a height too far ahead/behind"), peerID)
  220. }
  221. return
  222. }
  223. if requester.setBlock(block, peerID) {
  224. atomic.AddInt32(&pool.numPending, -1)
  225. peer := pool.peers[peerID]
  226. if peer != nil {
  227. peer.decrPending(blockSize)
  228. }
  229. } else {
  230. pool.Logger.Info("invalid peer", "peer", peerID, "blockHeight", block.Height)
  231. pool.sendError(errors.New("invalid peer"), peerID)
  232. }
  233. }
  234. // MaxPeerHeight returns the highest reported height.
  235. func (pool *BlockPool) MaxPeerHeight() int64 {
  236. pool.mtx.Lock()
  237. defer pool.mtx.Unlock()
  238. return pool.maxPeerHeight
  239. }
  240. // SetPeerHeight sets the peer's alleged blockchain height.
  241. func (pool *BlockPool) SetPeerHeight(peerID p2p.ID, height int64) {
  242. pool.mtx.Lock()
  243. defer pool.mtx.Unlock()
  244. peer := pool.peers[peerID]
  245. if peer != nil {
  246. peer.height = height
  247. } else {
  248. peer = newBPPeer(pool, peerID, height)
  249. peer.setLogger(pool.Logger.With("peer", peerID))
  250. pool.peers[peerID] = peer
  251. }
  252. if height > pool.maxPeerHeight {
  253. pool.maxPeerHeight = height
  254. }
  255. }
  256. // RemovePeer removes the peer with peerID from the pool. If there's no peer
  257. // with peerID, function is a no-op.
  258. func (pool *BlockPool) RemovePeer(peerID p2p.ID) {
  259. pool.mtx.Lock()
  260. defer pool.mtx.Unlock()
  261. pool.removePeer(peerID)
  262. }
  263. func (pool *BlockPool) removePeer(peerID p2p.ID) {
  264. for _, requester := range pool.requesters {
  265. if requester.getPeerID() == peerID {
  266. requester.redo(peerID)
  267. }
  268. }
  269. peer, ok := pool.peers[peerID]
  270. if ok {
  271. if peer.timeout != nil {
  272. peer.timeout.Stop()
  273. }
  274. delete(pool.peers, peerID)
  275. // Find a new peer with the biggest height and update maxPeerHeight if the
  276. // peer's height was the biggest.
  277. if peer.height == pool.maxPeerHeight {
  278. pool.updateMaxPeerHeight()
  279. }
  280. }
  281. }
  282. // If no peers are left, maxPeerHeight is set to 0.
  283. func (pool *BlockPool) updateMaxPeerHeight() {
  284. var max int64
  285. for _, peer := range pool.peers {
  286. if peer.height > max {
  287. max = peer.height
  288. }
  289. }
  290. pool.maxPeerHeight = max
  291. }
  292. // Pick an available peer with at least the given minHeight.
  293. // If no peers are available, returns nil.
  294. func (pool *BlockPool) pickIncrAvailablePeer(minHeight int64) *bpPeer {
  295. pool.mtx.Lock()
  296. defer pool.mtx.Unlock()
  297. for _, peer := range pool.peers {
  298. if peer.didTimeout {
  299. pool.removePeer(peer.id)
  300. continue
  301. }
  302. if peer.numPending >= maxPendingRequestsPerPeer {
  303. continue
  304. }
  305. if peer.height < minHeight {
  306. continue
  307. }
  308. peer.incrPending()
  309. return peer
  310. }
  311. return nil
  312. }
  313. func (pool *BlockPool) makeNextRequester() {
  314. pool.mtx.Lock()
  315. defer pool.mtx.Unlock()
  316. nextHeight := pool.height + pool.requestersLen()
  317. if nextHeight > pool.maxPeerHeight {
  318. return
  319. }
  320. request := newBPRequester(pool, nextHeight)
  321. pool.requesters[nextHeight] = request
  322. atomic.AddInt32(&pool.numPending, 1)
  323. err := request.Start()
  324. if err != nil {
  325. request.Logger.Error("Error starting request", "err", err)
  326. }
  327. }
  328. func (pool *BlockPool) requestersLen() int64 {
  329. return int64(len(pool.requesters))
  330. }
  331. func (pool *BlockPool) sendRequest(height int64, peerID p2p.ID) {
  332. if !pool.IsRunning() {
  333. return
  334. }
  335. pool.requestsCh <- BlockRequest{height, peerID}
  336. }
  337. func (pool *BlockPool) sendError(err error, peerID p2p.ID) {
  338. if !pool.IsRunning() {
  339. return
  340. }
  341. pool.errorsCh <- peerError{err, peerID}
  342. }
  343. // for debugging purposes
  344. //nolint:unused
  345. func (pool *BlockPool) debug() string {
  346. pool.mtx.Lock()
  347. defer pool.mtx.Unlock()
  348. str := ""
  349. nextHeight := pool.height + pool.requestersLen()
  350. for h := pool.height; h < nextHeight; h++ {
  351. if pool.requesters[h] == nil {
  352. str += fmt.Sprintf("H(%v):X ", h)
  353. } else {
  354. str += fmt.Sprintf("H(%v):", h)
  355. str += fmt.Sprintf("B?(%v) ", pool.requesters[h].block != nil)
  356. }
  357. }
  358. return str
  359. }
  360. //-------------------------------------
  361. type bpPeer struct {
  362. pool *BlockPool
  363. id p2p.ID
  364. recvMonitor *flow.Monitor
  365. height int64
  366. numPending int32
  367. timeout *time.Timer
  368. didTimeout bool
  369. logger log.Logger
  370. }
  371. func newBPPeer(pool *BlockPool, peerID p2p.ID, height int64) *bpPeer {
  372. peer := &bpPeer{
  373. pool: pool,
  374. id: peerID,
  375. height: height,
  376. numPending: 0,
  377. logger: log.NewNopLogger(),
  378. }
  379. return peer
  380. }
  381. func (peer *bpPeer) setLogger(l log.Logger) {
  382. peer.logger = l
  383. }
  384. func (peer *bpPeer) resetMonitor() {
  385. peer.recvMonitor = flow.New(time.Second, time.Second*40)
  386. initialValue := float64(minRecvRate) * math.E
  387. peer.recvMonitor.SetREMA(initialValue)
  388. }
  389. func (peer *bpPeer) resetTimeout() {
  390. if peer.timeout == nil {
  391. peer.timeout = time.AfterFunc(peerTimeout, peer.onTimeout)
  392. } else {
  393. peer.timeout.Reset(peerTimeout)
  394. }
  395. }
  396. func (peer *bpPeer) incrPending() {
  397. if peer.numPending == 0 {
  398. peer.resetMonitor()
  399. peer.resetTimeout()
  400. }
  401. peer.numPending++
  402. }
  403. func (peer *bpPeer) decrPending(recvSize int) {
  404. peer.numPending--
  405. if peer.numPending == 0 {
  406. peer.timeout.Stop()
  407. } else {
  408. peer.recvMonitor.Update(recvSize)
  409. peer.resetTimeout()
  410. }
  411. }
  412. func (peer *bpPeer) onTimeout() {
  413. peer.pool.mtx.Lock()
  414. defer peer.pool.mtx.Unlock()
  415. err := errors.New("peer did not send us anything")
  416. peer.pool.sendError(err, peer.id)
  417. peer.logger.Error("SendTimeout", "reason", err, "timeout", peerTimeout)
  418. peer.didTimeout = true
  419. }
  420. //-------------------------------------
  421. type bpRequester struct {
  422. cmn.BaseService
  423. pool *BlockPool
  424. height int64
  425. gotBlockCh chan struct{}
  426. redoCh chan p2p.ID //redo may send multitime, add peerId to identify repeat
  427. mtx sync.Mutex
  428. peerID p2p.ID
  429. block *types.Block
  430. }
  431. func newBPRequester(pool *BlockPool, height int64) *bpRequester {
  432. bpr := &bpRequester{
  433. pool: pool,
  434. height: height,
  435. gotBlockCh: make(chan struct{}, 1),
  436. redoCh: make(chan p2p.ID, 1),
  437. peerID: "",
  438. block: nil,
  439. }
  440. bpr.BaseService = *cmn.NewBaseService(nil, "bpRequester", bpr)
  441. return bpr
  442. }
  443. func (bpr *bpRequester) OnStart() error {
  444. go bpr.requestRoutine()
  445. return nil
  446. }
  447. // Returns true if the peer matches and block doesn't already exist.
  448. func (bpr *bpRequester) setBlock(block *types.Block, peerID p2p.ID) bool {
  449. bpr.mtx.Lock()
  450. if bpr.block != nil || bpr.peerID != peerID {
  451. bpr.mtx.Unlock()
  452. return false
  453. }
  454. bpr.block = block
  455. bpr.mtx.Unlock()
  456. select {
  457. case bpr.gotBlockCh <- struct{}{}:
  458. default:
  459. }
  460. return true
  461. }
  462. func (bpr *bpRequester) getBlock() *types.Block {
  463. bpr.mtx.Lock()
  464. defer bpr.mtx.Unlock()
  465. return bpr.block
  466. }
  467. func (bpr *bpRequester) getPeerID() p2p.ID {
  468. bpr.mtx.Lock()
  469. defer bpr.mtx.Unlock()
  470. return bpr.peerID
  471. }
  472. // This is called from the requestRoutine, upon redo().
  473. func (bpr *bpRequester) reset() {
  474. bpr.mtx.Lock()
  475. defer bpr.mtx.Unlock()
  476. if bpr.block != nil {
  477. atomic.AddInt32(&bpr.pool.numPending, 1)
  478. }
  479. bpr.peerID = ""
  480. bpr.block = nil
  481. }
  482. // Tells bpRequester to pick another peer and try again.
  483. // NOTE: Nonblocking, and does nothing if another redo
  484. // was already requested.
  485. func (bpr *bpRequester) redo(peerID p2p.ID) {
  486. select {
  487. case bpr.redoCh <- peerID:
  488. default:
  489. }
  490. }
  491. // Responsible for making more requests as necessary
  492. // Returns only when a block is found (e.g. AddBlock() is called)
  493. func (bpr *bpRequester) requestRoutine() {
  494. OUTER_LOOP:
  495. for {
  496. // Pick a peer to send request to.
  497. var peer *bpPeer
  498. PICK_PEER_LOOP:
  499. for {
  500. if !bpr.IsRunning() || !bpr.pool.IsRunning() {
  501. return
  502. }
  503. peer = bpr.pool.pickIncrAvailablePeer(bpr.height)
  504. if peer == nil {
  505. //log.Info("No peers available", "height", height)
  506. time.Sleep(requestIntervalMS * time.Millisecond)
  507. continue PICK_PEER_LOOP
  508. }
  509. break PICK_PEER_LOOP
  510. }
  511. bpr.mtx.Lock()
  512. bpr.peerID = peer.id
  513. bpr.mtx.Unlock()
  514. // Send request and wait.
  515. bpr.pool.sendRequest(bpr.height, peer.id)
  516. WAIT_LOOP:
  517. for {
  518. select {
  519. case <-bpr.pool.Quit():
  520. bpr.Stop()
  521. return
  522. case <-bpr.Quit():
  523. return
  524. case peerID := <-bpr.redoCh:
  525. if peerID == bpr.peerID {
  526. bpr.reset()
  527. continue OUTER_LOOP
  528. } else {
  529. continue WAIT_LOOP
  530. }
  531. case <-bpr.gotBlockCh:
  532. // We got a block!
  533. // Continue the for-loop and wait til Quit.
  534. continue WAIT_LOOP
  535. }
  536. }
  537. }
  538. }
  539. // BlockRequest stores a block request identified by the block Height and the PeerID responsible for
  540. // delivering the block
  541. type BlockRequest struct {
  542. Height int64
  543. PeerID p2p.ID
  544. }