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.

456 lines
12 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
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. "sync"
  6. "github.com/gogo/protobuf/proto"
  7. dbm "github.com/tendermint/tm-db"
  8. tmstore "github.com/tendermint/tendermint/proto/store"
  9. tmproto "github.com/tendermint/tendermint/proto/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 sync.RWMutex
  28. base int64
  29. height int64
  30. }
  31. // NewBlockStore returns a new BlockStore with the given DB,
  32. // initialized to the last height that was committed to the DB.
  33. func NewBlockStore(db dbm.DB) *BlockStore {
  34. bs := LoadBlockStoreState(db)
  35. return &BlockStore{
  36. base: bs.Base,
  37. height: bs.Height,
  38. db: db,
  39. }
  40. }
  41. // Base returns the first known contiguous block height, or 0 for empty block stores.
  42. func (bs *BlockStore) Base() int64 {
  43. bs.mtx.RLock()
  44. defer bs.mtx.RUnlock()
  45. return bs.base
  46. }
  47. // Height returns the last known contiguous block height, or 0 for empty block stores.
  48. func (bs *BlockStore) Height() int64 {
  49. bs.mtx.RLock()
  50. defer bs.mtx.RUnlock()
  51. return bs.height
  52. }
  53. // Size returns the number of blocks in the block store.
  54. func (bs *BlockStore) Size() int64 {
  55. bs.mtx.RLock()
  56. defer bs.mtx.RUnlock()
  57. if bs.height == 0 {
  58. return 0
  59. }
  60. return bs.height - bs.base + 1
  61. }
  62. // LoadBlock returns the block with the given height.
  63. // If no block is found for that height, it returns nil.
  64. func (bs *BlockStore) LoadBlock(height int64) *types.Block {
  65. var blockMeta = bs.LoadBlockMeta(height)
  66. if blockMeta == nil {
  67. return nil
  68. }
  69. pbb := new(tmproto.Block)
  70. buf := []byte{}
  71. for i := 0; i < int(blockMeta.BlockID.PartsHeader.Total); i++ {
  72. part := bs.LoadBlockPart(height, i)
  73. buf = append(buf, part.Bytes...)
  74. }
  75. err := proto.Unmarshal(buf, pbb)
  76. if err != nil {
  77. // NOTE: The existence of meta should imply the existence of the
  78. // block. So, make sure meta is only saved after blocks are saved.
  79. panic(fmt.Sprintf("Error reading block: %v", err))
  80. }
  81. block, err := types.BlockFromProto(pbb)
  82. if err != nil {
  83. panic(fmt.Errorf("error from proto block: %w", err))
  84. }
  85. return block
  86. }
  87. // LoadBlockByHash returns the block with the given hash.
  88. // If no block is found for that hash, it returns nil.
  89. // Panics if it fails to parse height associated with the given hash.
  90. func (bs *BlockStore) LoadBlockByHash(hash []byte) *types.Block {
  91. bz, err := bs.db.Get(calcBlockHashKey(hash))
  92. if err != nil {
  93. panic(err)
  94. }
  95. if len(bz) == 0 {
  96. return nil
  97. }
  98. s := string(bz)
  99. height, err := strconv.ParseInt(s, 10, 64)
  100. if err != nil {
  101. panic(fmt.Sprintf("failed to extract height from %s: %v", s, err))
  102. }
  103. return bs.LoadBlock(height)
  104. }
  105. // LoadBlockPart returns the Part at the given index
  106. // from the block at the given height.
  107. // If no part is found for the given height and index, it returns nil.
  108. func (bs *BlockStore) LoadBlockPart(height int64, index int) *types.Part {
  109. var pbpart = new(tmproto.Part)
  110. bz, err := bs.db.Get(calcBlockPartKey(height, index))
  111. if err != nil {
  112. panic(err)
  113. }
  114. if len(bz) == 0 {
  115. return nil
  116. }
  117. err = proto.Unmarshal(bz, pbpart)
  118. if err != nil {
  119. panic(fmt.Errorf("unmarshal to tmproto.Part failed: %w", err))
  120. }
  121. part, err := types.PartFromProto(pbpart)
  122. if err != nil {
  123. panic(fmt.Sprintf("Error reading block part: %v", err))
  124. }
  125. return part
  126. }
  127. // LoadBlockMeta returns the BlockMeta for the given height.
  128. // If no block is found for the given height, it returns nil.
  129. func (bs *BlockStore) LoadBlockMeta(height int64) *types.BlockMeta {
  130. var pbbm = new(tmproto.BlockMeta)
  131. bz, err := bs.db.Get(calcBlockMetaKey(height))
  132. if err != nil {
  133. panic(err)
  134. }
  135. if len(bz) == 0 {
  136. return nil
  137. }
  138. err = proto.Unmarshal(bz, pbbm)
  139. if err != nil {
  140. panic(fmt.Errorf("unmarshal to tmproto.BlockMeta: %w", err))
  141. }
  142. blockMeta, err := types.BlockMetaFromProto(pbbm)
  143. if err != nil {
  144. panic(fmt.Errorf("error from proto blockMeta: %w", err))
  145. }
  146. return blockMeta
  147. }
  148. // LoadBlockCommit returns the Commit for the given height.
  149. // This commit consists of the +2/3 and other Precommit-votes for block at `height`,
  150. // and it comes from the block.LastCommit for `height+1`.
  151. // If no commit is found for the given height, it returns nil.
  152. func (bs *BlockStore) LoadBlockCommit(height int64) *types.Commit {
  153. var pbc = new(tmproto.Commit)
  154. bz, err := bs.db.Get(calcBlockCommitKey(height))
  155. if err != nil {
  156. panic(err)
  157. }
  158. if len(bz) == 0 {
  159. return nil
  160. }
  161. err = proto.Unmarshal(bz, pbc)
  162. if err != nil {
  163. panic(fmt.Errorf("error reading block commit: %w", err))
  164. }
  165. commit, err := types.CommitFromProto(pbc)
  166. if err != nil {
  167. panic(fmt.Sprintf("Error reading block commit: %v", err))
  168. }
  169. return commit
  170. }
  171. // LoadSeenCommit returns the locally seen Commit for the given height.
  172. // This is useful when we've seen a commit, but there has not yet been
  173. // a new block at `height + 1` that includes this commit in its block.LastCommit.
  174. func (bs *BlockStore) LoadSeenCommit(height int64) *types.Commit {
  175. var pbc = new(tmproto.Commit)
  176. bz, err := bs.db.Get(calcSeenCommitKey(height))
  177. if err != nil {
  178. panic(err)
  179. }
  180. if len(bz) == 0 {
  181. return nil
  182. }
  183. err = proto.Unmarshal(bz, pbc)
  184. if err != nil {
  185. panic(fmt.Sprintf("error reading block seen commit: %v", err))
  186. }
  187. commit, err := types.CommitFromProto(pbc)
  188. if err != nil {
  189. panic(fmt.Errorf("error from proto commit: %w", err))
  190. }
  191. return commit
  192. }
  193. // PruneBlocks removes block up to (but not including) a height. It returns number of blocks pruned.
  194. func (bs *BlockStore) PruneBlocks(height int64) (uint64, error) {
  195. if height <= 0 {
  196. return 0, fmt.Errorf("height must be greater than 0")
  197. }
  198. bs.mtx.RLock()
  199. if height > bs.height {
  200. bs.mtx.RUnlock()
  201. return 0, fmt.Errorf("cannot prune beyond the latest height %v", bs.height)
  202. }
  203. base := bs.base
  204. bs.mtx.RUnlock()
  205. if height < base {
  206. return 0, fmt.Errorf("cannot prune to height %v, it is lower than base height %v",
  207. height, base)
  208. }
  209. pruned := uint64(0)
  210. batch := bs.db.NewBatch()
  211. defer batch.Close()
  212. flush := func(batch dbm.Batch, base int64) error {
  213. // We can't trust batches to be atomic, so update base first to make sure noone
  214. // tries to access missing blocks.
  215. bs.mtx.Lock()
  216. bs.base = base
  217. bs.mtx.Unlock()
  218. bs.saveState()
  219. err := batch.WriteSync()
  220. if err != nil {
  221. return fmt.Errorf("failed to prune up to height %v: %w", base, err)
  222. }
  223. batch.Close()
  224. return nil
  225. }
  226. for h := base; h < height; h++ {
  227. meta := bs.LoadBlockMeta(h)
  228. if meta == nil { // assume already deleted
  229. continue
  230. }
  231. batch.Delete(calcBlockMetaKey(h))
  232. batch.Delete(calcBlockHashKey(meta.BlockID.Hash))
  233. batch.Delete(calcBlockCommitKey(h))
  234. batch.Delete(calcSeenCommitKey(h))
  235. for p := 0; p < int(meta.BlockID.PartsHeader.Total); p++ {
  236. batch.Delete(calcBlockPartKey(h, p))
  237. }
  238. pruned++
  239. // flush every 1000 blocks to avoid batches becoming too large
  240. if pruned%1000 == 0 && pruned > 0 {
  241. err := flush(batch, h)
  242. if err != nil {
  243. return 0, err
  244. }
  245. batch = bs.db.NewBatch()
  246. defer batch.Close()
  247. }
  248. }
  249. err := flush(batch, height)
  250. if err != nil {
  251. return 0, err
  252. }
  253. return pruned, nil
  254. }
  255. // SaveBlock persists the given block, blockParts, and seenCommit to the underlying db.
  256. // blockParts: Must be parts of the block
  257. // seenCommit: The +2/3 precommits that were seen which committed at height.
  258. // If all the nodes restart after committing a block,
  259. // we need this to reload the precommits to catch-up nodes to the
  260. // most recent height. Otherwise they'd stall at H-1.
  261. func (bs *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) {
  262. if block == nil {
  263. panic("BlockStore can only save a non-nil block")
  264. }
  265. height := block.Height
  266. hash := block.Hash()
  267. if g, w := height, bs.Height()+1; bs.Base() > 0 && g != w {
  268. panic(fmt.Sprintf("BlockStore can only save contiguous blocks. Wanted %v, got %v", w, g))
  269. }
  270. if !blockParts.IsComplete() {
  271. panic("BlockStore can only save complete block part sets")
  272. }
  273. // Save block meta
  274. blockMeta := types.NewBlockMeta(block, blockParts)
  275. pbm := blockMeta.ToProto()
  276. if pbm == nil {
  277. panic("nil blockmeta")
  278. }
  279. metaBytes := mustEncode(pbm)
  280. bs.db.Set(calcBlockMetaKey(height), metaBytes)
  281. bs.db.Set(calcBlockHashKey(hash), []byte(fmt.Sprintf("%d", height)))
  282. // Save block parts
  283. for i := 0; i < int(blockParts.Total()); i++ {
  284. part := blockParts.GetPart(i)
  285. bs.saveBlockPart(height, i, part)
  286. }
  287. // Save block commit (duplicate and separate from the Block)
  288. pbc := block.LastCommit.ToProto()
  289. blockCommitBytes := mustEncode(pbc)
  290. bs.db.Set(calcBlockCommitKey(height-1), blockCommitBytes)
  291. // Save seen commit (seen +2/3 precommits for block)
  292. // NOTE: we can delete this at a later height
  293. pbsc := seenCommit.ToProto()
  294. seenCommitBytes := mustEncode(pbsc)
  295. bs.db.Set(calcSeenCommitKey(height), seenCommitBytes)
  296. // Done!
  297. bs.mtx.Lock()
  298. bs.height = height
  299. if bs.base == 0 {
  300. bs.base = height
  301. }
  302. bs.mtx.Unlock()
  303. // Save new BlockStoreState descriptor
  304. bs.saveState()
  305. // Flush
  306. bs.db.SetSync(nil, nil)
  307. }
  308. func (bs *BlockStore) saveBlockPart(height int64, index int, part *types.Part) {
  309. pbp, err := part.ToProto()
  310. if err != nil {
  311. panic(fmt.Errorf("unable to make part into proto: %w", err))
  312. }
  313. partBytes := mustEncode(pbp)
  314. bs.db.Set(calcBlockPartKey(height, index), partBytes)
  315. }
  316. func (bs *BlockStore) saveState() {
  317. bs.mtx.RLock()
  318. bss := tmstore.BlockStoreState{
  319. Base: bs.base,
  320. Height: bs.height,
  321. }
  322. bs.mtx.RUnlock()
  323. SaveBlockStoreState(&bss, bs.db)
  324. }
  325. // SaveSeenCommit saves a seen commit, used by e.g. the state sync reactor when bootstrapping node.
  326. func (bs *BlockStore) SaveSeenCommit(height int64, seenCommit *types.Commit) error {
  327. pbc := seenCommit.ToProto()
  328. seenCommitBytes, err := proto.Marshal(pbc)
  329. if err != nil {
  330. return fmt.Errorf("unable to marshal commit: %w", err)
  331. }
  332. return bs.db.Set(calcSeenCommitKey(height), seenCommitBytes)
  333. }
  334. //-----------------------------------------------------------------------------
  335. func calcBlockMetaKey(height int64) []byte {
  336. return []byte(fmt.Sprintf("H:%v", height))
  337. }
  338. func calcBlockPartKey(height int64, partIndex int) []byte {
  339. return []byte(fmt.Sprintf("P:%v:%v", height, partIndex))
  340. }
  341. func calcBlockCommitKey(height int64) []byte {
  342. return []byte(fmt.Sprintf("C:%v", height))
  343. }
  344. func calcSeenCommitKey(height int64) []byte {
  345. return []byte(fmt.Sprintf("SC:%v", height))
  346. }
  347. func calcBlockHashKey(hash []byte) []byte {
  348. return []byte(fmt.Sprintf("BH:%x", hash))
  349. }
  350. //-----------------------------------------------------------------------------
  351. var blockStoreKey = []byte("blockStore")
  352. // SaveBlockStoreState persists the blockStore state to the database.
  353. func SaveBlockStoreState(bsj *tmstore.BlockStoreState, db dbm.DB) {
  354. bytes, err := proto.Marshal(bsj)
  355. if err != nil {
  356. panic(fmt.Sprintf("Could not marshal state bytes: %v", err))
  357. }
  358. db.SetSync(blockStoreKey, bytes)
  359. }
  360. // LoadBlockStoreState returns the BlockStoreState as loaded from disk.
  361. // If no BlockStoreState was previously persisted, it returns the zero value.
  362. func LoadBlockStoreState(db dbm.DB) tmstore.BlockStoreState {
  363. bytes, err := db.Get(blockStoreKey)
  364. if err != nil {
  365. panic(err)
  366. }
  367. if len(bytes) == 0 {
  368. return tmstore.BlockStoreState{
  369. Base: 0,
  370. Height: 0,
  371. }
  372. }
  373. var bsj tmstore.BlockStoreState
  374. if err := proto.Unmarshal(bytes, &bsj); err != nil {
  375. panic(fmt.Sprintf("Could not unmarshal bytes: %X", bytes))
  376. }
  377. // Backwards compatibility with persisted data from before Base existed.
  378. if bsj.Height > 0 && bsj.Base == 0 {
  379. bsj.Base = 1
  380. }
  381. return bsj
  382. }
  383. //mustEncode proto encodes a proto.message and panics if fails
  384. func mustEncode(pb proto.Message) []byte {
  385. bz, err := proto.Marshal(pb)
  386. if err != nil {
  387. panic(fmt.Errorf("unable to marshal: %w", err))
  388. }
  389. return bz
  390. }