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.

693 lines
17 KiB

7 years ago
9 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>
4 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
4 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
4 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
4 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
4 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
4 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
4 years ago
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>
4 years ago
7 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 = newBPPeer(pool, peerID, base, height)
  287. peer.logger = pool.logger.With("peer", peerID)
  288. pool.peers[peerID] = peer
  289. }
  290. if height > pool.maxPeerHeight {
  291. pool.maxPeerHeight = height
  292. }
  293. }
  294. // RemovePeer removes the peer with peerID from the pool. If there's no peer
  295. // with peerID, function is a no-op.
  296. func (pool *BlockPool) RemovePeer(peerID types.NodeID) {
  297. pool.mtx.Lock()
  298. defer pool.mtx.Unlock()
  299. pool.removePeer(peerID)
  300. }
  301. func (pool *BlockPool) removePeer(peerID types.NodeID) {
  302. for _, requester := range pool.requesters {
  303. if requester.getPeerID() == peerID {
  304. requester.redo(peerID)
  305. }
  306. }
  307. peer, ok := pool.peers[peerID]
  308. if ok {
  309. if peer.timeout != nil {
  310. peer.timeout.Stop()
  311. }
  312. delete(pool.peers, peerID)
  313. // Find a new peer with the biggest height and update maxPeerHeight if the
  314. // peer's height was the biggest.
  315. if peer.height == pool.maxPeerHeight {
  316. pool.updateMaxPeerHeight()
  317. }
  318. }
  319. }
  320. // If no peers are left, maxPeerHeight is set to 0.
  321. func (pool *BlockPool) updateMaxPeerHeight() {
  322. var max int64
  323. for _, peer := range pool.peers {
  324. if peer.height > max {
  325. max = peer.height
  326. }
  327. }
  328. pool.maxPeerHeight = max
  329. }
  330. // Pick an available peer with the given height available.
  331. // If no peers are available, returns nil.
  332. func (pool *BlockPool) pickIncrAvailablePeer(height int64) *bpPeer {
  333. pool.mtx.Lock()
  334. defer pool.mtx.Unlock()
  335. for _, peer := range pool.peers {
  336. if peer.didTimeout {
  337. pool.removePeer(peer.id)
  338. continue
  339. }
  340. if peer.numPending >= maxPendingRequestsPerPeer {
  341. continue
  342. }
  343. if height < peer.base || height > peer.height {
  344. continue
  345. }
  346. peer.incrPending()
  347. return peer
  348. }
  349. return nil
  350. }
  351. func (pool *BlockPool) makeNextRequester(ctx context.Context) {
  352. pool.mtx.Lock()
  353. defer pool.mtx.Unlock()
  354. nextHeight := pool.height + pool.requestersLen()
  355. if nextHeight > pool.maxPeerHeight {
  356. return
  357. }
  358. request := newBPRequester(pool.logger, pool, nextHeight)
  359. pool.requesters[nextHeight] = request
  360. atomic.AddInt32(&pool.numPending, 1)
  361. err := request.Start(ctx)
  362. if err != nil {
  363. request.logger.Error("error starting request", "err", err)
  364. }
  365. }
  366. func (pool *BlockPool) requestersLen() int64 {
  367. return int64(len(pool.requesters))
  368. }
  369. func (pool *BlockPool) sendRequest(height int64, peerID types.NodeID) {
  370. if !pool.IsRunning() {
  371. return
  372. }
  373. pool.requestsCh <- BlockRequest{height, peerID}
  374. }
  375. func (pool *BlockPool) sendError(err error, peerID types.NodeID) {
  376. if !pool.IsRunning() {
  377. return
  378. }
  379. pool.errorsCh <- peerError{err, peerID}
  380. }
  381. // for debugging purposes
  382. //nolint:unused
  383. func (pool *BlockPool) debug() string {
  384. pool.mtx.Lock()
  385. defer pool.mtx.Unlock()
  386. str := ""
  387. nextHeight := pool.height + pool.requestersLen()
  388. for h := pool.height; h < nextHeight; h++ {
  389. if pool.requesters[h] == nil {
  390. str += fmt.Sprintf("H(%v):X ", h)
  391. } else {
  392. str += fmt.Sprintf("H(%v):", h)
  393. str += fmt.Sprintf("B?(%v) ", pool.requesters[h].block != nil)
  394. }
  395. }
  396. return str
  397. }
  398. func (pool *BlockPool) targetSyncBlocks() int64 {
  399. pool.mtx.RLock()
  400. defer pool.mtx.RUnlock()
  401. return pool.maxPeerHeight - pool.startHeight + 1
  402. }
  403. func (pool *BlockPool) getLastSyncRate() float64 {
  404. pool.mtx.RLock()
  405. defer pool.mtx.RUnlock()
  406. return pool.lastSyncRate
  407. }
  408. //-------------------------------------
  409. type bpPeer struct {
  410. didTimeout bool
  411. numPending int32
  412. height int64
  413. base int64
  414. pool *BlockPool
  415. id types.NodeID
  416. recvMonitor *flowrate.Monitor
  417. timeout *time.Timer
  418. logger log.Logger
  419. }
  420. func newBPPeer(pool *BlockPool, peerID types.NodeID, base int64, height int64) *bpPeer {
  421. peer := &bpPeer{
  422. pool: pool,
  423. id: peerID,
  424. base: base,
  425. height: height,
  426. numPending: 0,
  427. logger: log.NewNopLogger(),
  428. }
  429. return peer
  430. }
  431. func (peer *bpPeer) resetMonitor() {
  432. peer.recvMonitor = flowrate.New(time.Second, time.Second*40)
  433. initialValue := float64(minRecvRate) * math.E
  434. peer.recvMonitor.SetREMA(initialValue)
  435. }
  436. func (peer *bpPeer) resetTimeout() {
  437. if peer.timeout == nil {
  438. peer.timeout = time.AfterFunc(peerTimeout, peer.onTimeout)
  439. } else {
  440. peer.timeout.Reset(peerTimeout)
  441. }
  442. }
  443. func (peer *bpPeer) incrPending() {
  444. if peer.numPending == 0 {
  445. peer.resetMonitor()
  446. peer.resetTimeout()
  447. }
  448. peer.numPending++
  449. }
  450. func (peer *bpPeer) decrPending(recvSize int) {
  451. peer.numPending--
  452. if peer.numPending == 0 {
  453. peer.timeout.Stop()
  454. } else {
  455. peer.recvMonitor.Update(recvSize)
  456. peer.resetTimeout()
  457. }
  458. }
  459. func (peer *bpPeer) onTimeout() {
  460. peer.pool.mtx.Lock()
  461. defer peer.pool.mtx.Unlock()
  462. err := errors.New("peer did not send us anything")
  463. peer.pool.sendError(err, peer.id)
  464. peer.logger.Error("SendTimeout", "reason", err, "timeout", peerTimeout)
  465. peer.didTimeout = true
  466. }
  467. //-------------------------------------
  468. type bpRequester struct {
  469. service.BaseService
  470. logger log.Logger
  471. pool *BlockPool
  472. height int64
  473. gotBlockCh chan struct{}
  474. redoCh chan types.NodeID // redo may send multitime, add peerId to identify repeat
  475. mtx sync.Mutex
  476. peerID types.NodeID
  477. block *types.Block
  478. }
  479. func newBPRequester(logger log.Logger, pool *BlockPool, height int64) *bpRequester {
  480. bpr := &bpRequester{
  481. logger: pool.logger,
  482. pool: pool,
  483. height: height,
  484. gotBlockCh: make(chan struct{}, 1),
  485. redoCh: make(chan types.NodeID, 1),
  486. peerID: "",
  487. block: nil,
  488. }
  489. bpr.BaseService = *service.NewBaseService(logger, "bpRequester", bpr)
  490. return bpr
  491. }
  492. func (bpr *bpRequester) OnStart(ctx context.Context) error {
  493. go bpr.requestRoutine(ctx)
  494. return nil
  495. }
  496. func (*bpRequester) OnStop() {}
  497. // Returns true if the peer matches and block doesn't already exist.
  498. func (bpr *bpRequester) setBlock(block *types.Block, peerID types.NodeID) bool {
  499. bpr.mtx.Lock()
  500. if bpr.block != nil || bpr.peerID != peerID {
  501. bpr.mtx.Unlock()
  502. return false
  503. }
  504. bpr.block = block
  505. bpr.mtx.Unlock()
  506. select {
  507. case bpr.gotBlockCh <- struct{}{}:
  508. default:
  509. }
  510. return true
  511. }
  512. func (bpr *bpRequester) getBlock() *types.Block {
  513. bpr.mtx.Lock()
  514. defer bpr.mtx.Unlock()
  515. return bpr.block
  516. }
  517. func (bpr *bpRequester) getPeerID() types.NodeID {
  518. bpr.mtx.Lock()
  519. defer bpr.mtx.Unlock()
  520. return bpr.peerID
  521. }
  522. // This is called from the requestRoutine, upon redo().
  523. func (bpr *bpRequester) reset() {
  524. bpr.mtx.Lock()
  525. defer bpr.mtx.Unlock()
  526. if bpr.block != nil {
  527. atomic.AddInt32(&bpr.pool.numPending, 1)
  528. }
  529. bpr.peerID = ""
  530. bpr.block = nil
  531. }
  532. // Tells bpRequester to pick another peer and try again.
  533. // NOTE: Nonblocking, and does nothing if another redo
  534. // was already requested.
  535. func (bpr *bpRequester) redo(peerID types.NodeID) {
  536. select {
  537. case bpr.redoCh <- peerID:
  538. default:
  539. }
  540. }
  541. // Responsible for making more requests as necessary
  542. // Returns only when a block is found (e.g. AddBlock() is called)
  543. func (bpr *bpRequester) requestRoutine(ctx context.Context) {
  544. bprPoolDone := make(chan struct{})
  545. go func() {
  546. defer close(bprPoolDone)
  547. bpr.pool.Wait()
  548. }()
  549. OUTER_LOOP:
  550. for {
  551. // Pick a peer to send request to.
  552. var peer *bpPeer
  553. PICK_PEER_LOOP:
  554. for {
  555. if !bpr.IsRunning() || !bpr.pool.IsRunning() {
  556. return
  557. }
  558. peer = bpr.pool.pickIncrAvailablePeer(bpr.height)
  559. if peer == nil {
  560. time.Sleep(requestIntervalMS * time.Millisecond)
  561. continue PICK_PEER_LOOP
  562. }
  563. break PICK_PEER_LOOP
  564. }
  565. bpr.mtx.Lock()
  566. bpr.peerID = peer.id
  567. bpr.mtx.Unlock()
  568. // Send request and wait.
  569. bpr.pool.sendRequest(bpr.height, peer.id)
  570. WAIT_LOOP:
  571. for {
  572. select {
  573. case <-ctx.Done():
  574. return
  575. case <-bpr.pool.exitedCh:
  576. bpr.Stop()
  577. return
  578. case peerID := <-bpr.redoCh:
  579. if peerID == bpr.peerID {
  580. bpr.reset()
  581. continue OUTER_LOOP
  582. } else {
  583. continue WAIT_LOOP
  584. }
  585. case <-bpr.gotBlockCh:
  586. // We got a block!
  587. // Continue the for-loop and wait til Quit.
  588. continue WAIT_LOOP
  589. }
  590. }
  591. }
  592. }