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.

475 lines
13 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. "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 tmsync.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.PartSetHeader.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. if err := batch.Delete(calcBlockMetaKey(h)); err != nil {
  232. return 0, err
  233. }
  234. if err := batch.Delete(calcBlockHashKey(meta.BlockID.Hash)); err != nil {
  235. return 0, err
  236. }
  237. if err := batch.Delete(calcBlockCommitKey(h)); err != nil {
  238. return 0, err
  239. }
  240. if err := batch.Delete(calcSeenCommitKey(h)); err != nil {
  241. return 0, err
  242. }
  243. for p := 0; p < int(meta.BlockID.PartSetHeader.Total); p++ {
  244. if err := batch.Delete(calcBlockPartKey(h, p)); err != nil {
  245. return 0, err
  246. }
  247. }
  248. pruned++
  249. // flush every 1000 blocks to avoid batches becoming too large
  250. if pruned%1000 == 0 && pruned > 0 {
  251. err := flush(batch, h)
  252. if err != nil {
  253. return 0, err
  254. }
  255. batch = bs.db.NewBatch()
  256. defer batch.Close()
  257. }
  258. }
  259. err := flush(batch, height)
  260. if err != nil {
  261. return 0, err
  262. }
  263. return pruned, nil
  264. }
  265. // SaveBlock persists the given block, blockParts, and seenCommit to the underlying db.
  266. // blockParts: Must be parts of the block
  267. // seenCommit: The +2/3 precommits that were seen which committed at height.
  268. // If all the nodes restart after committing a block,
  269. // we need this to reload the precommits to catch-up nodes to the
  270. // most recent height. Otherwise they'd stall at H-1.
  271. func (bs *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) {
  272. if block == nil {
  273. panic("BlockStore can only save a non-nil block")
  274. }
  275. height := block.Height
  276. hash := block.Hash()
  277. if g, w := height, bs.Height()+1; bs.Base() > 0 && g != w {
  278. panic(fmt.Sprintf("BlockStore can only save contiguous blocks. Wanted %v, got %v", w, g))
  279. }
  280. if !blockParts.IsComplete() {
  281. panic("BlockStore can only save complete block part sets")
  282. }
  283. // Save block meta
  284. blockMeta := types.NewBlockMeta(block, blockParts)
  285. pbm := blockMeta.ToProto()
  286. if pbm == nil {
  287. panic("nil blockmeta")
  288. }
  289. metaBytes := mustEncode(pbm)
  290. if err := bs.db.Set(calcBlockMetaKey(height), metaBytes); err != nil {
  291. panic(err)
  292. }
  293. if err := bs.db.Set(calcBlockHashKey(hash), []byte(fmt.Sprintf("%d", height))); err != nil {
  294. panic(err)
  295. }
  296. // Save block parts
  297. for i := 0; i < int(blockParts.Total()); i++ {
  298. part := blockParts.GetPart(i)
  299. bs.saveBlockPart(height, i, part)
  300. }
  301. // Save block commit (duplicate and separate from the Block)
  302. pbc := block.LastCommit.ToProto()
  303. blockCommitBytes := mustEncode(pbc)
  304. if err := bs.db.Set(calcBlockCommitKey(height-1), blockCommitBytes); err != nil {
  305. panic(err)
  306. }
  307. // Save seen commit (seen +2/3 precommits for block)
  308. // NOTE: we can delete this at a later height
  309. pbsc := seenCommit.ToProto()
  310. seenCommitBytes := mustEncode(pbsc)
  311. if err := bs.db.Set(calcSeenCommitKey(height), seenCommitBytes); err != nil {
  312. panic(err)
  313. }
  314. // Done!
  315. bs.mtx.Lock()
  316. bs.height = height
  317. if bs.base == 0 {
  318. bs.base = height
  319. }
  320. bs.mtx.Unlock()
  321. // Save new BlockStoreState descriptor. This also flushes the database.
  322. bs.saveState()
  323. }
  324. func (bs *BlockStore) saveBlockPart(height int64, index int, part *types.Part) {
  325. pbp, err := part.ToProto()
  326. if err != nil {
  327. panic(fmt.Errorf("unable to make part into proto: %w", err))
  328. }
  329. partBytes := mustEncode(pbp)
  330. if err := bs.db.Set(calcBlockPartKey(height, index), partBytes); err != nil {
  331. panic(err)
  332. }
  333. }
  334. func (bs *BlockStore) saveState() {
  335. bs.mtx.RLock()
  336. bss := tmstore.BlockStoreState{
  337. Base: bs.base,
  338. Height: bs.height,
  339. }
  340. bs.mtx.RUnlock()
  341. SaveBlockStoreState(&bss, bs.db)
  342. }
  343. // SaveSeenCommit saves a seen commit, used by e.g. the state sync reactor when bootstrapping node.
  344. func (bs *BlockStore) SaveSeenCommit(height int64, seenCommit *types.Commit) error {
  345. pbc := seenCommit.ToProto()
  346. seenCommitBytes, err := proto.Marshal(pbc)
  347. if err != nil {
  348. return fmt.Errorf("unable to marshal commit: %w", err)
  349. }
  350. return bs.db.Set(calcSeenCommitKey(height), seenCommitBytes)
  351. }
  352. //-----------------------------------------------------------------------------
  353. func calcBlockMetaKey(height int64) []byte {
  354. return []byte(fmt.Sprintf("H:%v", height))
  355. }
  356. func calcBlockPartKey(height int64, partIndex int) []byte {
  357. return []byte(fmt.Sprintf("P:%v:%v", height, partIndex))
  358. }
  359. func calcBlockCommitKey(height int64) []byte {
  360. return []byte(fmt.Sprintf("C:%v", height))
  361. }
  362. func calcSeenCommitKey(height int64) []byte {
  363. return []byte(fmt.Sprintf("SC:%v", height))
  364. }
  365. func calcBlockHashKey(hash []byte) []byte {
  366. return []byte(fmt.Sprintf("BH:%x", hash))
  367. }
  368. //-----------------------------------------------------------------------------
  369. var blockStoreKey = []byte("blockStore")
  370. // SaveBlockStoreState persists the blockStore state to the database.
  371. func SaveBlockStoreState(bsj *tmstore.BlockStoreState, db dbm.DB) {
  372. bytes, err := proto.Marshal(bsj)
  373. if err != nil {
  374. panic(fmt.Sprintf("Could not marshal state bytes: %v", err))
  375. }
  376. if err := db.SetSync(blockStoreKey, bytes); err != nil {
  377. panic(err)
  378. }
  379. }
  380. // LoadBlockStoreState returns the BlockStoreState as loaded from disk.
  381. // If no BlockStoreState was previously persisted, it returns the zero value.
  382. func LoadBlockStoreState(db dbm.DB) tmstore.BlockStoreState {
  383. bytes, err := db.Get(blockStoreKey)
  384. if err != nil {
  385. panic(err)
  386. }
  387. if len(bytes) == 0 {
  388. return tmstore.BlockStoreState{
  389. Base: 0,
  390. Height: 0,
  391. }
  392. }
  393. var bsj tmstore.BlockStoreState
  394. if err := proto.Unmarshal(bytes, &bsj); err != nil {
  395. panic(fmt.Sprintf("Could not unmarshal bytes: %X", bytes))
  396. }
  397. // Backwards compatibility with persisted data from before Base existed.
  398. if bsj.Height > 0 && bsj.Base == 0 {
  399. bsj.Base = 1
  400. }
  401. return bsj
  402. }
  403. //mustEncode proto encodes a proto.message and panics if fails
  404. func mustEncode(pb proto.Message) []byte {
  405. bz, err := proto.Marshal(pb)
  406. if err != nil {
  407. panic(fmt.Errorf("unable to marshal: %w", err))
  408. }
  409. return bz
  410. }