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.

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