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.

655 lines
17 KiB

blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
10 years ago
  1. package store
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strconv"
  6. "github.com/gogo/protobuf/proto"
  7. "github.com/google/orderedcode"
  8. dbm "github.com/tendermint/tm-db"
  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. }
  28. // NewBlockStore returns a new BlockStore with the given DB,
  29. // initialized to the last height that was committed to the DB.
  30. func NewBlockStore(db dbm.DB) *BlockStore {
  31. return &BlockStore{db}
  32. }
  33. // Base returns the first known contiguous block height, or 0 for empty block stores.
  34. func (bs *BlockStore) Base() int64 {
  35. iter, err := bs.db.Iterator(
  36. blockMetaKey(1),
  37. blockMetaKey(1<<63-1),
  38. )
  39. if err != nil {
  40. panic(err)
  41. }
  42. defer iter.Close()
  43. if iter.Valid() {
  44. height, err := decodeBlockMetaKey(iter.Key())
  45. if err == nil {
  46. return height
  47. }
  48. }
  49. if err := iter.Error(); err != nil {
  50. panic(err)
  51. }
  52. return 0
  53. }
  54. // Height returns the last known contiguous block height, or 0 for empty block stores.
  55. func (bs *BlockStore) Height() int64 {
  56. iter, err := bs.db.ReverseIterator(
  57. blockMetaKey(1),
  58. blockMetaKey(1<<63-1),
  59. )
  60. if err != nil {
  61. panic(err)
  62. }
  63. defer iter.Close()
  64. if iter.Valid() {
  65. height, err := decodeBlockMetaKey(iter.Key())
  66. if err == nil {
  67. return height
  68. }
  69. }
  70. if err := iter.Error(); err != nil {
  71. panic(err)
  72. }
  73. return 0
  74. }
  75. // Size returns the number of blocks in the block store.
  76. func (bs *BlockStore) Size() int64 {
  77. height := bs.Height()
  78. if height == 0 {
  79. return 0
  80. }
  81. return height + 1 - bs.Base()
  82. }
  83. // LoadBase atomically loads the base block meta, or returns nil if no base is found.
  84. func (bs *BlockStore) LoadBaseMeta() *types.BlockMeta {
  85. iter, err := bs.db.Iterator(
  86. blockMetaKey(1),
  87. blockMetaKey(1<<63-1),
  88. )
  89. if err != nil {
  90. return nil
  91. }
  92. defer iter.Close()
  93. if iter.Valid() {
  94. var pbbm = new(tmproto.BlockMeta)
  95. err = proto.Unmarshal(iter.Value(), pbbm)
  96. if err != nil {
  97. panic(fmt.Errorf("unmarshal to tmproto.BlockMeta: %w", err))
  98. }
  99. blockMeta, err := types.BlockMetaFromProto(pbbm)
  100. if err != nil {
  101. panic(fmt.Errorf("error from proto blockMeta: %w", err))
  102. }
  103. return blockMeta
  104. }
  105. return nil
  106. }
  107. // LoadBlock returns the block with the given height.
  108. // If no block is found for that height, it returns nil.
  109. func (bs *BlockStore) LoadBlock(height int64) *types.Block {
  110. var blockMeta = bs.LoadBlockMeta(height)
  111. if blockMeta == nil {
  112. return nil
  113. }
  114. pbb := new(tmproto.Block)
  115. buf := []byte{}
  116. for i := 0; i < int(blockMeta.BlockID.PartSetHeader.Total); i++ {
  117. part := bs.LoadBlockPart(height, i)
  118. // If the part is missing (e.g. since it has been deleted after we
  119. // loaded the block meta) we consider the whole block to be missing.
  120. if part == nil {
  121. return nil
  122. }
  123. buf = append(buf, part.Bytes...)
  124. }
  125. err := proto.Unmarshal(buf, pbb)
  126. if err != nil {
  127. // NOTE: The existence of meta should imply the existence of the
  128. // block. So, make sure meta is only saved after blocks are saved.
  129. panic(fmt.Errorf("error reading block: %w", err))
  130. }
  131. block, err := types.BlockFromProto(pbb)
  132. if err != nil {
  133. panic(fmt.Errorf("error from proto block: %w", err))
  134. }
  135. return block
  136. }
  137. // LoadBlockByHash returns the block with the given hash.
  138. // If no block is found for that hash, it returns nil.
  139. // Panics if it fails to parse height associated with the given hash.
  140. func (bs *BlockStore) LoadBlockByHash(hash []byte) *types.Block {
  141. bz, err := bs.db.Get(blockHashKey(hash))
  142. if err != nil {
  143. panic(err)
  144. }
  145. if len(bz) == 0 {
  146. return nil
  147. }
  148. s := string(bz)
  149. height, err := strconv.ParseInt(s, 10, 64)
  150. if err != nil {
  151. panic(fmt.Sprintf("failed to extract height from %s: %v", s, err))
  152. }
  153. return bs.LoadBlock(height)
  154. }
  155. // LoadBlockMetaByHash returns the blockmeta who's header corresponds to the given
  156. // hash. If none is found, returns nil.
  157. func (bs *BlockStore) LoadBlockMetaByHash(hash []byte) *types.BlockMeta {
  158. bz, err := bs.db.Get(blockHashKey(hash))
  159. if err != nil {
  160. panic(err)
  161. }
  162. if len(bz) == 0 {
  163. return nil
  164. }
  165. s := string(bz)
  166. height, err := strconv.ParseInt(s, 10, 64)
  167. if err != nil {
  168. panic(fmt.Sprintf("failed to extract height from %s: %v", s, err))
  169. }
  170. return bs.LoadBlockMeta(height)
  171. }
  172. // LoadBlockPart returns the Part at the given index
  173. // from the block at the given height.
  174. // If no part is found for the given height and index, it returns nil.
  175. func (bs *BlockStore) LoadBlockPart(height int64, index int) *types.Part {
  176. var pbpart = new(tmproto.Part)
  177. bz, err := bs.db.Get(blockPartKey(height, index))
  178. if err != nil {
  179. panic(err)
  180. }
  181. if len(bz) == 0 {
  182. return nil
  183. }
  184. err = proto.Unmarshal(bz, pbpart)
  185. if err != nil {
  186. panic(fmt.Errorf("unmarshal to tmproto.Part failed: %w", err))
  187. }
  188. part, err := types.PartFromProto(pbpart)
  189. if err != nil {
  190. panic(fmt.Errorf("error reading block part: %w", err))
  191. }
  192. return part
  193. }
  194. // LoadBlockMeta returns the BlockMeta for the given height.
  195. // If no block is found for the given height, it returns nil.
  196. func (bs *BlockStore) LoadBlockMeta(height int64) *types.BlockMeta {
  197. var pbbm = new(tmproto.BlockMeta)
  198. bz, err := bs.db.Get(blockMetaKey(height))
  199. if err != nil {
  200. panic(err)
  201. }
  202. if len(bz) == 0 {
  203. return nil
  204. }
  205. err = proto.Unmarshal(bz, pbbm)
  206. if err != nil {
  207. panic(fmt.Errorf("unmarshal to tmproto.BlockMeta: %w", err))
  208. }
  209. blockMeta, err := types.BlockMetaFromProto(pbbm)
  210. if err != nil {
  211. panic(fmt.Errorf("error from proto blockMeta: %w", err))
  212. }
  213. return blockMeta
  214. }
  215. // LoadBlockCommit returns the Commit for the given height.
  216. // This commit consists of the +2/3 and other Precommit-votes for block at `height`,
  217. // and it comes from the block.LastCommit for `height+1`.
  218. // If no commit is found for the given height, it returns nil.
  219. func (bs *BlockStore) LoadBlockCommit(height int64) *types.Commit {
  220. var pbc = new(tmproto.Commit)
  221. bz, err := bs.db.Get(blockCommitKey(height))
  222. if err != nil {
  223. panic(err)
  224. }
  225. if len(bz) == 0 {
  226. return nil
  227. }
  228. err = proto.Unmarshal(bz, pbc)
  229. if err != nil {
  230. panic(fmt.Errorf("error reading block commit: %w", err))
  231. }
  232. commit, err := types.CommitFromProto(pbc)
  233. if err != nil {
  234. panic(fmt.Errorf("error reading block commit: %w", err))
  235. }
  236. return commit
  237. }
  238. // LoadSeenCommit returns the last locally seen Commit before being
  239. // cannonicalized. This is useful when we've seen a commit, but there
  240. // has not yet been a new block at `height + 1` that includes this
  241. // commit in its block.LastCommit.
  242. func (bs *BlockStore) LoadSeenCommit() *types.Commit {
  243. var pbc = new(tmproto.Commit)
  244. bz, err := bs.db.Get(seenCommitKey())
  245. if err != nil {
  246. panic(err)
  247. }
  248. if len(bz) == 0 {
  249. return nil
  250. }
  251. err = proto.Unmarshal(bz, pbc)
  252. if err != nil {
  253. panic(fmt.Errorf("error reading block seen commit: %w", err))
  254. }
  255. commit, err := types.CommitFromProto(pbc)
  256. if err != nil {
  257. panic(fmt.Errorf("error from proto commit: %w", err))
  258. }
  259. return commit
  260. }
  261. // PruneBlocks removes block up to (but not including) a height. It returns the number of blocks pruned.
  262. func (bs *BlockStore) PruneBlocks(height int64) (uint64, error) {
  263. if height <= 0 {
  264. return 0, fmt.Errorf("height must be greater than 0")
  265. }
  266. if height > bs.Height() {
  267. return 0, fmt.Errorf("height must be equal to or less than the latest height %d", bs.Height())
  268. }
  269. // when removing the block meta, use the hash to remove the hash key at the same time
  270. removeBlockHash := func(key, value []byte, batch dbm.Batch) error {
  271. // unmarshal block meta
  272. var pbbm = new(tmproto.BlockMeta)
  273. err := proto.Unmarshal(value, pbbm)
  274. if err != nil {
  275. return fmt.Errorf("unmarshal to tmproto.BlockMeta: %w", err)
  276. }
  277. blockMeta, err := types.BlockMetaFromProto(pbbm)
  278. if err != nil {
  279. return fmt.Errorf("error from proto blockMeta: %w", err)
  280. }
  281. // delete the hash key corresponding to the block meta's hash
  282. if err := batch.Delete(blockHashKey(blockMeta.BlockID.Hash)); err != nil {
  283. return fmt.Errorf("failed to delete hash key: %X: %w", blockHashKey(blockMeta.BlockID.Hash), err)
  284. }
  285. return nil
  286. }
  287. // remove block meta first as this is used to indicate whether the block exists.
  288. // For this reason, we also use ony block meta as a measure of the amount of blocks pruned
  289. pruned, err := bs.pruneRange(blockMetaKey(0), blockMetaKey(height), removeBlockHash)
  290. if err != nil {
  291. return pruned, err
  292. }
  293. if _, err := bs.pruneRange(blockPartKey(0, 0), blockPartKey(height, 0), nil); err != nil {
  294. return pruned, err
  295. }
  296. if _, err := bs.pruneRange(blockCommitKey(0), blockCommitKey(height), nil); err != nil {
  297. return pruned, err
  298. }
  299. return pruned, nil
  300. }
  301. // pruneRange is a generic function for deleting a range of values based on the lowest
  302. // height up to but excluding retainHeight. For each key/value pair, an optional hook can be
  303. // executed before the deletion itself is made. pruneRange will use batch delete to delete
  304. // keys in batches of at most 1000 keys.
  305. func (bs *BlockStore) pruneRange(
  306. start []byte,
  307. end []byte,
  308. preDeletionHook func(key, value []byte, batch dbm.Batch) error,
  309. ) (uint64, error) {
  310. var (
  311. err error
  312. pruned uint64
  313. totalPruned uint64
  314. )
  315. batch := bs.db.NewBatch()
  316. defer batch.Close()
  317. pruned, start, err = bs.batchDelete(batch, start, end, preDeletionHook)
  318. if err != nil {
  319. return totalPruned, err
  320. }
  321. // loop until we have finished iterating over all the keys by writing, opening a new batch
  322. // and incrementing through the next range of keys.
  323. for !bytes.Equal(start, end) {
  324. if err := batch.Write(); err != nil {
  325. return totalPruned, err
  326. }
  327. totalPruned += pruned
  328. if err := batch.Close(); err != nil {
  329. return totalPruned, err
  330. }
  331. batch = bs.db.NewBatch()
  332. pruned, start, err = bs.batchDelete(batch, start, end, preDeletionHook)
  333. if err != nil {
  334. return totalPruned, err
  335. }
  336. }
  337. // once we looped over all keys we do a final flush to disk
  338. if err := batch.WriteSync(); err != nil {
  339. return totalPruned, err
  340. }
  341. totalPruned += pruned
  342. return totalPruned, nil
  343. }
  344. // batchDelete runs an iterator over a set of keys, first preforming a pre deletion hook before adding it to the batch.
  345. // The function ends when either 1000 keys have been added to the batch or the iterator has reached the end.
  346. func (bs *BlockStore) batchDelete(
  347. batch dbm.Batch,
  348. start, end []byte,
  349. preDeletionHook func(key, value []byte, batch dbm.Batch) error,
  350. ) (uint64, []byte, error) {
  351. var pruned uint64
  352. iter, err := bs.db.Iterator(start, end)
  353. if err != nil {
  354. return pruned, start, err
  355. }
  356. defer iter.Close()
  357. for ; iter.Valid(); iter.Next() {
  358. key := iter.Key()
  359. if preDeletionHook != nil {
  360. if err := preDeletionHook(key, iter.Value(), batch); err != nil {
  361. return 0, start, fmt.Errorf("pruning error at key %X: %w", iter.Key(), err)
  362. }
  363. }
  364. if err := batch.Delete(key); err != nil {
  365. return 0, start, fmt.Errorf("pruning error at key %X: %w", iter.Key(), err)
  366. }
  367. pruned++
  368. if pruned == 1000 {
  369. return pruned, iter.Key(), iter.Error()
  370. }
  371. }
  372. return pruned, end, iter.Error()
  373. }
  374. // SaveBlock persists the given block, blockParts, and seenCommit to the underlying db.
  375. // blockParts: Must be parts of the block
  376. // seenCommit: The +2/3 precommits that were seen which committed at height.
  377. // If all the nodes restart after committing a block,
  378. // we need this to reload the precommits to catch-up nodes to the
  379. // most recent height. Otherwise they'd stall at H-1.
  380. func (bs *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) {
  381. if block == nil {
  382. panic("BlockStore can only save a non-nil block")
  383. }
  384. batch := bs.db.NewBatch()
  385. height := block.Height
  386. hash := block.Hash()
  387. if g, w := height, bs.Height()+1; bs.Base() > 0 && g != w {
  388. panic(fmt.Sprintf("BlockStore can only save contiguous blocks. Wanted %v, got %v", w, g))
  389. }
  390. if !blockParts.IsComplete() {
  391. panic("BlockStore can only save complete block part sets")
  392. }
  393. // Save block parts. This must be done before the block meta, since callers
  394. // typically load the block meta first as an indication that the block exists
  395. // and then go on to load block parts - we must make sure the block is
  396. // complete as soon as the block meta is written.
  397. for i := 0; i < int(blockParts.Total()); i++ {
  398. part := blockParts.GetPart(i)
  399. bs.saveBlockPart(height, i, part, batch)
  400. }
  401. blockMeta := types.NewBlockMeta(block, blockParts)
  402. pbm := blockMeta.ToProto()
  403. if pbm == nil {
  404. panic("nil blockmeta")
  405. }
  406. metaBytes := mustEncode(pbm)
  407. if err := batch.Set(blockMetaKey(height), metaBytes); err != nil {
  408. panic(err)
  409. }
  410. if err := batch.Set(blockHashKey(hash), []byte(fmt.Sprintf("%d", height))); err != nil {
  411. panic(err)
  412. }
  413. pbc := block.LastCommit.ToProto()
  414. blockCommitBytes := mustEncode(pbc)
  415. if err := batch.Set(blockCommitKey(height-1), blockCommitBytes); err != nil {
  416. panic(err)
  417. }
  418. // Save seen commit (seen +2/3 precommits for block)
  419. pbsc := seenCommit.ToProto()
  420. seenCommitBytes := mustEncode(pbsc)
  421. if err := batch.Set(seenCommitKey(), seenCommitBytes); err != nil {
  422. panic(err)
  423. }
  424. if err := batch.WriteSync(); err != nil {
  425. panic(err)
  426. }
  427. if err := batch.Close(); err != nil {
  428. panic(err)
  429. }
  430. }
  431. func (bs *BlockStore) saveBlockPart(height int64, index int, part *types.Part, batch dbm.Batch) {
  432. pbp, err := part.ToProto()
  433. if err != nil {
  434. panic(fmt.Errorf("unable to make part into proto: %w", err))
  435. }
  436. partBytes := mustEncode(pbp)
  437. if err := batch.Set(blockPartKey(height, index), partBytes); err != nil {
  438. panic(err)
  439. }
  440. }
  441. // SaveSeenCommit saves a seen commit, used by e.g. the state sync reactor when bootstrapping node.
  442. func (bs *BlockStore) SaveSeenCommit(height int64, seenCommit *types.Commit) error {
  443. pbc := seenCommit.ToProto()
  444. seenCommitBytes, err := proto.Marshal(pbc)
  445. if err != nil {
  446. return fmt.Errorf("unable to marshal commit: %w", err)
  447. }
  448. return bs.db.Set(seenCommitKey(), seenCommitBytes)
  449. }
  450. func (bs *BlockStore) SaveSignedHeader(sh *types.SignedHeader, blockID types.BlockID) error {
  451. // first check that the block store doesn't already have the block
  452. bz, err := bs.db.Get(blockMetaKey(sh.Height))
  453. if err != nil {
  454. return err
  455. }
  456. if bz != nil {
  457. return fmt.Errorf("block at height %d already saved", sh.Height)
  458. }
  459. // FIXME: saving signed headers although necessary for proving evidence,
  460. // doesn't have complete parity with block meta's thus block size and num
  461. // txs are filled with negative numbers. We should aim to find a solution to
  462. // this.
  463. blockMeta := &types.BlockMeta{
  464. BlockID: blockID,
  465. BlockSize: -1,
  466. Header: *sh.Header,
  467. NumTxs: -1,
  468. }
  469. batch := bs.db.NewBatch()
  470. pbm := blockMeta.ToProto()
  471. metaBytes := mustEncode(pbm)
  472. if err := batch.Set(blockMetaKey(sh.Height), metaBytes); err != nil {
  473. return fmt.Errorf("unable to save block meta: %w", err)
  474. }
  475. pbc := sh.Commit.ToProto()
  476. blockCommitBytes := mustEncode(pbc)
  477. if err := batch.Set(blockCommitKey(sh.Height), blockCommitBytes); err != nil {
  478. return fmt.Errorf("unable to save commit: %w", err)
  479. }
  480. if err := batch.WriteSync(); err != nil {
  481. return err
  482. }
  483. return batch.Close()
  484. }
  485. func (bs *BlockStore) Close() error {
  486. return bs.db.Close()
  487. }
  488. //---------------------------------- KEY ENCODING -----------------------------------------
  489. // key prefixes
  490. const (
  491. // prefixes are unique across all tm db's
  492. prefixBlockMeta = int64(0)
  493. prefixBlockPart = int64(1)
  494. prefixBlockCommit = int64(2)
  495. prefixSeenCommit = int64(3)
  496. prefixBlockHash = int64(4)
  497. )
  498. func blockMetaKey(height int64) []byte {
  499. key, err := orderedcode.Append(nil, prefixBlockMeta, height)
  500. if err != nil {
  501. panic(err)
  502. }
  503. return key
  504. }
  505. func decodeBlockMetaKey(key []byte) (height int64, err error) {
  506. var prefix int64
  507. remaining, err := orderedcode.Parse(string(key), &prefix, &height)
  508. if err != nil {
  509. return
  510. }
  511. if len(remaining) != 0 {
  512. return -1, fmt.Errorf("expected complete key but got remainder: %s", remaining)
  513. }
  514. if prefix != prefixBlockMeta {
  515. return -1, fmt.Errorf("incorrect prefix. Expected %v, got %v", prefixBlockMeta, prefix)
  516. }
  517. return
  518. }
  519. func blockPartKey(height int64, partIndex int) []byte {
  520. key, err := orderedcode.Append(nil, prefixBlockPart, height, int64(partIndex))
  521. if err != nil {
  522. panic(err)
  523. }
  524. return key
  525. }
  526. func blockCommitKey(height int64) []byte {
  527. key, err := orderedcode.Append(nil, prefixBlockCommit, height)
  528. if err != nil {
  529. panic(err)
  530. }
  531. return key
  532. }
  533. func seenCommitKey() []byte {
  534. key, err := orderedcode.Append(nil, prefixSeenCommit)
  535. if err != nil {
  536. panic(err)
  537. }
  538. return key
  539. }
  540. func blockHashKey(hash []byte) []byte {
  541. key, err := orderedcode.Append(nil, prefixBlockHash, string(hash))
  542. if err != nil {
  543. panic(err)
  544. }
  545. return key
  546. }
  547. //-----------------------------------------------------------------------------
  548. // mustEncode proto encodes a proto.message and panics if fails
  549. func mustEncode(pb proto.Message) []byte {
  550. bz, err := proto.Marshal(pb)
  551. if err != nil {
  552. panic(fmt.Errorf("unable to marshal: %w", err))
  553. }
  554. return bz
  555. }