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.

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