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.

672 lines
20 KiB

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
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
7 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
3 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
3 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
3 years ago
7 years ago
  1. package state
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "github.com/gogo/protobuf/proto"
  7. "github.com/google/orderedcode"
  8. dbm "github.com/tendermint/tm-db"
  9. abci "github.com/tendermint/tendermint/abci/types"
  10. tmmath "github.com/tendermint/tendermint/libs/math"
  11. tmstate "github.com/tendermint/tendermint/proto/tendermint/state"
  12. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  13. "github.com/tendermint/tendermint/types"
  14. )
  15. const (
  16. // persist validators every valSetCheckpointInterval blocks to avoid
  17. // LoadValidators taking too much time.
  18. // https://github.com/tendermint/tendermint/pull/3438
  19. // 100000 results in ~ 100ms to get 100 validators (see BenchmarkLoadValidators)
  20. valSetCheckpointInterval = 100000
  21. )
  22. //------------------------------------------------------------------------
  23. const (
  24. // prefixes are unique across all tm db's
  25. prefixValidators = int64(5)
  26. prefixConsensusParams = int64(6)
  27. prefixABCIResponses = int64(7)
  28. prefixState = int64(8)
  29. )
  30. func encodeKey(prefix int64, height int64) []byte {
  31. res, err := orderedcode.Append(nil, prefix, height)
  32. if err != nil {
  33. panic(err)
  34. }
  35. return res
  36. }
  37. func validatorsKey(height int64) []byte {
  38. return encodeKey(prefixValidators, height)
  39. }
  40. func consensusParamsKey(height int64) []byte {
  41. return encodeKey(prefixConsensusParams, height)
  42. }
  43. func abciResponsesKey(height int64) []byte {
  44. return encodeKey(prefixABCIResponses, height)
  45. }
  46. // stateKey should never change after being set in init()
  47. var stateKey []byte
  48. func init() {
  49. var err error
  50. stateKey, err = orderedcode.Append(nil, prefixState)
  51. if err != nil {
  52. panic(err)
  53. }
  54. }
  55. //----------------------
  56. //go:generate ../../scripts/mockery_generate.sh Store
  57. // Store defines the state store interface
  58. //
  59. // It is used to retrieve current state and save and load ABCI responses,
  60. // validators and consensus parameters
  61. type Store interface {
  62. // Load loads the current state of the blockchain
  63. Load() (State, error)
  64. // LoadValidators loads the validator set at a given height
  65. LoadValidators(int64) (*types.ValidatorSet, error)
  66. // LoadABCIResponses loads the abciResponse for a given height
  67. LoadABCIResponses(int64) (*tmstate.ABCIResponses, error)
  68. // LoadConsensusParams loads the consensus params for a given height
  69. LoadConsensusParams(int64) (types.ConsensusParams, error)
  70. // Save overwrites the previous state with the updated one
  71. Save(State) error
  72. // SaveABCIResponses saves ABCIResponses for a given height
  73. SaveABCIResponses(int64, *tmstate.ABCIResponses) error
  74. // SaveValidatorSet saves the validator set at a given height
  75. SaveValidatorSets(int64, int64, *types.ValidatorSet) error
  76. // Bootstrap is used for bootstrapping state when not starting from a initial height.
  77. Bootstrap(State) error
  78. // PruneStates takes the height from which to prune up to (exclusive)
  79. PruneStates(int64) error
  80. // Close closes the connection with the database
  81. Close() error
  82. }
  83. // dbStore wraps a db (github.com/tendermint/tm-db)
  84. type dbStore struct {
  85. db dbm.DB
  86. }
  87. var _ Store = (*dbStore)(nil)
  88. // NewStore creates the dbStore of the state pkg.
  89. func NewStore(db dbm.DB) Store {
  90. return dbStore{db}
  91. }
  92. // LoadState loads the State from the database.
  93. func (store dbStore) Load() (State, error) {
  94. return store.loadState(stateKey)
  95. }
  96. func (store dbStore) loadState(key []byte) (state State, err error) {
  97. buf, err := store.db.Get(key)
  98. if err != nil {
  99. return state, err
  100. }
  101. if len(buf) == 0 {
  102. return state, nil
  103. }
  104. sp := new(tmstate.State)
  105. err = proto.Unmarshal(buf, sp)
  106. if err != nil {
  107. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  108. panic(fmt.Sprintf("data has been corrupted or its spec has changed: %+v", err))
  109. }
  110. sm, err := FromProto(sp)
  111. if err != nil {
  112. return state, err
  113. }
  114. return *sm, nil
  115. }
  116. // Save persists the State, the ValidatorsInfo, and the ConsensusParamsInfo to the database.
  117. // This flushes the writes (e.g. calls SetSync).
  118. func (store dbStore) Save(state State) error {
  119. return store.save(state, stateKey)
  120. }
  121. func (store dbStore) save(state State, key []byte) error {
  122. batch := store.db.NewBatch()
  123. defer batch.Close()
  124. nextHeight := state.LastBlockHeight + 1
  125. // If first block, save validators for the block.
  126. if nextHeight == 1 {
  127. nextHeight = state.InitialHeight
  128. // This extra logic due to Tendermint validator set changes being delayed 1 block.
  129. // It may get overwritten due to InitChain validator updates.
  130. if err := store.saveValidatorsInfo(nextHeight, nextHeight, state.Validators, batch); err != nil {
  131. return err
  132. }
  133. }
  134. // Save next validators.
  135. err := store.saveValidatorsInfo(nextHeight+1, state.LastHeightValidatorsChanged, state.NextValidators, batch)
  136. if err != nil {
  137. return err
  138. }
  139. // Save next consensus params.
  140. if err := store.saveConsensusParamsInfo(nextHeight,
  141. state.LastHeightConsensusParamsChanged, state.ConsensusParams, batch); err != nil {
  142. return err
  143. }
  144. stateBz, err := state.Bytes()
  145. if err != nil {
  146. return err
  147. }
  148. if err := batch.Set(key, stateBz); err != nil {
  149. return err
  150. }
  151. return batch.WriteSync()
  152. }
  153. // BootstrapState saves a new state, used e.g. by state sync when starting from non-zero height.
  154. func (store dbStore) Bootstrap(state State) error {
  155. height := state.LastBlockHeight + 1
  156. if height == 1 {
  157. height = state.InitialHeight
  158. }
  159. batch := store.db.NewBatch()
  160. defer batch.Close()
  161. if height > 1 && !state.LastValidators.IsNilOrEmpty() {
  162. if err := store.saveValidatorsInfo(height-1, height-1, state.LastValidators, batch); err != nil {
  163. return err
  164. }
  165. }
  166. if err := store.saveValidatorsInfo(height, height, state.Validators, batch); err != nil {
  167. return err
  168. }
  169. if err := store.saveValidatorsInfo(height+1, height+1, state.NextValidators, batch); err != nil {
  170. return err
  171. }
  172. if err := store.saveConsensusParamsInfo(height,
  173. state.LastHeightConsensusParamsChanged, state.ConsensusParams, batch); err != nil {
  174. return err
  175. }
  176. stateBz, err := state.Bytes()
  177. if err != nil {
  178. return err
  179. }
  180. if err := batch.Set(stateKey, stateBz); err != nil {
  181. return err
  182. }
  183. return batch.WriteSync()
  184. }
  185. // PruneStates deletes states up to the height specified (exclusive). It is not
  186. // guaranteed to delete all states, since the last checkpointed state and states being pointed to by
  187. // e.g. `LastHeightChanged` must remain. The state at retain height must also exist.
  188. // Pruning is done in descending order.
  189. func (store dbStore) PruneStates(retainHeight int64) error {
  190. if retainHeight <= 0 {
  191. return fmt.Errorf("height %v must be greater than 0", retainHeight)
  192. }
  193. // NOTE: We need to prune consensus params first because the validator
  194. // sets have always one extra height. If validator sets were pruned first
  195. // we could get a situation where we prune up to the last validator set
  196. // yet don't have the respective consensus params at that height and thus
  197. // return an error
  198. if err := store.pruneConsensusParams(retainHeight); err != nil {
  199. return err
  200. }
  201. if err := store.pruneValidatorSets(retainHeight); err != nil {
  202. return err
  203. }
  204. if err := store.pruneABCIResponses(retainHeight); err != nil {
  205. return err
  206. }
  207. return nil
  208. }
  209. // pruneValidatorSets calls a reverse iterator from base height to retain height (exclusive), deleting
  210. // all validator sets in between. Due to the fact that most validator sets stored reference an earlier
  211. // validator set, it is likely that there will remain one validator set left after pruning.
  212. func (store dbStore) pruneValidatorSets(retainHeight int64) error {
  213. valInfo, err := loadValidatorsInfo(store.db, retainHeight)
  214. if err != nil {
  215. return fmt.Errorf("validators at height %v not found: %w", retainHeight, err)
  216. }
  217. // We will prune up to the validator set at the given "height". As we don't save validator sets every
  218. // height but only when they change or at a check point, it is likely that the validator set at the height
  219. // we prune to is empty and thus dependent on the validator set saved at a previous height. We must find
  220. // that validator set and make sure it is not pruned.
  221. lastRecordedValSetHeight := lastStoredHeightFor(retainHeight, valInfo.LastHeightChanged)
  222. lastRecordedValSet, err := loadValidatorsInfo(store.db, lastRecordedValSetHeight)
  223. if err != nil || lastRecordedValSet.ValidatorSet == nil {
  224. return fmt.Errorf("couldn't find validators at height %d (height %d was originally requested): %w",
  225. lastStoredHeightFor(retainHeight, valInfo.LastHeightChanged),
  226. retainHeight,
  227. err,
  228. )
  229. }
  230. // if this is not equal to the retain height, prune from the retain height to the height above
  231. // the last saved validator set. This way we can skip over the dependent validator set.
  232. if lastRecordedValSetHeight < retainHeight {
  233. err := store.pruneRange(
  234. validatorsKey(lastRecordedValSetHeight+1),
  235. validatorsKey(retainHeight),
  236. )
  237. if err != nil {
  238. return err
  239. }
  240. }
  241. // prune all the validators sets up to last saved validator set
  242. return store.pruneRange(
  243. validatorsKey(1),
  244. validatorsKey(lastRecordedValSetHeight),
  245. )
  246. }
  247. // pruneConsensusParams calls a reverse iterator from base height to retain height batch deleting
  248. // all consensus params in between. If the consensus params at the new base height is dependent
  249. // on a prior height then this will keep that lower height too.
  250. func (store dbStore) pruneConsensusParams(retainHeight int64) error {
  251. paramsInfo, err := store.loadConsensusParamsInfo(retainHeight)
  252. if err != nil {
  253. return fmt.Errorf("consensus params at height %v not found: %w", retainHeight, err)
  254. }
  255. // As we don't save the consensus params at every height, only when there is a consensus params change,
  256. // we must not prune (or save) the last consensus params that the consensus params info at height
  257. // is dependent on.
  258. if paramsInfo.ConsensusParams.Equal(&tmproto.ConsensusParams{}) {
  259. // sanity check that the consensus params at the last height it was changed is there
  260. lastRecordedConsensusParams, err := store.loadConsensusParamsInfo(paramsInfo.LastHeightChanged)
  261. if err != nil || lastRecordedConsensusParams.ConsensusParams.Equal(&tmproto.ConsensusParams{}) {
  262. return fmt.Errorf(
  263. "couldn't find consensus params at height %d (height %d was originally requested): %w",
  264. paramsInfo.LastHeightChanged,
  265. retainHeight,
  266. err,
  267. )
  268. }
  269. // prune the params above the height with which it last changed and below the retain height.
  270. err = store.pruneRange(
  271. consensusParamsKey(paramsInfo.LastHeightChanged+1),
  272. consensusParamsKey(retainHeight),
  273. )
  274. if err != nil {
  275. return err
  276. }
  277. }
  278. // prune all the consensus params up to either the last height the params changed or if the params
  279. // last changed at the retain height, then up to the retain height.
  280. return store.pruneRange(
  281. consensusParamsKey(1),
  282. consensusParamsKey(paramsInfo.LastHeightChanged),
  283. )
  284. }
  285. // pruneABCIResponses calls a reverse iterator from base height to retain height batch deleting
  286. // all abci responses in between
  287. func (store dbStore) pruneABCIResponses(height int64) error {
  288. return store.pruneRange(abciResponsesKey(1), abciResponsesKey(height))
  289. }
  290. // pruneRange is a generic function for deleting a range of keys in reverse order.
  291. // we keep filling up batches of at most 1000 keys, perform a deletion and continue until
  292. // we have gone through all of keys in the range. This avoids doing any writes whilst
  293. // iterating.
  294. func (store dbStore) pruneRange(start []byte, end []byte) error {
  295. var err error
  296. batch := store.db.NewBatch()
  297. defer batch.Close()
  298. end, err = store.reverseBatchDelete(batch, start, end)
  299. if err != nil {
  300. return err
  301. }
  302. // iterate until the last batch of the pruning range in which case we will perform a
  303. // write sync
  304. for !bytes.Equal(start, end) {
  305. if err := batch.Write(); err != nil {
  306. return err
  307. }
  308. if err := batch.Close(); err != nil {
  309. return err
  310. }
  311. batch = store.db.NewBatch()
  312. // fill a new batch of keys for deletion over the remainding range
  313. end, err = store.reverseBatchDelete(batch, start, end)
  314. if err != nil {
  315. return err
  316. }
  317. }
  318. return batch.WriteSync()
  319. }
  320. // reverseBatchDelete runs a reverse iterator (from end to start) filling up a batch until either
  321. // (a) the iterator reaches the start or (b) the iterator has added a 1000 keys (this avoids the
  322. // batch from growing too large)
  323. func (store dbStore) reverseBatchDelete(batch dbm.Batch, start, end []byte) ([]byte, error) {
  324. iter, err := store.db.ReverseIterator(start, end)
  325. if err != nil {
  326. return end, fmt.Errorf("iterator error: %w", err)
  327. }
  328. defer iter.Close()
  329. size := 0
  330. for ; iter.Valid(); iter.Next() {
  331. if err := batch.Delete(iter.Key()); err != nil {
  332. return end, fmt.Errorf("pruning error at key %X: %w", iter.Key(), err)
  333. }
  334. // avoid batches growing too large by capping them
  335. size++
  336. if size == 1000 {
  337. return iter.Key(), iter.Error()
  338. }
  339. }
  340. return start, iter.Error()
  341. }
  342. //------------------------------------------------------------------------
  343. // LoadABCIResponses loads the ABCIResponses for the given height from the
  344. // database. If not found, ErrNoABCIResponsesForHeight is returned.
  345. //
  346. // This is useful for recovering from crashes where we called app.Commit and
  347. // before we called s.Save(). It can also be used to produce Merkle proofs of
  348. // the result of txs.
  349. func (store dbStore) LoadABCIResponses(height int64) (*tmstate.ABCIResponses, error) {
  350. buf, err := store.db.Get(abciResponsesKey(height))
  351. if err != nil {
  352. return nil, err
  353. }
  354. if len(buf) == 0 {
  355. return nil, ErrNoABCIResponsesForHeight{height}
  356. }
  357. abciResponses := new(tmstate.ABCIResponses)
  358. err = abciResponses.Unmarshal(buf)
  359. if err != nil {
  360. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  361. panic(fmt.Sprintf("data has been corrupted or its spec has changed: %+v", err))
  362. }
  363. // TODO: ensure that buf is completely read.
  364. return abciResponses, nil
  365. }
  366. // SaveABCIResponses persists the ABCIResponses to the database.
  367. // This is useful in case we crash after app.Commit and before s.Save().
  368. // Responses are indexed by height so they can also be loaded later to produce
  369. // Merkle proofs.
  370. //
  371. // Exposed for testing.
  372. func (store dbStore) SaveABCIResponses(height int64, abciResponses *tmstate.ABCIResponses) error {
  373. return store.saveABCIResponses(height, abciResponses)
  374. }
  375. func (store dbStore) saveABCIResponses(height int64, abciResponses *tmstate.ABCIResponses) error {
  376. var dtxs []*abci.ExecTxResult
  377. // strip nil values,
  378. for _, tx := range abciResponses.FinalizeBlock.TxResults {
  379. if tx != nil {
  380. dtxs = append(dtxs, tx)
  381. }
  382. }
  383. abciResponses.FinalizeBlock.TxResults = dtxs
  384. bz, err := abciResponses.Marshal()
  385. if err != nil {
  386. return err
  387. }
  388. return store.db.SetSync(abciResponsesKey(height), bz)
  389. }
  390. // SaveValidatorSets is used to save the validator set over multiple heights.
  391. // It is exposed so that a backfill operation during state sync can populate
  392. // the store with the necessary amount of validator sets to verify any evidence
  393. // it may encounter.
  394. func (store dbStore) SaveValidatorSets(lowerHeight, upperHeight int64, vals *types.ValidatorSet) error {
  395. batch := store.db.NewBatch()
  396. defer batch.Close()
  397. // batch together all the validator sets from lowerHeight to upperHeight
  398. for height := lowerHeight; height <= upperHeight; height++ {
  399. if err := store.saveValidatorsInfo(height, lowerHeight, vals, batch); err != nil {
  400. return err
  401. }
  402. }
  403. return batch.WriteSync()
  404. }
  405. //-----------------------------------------------------------------------------
  406. // LoadValidators loads the ValidatorSet for a given height.
  407. // Returns ErrNoValSetForHeight if the validator set can't be found for this height.
  408. func (store dbStore) LoadValidators(height int64) (*types.ValidatorSet, error) {
  409. valInfo, err := loadValidatorsInfo(store.db, height)
  410. if err != nil {
  411. return nil, ErrNoValSetForHeight{Height: height, Err: err}
  412. }
  413. if valInfo.ValidatorSet == nil {
  414. lastStoredHeight := lastStoredHeightFor(height, valInfo.LastHeightChanged)
  415. valInfo2, err := loadValidatorsInfo(store.db, lastStoredHeight)
  416. if err != nil || valInfo2.ValidatorSet == nil {
  417. return nil,
  418. fmt.Errorf("couldn't find validators at height %d (height %d was originally requested): %w",
  419. lastStoredHeight,
  420. height,
  421. err,
  422. )
  423. }
  424. vs, err := types.ValidatorSetFromProto(valInfo2.ValidatorSet)
  425. if err != nil {
  426. return nil, err
  427. }
  428. h, err := tmmath.SafeConvertInt32(height - lastStoredHeight)
  429. if err != nil {
  430. return nil, err
  431. }
  432. vs.IncrementProposerPriority(h) // mutate
  433. vi2, err := vs.ToProto()
  434. if err != nil {
  435. return nil, err
  436. }
  437. valInfo2.ValidatorSet = vi2
  438. valInfo = valInfo2
  439. }
  440. vip, err := types.ValidatorSetFromProto(valInfo.ValidatorSet)
  441. if err != nil {
  442. return nil, err
  443. }
  444. return vip, nil
  445. }
  446. func lastStoredHeightFor(height, lastHeightChanged int64) int64 {
  447. checkpointHeight := height - height%valSetCheckpointInterval
  448. return tmmath.MaxInt64(checkpointHeight, lastHeightChanged)
  449. }
  450. // CONTRACT: Returned ValidatorsInfo can be mutated.
  451. func loadValidatorsInfo(db dbm.DB, height int64) (*tmstate.ValidatorsInfo, error) {
  452. buf, err := db.Get(validatorsKey(height))
  453. if err != nil {
  454. return nil, err
  455. }
  456. if len(buf) == 0 {
  457. return nil, errors.New("value retrieved from db is empty")
  458. }
  459. v := new(tmstate.ValidatorsInfo)
  460. err = v.Unmarshal(buf)
  461. if err != nil {
  462. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  463. panic(fmt.Sprintf("data has been corrupted or its spec has changed: %+v", err))
  464. }
  465. // TODO: ensure that buf is completely read.
  466. return v, nil
  467. }
  468. // saveValidatorsInfo persists the validator set.
  469. //
  470. // `height` is the effective height for which the validator is responsible for
  471. // signing. It should be called from s.Save(), right before the state itself is
  472. // persisted.
  473. func (store dbStore) saveValidatorsInfo(
  474. height, lastHeightChanged int64,
  475. valSet *types.ValidatorSet,
  476. batch dbm.Batch,
  477. ) error {
  478. if lastHeightChanged > height {
  479. return errors.New("lastHeightChanged cannot be greater than ValidatorsInfo height")
  480. }
  481. valInfo := &tmstate.ValidatorsInfo{
  482. LastHeightChanged: lastHeightChanged,
  483. }
  484. // Only persist validator set if it was updated or checkpoint height (see
  485. // valSetCheckpointInterval) is reached.
  486. if height == lastHeightChanged || height%valSetCheckpointInterval == 0 {
  487. pv, err := valSet.ToProto()
  488. if err != nil {
  489. return err
  490. }
  491. valInfo.ValidatorSet = pv
  492. }
  493. bz, err := valInfo.Marshal()
  494. if err != nil {
  495. return err
  496. }
  497. return batch.Set(validatorsKey(height), bz)
  498. }
  499. //-----------------------------------------------------------------------------
  500. // ConsensusParamsInfo represents the latest consensus params, or the last height it changed
  501. // Allocate empty Consensus params at compile time to avoid multiple allocations during runtime
  502. var (
  503. empty = types.ConsensusParams{}
  504. emptypb = tmproto.ConsensusParams{}
  505. )
  506. // LoadConsensusParams loads the ConsensusParams for a given height.
  507. func (store dbStore) LoadConsensusParams(height int64) (types.ConsensusParams, error) {
  508. paramsInfo, err := store.loadConsensusParamsInfo(height)
  509. if err != nil {
  510. return empty, fmt.Errorf("could not find consensus params for height #%d: %w", height, err)
  511. }
  512. if paramsInfo.ConsensusParams.Equal(&emptypb) {
  513. paramsInfo2, err := store.loadConsensusParamsInfo(paramsInfo.LastHeightChanged)
  514. if err != nil {
  515. return empty, fmt.Errorf(
  516. "couldn't find consensus params at height %d (height %d was originally requested): %w",
  517. paramsInfo.LastHeightChanged,
  518. height,
  519. err,
  520. )
  521. }
  522. paramsInfo = paramsInfo2
  523. }
  524. return types.ConsensusParamsFromProto(paramsInfo.ConsensusParams), nil
  525. }
  526. func (store dbStore) loadConsensusParamsInfo(height int64) (*tmstate.ConsensusParamsInfo, error) {
  527. buf, err := store.db.Get(consensusParamsKey(height))
  528. if err != nil {
  529. return nil, err
  530. }
  531. if len(buf) == 0 {
  532. return nil, errors.New("value retrieved from db is empty")
  533. }
  534. paramsInfo := new(tmstate.ConsensusParamsInfo)
  535. if err = paramsInfo.Unmarshal(buf); err != nil {
  536. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  537. panic(fmt.Sprintf(`data has been corrupted or its spec has changed: %+v`, err))
  538. }
  539. // TODO: ensure that buf is completely read.
  540. return paramsInfo, nil
  541. }
  542. // saveConsensusParamsInfo persists the consensus params for the next block to disk.
  543. // It should be called from s.Save(), right before the state itself is persisted.
  544. // If the consensus params did not change after processing the latest block,
  545. // only the last height for which they changed is persisted.
  546. func (store dbStore) saveConsensusParamsInfo(
  547. nextHeight, changeHeight int64,
  548. params types.ConsensusParams,
  549. batch dbm.Batch,
  550. ) error {
  551. paramsInfo := &tmstate.ConsensusParamsInfo{
  552. LastHeightChanged: changeHeight,
  553. }
  554. if changeHeight == nextHeight {
  555. paramsInfo.ConsensusParams = params.ToProto()
  556. }
  557. bz, err := paramsInfo.Marshal()
  558. if err != nil {
  559. return err
  560. }
  561. return batch.Set(consensusParamsKey(nextHeight), bz)
  562. }
  563. func (store dbStore) Close() error {
  564. return store.db.Close()
  565. }