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.

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