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.

647 lines
16 KiB

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