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.

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