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.

673 lines
17 KiB

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