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.

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