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.

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