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.

674 lines
16 KiB

10 years ago
8 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
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
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
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
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
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
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
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
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
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
5 years ago
  1. package blocksync
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "math"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "github.com/tendermint/tendermint/internal/libs/flowrate"
  11. "github.com/tendermint/tendermint/libs/log"
  12. "github.com/tendermint/tendermint/libs/service"
  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. maxPeerErrBuffer = 1000
  29. maxPendingRequests = maxTotalRequesters
  30. maxPendingRequestsPerPeer = 20
  31. // Minimum recv rate to ensure we're receiving blocks from a peer fast
  32. // enough. If a peer is not sending us data at at least that rate, we
  33. // consider them to have timedout and we disconnect.
  34. //
  35. // Assuming a DSL connection (not a good choice) 128 Kbps (upload) ~ 15 KB/s,
  36. // sending data across atlantic ~ 7.5 KB/s.
  37. minRecvRate = 7680
  38. // Maximum difference between current and new block's height.
  39. maxDiffBetweenCurrentAndReceivedBlockHeight = 100
  40. )
  41. var peerTimeout = 15 * time.Second // not const so we can override with tests
  42. /*
  43. Peers self report their heights when we join the block pool.
  44. Starting from our latest pool.height, we request blocks
  45. in sequence from peers that reported higher heights than ours.
  46. Every so often we ask peers what height they're on so we can keep going.
  47. Requests are continuously made for blocks of higher heights until
  48. the limit is reached. If most of the requests have no available peers, and we
  49. are not at peer limits, we can probably switch to consensus reactor
  50. */
  51. // BlockRequest stores a block request identified by the block Height and the
  52. // PeerID responsible for delivering the block.
  53. type BlockRequest struct {
  54. Height int64
  55. PeerID types.NodeID
  56. }
  57. // BlockPool keeps track of the block sync peers, block requests and block responses.
  58. type BlockPool struct {
  59. service.BaseService
  60. logger log.Logger
  61. lastAdvance time.Time
  62. mtx sync.RWMutex
  63. // block requests
  64. requesters map[int64]*bpRequester
  65. height int64 // the lowest key in requesters.
  66. // peers
  67. peers map[types.NodeID]*bpPeer
  68. maxPeerHeight int64 // the biggest reported height
  69. // atomic
  70. numPending int32 // number of requests pending assignment or block response
  71. requestsCh chan<- BlockRequest
  72. errorsCh chan<- peerError
  73. startHeight int64
  74. lastHundredBlockTimeStamp time.Time
  75. lastSyncRate float64
  76. }
  77. // NewBlockPool returns a new BlockPool with the height equal to start. Block
  78. // requests and errors will be sent to requestsCh and errorsCh accordingly.
  79. func NewBlockPool(
  80. logger log.Logger,
  81. start int64,
  82. requestsCh chan<- BlockRequest,
  83. errorsCh chan<- peerError,
  84. ) *BlockPool {
  85. bp := &BlockPool{
  86. logger: logger,
  87. peers: make(map[types.NodeID]*bpPeer),
  88. requesters: make(map[int64]*bpRequester),
  89. height: start,
  90. startHeight: start,
  91. numPending: 0,
  92. requestsCh: requestsCh,
  93. errorsCh: errorsCh,
  94. lastSyncRate: 0,
  95. }
  96. bp.BaseService = *service.NewBaseService(logger, "BlockPool", bp)
  97. return bp
  98. }
  99. // OnStart implements service.Service by spawning requesters routine and recording
  100. // pool's start time.
  101. func (pool *BlockPool) OnStart(ctx context.Context) error {
  102. pool.lastAdvance = time.Now()
  103. pool.lastHundredBlockTimeStamp = pool.lastAdvance
  104. go pool.makeRequestersRoutine(ctx)
  105. return nil
  106. }
  107. func (*BlockPool) OnStop() {}
  108. // spawns requesters as needed
  109. func (pool *BlockPool) makeRequestersRoutine(ctx context.Context) {
  110. for {
  111. if !pool.IsRunning() {
  112. break
  113. }
  114. _, numPending, lenRequesters := pool.GetStatus()
  115. switch {
  116. case numPending >= maxPendingRequests:
  117. // sleep for a bit.
  118. time.Sleep(requestIntervalMS * time.Millisecond)
  119. // check for timed out peers
  120. pool.removeTimedoutPeers()
  121. case lenRequesters >= maxTotalRequesters:
  122. // sleep for a bit.
  123. time.Sleep(requestIntervalMS * time.Millisecond)
  124. // check for timed out peers
  125. pool.removeTimedoutPeers()
  126. default:
  127. // request for more blocks.
  128. pool.makeNextRequester(ctx)
  129. }
  130. }
  131. }
  132. func (pool *BlockPool) removeTimedoutPeers() {
  133. pool.mtx.Lock()
  134. defer pool.mtx.Unlock()
  135. for _, peer := range pool.peers {
  136. // check if peer timed out
  137. if !peer.didTimeout && peer.numPending > 0 {
  138. curRate := peer.recvMonitor.CurrentTransferRate()
  139. // curRate can be 0 on start
  140. if curRate != 0 && curRate < minRecvRate {
  141. err := errors.New("peer is not sending us data fast enough")
  142. pool.sendError(err, peer.id)
  143. pool.logger.Error("SendTimeout", "peer", peer.id,
  144. "reason", err,
  145. "curRate", fmt.Sprintf("%d KB/s", curRate/1024),
  146. "minRate", fmt.Sprintf("%d KB/s", minRecvRate/1024))
  147. peer.didTimeout = true
  148. }
  149. }
  150. if peer.didTimeout {
  151. pool.removePeer(peer.id)
  152. }
  153. }
  154. }
  155. // GetStatus returns pool's height, numPending requests and the number of
  156. // requesters.
  157. func (pool *BlockPool) GetStatus() (height int64, numPending int32, lenRequesters int) {
  158. pool.mtx.RLock()
  159. defer pool.mtx.RUnlock()
  160. return pool.height, atomic.LoadInt32(&pool.numPending), len(pool.requesters)
  161. }
  162. // IsCaughtUp returns true if this node is caught up, false - otherwise.
  163. func (pool *BlockPool) IsCaughtUp() bool {
  164. pool.mtx.RLock()
  165. defer pool.mtx.RUnlock()
  166. // Need at least 1 peer to be considered caught up.
  167. if len(pool.peers) == 0 {
  168. return false
  169. }
  170. // NOTE: we use maxPeerHeight - 1 because to sync block H requires block H+1
  171. // to verify the LastCommit.
  172. return pool.height >= (pool.maxPeerHeight - 1)
  173. }
  174. // PeekTwoBlocks returns blocks at pool.height and pool.height+1.
  175. // We need to see the second block's Commit to validate the first block.
  176. // So we peek two blocks at a time.
  177. // The caller will verify the commit.
  178. func (pool *BlockPool) PeekTwoBlocks() (first *types.Block, second *types.Block) {
  179. pool.mtx.RLock()
  180. defer pool.mtx.RUnlock()
  181. if r := pool.requesters[pool.height]; r != nil {
  182. first = r.getBlock()
  183. }
  184. if r := pool.requesters[pool.height+1]; r != nil {
  185. second = r.getBlock()
  186. }
  187. return
  188. }
  189. // PopRequest pops the first block at pool.height.
  190. // It must have been validated by 'second'.Commit from PeekTwoBlocks().
  191. func (pool *BlockPool) PopRequest() {
  192. pool.mtx.Lock()
  193. defer pool.mtx.Unlock()
  194. if r := pool.requesters[pool.height]; r != nil {
  195. r.Stop()
  196. delete(pool.requesters, pool.height)
  197. pool.height++
  198. pool.lastAdvance = time.Now()
  199. // the lastSyncRate will be updated every 100 blocks, it uses the adaptive filter
  200. // to smooth the block sync rate and the unit represents the number of blocks per second.
  201. if (pool.height-pool.startHeight)%100 == 0 {
  202. newSyncRate := 100 / time.Since(pool.lastHundredBlockTimeStamp).Seconds()
  203. if pool.lastSyncRate == 0 {
  204. pool.lastSyncRate = newSyncRate
  205. } else {
  206. pool.lastSyncRate = 0.9*pool.lastSyncRate + 0.1*newSyncRate
  207. }
  208. pool.lastHundredBlockTimeStamp = time.Now()
  209. }
  210. } else {
  211. panic(fmt.Sprintf("Expected requester to pop, got nothing at height %v", pool.height))
  212. }
  213. }
  214. // RedoRequest invalidates the block at pool.height,
  215. // Remove the peer and redo request from others.
  216. // Returns the ID of the removed peer.
  217. func (pool *BlockPool) RedoRequest(height int64) types.NodeID {
  218. pool.mtx.Lock()
  219. defer pool.mtx.Unlock()
  220. request := pool.requesters[height]
  221. peerID := request.getPeerID()
  222. if peerID != types.NodeID("") {
  223. // RemovePeer will redo all requesters associated with this peer.
  224. pool.removePeer(peerID)
  225. }
  226. return peerID
  227. }
  228. // AddBlock validates that the block comes from the peer it was expected from and calls the requester to store it.
  229. // TODO: ensure that blocks come in order for each peer.
  230. func (pool *BlockPool) AddBlock(peerID types.NodeID, block *types.Block, blockSize int) {
  231. pool.mtx.Lock()
  232. defer pool.mtx.Unlock()
  233. requester := pool.requesters[block.Height]
  234. if requester == nil {
  235. pool.logger.Error("peer sent us a block we didn't expect",
  236. "peer", peerID, "curHeight", pool.height, "blockHeight", block.Height)
  237. diff := pool.height - block.Height
  238. if diff < 0 {
  239. diff *= -1
  240. }
  241. if diff > maxDiffBetweenCurrentAndReceivedBlockHeight {
  242. pool.sendError(errors.New("peer sent us a block we didn't expect with a height too far ahead/behind"), peerID)
  243. }
  244. return
  245. }
  246. if requester.setBlock(block, peerID) {
  247. atomic.AddInt32(&pool.numPending, -1)
  248. peer := pool.peers[peerID]
  249. if peer != nil {
  250. peer.decrPending(blockSize)
  251. }
  252. } else {
  253. err := errors.New("requester is different or block already exists")
  254. pool.logger.Error(err.Error(), "peer", peerID, "requester", requester.getPeerID(), "blockHeight", block.Height)
  255. pool.sendError(err, peerID)
  256. }
  257. }
  258. // MaxPeerHeight returns the highest reported height.
  259. func (pool *BlockPool) MaxPeerHeight() int64 {
  260. pool.mtx.RLock()
  261. defer pool.mtx.RUnlock()
  262. return pool.maxPeerHeight
  263. }
  264. // LastAdvance returns the time when the last block was processed (or start
  265. // time if no blocks were processed).
  266. func (pool *BlockPool) LastAdvance() time.Time {
  267. pool.mtx.RLock()
  268. defer pool.mtx.RUnlock()
  269. return pool.lastAdvance
  270. }
  271. // SetPeerRange sets the peer's alleged blockchain base and height.
  272. func (pool *BlockPool) SetPeerRange(peerID types.NodeID, base int64, height int64) {
  273. pool.mtx.Lock()
  274. defer pool.mtx.Unlock()
  275. peer := pool.peers[peerID]
  276. if peer != nil {
  277. peer.base = base
  278. peer.height = height
  279. } else {
  280. peer = &bpPeer{
  281. pool: pool,
  282. id: peerID,
  283. base: base,
  284. height: height,
  285. numPending: 0,
  286. logger: pool.logger.With("peer", peerID),
  287. startAt: time.Now(),
  288. }
  289. pool.peers[peerID] = peer
  290. }
  291. if height > pool.maxPeerHeight {
  292. pool.maxPeerHeight = height
  293. }
  294. }
  295. // RemovePeer removes the peer with peerID from the pool. If there's no peer
  296. // with peerID, function is a no-op.
  297. func (pool *BlockPool) RemovePeer(peerID types.NodeID) {
  298. pool.mtx.Lock()
  299. defer pool.mtx.Unlock()
  300. pool.removePeer(peerID)
  301. }
  302. func (pool *BlockPool) removePeer(peerID types.NodeID) {
  303. for _, requester := range pool.requesters {
  304. if requester.getPeerID() == peerID {
  305. requester.redo(peerID)
  306. }
  307. }
  308. peer, ok := pool.peers[peerID]
  309. if ok {
  310. if peer.timeout != nil {
  311. peer.timeout.Stop()
  312. }
  313. delete(pool.peers, peerID)
  314. // Find a new peer with the biggest height and update maxPeerHeight if the
  315. // peer's height was the biggest.
  316. if peer.height == pool.maxPeerHeight {
  317. pool.updateMaxPeerHeight()
  318. }
  319. }
  320. }
  321. // If no peers are left, maxPeerHeight is set to 0.
  322. func (pool *BlockPool) updateMaxPeerHeight() {
  323. var max int64
  324. for _, peer := range pool.peers {
  325. if peer.height > max {
  326. max = peer.height
  327. }
  328. }
  329. pool.maxPeerHeight = max
  330. }
  331. // Pick an available peer with the given height available.
  332. // If no peers are available, returns nil.
  333. func (pool *BlockPool) pickIncrAvailablePeer(height int64) *bpPeer {
  334. pool.mtx.Lock()
  335. defer pool.mtx.Unlock()
  336. for _, peer := range pool.peers {
  337. if peer.didTimeout {
  338. pool.removePeer(peer.id)
  339. continue
  340. }
  341. if peer.numPending >= maxPendingRequestsPerPeer {
  342. continue
  343. }
  344. if height < peer.base || height > peer.height {
  345. continue
  346. }
  347. peer.incrPending()
  348. return peer
  349. }
  350. return nil
  351. }
  352. func (pool *BlockPool) makeNextRequester(ctx context.Context) {
  353. pool.mtx.Lock()
  354. defer pool.mtx.Unlock()
  355. nextHeight := pool.height + pool.requestersLen()
  356. if nextHeight > pool.maxPeerHeight {
  357. return
  358. }
  359. request := newBPRequester(pool.logger, pool, nextHeight)
  360. pool.requesters[nextHeight] = request
  361. atomic.AddInt32(&pool.numPending, 1)
  362. err := request.Start(ctx)
  363. if err != nil {
  364. request.logger.Error("error starting request", "err", err)
  365. }
  366. }
  367. func (pool *BlockPool) requestersLen() int64 {
  368. return int64(len(pool.requesters))
  369. }
  370. func (pool *BlockPool) sendRequest(height int64, peerID types.NodeID) {
  371. if !pool.IsRunning() {
  372. return
  373. }
  374. pool.requestsCh <- BlockRequest{height, peerID}
  375. }
  376. func (pool *BlockPool) sendError(err error, peerID types.NodeID) {
  377. if !pool.IsRunning() {
  378. return
  379. }
  380. pool.errorsCh <- peerError{err, peerID}
  381. }
  382. // for debugging purposes
  383. //nolint:unused
  384. func (pool *BlockPool) debug() string {
  385. pool.mtx.Lock()
  386. defer pool.mtx.Unlock()
  387. str := ""
  388. nextHeight := pool.height + pool.requestersLen()
  389. for h := pool.height; h < nextHeight; h++ {
  390. if pool.requesters[h] == nil {
  391. str += fmt.Sprintf("H(%v):X ", h)
  392. } else {
  393. str += fmt.Sprintf("H(%v):", h)
  394. str += fmt.Sprintf("B?(%v) ", pool.requesters[h].block != nil)
  395. }
  396. }
  397. return str
  398. }
  399. func (pool *BlockPool) targetSyncBlocks() int64 {
  400. pool.mtx.RLock()
  401. defer pool.mtx.RUnlock()
  402. return pool.maxPeerHeight - pool.startHeight + 1
  403. }
  404. func (pool *BlockPool) getLastSyncRate() float64 {
  405. pool.mtx.RLock()
  406. defer pool.mtx.RUnlock()
  407. return pool.lastSyncRate
  408. }
  409. //-------------------------------------
  410. type bpPeer struct {
  411. didTimeout bool
  412. numPending int32
  413. height int64
  414. base int64
  415. pool *BlockPool
  416. id types.NodeID
  417. recvMonitor *flowrate.Monitor
  418. timeout *time.Timer
  419. startAt time.Time
  420. logger log.Logger
  421. }
  422. func (peer *bpPeer) resetMonitor() {
  423. peer.recvMonitor = flowrate.New(peer.startAt, time.Second, time.Second*40)
  424. initialValue := float64(minRecvRate) * math.E
  425. peer.recvMonitor.SetREMA(initialValue)
  426. }
  427. func (peer *bpPeer) resetTimeout() {
  428. if peer.timeout == nil {
  429. peer.timeout = time.AfterFunc(peerTimeout, peer.onTimeout)
  430. } else {
  431. peer.timeout.Reset(peerTimeout)
  432. }
  433. }
  434. func (peer *bpPeer) incrPending() {
  435. if peer.numPending == 0 {
  436. peer.resetMonitor()
  437. peer.resetTimeout()
  438. }
  439. peer.numPending++
  440. }
  441. func (peer *bpPeer) decrPending(recvSize int) {
  442. peer.numPending--
  443. if peer.numPending == 0 {
  444. peer.timeout.Stop()
  445. } else {
  446. peer.recvMonitor.Update(recvSize)
  447. peer.resetTimeout()
  448. }
  449. }
  450. func (peer *bpPeer) onTimeout() {
  451. peer.pool.mtx.Lock()
  452. defer peer.pool.mtx.Unlock()
  453. err := errors.New("peer did not send us anything")
  454. peer.pool.sendError(err, peer.id)
  455. peer.logger.Error("SendTimeout", "reason", err, "timeout", peerTimeout)
  456. peer.didTimeout = true
  457. }
  458. //-------------------------------------
  459. type bpRequester struct {
  460. service.BaseService
  461. logger log.Logger
  462. pool *BlockPool
  463. height int64
  464. gotBlockCh chan struct{}
  465. redoCh chan types.NodeID // redo may send multitime, add peerId to identify repeat
  466. mtx sync.Mutex
  467. peerID types.NodeID
  468. block *types.Block
  469. }
  470. func newBPRequester(logger log.Logger, pool *BlockPool, height int64) *bpRequester {
  471. bpr := &bpRequester{
  472. logger: pool.logger,
  473. pool: pool,
  474. height: height,
  475. gotBlockCh: make(chan struct{}, 1),
  476. redoCh: make(chan types.NodeID, 1),
  477. peerID: "",
  478. block: nil,
  479. }
  480. bpr.BaseService = *service.NewBaseService(logger, "bpRequester", bpr)
  481. return bpr
  482. }
  483. func (bpr *bpRequester) OnStart(ctx context.Context) error {
  484. go bpr.requestRoutine(ctx)
  485. return nil
  486. }
  487. func (*bpRequester) OnStop() {}
  488. // Returns true if the peer matches and block doesn't already exist.
  489. func (bpr *bpRequester) setBlock(block *types.Block, peerID types.NodeID) bool {
  490. bpr.mtx.Lock()
  491. if bpr.block != nil || bpr.peerID != peerID {
  492. bpr.mtx.Unlock()
  493. return false
  494. }
  495. bpr.block = block
  496. bpr.mtx.Unlock()
  497. select {
  498. case bpr.gotBlockCh <- struct{}{}:
  499. default:
  500. }
  501. return true
  502. }
  503. func (bpr *bpRequester) getBlock() *types.Block {
  504. bpr.mtx.Lock()
  505. defer bpr.mtx.Unlock()
  506. return bpr.block
  507. }
  508. func (bpr *bpRequester) getPeerID() types.NodeID {
  509. bpr.mtx.Lock()
  510. defer bpr.mtx.Unlock()
  511. return bpr.peerID
  512. }
  513. // This is called from the requestRoutine, upon redo().
  514. func (bpr *bpRequester) reset() {
  515. bpr.mtx.Lock()
  516. defer bpr.mtx.Unlock()
  517. if bpr.block != nil {
  518. atomic.AddInt32(&bpr.pool.numPending, 1)
  519. }
  520. bpr.peerID = ""
  521. bpr.block = nil
  522. }
  523. // Tells bpRequester to pick another peer and try again.
  524. // NOTE: Nonblocking, and does nothing if another redo
  525. // was already requested.
  526. func (bpr *bpRequester) redo(peerID types.NodeID) {
  527. select {
  528. case bpr.redoCh <- peerID:
  529. default:
  530. }
  531. }
  532. // Responsible for making more requests as necessary
  533. // Returns only when a block is found (e.g. AddBlock() is called)
  534. func (bpr *bpRequester) requestRoutine(ctx context.Context) {
  535. OUTER_LOOP:
  536. for {
  537. // Pick a peer to send request to.
  538. var peer *bpPeer
  539. PICK_PEER_LOOP:
  540. for {
  541. if !bpr.IsRunning() || !bpr.pool.IsRunning() {
  542. return
  543. }
  544. peer = bpr.pool.pickIncrAvailablePeer(bpr.height)
  545. if peer == nil {
  546. time.Sleep(requestIntervalMS * time.Millisecond)
  547. continue PICK_PEER_LOOP
  548. }
  549. break PICK_PEER_LOOP
  550. }
  551. bpr.mtx.Lock()
  552. bpr.peerID = peer.id
  553. bpr.mtx.Unlock()
  554. // Send request and wait.
  555. bpr.pool.sendRequest(bpr.height, peer.id)
  556. WAIT_LOOP:
  557. for {
  558. select {
  559. case <-ctx.Done():
  560. return
  561. case peerID := <-bpr.redoCh:
  562. if peerID == bpr.peerID {
  563. bpr.reset()
  564. continue OUTER_LOOP
  565. } else {
  566. continue WAIT_LOOP
  567. }
  568. case <-bpr.gotBlockCh:
  569. // We got a block!
  570. // Continue the for-loop and wait til Quit.
  571. continue WAIT_LOOP
  572. }
  573. }
  574. }
  575. }