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.

501 lines
15 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
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
8 years ago
7 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
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
7 years ago
7 years ago
8 years ago
10 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
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
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
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
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
  1. package v0
  2. import (
  3. "errors"
  4. "fmt"
  5. "reflect"
  6. "time"
  7. amino "github.com/tendermint/go-amino"
  8. "github.com/tendermint/tendermint/libs/log"
  9. "github.com/tendermint/tendermint/p2p"
  10. sm "github.com/tendermint/tendermint/state"
  11. "github.com/tendermint/tendermint/store"
  12. "github.com/tendermint/tendermint/types"
  13. )
  14. const (
  15. // BlockchainChannel is a channel for blocks and status updates (`BlockStore` height)
  16. BlockchainChannel = byte(0x40)
  17. trySyncIntervalMS = 10
  18. // stop syncing when last block's time is
  19. // within this much of the system time.
  20. // stopSyncingDurationMinutes = 10
  21. // ask for best height every 10s
  22. statusUpdateIntervalSeconds = 10
  23. // check if we should switch to consensus reactor
  24. switchToConsensusIntervalSeconds = 1
  25. // NOTE: keep up to date with bcBlockResponseMessage
  26. bcBlockResponseMessagePrefixSize = 4
  27. bcBlockResponseMessageFieldKeySize = 1
  28. maxMsgSize = types.MaxBlockSizeBytes +
  29. bcBlockResponseMessagePrefixSize +
  30. bcBlockResponseMessageFieldKeySize
  31. )
  32. type consensusReactor interface {
  33. // for when we switch from blockchain reactor and fast sync to
  34. // the consensus machine
  35. SwitchToConsensus(sm.State, uint64)
  36. }
  37. type peerError struct {
  38. err error
  39. peerID p2p.ID
  40. }
  41. func (e peerError) Error() string {
  42. return fmt.Sprintf("error with peer %v: %s", e.peerID, e.err.Error())
  43. }
  44. // BlockchainReactor handles long-term catchup syncing.
  45. type BlockchainReactor struct {
  46. p2p.BaseReactor
  47. // immutable
  48. initialState sm.State
  49. blockExec *sm.BlockExecutor
  50. store *store.BlockStore
  51. pool *BlockPool
  52. fastSync bool
  53. requestsCh <-chan BlockRequest
  54. errorsCh <-chan peerError
  55. }
  56. // NewBlockchainReactor returns new reactor instance.
  57. func NewBlockchainReactor(state sm.State, blockExec *sm.BlockExecutor, store *store.BlockStore,
  58. fastSync bool) *BlockchainReactor {
  59. if state.LastBlockHeight != store.Height() {
  60. panic(fmt.Sprintf("state (%v) and store (%v) height mismatch", state.LastBlockHeight,
  61. store.Height()))
  62. }
  63. requestsCh := make(chan BlockRequest, maxTotalRequesters)
  64. const capacity = 1000 // must be bigger than peers count
  65. errorsCh := make(chan peerError, capacity) // so we don't block in #Receive#pool.AddBlock
  66. pool := NewBlockPool(
  67. store.Height()+1,
  68. requestsCh,
  69. errorsCh,
  70. )
  71. bcR := &BlockchainReactor{
  72. initialState: state,
  73. blockExec: blockExec,
  74. store: store,
  75. pool: pool,
  76. fastSync: fastSync,
  77. requestsCh: requestsCh,
  78. errorsCh: errorsCh,
  79. }
  80. bcR.BaseReactor = *p2p.NewBaseReactor("BlockchainReactor", bcR)
  81. return bcR
  82. }
  83. // SetLogger implements service.Service by setting the logger on reactor and pool.
  84. func (bcR *BlockchainReactor) SetLogger(l log.Logger) {
  85. bcR.BaseService.Logger = l
  86. bcR.pool.Logger = l
  87. }
  88. // OnStart implements service.Service.
  89. func (bcR *BlockchainReactor) OnStart() error {
  90. if bcR.fastSync {
  91. err := bcR.pool.Start()
  92. if err != nil {
  93. return err
  94. }
  95. go bcR.poolRoutine()
  96. }
  97. return nil
  98. }
  99. // OnStop implements service.Service.
  100. func (bcR *BlockchainReactor) OnStop() {
  101. bcR.pool.Stop()
  102. }
  103. // GetChannels implements Reactor
  104. func (bcR *BlockchainReactor) GetChannels() []*p2p.ChannelDescriptor {
  105. return []*p2p.ChannelDescriptor{
  106. {
  107. ID: BlockchainChannel,
  108. Priority: 10,
  109. SendQueueCapacity: 1000,
  110. RecvBufferCapacity: 50 * 4096,
  111. RecvMessageCapacity: maxMsgSize,
  112. },
  113. }
  114. }
  115. // AddPeer implements Reactor by sending our state to peer.
  116. func (bcR *BlockchainReactor) AddPeer(peer p2p.Peer) {
  117. msgBytes := cdc.MustMarshalBinaryBare(&bcStatusResponseMessage{
  118. Height: bcR.store.Height(),
  119. Base: bcR.store.Base(),
  120. })
  121. peer.Send(BlockchainChannel, msgBytes)
  122. // it's OK if send fails. will try later in poolRoutine
  123. // peer is added to the pool once we receive the first
  124. // bcStatusResponseMessage from the peer and call pool.SetPeerRange
  125. }
  126. // RemovePeer implements Reactor by removing peer from the pool.
  127. func (bcR *BlockchainReactor) RemovePeer(peer p2p.Peer, reason interface{}) {
  128. bcR.pool.RemovePeer(peer.ID())
  129. }
  130. // respondToPeer loads a block and sends it to the requesting peer,
  131. // if we have it. Otherwise, we'll respond saying we don't have it.
  132. func (bcR *BlockchainReactor) respondToPeer(msg *bcBlockRequestMessage,
  133. src p2p.Peer) (queued bool) {
  134. block := bcR.store.LoadBlock(msg.Height)
  135. if block != nil {
  136. msgBytes := cdc.MustMarshalBinaryBare(&bcBlockResponseMessage{Block: block})
  137. return src.TrySend(BlockchainChannel, msgBytes)
  138. }
  139. bcR.Logger.Info("Peer asking for a block we don't have", "src", src, "height", msg.Height)
  140. msgBytes := cdc.MustMarshalBinaryBare(&bcNoBlockResponseMessage{Height: msg.Height})
  141. return src.TrySend(BlockchainChannel, msgBytes)
  142. }
  143. // Receive implements Reactor by handling 4 types of messages (look below).
  144. func (bcR *BlockchainReactor) Receive(chID byte, src p2p.Peer, msgBytes []byte) {
  145. msg, err := decodeMsg(msgBytes)
  146. if err != nil {
  147. bcR.Logger.Error("Error decoding message", "src", src, "chId", chID, "msg", msg, "err", err, "bytes", msgBytes)
  148. bcR.Switch.StopPeerForError(src, err)
  149. return
  150. }
  151. if err = msg.ValidateBasic(); err != nil {
  152. bcR.Logger.Error("Peer sent us invalid msg", "peer", src, "msg", msg, "err", err)
  153. bcR.Switch.StopPeerForError(src, err)
  154. return
  155. }
  156. bcR.Logger.Debug("Receive", "src", src, "chID", chID, "msg", msg)
  157. switch msg := msg.(type) {
  158. case *bcBlockRequestMessage:
  159. bcR.respondToPeer(msg, src)
  160. case *bcBlockResponseMessage:
  161. bcR.pool.AddBlock(src.ID(), msg.Block, len(msgBytes))
  162. case *bcStatusRequestMessage:
  163. // Send peer our state.
  164. src.TrySend(BlockchainChannel, cdc.MustMarshalBinaryBare(&bcStatusResponseMessage{
  165. Height: bcR.store.Height(),
  166. Base: bcR.store.Base(),
  167. }))
  168. case *bcStatusResponseMessage:
  169. // Got a peer status. Unverified.
  170. bcR.pool.SetPeerRange(src.ID(), msg.Base, msg.Height)
  171. case *bcNoBlockResponseMessage:
  172. bcR.Logger.Debug("Peer does not have requested block", "peer", src, "height", msg.Height)
  173. default:
  174. bcR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg)))
  175. }
  176. }
  177. // Handle messages from the poolReactor telling the reactor what to do.
  178. // NOTE: Don't sleep in the FOR_LOOP or otherwise slow it down!
  179. func (bcR *BlockchainReactor) poolRoutine() {
  180. trySyncTicker := time.NewTicker(trySyncIntervalMS * time.Millisecond)
  181. statusUpdateTicker := time.NewTicker(statusUpdateIntervalSeconds * time.Second)
  182. switchToConsensusTicker := time.NewTicker(switchToConsensusIntervalSeconds * time.Second)
  183. blocksSynced := uint64(0)
  184. chainID := bcR.initialState.ChainID
  185. state := bcR.initialState
  186. lastHundred := time.Now()
  187. lastRate := 0.0
  188. didProcessCh := make(chan struct{}, 1)
  189. go func() {
  190. for {
  191. select {
  192. case <-bcR.Quit():
  193. return
  194. case <-bcR.pool.Quit():
  195. return
  196. case request := <-bcR.requestsCh:
  197. peer := bcR.Switch.Peers().Get(request.PeerID)
  198. if peer == nil {
  199. continue
  200. }
  201. msgBytes := cdc.MustMarshalBinaryBare(&bcBlockRequestMessage{request.Height})
  202. queued := peer.TrySend(BlockchainChannel, msgBytes)
  203. if !queued {
  204. bcR.Logger.Debug("Send queue is full, drop block request", "peer", peer.ID(), "height", request.Height)
  205. }
  206. case err := <-bcR.errorsCh:
  207. peer := bcR.Switch.Peers().Get(err.peerID)
  208. if peer != nil {
  209. bcR.Switch.StopPeerForError(peer, err)
  210. }
  211. case <-statusUpdateTicker.C:
  212. // ask for status updates
  213. go bcR.BroadcastStatusRequest() // nolint: errcheck
  214. }
  215. }
  216. }()
  217. FOR_LOOP:
  218. for {
  219. select {
  220. case <-switchToConsensusTicker.C:
  221. height, numPending, lenRequesters := bcR.pool.GetStatus()
  222. outbound, inbound, _ := bcR.Switch.NumPeers()
  223. bcR.Logger.Debug("Consensus ticker", "numPending", numPending, "total", lenRequesters,
  224. "outbound", outbound, "inbound", inbound)
  225. if bcR.pool.IsCaughtUp() {
  226. bcR.Logger.Info("Time to switch to consensus reactor!", "height", height)
  227. bcR.pool.Stop()
  228. conR, ok := bcR.Switch.Reactor("CONSENSUS").(consensusReactor)
  229. if ok {
  230. conR.SwitchToConsensus(state, blocksSynced)
  231. }
  232. // else {
  233. // should only happen during testing
  234. // }
  235. break FOR_LOOP
  236. }
  237. case <-trySyncTicker.C: // chan time
  238. select {
  239. case didProcessCh <- struct{}{}:
  240. default:
  241. }
  242. case <-didProcessCh:
  243. // NOTE: It is a subtle mistake to process more than a single block
  244. // at a time (e.g. 10) here, because we only TrySend 1 request per
  245. // loop. The ratio mismatch can result in starving of blocks, a
  246. // sudden burst of requests and responses, and repeat.
  247. // Consequently, it is better to split these routines rather than
  248. // coupling them as it's written here. TODO uncouple from request
  249. // routine.
  250. // See if there are any blocks to sync.
  251. first, second := bcR.pool.PeekTwoBlocks()
  252. //bcR.Logger.Info("TrySync peeked", "first", first, "second", second)
  253. if first == nil || second == nil {
  254. // We need both to sync the first block.
  255. continue FOR_LOOP
  256. } else {
  257. // Try again quickly next loop.
  258. didProcessCh <- struct{}{}
  259. }
  260. firstParts := first.MakePartSet(types.BlockPartSizeBytes)
  261. firstPartsHeader := firstParts.Header()
  262. firstID := types.BlockID{Hash: first.Hash(), PartsHeader: firstPartsHeader}
  263. // Finally, verify the first block using the second's commit
  264. // NOTE: we can probably make this more efficient, but note that calling
  265. // first.Hash() doesn't verify the tx contents, so MakePartSet() is
  266. // currently necessary.
  267. err := state.Validators.VerifyCommit(
  268. chainID, firstID, first.Height, second.LastCommit)
  269. if err != nil {
  270. bcR.Logger.Error("Error in validation", "err", err)
  271. peerID := bcR.pool.RedoRequest(first.Height)
  272. peer := bcR.Switch.Peers().Get(peerID)
  273. if peer != nil {
  274. // NOTE: we've already removed the peer's request, but we
  275. // still need to clean up the rest.
  276. bcR.Switch.StopPeerForError(peer, fmt.Errorf("blockchainReactor validation error: %v", err))
  277. }
  278. peerID2 := bcR.pool.RedoRequest(second.Height)
  279. peer2 := bcR.Switch.Peers().Get(peerID2)
  280. if peer2 != nil && peer2 != peer {
  281. // NOTE: we've already removed the peer's request, but we
  282. // still need to clean up the rest.
  283. bcR.Switch.StopPeerForError(peer2, fmt.Errorf("blockchainReactor validation error: %v", err))
  284. }
  285. continue FOR_LOOP
  286. } else {
  287. bcR.pool.PopRequest()
  288. // TODO: batch saves so we dont persist to disk every block
  289. bcR.store.SaveBlock(first, firstParts, second.LastCommit)
  290. // TODO: same thing for app - but we would need a way to
  291. // get the hash without persisting the state
  292. var err error
  293. state, _, err = bcR.blockExec.ApplyBlock(state, firstID, first)
  294. if err != nil {
  295. // TODO This is bad, are we zombie?
  296. panic(fmt.Sprintf("Failed to process committed block (%d:%X): %v", first.Height, first.Hash(), err))
  297. }
  298. blocksSynced++
  299. if blocksSynced%100 == 0 {
  300. lastRate = 0.9*lastRate + 0.1*(100/time.Since(lastHundred).Seconds())
  301. bcR.Logger.Info("Fast Sync Rate", "height", bcR.pool.height,
  302. "max_peer_height", bcR.pool.MaxPeerHeight(), "blocks/s", lastRate)
  303. lastHundred = time.Now()
  304. }
  305. }
  306. continue FOR_LOOP
  307. case <-bcR.Quit():
  308. break FOR_LOOP
  309. }
  310. }
  311. }
  312. // BroadcastStatusRequest broadcasts `BlockStore` base and height.
  313. func (bcR *BlockchainReactor) BroadcastStatusRequest() error {
  314. msgBytes := cdc.MustMarshalBinaryBare(&bcStatusRequestMessage{
  315. Base: bcR.store.Base(),
  316. Height: bcR.store.Height(),
  317. })
  318. bcR.Switch.Broadcast(BlockchainChannel, msgBytes)
  319. return nil
  320. }
  321. //-----------------------------------------------------------------------------
  322. // Messages
  323. // BlockchainMessage is a generic message for this reactor.
  324. type BlockchainMessage interface {
  325. ValidateBasic() error
  326. }
  327. // RegisterBlockchainMessages registers the fast sync messages for amino encoding.
  328. func RegisterBlockchainMessages(cdc *amino.Codec) {
  329. cdc.RegisterInterface((*BlockchainMessage)(nil), nil)
  330. cdc.RegisterConcrete(&bcBlockRequestMessage{}, "tendermint/blockchain/BlockRequest", nil)
  331. cdc.RegisterConcrete(&bcBlockResponseMessage{}, "tendermint/blockchain/BlockResponse", nil)
  332. cdc.RegisterConcrete(&bcNoBlockResponseMessage{}, "tendermint/blockchain/NoBlockResponse", nil)
  333. cdc.RegisterConcrete(&bcStatusResponseMessage{}, "tendermint/blockchain/StatusResponse", nil)
  334. cdc.RegisterConcrete(&bcStatusRequestMessage{}, "tendermint/blockchain/StatusRequest", nil)
  335. }
  336. func decodeMsg(bz []byte) (msg BlockchainMessage, err error) {
  337. if len(bz) > maxMsgSize {
  338. return msg, fmt.Errorf("msg exceeds max size (%d > %d)", len(bz), maxMsgSize)
  339. }
  340. err = cdc.UnmarshalBinaryBare(bz, &msg)
  341. return
  342. }
  343. //-------------------------------------
  344. type bcBlockRequestMessage struct {
  345. Height int64
  346. }
  347. // ValidateBasic performs basic validation.
  348. func (m *bcBlockRequestMessage) ValidateBasic() error {
  349. if m.Height < 0 {
  350. return errors.New("negative Height")
  351. }
  352. return nil
  353. }
  354. func (m *bcBlockRequestMessage) String() string {
  355. return fmt.Sprintf("[bcBlockRequestMessage %v]", m.Height)
  356. }
  357. type bcNoBlockResponseMessage struct {
  358. Height int64
  359. }
  360. // ValidateBasic performs basic validation.
  361. func (m *bcNoBlockResponseMessage) ValidateBasic() error {
  362. if m.Height < 0 {
  363. return errors.New("negative Height")
  364. }
  365. return nil
  366. }
  367. func (m *bcNoBlockResponseMessage) String() string {
  368. return fmt.Sprintf("[bcNoBlockResponseMessage %d]", m.Height)
  369. }
  370. //-------------------------------------
  371. type bcBlockResponseMessage struct {
  372. Block *types.Block
  373. }
  374. // ValidateBasic performs basic validation.
  375. func (m *bcBlockResponseMessage) ValidateBasic() error {
  376. return m.Block.ValidateBasic()
  377. }
  378. func (m *bcBlockResponseMessage) String() string {
  379. return fmt.Sprintf("[bcBlockResponseMessage %v]", m.Block.Height)
  380. }
  381. //-------------------------------------
  382. type bcStatusRequestMessage struct {
  383. Height int64
  384. Base int64
  385. }
  386. // ValidateBasic performs basic validation.
  387. func (m *bcStatusRequestMessage) ValidateBasic() error {
  388. if m.Base < 0 {
  389. return errors.New("negative Base")
  390. }
  391. if m.Height < 0 {
  392. return errors.New("negative Height")
  393. }
  394. if m.Base > m.Height {
  395. return fmt.Errorf("base %v cannot be greater than height %v", m.Base, m.Height)
  396. }
  397. return nil
  398. }
  399. func (m *bcStatusRequestMessage) String() string {
  400. return fmt.Sprintf("[bcStatusRequestMessage %v:%v]", m.Base, m.Height)
  401. }
  402. //-------------------------------------
  403. type bcStatusResponseMessage struct {
  404. Height int64
  405. Base int64
  406. }
  407. // ValidateBasic performs basic validation.
  408. func (m *bcStatusResponseMessage) ValidateBasic() error {
  409. if m.Base < 0 {
  410. return errors.New("negative Base")
  411. }
  412. if m.Height < 0 {
  413. return errors.New("negative Height")
  414. }
  415. if m.Base > m.Height {
  416. return fmt.Errorf("base %v cannot be greater than height %v", m.Base, m.Height)
  417. }
  418. return nil
  419. }
  420. func (m *bcStatusResponseMessage) String() string {
  421. return fmt.Sprintf("[bcStatusResponseMessage %v:%v]", m.Base, m.Height)
  422. }