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.

680 lines
17 KiB

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