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.

690 lines
17 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. exitedCh chan struct{}
  74. startHeight int64
  75. lastHundredBlockTimeStamp time.Time
  76. lastSyncRate float64
  77. }
  78. // NewBlockPool returns a new BlockPool with the height equal to start. Block
  79. // requests and errors will be sent to requestsCh and errorsCh accordingly.
  80. func NewBlockPool(
  81. logger log.Logger,
  82. start int64,
  83. requestsCh chan<- BlockRequest,
  84. errorsCh chan<- peerError,
  85. ) *BlockPool {
  86. bp := &BlockPool{
  87. logger: logger,
  88. peers: make(map[types.NodeID]*bpPeer),
  89. requesters: make(map[int64]*bpRequester),
  90. height: start,
  91. startHeight: start,
  92. numPending: 0,
  93. exitedCh: make(chan struct{}),
  94. requestsCh: requestsCh,
  95. errorsCh: errorsCh,
  96. lastSyncRate: 0,
  97. }
  98. bp.BaseService = *service.NewBaseService(logger, "BlockPool", bp)
  99. return bp
  100. }
  101. // OnStart implements service.Service by spawning requesters routine and recording
  102. // pool's start time.
  103. func (pool *BlockPool) OnStart(ctx context.Context) error {
  104. pool.lastAdvance = time.Now()
  105. pool.lastHundredBlockTimeStamp = pool.lastAdvance
  106. go pool.makeRequestersRoutine(ctx)
  107. go func() {
  108. defer close(pool.exitedCh)
  109. pool.Wait()
  110. }()
  111. return nil
  112. }
  113. func (*BlockPool) OnStop() {}
  114. // spawns requesters as needed
  115. func (pool *BlockPool) makeRequestersRoutine(ctx context.Context) {
  116. for {
  117. if !pool.IsRunning() {
  118. break
  119. }
  120. _, numPending, lenRequesters := pool.GetStatus()
  121. switch {
  122. case numPending >= maxPendingRequests:
  123. // sleep for a bit.
  124. time.Sleep(requestIntervalMS * time.Millisecond)
  125. // check for timed out peers
  126. pool.removeTimedoutPeers()
  127. case lenRequesters >= maxTotalRequesters:
  128. // sleep for a bit.
  129. time.Sleep(requestIntervalMS * time.Millisecond)
  130. // check for timed out peers
  131. pool.removeTimedoutPeers()
  132. default:
  133. // request for more blocks.
  134. pool.makeNextRequester(ctx)
  135. }
  136. }
  137. }
  138. func (pool *BlockPool) removeTimedoutPeers() {
  139. pool.mtx.Lock()
  140. defer pool.mtx.Unlock()
  141. for _, peer := range pool.peers {
  142. // check if peer timed out
  143. if !peer.didTimeout && peer.numPending > 0 {
  144. curRate := peer.recvMonitor.Status().CurRate
  145. // curRate can be 0 on start
  146. if curRate != 0 && curRate < minRecvRate {
  147. err := errors.New("peer is not sending us data fast enough")
  148. pool.sendError(err, peer.id)
  149. pool.logger.Error("SendTimeout", "peer", peer.id,
  150. "reason", err,
  151. "curRate", fmt.Sprintf("%d KB/s", curRate/1024),
  152. "minRate", fmt.Sprintf("%d KB/s", minRecvRate/1024))
  153. peer.didTimeout = true
  154. }
  155. }
  156. if peer.didTimeout {
  157. pool.removePeer(peer.id)
  158. }
  159. }
  160. }
  161. // GetStatus returns pool's height, numPending requests and the number of
  162. // requesters.
  163. func (pool *BlockPool) GetStatus() (height int64, numPending int32, lenRequesters int) {
  164. pool.mtx.RLock()
  165. defer pool.mtx.RUnlock()
  166. return pool.height, atomic.LoadInt32(&pool.numPending), len(pool.requesters)
  167. }
  168. // IsCaughtUp returns true if this node is caught up, false - otherwise.
  169. func (pool *BlockPool) IsCaughtUp() bool {
  170. pool.mtx.RLock()
  171. defer pool.mtx.RUnlock()
  172. // Need at least 1 peer to be considered caught up.
  173. if len(pool.peers) == 0 {
  174. return false
  175. }
  176. // NOTE: we use maxPeerHeight - 1 because to sync block H requires block H+1
  177. // to verify the LastCommit.
  178. return pool.height >= (pool.maxPeerHeight - 1)
  179. }
  180. // PeekTwoBlocks returns blocks at pool.height and pool.height+1.
  181. // We need to see the second block's Commit to validate the first block.
  182. // So we peek two blocks at a time.
  183. // The caller will verify the commit.
  184. func (pool *BlockPool) PeekTwoBlocks() (first *types.Block, second *types.Block) {
  185. pool.mtx.RLock()
  186. defer pool.mtx.RUnlock()
  187. if r := pool.requesters[pool.height]; r != nil {
  188. first = r.getBlock()
  189. }
  190. if r := pool.requesters[pool.height+1]; r != nil {
  191. second = r.getBlock()
  192. }
  193. return
  194. }
  195. // PopRequest pops the first block at pool.height.
  196. // It must have been validated by 'second'.Commit from PeekTwoBlocks().
  197. func (pool *BlockPool) PopRequest() {
  198. pool.mtx.Lock()
  199. defer pool.mtx.Unlock()
  200. if r := pool.requesters[pool.height]; r != nil {
  201. r.Stop()
  202. delete(pool.requesters, pool.height)
  203. pool.height++
  204. pool.lastAdvance = time.Now()
  205. // the lastSyncRate will be updated every 100 blocks, it uses the adaptive filter
  206. // to smooth the block sync rate and the unit represents the number of blocks per second.
  207. if (pool.height-pool.startHeight)%100 == 0 {
  208. newSyncRate := 100 / time.Since(pool.lastHundredBlockTimeStamp).Seconds()
  209. if pool.lastSyncRate == 0 {
  210. pool.lastSyncRate = newSyncRate
  211. } else {
  212. pool.lastSyncRate = 0.9*pool.lastSyncRate + 0.1*newSyncRate
  213. }
  214. pool.lastHundredBlockTimeStamp = time.Now()
  215. }
  216. } else {
  217. panic(fmt.Sprintf("Expected requester to pop, got nothing at height %v", pool.height))
  218. }
  219. }
  220. // RedoRequest invalidates the block at pool.height,
  221. // Remove the peer and redo request from others.
  222. // Returns the ID of the removed peer.
  223. func (pool *BlockPool) RedoRequest(height int64) types.NodeID {
  224. pool.mtx.Lock()
  225. defer pool.mtx.Unlock()
  226. request := pool.requesters[height]
  227. peerID := request.getPeerID()
  228. if peerID != types.NodeID("") {
  229. // RemovePeer will redo all requesters associated with this peer.
  230. pool.removePeer(peerID)
  231. }
  232. return peerID
  233. }
  234. // AddBlock validates that the block comes from the peer it was expected from and calls the requester to store it.
  235. // TODO: ensure that blocks come in order for each peer.
  236. func (pool *BlockPool) AddBlock(peerID types.NodeID, block *types.Block, blockSize int) {
  237. pool.mtx.Lock()
  238. defer pool.mtx.Unlock()
  239. requester := pool.requesters[block.Height]
  240. if requester == nil {
  241. pool.logger.Error("peer sent us a block we didn't expect",
  242. "peer", peerID, "curHeight", pool.height, "blockHeight", block.Height)
  243. diff := pool.height - block.Height
  244. if diff < 0 {
  245. diff *= -1
  246. }
  247. if diff > maxDiffBetweenCurrentAndReceivedBlockHeight {
  248. pool.sendError(errors.New("peer sent us a block we didn't expect with a height too far ahead/behind"), peerID)
  249. }
  250. return
  251. }
  252. if requester.setBlock(block, peerID) {
  253. atomic.AddInt32(&pool.numPending, -1)
  254. peer := pool.peers[peerID]
  255. if peer != nil {
  256. peer.decrPending(blockSize)
  257. }
  258. } else {
  259. err := errors.New("requester is different or block already exists")
  260. pool.logger.Error(err.Error(), "peer", peerID, "requester", requester.getPeerID(), "blockHeight", block.Height)
  261. pool.sendError(err, peerID)
  262. }
  263. }
  264. // MaxPeerHeight returns the highest reported height.
  265. func (pool *BlockPool) MaxPeerHeight() int64 {
  266. pool.mtx.RLock()
  267. defer pool.mtx.RUnlock()
  268. return pool.maxPeerHeight
  269. }
  270. // LastAdvance returns the time when the last block was processed (or start
  271. // time if no blocks were processed).
  272. func (pool *BlockPool) LastAdvance() time.Time {
  273. pool.mtx.RLock()
  274. defer pool.mtx.RUnlock()
  275. return pool.lastAdvance
  276. }
  277. // SetPeerRange sets the peer's alleged blockchain base and height.
  278. func (pool *BlockPool) SetPeerRange(peerID types.NodeID, base int64, height int64) {
  279. pool.mtx.Lock()
  280. defer pool.mtx.Unlock()
  281. peer := pool.peers[peerID]
  282. if peer != nil {
  283. peer.base = base
  284. peer.height = height
  285. } else {
  286. peer = &bpPeer{
  287. pool: pool,
  288. id: peerID,
  289. base: base,
  290. height: height,
  291. numPending: 0,
  292. logger: pool.logger.With("peer", peerID),
  293. startAt: time.Now(),
  294. }
  295. pool.peers[peerID] = peer
  296. }
  297. if height > pool.maxPeerHeight {
  298. pool.maxPeerHeight = height
  299. }
  300. }
  301. // RemovePeer removes the peer with peerID from the pool. If there's no peer
  302. // with peerID, function is a no-op.
  303. func (pool *BlockPool) RemovePeer(peerID types.NodeID) {
  304. pool.mtx.Lock()
  305. defer pool.mtx.Unlock()
  306. pool.removePeer(peerID)
  307. }
  308. func (pool *BlockPool) removePeer(peerID types.NodeID) {
  309. for _, requester := range pool.requesters {
  310. if requester.getPeerID() == peerID {
  311. requester.redo(peerID)
  312. }
  313. }
  314. peer, ok := pool.peers[peerID]
  315. if ok {
  316. if peer.timeout != nil {
  317. peer.timeout.Stop()
  318. }
  319. delete(pool.peers, peerID)
  320. // Find a new peer with the biggest height and update maxPeerHeight if the
  321. // peer's height was the biggest.
  322. if peer.height == pool.maxPeerHeight {
  323. pool.updateMaxPeerHeight()
  324. }
  325. }
  326. }
  327. // If no peers are left, maxPeerHeight is set to 0.
  328. func (pool *BlockPool) updateMaxPeerHeight() {
  329. var max int64
  330. for _, peer := range pool.peers {
  331. if peer.height > max {
  332. max = peer.height
  333. }
  334. }
  335. pool.maxPeerHeight = max
  336. }
  337. // Pick an available peer with the given height available.
  338. // If no peers are available, returns nil.
  339. func (pool *BlockPool) pickIncrAvailablePeer(height int64) *bpPeer {
  340. pool.mtx.Lock()
  341. defer pool.mtx.Unlock()
  342. for _, peer := range pool.peers {
  343. if peer.didTimeout {
  344. pool.removePeer(peer.id)
  345. continue
  346. }
  347. if peer.numPending >= maxPendingRequestsPerPeer {
  348. continue
  349. }
  350. if height < peer.base || height > peer.height {
  351. continue
  352. }
  353. peer.incrPending()
  354. return peer
  355. }
  356. return nil
  357. }
  358. func (pool *BlockPool) makeNextRequester(ctx context.Context) {
  359. pool.mtx.Lock()
  360. defer pool.mtx.Unlock()
  361. nextHeight := pool.height + pool.requestersLen()
  362. if nextHeight > pool.maxPeerHeight {
  363. return
  364. }
  365. request := newBPRequester(pool.logger, pool, nextHeight)
  366. pool.requesters[nextHeight] = request
  367. atomic.AddInt32(&pool.numPending, 1)
  368. err := request.Start(ctx)
  369. if err != nil {
  370. request.logger.Error("error starting request", "err", err)
  371. }
  372. }
  373. func (pool *BlockPool) requestersLen() int64 {
  374. return int64(len(pool.requesters))
  375. }
  376. func (pool *BlockPool) sendRequest(height int64, peerID types.NodeID) {
  377. if !pool.IsRunning() {
  378. return
  379. }
  380. pool.requestsCh <- BlockRequest{height, peerID}
  381. }
  382. func (pool *BlockPool) sendError(err error, peerID types.NodeID) {
  383. if !pool.IsRunning() {
  384. return
  385. }
  386. pool.errorsCh <- peerError{err, peerID}
  387. }
  388. // for debugging purposes
  389. //nolint:unused
  390. func (pool *BlockPool) debug() string {
  391. pool.mtx.Lock()
  392. defer pool.mtx.Unlock()
  393. str := ""
  394. nextHeight := pool.height + pool.requestersLen()
  395. for h := pool.height; h < nextHeight; h++ {
  396. if pool.requesters[h] == nil {
  397. str += fmt.Sprintf("H(%v):X ", h)
  398. } else {
  399. str += fmt.Sprintf("H(%v):", h)
  400. str += fmt.Sprintf("B?(%v) ", pool.requesters[h].block != nil)
  401. }
  402. }
  403. return str
  404. }
  405. func (pool *BlockPool) targetSyncBlocks() int64 {
  406. pool.mtx.RLock()
  407. defer pool.mtx.RUnlock()
  408. return pool.maxPeerHeight - pool.startHeight + 1
  409. }
  410. func (pool *BlockPool) getLastSyncRate() float64 {
  411. pool.mtx.RLock()
  412. defer pool.mtx.RUnlock()
  413. return pool.lastSyncRate
  414. }
  415. //-------------------------------------
  416. type bpPeer struct {
  417. didTimeout bool
  418. numPending int32
  419. height int64
  420. base int64
  421. pool *BlockPool
  422. id types.NodeID
  423. recvMonitor *flowrate.Monitor
  424. timeout *time.Timer
  425. startAt time.Time
  426. logger log.Logger
  427. }
  428. func (peer *bpPeer) resetMonitor() {
  429. peer.recvMonitor = flowrate.New(peer.startAt, time.Second, time.Second*40)
  430. initialValue := float64(minRecvRate) * math.E
  431. peer.recvMonitor.SetREMA(initialValue)
  432. }
  433. func (peer *bpPeer) resetTimeout() {
  434. if peer.timeout == nil {
  435. peer.timeout = time.AfterFunc(peerTimeout, peer.onTimeout)
  436. } else {
  437. peer.timeout.Reset(peerTimeout)
  438. }
  439. }
  440. func (peer *bpPeer) incrPending() {
  441. if peer.numPending == 0 {
  442. peer.resetMonitor()
  443. peer.resetTimeout()
  444. }
  445. peer.numPending++
  446. }
  447. func (peer *bpPeer) decrPending(recvSize int) {
  448. peer.numPending--
  449. if peer.numPending == 0 {
  450. peer.timeout.Stop()
  451. } else {
  452. peer.recvMonitor.Update(recvSize)
  453. peer.resetTimeout()
  454. }
  455. }
  456. func (peer *bpPeer) onTimeout() {
  457. peer.pool.mtx.Lock()
  458. defer peer.pool.mtx.Unlock()
  459. err := errors.New("peer did not send us anything")
  460. peer.pool.sendError(err, peer.id)
  461. peer.logger.Error("SendTimeout", "reason", err, "timeout", peerTimeout)
  462. peer.didTimeout = true
  463. }
  464. //-------------------------------------
  465. type bpRequester struct {
  466. service.BaseService
  467. logger log.Logger
  468. pool *BlockPool
  469. height int64
  470. gotBlockCh chan struct{}
  471. redoCh chan types.NodeID // redo may send multitime, add peerId to identify repeat
  472. mtx sync.Mutex
  473. peerID types.NodeID
  474. block *types.Block
  475. }
  476. func newBPRequester(logger log.Logger, pool *BlockPool, height int64) *bpRequester {
  477. bpr := &bpRequester{
  478. logger: pool.logger,
  479. pool: pool,
  480. height: height,
  481. gotBlockCh: make(chan struct{}, 1),
  482. redoCh: make(chan types.NodeID, 1),
  483. peerID: "",
  484. block: nil,
  485. }
  486. bpr.BaseService = *service.NewBaseService(logger, "bpRequester", bpr)
  487. return bpr
  488. }
  489. func (bpr *bpRequester) OnStart(ctx context.Context) error {
  490. go bpr.requestRoutine(ctx)
  491. return nil
  492. }
  493. func (*bpRequester) OnStop() {}
  494. // Returns true if the peer matches and block doesn't already exist.
  495. func (bpr *bpRequester) setBlock(block *types.Block, peerID types.NodeID) bool {
  496. bpr.mtx.Lock()
  497. if bpr.block != nil || bpr.peerID != peerID {
  498. bpr.mtx.Unlock()
  499. return false
  500. }
  501. bpr.block = block
  502. bpr.mtx.Unlock()
  503. select {
  504. case bpr.gotBlockCh <- struct{}{}:
  505. default:
  506. }
  507. return true
  508. }
  509. func (bpr *bpRequester) getBlock() *types.Block {
  510. bpr.mtx.Lock()
  511. defer bpr.mtx.Unlock()
  512. return bpr.block
  513. }
  514. func (bpr *bpRequester) getPeerID() types.NodeID {
  515. bpr.mtx.Lock()
  516. defer bpr.mtx.Unlock()
  517. return bpr.peerID
  518. }
  519. // This is called from the requestRoutine, upon redo().
  520. func (bpr *bpRequester) reset() {
  521. bpr.mtx.Lock()
  522. defer bpr.mtx.Unlock()
  523. if bpr.block != nil {
  524. atomic.AddInt32(&bpr.pool.numPending, 1)
  525. }
  526. bpr.peerID = ""
  527. bpr.block = nil
  528. }
  529. // Tells bpRequester to pick another peer and try again.
  530. // NOTE: Nonblocking, and does nothing if another redo
  531. // was already requested.
  532. func (bpr *bpRequester) redo(peerID types.NodeID) {
  533. select {
  534. case bpr.redoCh <- peerID:
  535. default:
  536. }
  537. }
  538. // Responsible for making more requests as necessary
  539. // Returns only when a block is found (e.g. AddBlock() is called)
  540. func (bpr *bpRequester) requestRoutine(ctx context.Context) {
  541. bprPoolDone := make(chan struct{})
  542. go func() {
  543. defer close(bprPoolDone)
  544. bpr.pool.Wait()
  545. }()
  546. OUTER_LOOP:
  547. for {
  548. // Pick a peer to send request to.
  549. var peer *bpPeer
  550. PICK_PEER_LOOP:
  551. for {
  552. if !bpr.IsRunning() || !bpr.pool.IsRunning() {
  553. return
  554. }
  555. peer = bpr.pool.pickIncrAvailablePeer(bpr.height)
  556. if peer == nil {
  557. time.Sleep(requestIntervalMS * time.Millisecond)
  558. continue PICK_PEER_LOOP
  559. }
  560. break PICK_PEER_LOOP
  561. }
  562. bpr.mtx.Lock()
  563. bpr.peerID = peer.id
  564. bpr.mtx.Unlock()
  565. // Send request and wait.
  566. bpr.pool.sendRequest(bpr.height, peer.id)
  567. WAIT_LOOP:
  568. for {
  569. select {
  570. case <-ctx.Done():
  571. return
  572. case <-bpr.pool.exitedCh:
  573. bpr.Stop()
  574. return
  575. case peerID := <-bpr.redoCh:
  576. if peerID == bpr.peerID {
  577. bpr.reset()
  578. continue OUTER_LOOP
  579. } else {
  580. continue WAIT_LOOP
  581. }
  582. case <-bpr.gotBlockCh:
  583. // We got a block!
  584. // Continue the for-loop and wait til Quit.
  585. continue WAIT_LOOP
  586. }
  587. }
  588. }
  589. }