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.

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