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.

571 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
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
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
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
10 years ago
8 years ago
  1. package store
  2. import (
  3. "fmt"
  4. "strconv"
  5. "github.com/gogo/protobuf/proto"
  6. "github.com/google/orderedcode"
  7. dbm "github.com/tendermint/tm-db"
  8. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  9. "github.com/tendermint/tendermint/types"
  10. )
  11. /*
  12. BlockStore is a simple low level store for blocks.
  13. There are three types of information stored:
  14. - BlockMeta: Meta information about each block
  15. - Block part: Parts of each block, aggregated w/ PartSet
  16. - Commit: The commit part of each block, for gossiping precommit votes
  17. Currently the precommit signatures are duplicated in the Block parts as
  18. well as the Commit. In the future this may change, perhaps by moving
  19. the Commit data outside the Block. (TODO)
  20. The store can be assumed to contain all contiguous blocks between base and height (inclusive).
  21. // NOTE: BlockStore methods will panic if they encounter errors
  22. // deserializing loaded data, indicating probable corruption on disk.
  23. */
  24. type BlockStore struct {
  25. db dbm.DB
  26. }
  27. // NewBlockStore returns a new BlockStore with the given DB,
  28. // initialized to the last height that was committed to the DB.
  29. func NewBlockStore(db dbm.DB) *BlockStore {
  30. return &BlockStore{db}
  31. }
  32. // Base returns the first known contiguous block height, or 0 for empty block stores.
  33. func (bs *BlockStore) Base() int64 {
  34. iter, err := bs.db.Iterator(
  35. blockMetaKey(1),
  36. blockMetaKey(1<<63-1),
  37. )
  38. if err != nil {
  39. panic(err)
  40. }
  41. defer iter.Close()
  42. if iter.Valid() {
  43. height, err := decodeBlockMetaKey(iter.Key())
  44. if err == nil {
  45. return height
  46. }
  47. }
  48. if err := iter.Error(); err != nil {
  49. panic(err)
  50. }
  51. return 0
  52. }
  53. // Height returns the last known contiguous block height, or 0 for empty block stores.
  54. func (bs *BlockStore) Height() int64 {
  55. iter, err := bs.db.ReverseIterator(
  56. blockMetaKey(1),
  57. blockMetaKey(1<<63-1),
  58. )
  59. if err != nil {
  60. panic(err)
  61. }
  62. defer iter.Close()
  63. if iter.Valid() {
  64. height, err := decodeBlockMetaKey(iter.Key())
  65. if err == nil {
  66. return height
  67. }
  68. }
  69. if err := iter.Error(); err != nil {
  70. panic(err)
  71. }
  72. return 0
  73. }
  74. // Size returns the number of blocks in the block store.
  75. func (bs *BlockStore) Size() int64 {
  76. height := bs.Height()
  77. if height == 0 {
  78. return 0
  79. }
  80. return height + 1 - bs.Base()
  81. }
  82. // LoadBase atomically loads the base block meta, or returns nil if no base is found.
  83. func (bs *BlockStore) LoadBaseMeta() *types.BlockMeta {
  84. iter, err := bs.db.Iterator(
  85. blockMetaKey(1),
  86. blockMetaKey(1<<63-1),
  87. )
  88. if err != nil {
  89. return nil
  90. }
  91. defer iter.Close()
  92. if iter.Valid() {
  93. var pbbm = new(tmproto.BlockMeta)
  94. err = proto.Unmarshal(iter.Value(), pbbm)
  95. if err != nil {
  96. panic(fmt.Errorf("unmarshal to tmproto.BlockMeta: %w", err))
  97. }
  98. blockMeta, err := types.BlockMetaFromProto(pbbm)
  99. if err != nil {
  100. panic(fmt.Errorf("error from proto blockMeta: %w", err))
  101. }
  102. return blockMeta
  103. }
  104. return nil
  105. }
  106. // LoadBlock returns the block with the given height.
  107. // If no block is found for that height, it returns nil.
  108. func (bs *BlockStore) LoadBlock(height int64) *types.Block {
  109. var blockMeta = bs.LoadBlockMeta(height)
  110. if blockMeta == nil {
  111. return nil
  112. }
  113. pbb := new(tmproto.Block)
  114. buf := []byte{}
  115. for i := 0; i < int(blockMeta.BlockID.PartSetHeader.Total); i++ {
  116. part := bs.LoadBlockPart(height, i)
  117. // If the part is missing (e.g. since it has been deleted after we
  118. // loaded the block meta) we consider the whole block to be missing.
  119. if part == nil {
  120. return nil
  121. }
  122. buf = append(buf, part.Bytes...)
  123. }
  124. err := proto.Unmarshal(buf, pbb)
  125. if err != nil {
  126. // NOTE: The existence of meta should imply the existence of the
  127. // block. So, make sure meta is only saved after blocks are saved.
  128. panic(fmt.Sprintf("Error reading block: %v", err))
  129. }
  130. block, err := types.BlockFromProto(pbb)
  131. if err != nil {
  132. panic(fmt.Errorf("error from proto block: %w", err))
  133. }
  134. return block
  135. }
  136. // LoadBlockByHash returns the block with the given hash.
  137. // If no block is found for that hash, it returns nil.
  138. // Panics if it fails to parse height associated with the given hash.
  139. func (bs *BlockStore) LoadBlockByHash(hash []byte) *types.Block {
  140. bz, err := bs.db.Get(blockHashKey(hash))
  141. if err != nil {
  142. panic(err)
  143. }
  144. if len(bz) == 0 {
  145. return nil
  146. }
  147. s := string(bz)
  148. height, err := strconv.ParseInt(s, 10, 64)
  149. if err != nil {
  150. panic(fmt.Sprintf("failed to extract height from %s: %v", s, err))
  151. }
  152. return bs.LoadBlock(height)
  153. }
  154. // LoadBlockPart returns the Part at the given index
  155. // from the block at the given height.
  156. // If no part is found for the given height and index, it returns nil.
  157. func (bs *BlockStore) LoadBlockPart(height int64, index int) *types.Part {
  158. var pbpart = new(tmproto.Part)
  159. bz, err := bs.db.Get(blockPartKey(height, index))
  160. if err != nil {
  161. panic(err)
  162. }
  163. if len(bz) == 0 {
  164. return nil
  165. }
  166. err = proto.Unmarshal(bz, pbpart)
  167. if err != nil {
  168. panic(fmt.Errorf("unmarshal to tmproto.Part failed: %w", err))
  169. }
  170. part, err := types.PartFromProto(pbpart)
  171. if err != nil {
  172. panic(fmt.Sprintf("Error reading block part: %v", err))
  173. }
  174. return part
  175. }
  176. // LoadBlockMeta returns the BlockMeta for the given height.
  177. // If no block is found for the given height, it returns nil.
  178. func (bs *BlockStore) LoadBlockMeta(height int64) *types.BlockMeta {
  179. var pbbm = new(tmproto.BlockMeta)
  180. bz, err := bs.db.Get(blockMetaKey(height))
  181. if err != nil {
  182. panic(err)
  183. }
  184. if len(bz) == 0 {
  185. return nil
  186. }
  187. err = proto.Unmarshal(bz, pbbm)
  188. if err != nil {
  189. panic(fmt.Errorf("unmarshal to tmproto.BlockMeta: %w", err))
  190. }
  191. blockMeta, err := types.BlockMetaFromProto(pbbm)
  192. if err != nil {
  193. panic(fmt.Errorf("error from proto blockMeta: %w", err))
  194. }
  195. return blockMeta
  196. }
  197. // LoadBlockCommit returns the Commit for the given height.
  198. // This commit consists of the +2/3 and other Precommit-votes for block at `height`,
  199. // and it comes from the block.LastCommit for `height+1`.
  200. // If no commit is found for the given height, it returns nil.
  201. func (bs *BlockStore) LoadBlockCommit(height int64) *types.Commit {
  202. var pbc = new(tmproto.Commit)
  203. bz, err := bs.db.Get(blockCommitKey(height))
  204. if err != nil {
  205. panic(err)
  206. }
  207. if len(bz) == 0 {
  208. return nil
  209. }
  210. err = proto.Unmarshal(bz, pbc)
  211. if err != nil {
  212. panic(fmt.Errorf("error reading block commit: %w", err))
  213. }
  214. commit, err := types.CommitFromProto(pbc)
  215. if err != nil {
  216. panic(fmt.Sprintf("Error reading block commit: %v", err))
  217. }
  218. return commit
  219. }
  220. // LoadSeenCommit returns the locally seen Commit for the given height.
  221. // This is useful when we've seen a commit, but there has not yet been
  222. // a new block at `height + 1` that includes this commit in its block.LastCommit.
  223. func (bs *BlockStore) LoadSeenCommit(height int64) *types.Commit {
  224. var pbc = new(tmproto.Commit)
  225. bz, err := bs.db.Get(seenCommitKey(height))
  226. if err != nil {
  227. panic(err)
  228. }
  229. if len(bz) == 0 {
  230. return nil
  231. }
  232. err = proto.Unmarshal(bz, pbc)
  233. if err != nil {
  234. panic(fmt.Sprintf("error reading block seen commit: %v", err))
  235. }
  236. commit, err := types.CommitFromProto(pbc)
  237. if err != nil {
  238. panic(fmt.Errorf("error from proto commit: %w", err))
  239. }
  240. return commit
  241. }
  242. // PruneBlocks removes block up to (but not including) a height. It returns the number of blocks pruned.
  243. func (bs *BlockStore) PruneBlocks(height int64) (uint64, error) {
  244. if height <= 0 {
  245. return 0, fmt.Errorf("height must be greater than 0")
  246. }
  247. if height > bs.Height() {
  248. return 0, fmt.Errorf("height must be equal to or less than the latest height %d", bs.Height())
  249. }
  250. // when removing the block meta, use the hash to remove the hash key at the same time
  251. removeBlockHash := func(key, value []byte, batch dbm.Batch) error {
  252. // unmarshal block meta
  253. var pbbm = new(tmproto.BlockMeta)
  254. err := proto.Unmarshal(value, pbbm)
  255. if err != nil {
  256. return fmt.Errorf("unmarshal to tmproto.BlockMeta: %w", err)
  257. }
  258. blockMeta, err := types.BlockMetaFromProto(pbbm)
  259. if err != nil {
  260. return fmt.Errorf("error from proto blockMeta: %w", err)
  261. }
  262. // delete the hash key corresponding to the block meta's hash
  263. if err := batch.Delete(blockHashKey(blockMeta.BlockID.Hash)); err != nil {
  264. return fmt.Errorf("failed to delete hash key: %X: %w", blockHashKey(blockMeta.BlockID.Hash), err)
  265. }
  266. return nil
  267. }
  268. // remove block meta first as this is used to indicate whether the block exists.
  269. // For this reason, we also use ony block meta as a measure of the amount of blocks pruned
  270. pruned, err := bs.batchDelete(blockMetaKey(0), blockMetaKey(height), removeBlockHash)
  271. if err != nil {
  272. return pruned, err
  273. }
  274. if _, err := bs.batchDelete(blockPartKey(0, 0), blockPartKey(height, 0), nil); err != nil {
  275. return pruned, err
  276. }
  277. if _, err := bs.batchDelete(blockCommitKey(0), blockCommitKey(height), nil); err != nil {
  278. return pruned, err
  279. }
  280. if _, err := bs.batchDelete(seenCommitKey(0), seenCommitKey(height), nil); err != nil {
  281. return pruned, err
  282. }
  283. return pruned, nil
  284. }
  285. // batchDelete is a generic function for deleting a range of values based on the lowest
  286. // height up to but excluding retainHeight. For each key/value pair, an optional hook can be
  287. // executed before the deletion itself is made
  288. func (bs *BlockStore) batchDelete(
  289. start []byte,
  290. end []byte,
  291. preDeletionHook func(key, value []byte, batch dbm.Batch) error,
  292. ) (uint64, error) {
  293. iter, err := bs.db.Iterator(start, end)
  294. if err != nil {
  295. panic(err)
  296. }
  297. defer iter.Close()
  298. batch := bs.db.NewBatch()
  299. defer batch.Close()
  300. pruned := uint64(0)
  301. flushed := pruned
  302. for iter.Valid() {
  303. key := iter.Key()
  304. if preDeletionHook != nil {
  305. if err := preDeletionHook(key, iter.Value(), batch); err != nil {
  306. return flushed, err
  307. }
  308. }
  309. if err := batch.Delete(key); err != nil {
  310. return flushed, fmt.Errorf("pruning error at key %X: %w", iter.Key(), err)
  311. }
  312. pruned++
  313. // avoid batches growing too large by flushing to database regularly
  314. if pruned%1000 == 0 {
  315. if err := iter.Error(); err != nil {
  316. return flushed, err
  317. }
  318. if err := iter.Close(); err != nil {
  319. return flushed, err
  320. }
  321. err := batch.Write()
  322. if err != nil {
  323. return flushed, fmt.Errorf("pruning error at key %X: %w", iter.Key(), err)
  324. }
  325. if err := batch.Close(); err != nil {
  326. return flushed, err
  327. }
  328. flushed = pruned
  329. iter, err = bs.db.Iterator(start, end)
  330. if err != nil {
  331. panic(err)
  332. }
  333. defer iter.Close()
  334. batch = bs.db.NewBatch()
  335. defer batch.Close()
  336. } else {
  337. iter.Next()
  338. }
  339. }
  340. flushed = pruned
  341. if err := iter.Error(); err != nil {
  342. return flushed, err
  343. }
  344. err = batch.WriteSync()
  345. if err != nil {
  346. return flushed, fmt.Errorf("pruning error at key %X: %w", iter.Key(), err)
  347. }
  348. return flushed, nil
  349. }
  350. // SaveBlock persists the given block, blockParts, and seenCommit to the underlying db.
  351. // blockParts: Must be parts of the block
  352. // seenCommit: The +2/3 precommits that were seen which committed at height.
  353. // If all the nodes restart after committing a block,
  354. // we need this to reload the precommits to catch-up nodes to the
  355. // most recent height. Otherwise they'd stall at H-1.
  356. func (bs *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) {
  357. if block == nil {
  358. panic("BlockStore can only save a non-nil block")
  359. }
  360. height := block.Height
  361. hash := block.Hash()
  362. if g, w := height, bs.Height()+1; bs.Base() > 0 && g != w {
  363. panic(fmt.Sprintf("BlockStore can only save contiguous blocks. Wanted %v, got %v", w, g))
  364. }
  365. if !blockParts.IsComplete() {
  366. panic("BlockStore can only save complete block part sets")
  367. }
  368. // Save block parts. This must be done before the block meta, since callers
  369. // typically load the block meta first as an indication that the block exists
  370. // and then go on to load block parts - we must make sure the block is
  371. // complete as soon as the block meta is written.
  372. for i := 0; i < int(blockParts.Total()); i++ {
  373. part := blockParts.GetPart(i)
  374. bs.saveBlockPart(height, i, part)
  375. }
  376. // Save block meta
  377. blockMeta := types.NewBlockMeta(block, blockParts)
  378. pbm := blockMeta.ToProto()
  379. if pbm == nil {
  380. panic("nil blockmeta")
  381. }
  382. metaBytes := mustEncode(pbm)
  383. if err := bs.db.Set(blockMetaKey(height), metaBytes); err != nil {
  384. panic(err)
  385. }
  386. if err := bs.db.Set(blockHashKey(hash), []byte(fmt.Sprintf("%d", height))); err != nil {
  387. panic(err)
  388. }
  389. // Save block commit (duplicate and separate from the Block)
  390. pbc := block.LastCommit.ToProto()
  391. blockCommitBytes := mustEncode(pbc)
  392. if err := bs.db.Set(blockCommitKey(height-1), blockCommitBytes); err != nil {
  393. panic(err)
  394. }
  395. // Save seen commit (seen +2/3 precommits for block)
  396. // NOTE: we can delete this at a later height
  397. pbsc := seenCommit.ToProto()
  398. seenCommitBytes := mustEncode(pbsc)
  399. if err := bs.db.SetSync(seenCommitKey(height), seenCommitBytes); err != nil {
  400. panic(err)
  401. }
  402. }
  403. func (bs *BlockStore) saveBlockPart(height int64, index int, part *types.Part) {
  404. pbp, err := part.ToProto()
  405. if err != nil {
  406. panic(fmt.Errorf("unable to make part into proto: %w", err))
  407. }
  408. partBytes := mustEncode(pbp)
  409. if err := bs.db.Set(blockPartKey(height, index), partBytes); err != nil {
  410. panic(err)
  411. }
  412. }
  413. // SaveSeenCommit saves a seen commit, used by e.g. the state sync reactor when bootstrapping node.
  414. func (bs *BlockStore) SaveSeenCommit(height int64, seenCommit *types.Commit) error {
  415. pbc := seenCommit.ToProto()
  416. seenCommitBytes, err := proto.Marshal(pbc)
  417. if err != nil {
  418. return fmt.Errorf("unable to marshal commit: %w", err)
  419. }
  420. return bs.db.Set(seenCommitKey(height), seenCommitBytes)
  421. }
  422. //---------------------------------- KEY ENCODING -----------------------------------------
  423. // key prefixes
  424. const (
  425. // prefixes are unique across all tm db's
  426. prefixBlockMeta = int64(0)
  427. prefixBlockPart = int64(1)
  428. prefixBlockCommit = int64(2)
  429. prefixSeenCommit = int64(3)
  430. prefixBlockHash = int64(4)
  431. )
  432. func blockMetaKey(height int64) []byte {
  433. key, err := orderedcode.Append(nil, prefixBlockMeta, height)
  434. if err != nil {
  435. panic(err)
  436. }
  437. return key
  438. }
  439. func decodeBlockMetaKey(key []byte) (height int64, err error) {
  440. var prefix int64
  441. remaining, err := orderedcode.Parse(string(key), &prefix, &height)
  442. if err != nil {
  443. return
  444. }
  445. if len(remaining) != 0 {
  446. return -1, fmt.Errorf("expected complete key but got remainder: %s", remaining)
  447. }
  448. if prefix != prefixBlockMeta {
  449. return -1, fmt.Errorf("incorrect prefix. Expected %v, got %v", prefixBlockMeta, prefix)
  450. }
  451. return
  452. }
  453. func blockPartKey(height int64, partIndex int) []byte {
  454. key, err := orderedcode.Append(nil, prefixBlockPart, height, int64(partIndex))
  455. if err != nil {
  456. panic(err)
  457. }
  458. return key
  459. }
  460. func blockCommitKey(height int64) []byte {
  461. key, err := orderedcode.Append(nil, prefixBlockCommit, height)
  462. if err != nil {
  463. panic(err)
  464. }
  465. return key
  466. }
  467. func seenCommitKey(height int64) []byte {
  468. key, err := orderedcode.Append(nil, prefixSeenCommit, height)
  469. if err != nil {
  470. panic(err)
  471. }
  472. return key
  473. }
  474. func blockHashKey(hash []byte) []byte {
  475. key, err := orderedcode.Append(nil, prefixBlockHash, string(hash))
  476. if err != nil {
  477. panic(err)
  478. }
  479. return key
  480. }
  481. //-----------------------------------------------------------------------------
  482. // mustEncode proto encodes a proto.message and panics if fails
  483. func mustEncode(pb proto.Message) []byte {
  484. bz, err := proto.Marshal(pb)
  485. if err != nil {
  486. panic(fmt.Errorf("unable to marshal: %w", err))
  487. }
  488. return bz
  489. }