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.

697 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
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
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
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/atomic"
  8. "time"
  9. "github.com/tendermint/tendermint/internal/libs/flowrate"
  10. tmsync "github.com/tendermint/tendermint/internal/libs/sync"
  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. lastAdvance time.Time
  61. mtx tmsync.RWMutex
  62. // block requests
  63. requesters map[int64]*bpRequester
  64. height int64 // the lowest key in requesters.
  65. // peers
  66. peers map[types.NodeID]*bpPeer
  67. maxPeerHeight int64 // the biggest reported height
  68. // atomic
  69. numPending int32 // number of requests pending assignment or block response
  70. requestsCh chan<- BlockRequest
  71. errorsCh chan<- peerError
  72. exitedCh chan struct{}
  73. startHeight int64
  74. lastHundredBlockTimeStamp time.Time
  75. lastSyncRate float64
  76. }
  77. // NewBlockPool returns a new BlockPool with the height equal to start. Block
  78. // requests and errors will be sent to requestsCh and errorsCh accordingly.
  79. func NewBlockPool(
  80. logger log.Logger,
  81. start int64,
  82. requestsCh chan<- BlockRequest,
  83. errorsCh chan<- peerError,
  84. ) *BlockPool {
  85. bp := &BlockPool{
  86. peers: make(map[types.NodeID]*bpPeer),
  87. requesters: make(map[int64]*bpRequester),
  88. height: start,
  89. startHeight: start,
  90. numPending: 0,
  91. exitedCh: make(chan struct{}),
  92. requestsCh: requestsCh,
  93. errorsCh: errorsCh,
  94. lastSyncRate: 0,
  95. }
  96. bp.BaseService = *service.NewBaseService(logger, "BlockPool", bp)
  97. return bp
  98. }
  99. // OnStart implements service.Service by spawning requesters routine and recording
  100. // pool's start time.
  101. func (pool *BlockPool) OnStart(ctx context.Context) error {
  102. pool.lastAdvance = time.Now()
  103. pool.lastHundredBlockTimeStamp = pool.lastAdvance
  104. go pool.makeRequestersRoutine(ctx)
  105. go func() {
  106. defer close(pool.exitedCh)
  107. pool.Wait()
  108. }()
  109. return nil
  110. }
  111. func (*BlockPool) OnStop() {}
  112. // spawns requesters as needed
  113. func (pool *BlockPool) makeRequestersRoutine(ctx context.Context) {
  114. for {
  115. if !pool.IsRunning() {
  116. break
  117. }
  118. _, numPending, lenRequesters := pool.GetStatus()
  119. switch {
  120. case numPending >= maxPendingRequests:
  121. // sleep for a bit.
  122. time.Sleep(requestIntervalMS * time.Millisecond)
  123. // check for timed out peers
  124. pool.removeTimedoutPeers()
  125. case lenRequesters >= maxTotalRequesters:
  126. // sleep for a bit.
  127. time.Sleep(requestIntervalMS * time.Millisecond)
  128. // check for timed out peers
  129. pool.removeTimedoutPeers()
  130. default:
  131. // request for more blocks.
  132. pool.makeNextRequester(ctx)
  133. }
  134. }
  135. }
  136. func (pool *BlockPool) removeTimedoutPeers() {
  137. pool.mtx.Lock()
  138. defer pool.mtx.Unlock()
  139. for _, peer := range pool.peers {
  140. // check if peer timed out
  141. if !peer.didTimeout && peer.numPending > 0 {
  142. curRate := peer.recvMonitor.Status().CurRate
  143. // curRate can be 0 on start
  144. if curRate != 0 && curRate < minRecvRate {
  145. err := errors.New("peer is not sending us data fast enough")
  146. pool.sendError(err, peer.id)
  147. pool.Logger.Error("SendTimeout", "peer", peer.id,
  148. "reason", err,
  149. "curRate", fmt.Sprintf("%d KB/s", curRate/1024),
  150. "minRate", fmt.Sprintf("%d KB/s", minRecvRate/1024))
  151. peer.didTimeout = true
  152. }
  153. }
  154. if peer.didTimeout {
  155. pool.removePeer(peer.id)
  156. }
  157. }
  158. }
  159. // GetStatus returns pool's height, numPending requests and the number of
  160. // requesters.
  161. func (pool *BlockPool) GetStatus() (height int64, numPending int32, lenRequesters int) {
  162. pool.mtx.RLock()
  163. defer pool.mtx.RUnlock()
  164. return pool.height, atomic.LoadInt32(&pool.numPending), len(pool.requesters)
  165. }
  166. // IsCaughtUp returns true if this node is caught up, false - otherwise.
  167. func (pool *BlockPool) IsCaughtUp() bool {
  168. pool.mtx.RLock()
  169. defer pool.mtx.RUnlock()
  170. // Need at least 1 peer to be considered caught up.
  171. if len(pool.peers) == 0 {
  172. return false
  173. }
  174. // NOTE: we use maxPeerHeight - 1 because to sync block H requires block H+1
  175. // to verify the LastCommit.
  176. return pool.height >= (pool.maxPeerHeight - 1)
  177. }
  178. // PeekTwoBlocks returns blocks at pool.height and pool.height+1.
  179. // We need to see the second block's Commit to validate the first block.
  180. // So we peek two blocks at a time.
  181. // The caller will verify the commit.
  182. func (pool *BlockPool) PeekTwoBlocks() (first *types.Block, second *types.Block) {
  183. pool.mtx.RLock()
  184. defer pool.mtx.RUnlock()
  185. if r := pool.requesters[pool.height]; r != nil {
  186. first = r.getBlock()
  187. }
  188. if r := pool.requesters[pool.height+1]; r != nil {
  189. second = r.getBlock()
  190. }
  191. return
  192. }
  193. // PopRequest pops the first block at pool.height.
  194. // It must have been validated by 'second'.Commit from PeekTwoBlocks().
  195. func (pool *BlockPool) PopRequest() {
  196. pool.mtx.Lock()
  197. defer pool.mtx.Unlock()
  198. if r := pool.requesters[pool.height]; r != nil {
  199. if err := r.Stop(); err != nil {
  200. pool.Logger.Error("Error stopping requester", "err", err)
  201. }
  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.setLogger(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, 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) setLogger(l log.Logger) {
  432. peer.logger = l
  433. }
  434. func (peer *bpPeer) resetMonitor() {
  435. peer.recvMonitor = flowrate.New(time.Second, time.Second*40)
  436. initialValue := float64(minRecvRate) * math.E
  437. peer.recvMonitor.SetREMA(initialValue)
  438. }
  439. func (peer *bpPeer) resetTimeout() {
  440. if peer.timeout == nil {
  441. peer.timeout = time.AfterFunc(peerTimeout, peer.onTimeout)
  442. } else {
  443. peer.timeout.Reset(peerTimeout)
  444. }
  445. }
  446. func (peer *bpPeer) incrPending() {
  447. if peer.numPending == 0 {
  448. peer.resetMonitor()
  449. peer.resetTimeout()
  450. }
  451. peer.numPending++
  452. }
  453. func (peer *bpPeer) decrPending(recvSize int) {
  454. peer.numPending--
  455. if peer.numPending == 0 {
  456. peer.timeout.Stop()
  457. } else {
  458. peer.recvMonitor.Update(recvSize)
  459. peer.resetTimeout()
  460. }
  461. }
  462. func (peer *bpPeer) onTimeout() {
  463. peer.pool.mtx.Lock()
  464. defer peer.pool.mtx.Unlock()
  465. err := errors.New("peer did not send us anything")
  466. peer.pool.sendError(err, peer.id)
  467. peer.logger.Error("SendTimeout", "reason", err, "timeout", peerTimeout)
  468. peer.didTimeout = true
  469. }
  470. //-------------------------------------
  471. type bpRequester struct {
  472. service.BaseService
  473. pool *BlockPool
  474. height int64
  475. gotBlockCh chan struct{}
  476. redoCh chan types.NodeID // redo may send multitime, add peerId to identify repeat
  477. mtx tmsync.Mutex
  478. peerID types.NodeID
  479. block *types.Block
  480. }
  481. func newBPRequester(pool *BlockPool, height int64) *bpRequester {
  482. bpr := &bpRequester{
  483. pool: pool,
  484. height: height,
  485. gotBlockCh: make(chan struct{}, 1),
  486. redoCh: make(chan types.NodeID, 1),
  487. peerID: "",
  488. block: nil,
  489. }
  490. bpr.BaseService = *service.NewBaseService(nil, "bpRequester", bpr)
  491. return bpr
  492. }
  493. func (bpr *bpRequester) OnStart(ctx context.Context) error {
  494. go bpr.requestRoutine(ctx)
  495. return nil
  496. }
  497. func (*bpRequester) OnStop() {}
  498. // Returns true if the peer matches and block doesn't already exist.
  499. func (bpr *bpRequester) setBlock(block *types.Block, peerID types.NodeID) bool {
  500. bpr.mtx.Lock()
  501. if bpr.block != nil || bpr.peerID != peerID {
  502. bpr.mtx.Unlock()
  503. return false
  504. }
  505. bpr.block = block
  506. bpr.mtx.Unlock()
  507. select {
  508. case bpr.gotBlockCh <- struct{}{}:
  509. default:
  510. }
  511. return true
  512. }
  513. func (bpr *bpRequester) getBlock() *types.Block {
  514. bpr.mtx.Lock()
  515. defer bpr.mtx.Unlock()
  516. return bpr.block
  517. }
  518. func (bpr *bpRequester) getPeerID() types.NodeID {
  519. bpr.mtx.Lock()
  520. defer bpr.mtx.Unlock()
  521. return bpr.peerID
  522. }
  523. // This is called from the requestRoutine, upon redo().
  524. func (bpr *bpRequester) reset() {
  525. bpr.mtx.Lock()
  526. defer bpr.mtx.Unlock()
  527. if bpr.block != nil {
  528. atomic.AddInt32(&bpr.pool.numPending, 1)
  529. }
  530. bpr.peerID = ""
  531. bpr.block = nil
  532. }
  533. // Tells bpRequester to pick another peer and try again.
  534. // NOTE: Nonblocking, and does nothing if another redo
  535. // was already requested.
  536. func (bpr *bpRequester) redo(peerID types.NodeID) {
  537. select {
  538. case bpr.redoCh <- peerID:
  539. default:
  540. }
  541. }
  542. // Responsible for making more requests as necessary
  543. // Returns only when a block is found (e.g. AddBlock() is called)
  544. func (bpr *bpRequester) requestRoutine(ctx context.Context) {
  545. bprPoolDone := make(chan struct{})
  546. go func() {
  547. defer close(bprPoolDone)
  548. bpr.pool.Wait()
  549. }()
  550. OUTER_LOOP:
  551. for {
  552. // Pick a peer to send request to.
  553. var peer *bpPeer
  554. PICK_PEER_LOOP:
  555. for {
  556. if !bpr.IsRunning() || !bpr.pool.IsRunning() {
  557. return
  558. }
  559. peer = bpr.pool.pickIncrAvailablePeer(bpr.height)
  560. if peer == nil {
  561. time.Sleep(requestIntervalMS * time.Millisecond)
  562. continue PICK_PEER_LOOP
  563. }
  564. break PICK_PEER_LOOP
  565. }
  566. bpr.mtx.Lock()
  567. bpr.peerID = peer.id
  568. bpr.mtx.Unlock()
  569. // Send request and wait.
  570. bpr.pool.sendRequest(bpr.height, peer.id)
  571. WAIT_LOOP:
  572. for {
  573. select {
  574. case <-ctx.Done():
  575. return
  576. case <-bpr.pool.exitedCh:
  577. if err := bpr.Stop(); err != nil {
  578. bpr.Logger.Error("Error stopped requester", "err", err)
  579. }
  580. return
  581. case peerID := <-bpr.redoCh:
  582. if peerID == bpr.peerID {
  583. bpr.reset()
  584. continue OUTER_LOOP
  585. } else {
  586. continue WAIT_LOOP
  587. }
  588. case <-bpr.gotBlockCh:
  589. // We got a block!
  590. // Continue the for-loop and wait til Quit.
  591. continue WAIT_LOOP
  592. }
  593. }
  594. }
  595. }