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.

498 lines
14 KiB

blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
6 years ago
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
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 store
  2. import (
  3. "fmt"
  4. "strconv"
  5. "github.com/gogo/protobuf/proto"
  6. dbm "github.com/tendermint/tm-db"
  7. tmsync "github.com/tendermint/tendermint/libs/sync"
  8. tmstore "github.com/tendermint/tendermint/proto/tendermint/store"
  9. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  10. "github.com/tendermint/tendermint/types"
  11. )
  12. /*
  13. BlockStore is a simple low level store for blocks.
  14. There are three types of information stored:
  15. - BlockMeta: Meta information about each block
  16. - Block part: Parts of each block, aggregated w/ PartSet
  17. - Commit: The commit part of each block, for gossiping precommit votes
  18. Currently the precommit signatures are duplicated in the Block parts as
  19. well as the Commit. In the future this may change, perhaps by moving
  20. the Commit data outside the Block. (TODO)
  21. The store can be assumed to contain all contiguous blocks between base and height (inclusive).
  22. // NOTE: BlockStore methods will panic if they encounter errors
  23. // deserializing loaded data, indicating probable corruption on disk.
  24. */
  25. type BlockStore struct {
  26. db dbm.DB
  27. // mtx guards access to the struct fields listed below it. We rely on the database to enforce
  28. // fine-grained concurrency control for its data, and thus this mutex does not apply to
  29. // database contents. The only reason for keeping these fields in the struct is that the data
  30. // can't efficiently be queried from the database since the key encoding we use is not
  31. // lexicographically ordered (see https://github.com/tendermint/tendermint/issues/4567).
  32. mtx tmsync.RWMutex
  33. base int64
  34. height int64
  35. }
  36. // NewBlockStore returns a new BlockStore with the given DB,
  37. // initialized to the last height that was committed to the DB.
  38. func NewBlockStore(db dbm.DB) *BlockStore {
  39. bs := LoadBlockStoreState(db)
  40. return &BlockStore{
  41. base: bs.Base,
  42. height: bs.Height,
  43. db: db,
  44. }
  45. }
  46. // Base returns the first known contiguous block height, or 0 for empty block stores.
  47. func (bs *BlockStore) Base() int64 {
  48. bs.mtx.RLock()
  49. defer bs.mtx.RUnlock()
  50. return bs.base
  51. }
  52. // Height returns the last known contiguous block height, or 0 for empty block stores.
  53. func (bs *BlockStore) Height() int64 {
  54. bs.mtx.RLock()
  55. defer bs.mtx.RUnlock()
  56. return bs.height
  57. }
  58. // Size returns the number of blocks in the block store.
  59. func (bs *BlockStore) Size() int64 {
  60. bs.mtx.RLock()
  61. defer bs.mtx.RUnlock()
  62. if bs.height == 0 {
  63. return 0
  64. }
  65. return bs.height - bs.base + 1
  66. }
  67. // LoadBase atomically loads the base block meta, or returns nil if no base is found.
  68. func (bs *BlockStore) LoadBaseMeta() *types.BlockMeta {
  69. bs.mtx.RLock()
  70. defer bs.mtx.RUnlock()
  71. if bs.base == 0 {
  72. return nil
  73. }
  74. return bs.LoadBlockMeta(bs.base)
  75. }
  76. // LoadBlock returns the block with the given height.
  77. // If no block is found for that height, it returns nil.
  78. func (bs *BlockStore) LoadBlock(height int64) *types.Block {
  79. var blockMeta = bs.LoadBlockMeta(height)
  80. if blockMeta == nil {
  81. return nil
  82. }
  83. pbb := new(tmproto.Block)
  84. buf := []byte{}
  85. for i := 0; i < int(blockMeta.BlockID.PartSetHeader.Total); i++ {
  86. part := bs.LoadBlockPart(height, i)
  87. // If the part is missing (e.g. since it has been deleted after we
  88. // loaded the block meta) we consider the whole block to be missing.
  89. if part == nil {
  90. return nil
  91. }
  92. buf = append(buf, part.Bytes...)
  93. }
  94. err := proto.Unmarshal(buf, pbb)
  95. if err != nil {
  96. // NOTE: The existence of meta should imply the existence of the
  97. // block. So, make sure meta is only saved after blocks are saved.
  98. panic(fmt.Sprintf("Error reading block: %v", err))
  99. }
  100. block, err := types.BlockFromProto(pbb)
  101. if err != nil {
  102. panic(fmt.Errorf("error from proto block: %w", err))
  103. }
  104. return block
  105. }
  106. // LoadBlockByHash returns the block with the given hash.
  107. // If no block is found for that hash, it returns nil.
  108. // Panics if it fails to parse height associated with the given hash.
  109. func (bs *BlockStore) LoadBlockByHash(hash []byte) *types.Block {
  110. bz, err := bs.db.Get(calcBlockHashKey(hash))
  111. if err != nil {
  112. panic(err)
  113. }
  114. if len(bz) == 0 {
  115. return nil
  116. }
  117. s := string(bz)
  118. height, err := strconv.ParseInt(s, 10, 64)
  119. if err != nil {
  120. panic(fmt.Sprintf("failed to extract height from %s: %v", s, err))
  121. }
  122. return bs.LoadBlock(height)
  123. }
  124. // LoadBlockPart returns the Part at the given index
  125. // from the block at the given height.
  126. // If no part is found for the given height and index, it returns nil.
  127. func (bs *BlockStore) LoadBlockPart(height int64, index int) *types.Part {
  128. var pbpart = new(tmproto.Part)
  129. bz, err := bs.db.Get(calcBlockPartKey(height, index))
  130. if err != nil {
  131. panic(err)
  132. }
  133. if len(bz) == 0 {
  134. return nil
  135. }
  136. err = proto.Unmarshal(bz, pbpart)
  137. if err != nil {
  138. panic(fmt.Errorf("unmarshal to tmproto.Part failed: %w", err))
  139. }
  140. part, err := types.PartFromProto(pbpart)
  141. if err != nil {
  142. panic(fmt.Sprintf("Error reading block part: %v", err))
  143. }
  144. return part
  145. }
  146. // LoadBlockMeta returns the BlockMeta for the given height.
  147. // If no block is found for the given height, it returns nil.
  148. func (bs *BlockStore) LoadBlockMeta(height int64) *types.BlockMeta {
  149. var pbbm = new(tmproto.BlockMeta)
  150. bz, err := bs.db.Get(calcBlockMetaKey(height))
  151. if err != nil {
  152. panic(err)
  153. }
  154. if len(bz) == 0 {
  155. return nil
  156. }
  157. err = proto.Unmarshal(bz, pbbm)
  158. if err != nil {
  159. panic(fmt.Errorf("unmarshal to tmproto.BlockMeta: %w", err))
  160. }
  161. blockMeta, err := types.BlockMetaFromProto(pbbm)
  162. if err != nil {
  163. panic(fmt.Errorf("error from proto blockMeta: %w", err))
  164. }
  165. return blockMeta
  166. }
  167. // LoadBlockCommit returns the Commit for the given height.
  168. // This commit consists of the +2/3 and other Precommit-votes for block at `height`,
  169. // and it comes from the block.LastCommit for `height+1`.
  170. // If no commit is found for the given height, it returns nil.
  171. func (bs *BlockStore) LoadBlockCommit(height int64) *types.Commit {
  172. var pbc = new(tmproto.Commit)
  173. bz, err := bs.db.Get(calcBlockCommitKey(height))
  174. if err != nil {
  175. panic(err)
  176. }
  177. if len(bz) == 0 {
  178. return nil
  179. }
  180. err = proto.Unmarshal(bz, pbc)
  181. if err != nil {
  182. panic(fmt.Errorf("error reading block commit: %w", err))
  183. }
  184. commit, err := types.CommitFromProto(pbc)
  185. if err != nil {
  186. panic(fmt.Sprintf("Error reading block commit: %v", err))
  187. }
  188. return commit
  189. }
  190. // LoadSeenCommit returns the locally seen Commit for the given height.
  191. // This is useful when we've seen a commit, but there has not yet been
  192. // a new block at `height + 1` that includes this commit in its block.LastCommit.
  193. func (bs *BlockStore) LoadSeenCommit(height int64) *types.Commit {
  194. var pbc = new(tmproto.Commit)
  195. bz, err := bs.db.Get(calcSeenCommitKey(height))
  196. if err != nil {
  197. panic(err)
  198. }
  199. if len(bz) == 0 {
  200. return nil
  201. }
  202. err = proto.Unmarshal(bz, pbc)
  203. if err != nil {
  204. panic(fmt.Sprintf("error reading block seen commit: %v", err))
  205. }
  206. commit, err := types.CommitFromProto(pbc)
  207. if err != nil {
  208. panic(fmt.Errorf("error from proto commit: %w", err))
  209. }
  210. return commit
  211. }
  212. // PruneBlocks removes block up to (but not including) a height. It returns number of blocks pruned.
  213. func (bs *BlockStore) PruneBlocks(height int64) (uint64, error) {
  214. if height <= 0 {
  215. return 0, fmt.Errorf("height must be greater than 0")
  216. }
  217. bs.mtx.RLock()
  218. if height > bs.height {
  219. bs.mtx.RUnlock()
  220. return 0, fmt.Errorf("cannot prune beyond the latest height %v", bs.height)
  221. }
  222. base := bs.base
  223. bs.mtx.RUnlock()
  224. if height < base {
  225. return 0, fmt.Errorf("cannot prune to height %v, it is lower than base height %v",
  226. height, base)
  227. }
  228. pruned := uint64(0)
  229. batch := bs.db.NewBatch()
  230. defer batch.Close()
  231. flush := func(batch dbm.Batch, base int64) error {
  232. // We can't trust batches to be atomic, so update base first to make sure noone
  233. // tries to access missing blocks.
  234. bs.mtx.Lock()
  235. bs.base = base
  236. bs.mtx.Unlock()
  237. bs.saveState()
  238. err := batch.WriteSync()
  239. if err != nil {
  240. return fmt.Errorf("failed to prune up to height %v: %w", base, err)
  241. }
  242. batch.Close()
  243. return nil
  244. }
  245. for h := base; h < height; h++ {
  246. meta := bs.LoadBlockMeta(h)
  247. if meta == nil { // assume already deleted
  248. continue
  249. }
  250. if err := batch.Delete(calcBlockMetaKey(h)); err != nil {
  251. return 0, err
  252. }
  253. if err := batch.Delete(calcBlockHashKey(meta.BlockID.Hash)); err != nil {
  254. return 0, err
  255. }
  256. if err := batch.Delete(calcBlockCommitKey(h)); err != nil {
  257. return 0, err
  258. }
  259. if err := batch.Delete(calcSeenCommitKey(h)); err != nil {
  260. return 0, err
  261. }
  262. for p := 0; p < int(meta.BlockID.PartSetHeader.Total); p++ {
  263. if err := batch.Delete(calcBlockPartKey(h, p)); err != nil {
  264. return 0, err
  265. }
  266. }
  267. pruned++
  268. // flush every 1000 blocks to avoid batches becoming too large
  269. if pruned%1000 == 0 && pruned > 0 {
  270. err := flush(batch, h)
  271. if err != nil {
  272. return 0, err
  273. }
  274. batch = bs.db.NewBatch()
  275. defer batch.Close()
  276. }
  277. }
  278. err := flush(batch, height)
  279. if err != nil {
  280. return 0, err
  281. }
  282. return pruned, nil
  283. }
  284. // SaveBlock persists the given block, blockParts, and seenCommit to the underlying db.
  285. // blockParts: Must be parts of the block
  286. // seenCommit: The +2/3 precommits that were seen which committed at height.
  287. // If all the nodes restart after committing a block,
  288. // we need this to reload the precommits to catch-up nodes to the
  289. // most recent height. Otherwise they'd stall at H-1.
  290. func (bs *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) {
  291. if block == nil {
  292. panic("BlockStore can only save a non-nil block")
  293. }
  294. height := block.Height
  295. hash := block.Hash()
  296. if g, w := height, bs.Height()+1; bs.Base() > 0 && g != w {
  297. panic(fmt.Sprintf("BlockStore can only save contiguous blocks. Wanted %v, got %v", w, g))
  298. }
  299. if !blockParts.IsComplete() {
  300. panic("BlockStore can only save complete block part sets")
  301. }
  302. // Save block parts. This must be done before the block meta, since callers
  303. // typically load the block meta first as an indication that the block exists
  304. // and then go on to load block parts - we must make sure the block is
  305. // complete as soon as the block meta is written.
  306. for i := 0; i < int(blockParts.Total()); i++ {
  307. part := blockParts.GetPart(i)
  308. bs.saveBlockPart(height, i, part)
  309. }
  310. // Save block meta
  311. blockMeta := types.NewBlockMeta(block, blockParts)
  312. pbm := blockMeta.ToProto()
  313. if pbm == nil {
  314. panic("nil blockmeta")
  315. }
  316. metaBytes := mustEncode(pbm)
  317. if err := bs.db.Set(calcBlockMetaKey(height), metaBytes); err != nil {
  318. panic(err)
  319. }
  320. if err := bs.db.Set(calcBlockHashKey(hash), []byte(fmt.Sprintf("%d", height))); err != nil {
  321. panic(err)
  322. }
  323. // Save block commit (duplicate and separate from the Block)
  324. pbc := block.LastCommit.ToProto()
  325. blockCommitBytes := mustEncode(pbc)
  326. if err := bs.db.Set(calcBlockCommitKey(height-1), blockCommitBytes); err != nil {
  327. panic(err)
  328. }
  329. // Save seen commit (seen +2/3 precommits for block)
  330. // NOTE: we can delete this at a later height
  331. pbsc := seenCommit.ToProto()
  332. seenCommitBytes := mustEncode(pbsc)
  333. if err := bs.db.Set(calcSeenCommitKey(height), seenCommitBytes); err != nil {
  334. panic(err)
  335. }
  336. // Done!
  337. bs.mtx.Lock()
  338. bs.height = height
  339. if bs.base == 0 {
  340. bs.base = height
  341. }
  342. bs.mtx.Unlock()
  343. // Save new BlockStoreState descriptor. This also flushes the database.
  344. bs.saveState()
  345. }
  346. func (bs *BlockStore) saveBlockPart(height int64, index int, part *types.Part) {
  347. pbp, err := part.ToProto()
  348. if err != nil {
  349. panic(fmt.Errorf("unable to make part into proto: %w", err))
  350. }
  351. partBytes := mustEncode(pbp)
  352. if err := bs.db.Set(calcBlockPartKey(height, index), partBytes); err != nil {
  353. panic(err)
  354. }
  355. }
  356. func (bs *BlockStore) saveState() {
  357. bs.mtx.RLock()
  358. bss := tmstore.BlockStoreState{
  359. Base: bs.base,
  360. Height: bs.height,
  361. }
  362. bs.mtx.RUnlock()
  363. SaveBlockStoreState(&bss, bs.db)
  364. }
  365. // SaveSeenCommit saves a seen commit, used by e.g. the state sync reactor when bootstrapping node.
  366. func (bs *BlockStore) SaveSeenCommit(height int64, seenCommit *types.Commit) error {
  367. pbc := seenCommit.ToProto()
  368. seenCommitBytes, err := proto.Marshal(pbc)
  369. if err != nil {
  370. return fmt.Errorf("unable to marshal commit: %w", err)
  371. }
  372. return bs.db.Set(calcSeenCommitKey(height), seenCommitBytes)
  373. }
  374. //-----------------------------------------------------------------------------
  375. func calcBlockMetaKey(height int64) []byte {
  376. return []byte(fmt.Sprintf("H:%v", height))
  377. }
  378. func calcBlockPartKey(height int64, partIndex int) []byte {
  379. return []byte(fmt.Sprintf("P:%v:%v", height, partIndex))
  380. }
  381. func calcBlockCommitKey(height int64) []byte {
  382. return []byte(fmt.Sprintf("C:%v", height))
  383. }
  384. func calcSeenCommitKey(height int64) []byte {
  385. return []byte(fmt.Sprintf("SC:%v", height))
  386. }
  387. func calcBlockHashKey(hash []byte) []byte {
  388. return []byte(fmt.Sprintf("BH:%x", hash))
  389. }
  390. //-----------------------------------------------------------------------------
  391. var blockStoreKey = []byte("blockStore")
  392. // SaveBlockStoreState persists the blockStore state to the database.
  393. func SaveBlockStoreState(bsj *tmstore.BlockStoreState, db dbm.DB) {
  394. bytes, err := proto.Marshal(bsj)
  395. if err != nil {
  396. panic(fmt.Sprintf("Could not marshal state bytes: %v", err))
  397. }
  398. if err := db.SetSync(blockStoreKey, bytes); err != nil {
  399. panic(err)
  400. }
  401. }
  402. // LoadBlockStoreState returns the BlockStoreState as loaded from disk.
  403. // If no BlockStoreState was previously persisted, it returns the zero value.
  404. func LoadBlockStoreState(db dbm.DB) tmstore.BlockStoreState {
  405. bytes, err := db.Get(blockStoreKey)
  406. if err != nil {
  407. panic(err)
  408. }
  409. if len(bytes) == 0 {
  410. return tmstore.BlockStoreState{
  411. Base: 0,
  412. Height: 0,
  413. }
  414. }
  415. var bsj tmstore.BlockStoreState
  416. if err := proto.Unmarshal(bytes, &bsj); err != nil {
  417. panic(fmt.Sprintf("Could not unmarshal bytes: %X", bytes))
  418. }
  419. // Backwards compatibility with persisted data from before Base existed.
  420. if bsj.Height > 0 && bsj.Base == 0 {
  421. bsj.Base = 1
  422. }
  423. return bsj
  424. }
  425. // mustEncode proto encodes a proto.message and panics if fails
  426. func mustEncode(pb proto.Message) []byte {
  427. bz, err := proto.Marshal(pb)
  428. if err != nil {
  429. panic(fmt.Errorf("unable to marshal: %w", err))
  430. }
  431. return bz
  432. }