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.

510 lines
14 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
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package state
  2. import (
  3. "fmt"
  4. "github.com/gogo/protobuf/proto"
  5. dbm "github.com/tendermint/tm-db"
  6. abci "github.com/tendermint/tendermint/abci/types"
  7. tmmath "github.com/tendermint/tendermint/libs/math"
  8. tmos "github.com/tendermint/tendermint/libs/os"
  9. tmstate "github.com/tendermint/tendermint/proto/tendermint/state"
  10. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  11. "github.com/tendermint/tendermint/types"
  12. )
  13. const (
  14. // persist validators every valSetCheckpointInterval blocks to avoid
  15. // LoadValidators taking too much time.
  16. // https://github.com/tendermint/tendermint/pull/3438
  17. // 100000 results in ~ 100ms to get 100 validators (see BenchmarkLoadValidators)
  18. valSetCheckpointInterval = 100000
  19. )
  20. //------------------------------------------------------------------------
  21. func calcValidatorsKey(height int64) []byte {
  22. return []byte(fmt.Sprintf("validatorsKey:%v", height))
  23. }
  24. func calcConsensusParamsKey(height int64) []byte {
  25. return []byte(fmt.Sprintf("consensusParamsKey:%v", height))
  26. }
  27. func calcABCIResponsesKey(height int64) []byte {
  28. return []byte(fmt.Sprintf("abciResponsesKey:%v", height))
  29. }
  30. // LoadStateFromDBOrGenesisFile loads the most recent state from the database,
  31. // or creates a new one from the given genesisFilePath and persists the result
  32. // to the database.
  33. func LoadStateFromDBOrGenesisFile(stateDB dbm.DB, genesisFilePath string) (State, error) {
  34. state := LoadState(stateDB)
  35. if state.IsEmpty() {
  36. var err error
  37. state, err = MakeGenesisStateFromFile(genesisFilePath)
  38. if err != nil {
  39. return state, err
  40. }
  41. SaveState(stateDB, state)
  42. }
  43. return state, nil
  44. }
  45. // LoadStateFromDBOrGenesisDoc loads the most recent state from the database,
  46. // or creates a new one from the given genesisDoc and persists the result
  47. // to the database.
  48. func LoadStateFromDBOrGenesisDoc(stateDB dbm.DB, genesisDoc *types.GenesisDoc) (State, error) {
  49. state := LoadState(stateDB)
  50. if state.IsEmpty() {
  51. var err error
  52. state, err = MakeGenesisState(genesisDoc)
  53. if err != nil {
  54. return state, err
  55. }
  56. SaveState(stateDB, state)
  57. }
  58. return state, nil
  59. }
  60. // LoadState loads the State from the database.
  61. func LoadState(db dbm.DB) State {
  62. return loadState(db, stateKey)
  63. }
  64. func loadState(db dbm.DB, key []byte) (state State) {
  65. buf, err := db.Get(key)
  66. if err != nil {
  67. panic(err)
  68. }
  69. if len(buf) == 0 {
  70. return state
  71. }
  72. sp := new(tmstate.State)
  73. err = proto.Unmarshal(buf, sp)
  74. if err != nil {
  75. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  76. tmos.Exit(fmt.Sprintf(`LoadState: Data has been corrupted or its spec has changed:
  77. %v\n`, err))
  78. }
  79. sm, err := StateFromProto(sp)
  80. if err != nil {
  81. panic(err)
  82. }
  83. return *sm
  84. }
  85. // SaveState persists the State, the ValidatorsInfo, and the ConsensusParamsInfo to the database.
  86. // This flushes the writes (e.g. calls SetSync).
  87. func SaveState(db dbm.DB, state State) {
  88. saveState(db, state, stateKey)
  89. }
  90. func saveState(db dbm.DB, state State, key []byte) {
  91. nextHeight := state.LastBlockHeight + 1
  92. // If first block, save validators for block 1.
  93. if nextHeight == 1 {
  94. // This extra logic due to Tendermint validator set changes being delayed 1 block.
  95. // It may get overwritten due to InitChain validator updates.
  96. lastHeightVoteChanged := int64(1)
  97. saveValidatorsInfo(db, nextHeight, lastHeightVoteChanged, state.Validators)
  98. }
  99. // Save next validators.
  100. saveValidatorsInfo(db, nextHeight+1, state.LastHeightValidatorsChanged, state.NextValidators)
  101. // Save next consensus params.
  102. saveConsensusParamsInfo(db, nextHeight, state.LastHeightConsensusParamsChanged, state.ConsensusParams)
  103. err := db.SetSync(key, state.Bytes())
  104. if err != nil {
  105. panic(err)
  106. }
  107. }
  108. // BootstrapState saves a new state, used e.g. by state sync when starting from non-zero height.
  109. func BootstrapState(db dbm.DB, state State) error {
  110. height := state.LastBlockHeight
  111. saveValidatorsInfo(db, height, height, state.LastValidators)
  112. saveValidatorsInfo(db, height+1, height+1, state.Validators)
  113. saveValidatorsInfo(db, height+2, height+2, state.NextValidators)
  114. saveConsensusParamsInfo(db, height+1, height+1, state.ConsensusParams)
  115. return db.SetSync(stateKey, state.Bytes())
  116. }
  117. // PruneStates deletes states between the given heights (including from, excluding to). It is not
  118. // guaranteed to delete all states, since the last checkpointed state and states being pointed to by
  119. // e.g. `LastHeightChanged` must remain. The state at to must also exist.
  120. //
  121. // The from parameter is necessary since we can't do a key scan in a performant way due to the key
  122. // encoding not preserving ordering: https://github.com/tendermint/tendermint/issues/4567
  123. // This will cause some old states to be left behind when doing incremental partial prunes,
  124. // specifically older checkpoints and LastHeightChanged targets.
  125. func PruneStates(db dbm.DB, from int64, to int64) error {
  126. if from <= 0 || to <= 0 {
  127. return fmt.Errorf("from height %v and to height %v must be greater than 0", from, to)
  128. }
  129. if from >= to {
  130. return fmt.Errorf("from height %v must be lower than to height %v", from, to)
  131. }
  132. valInfo := loadValidatorsInfo(db, to)
  133. if valInfo == nil {
  134. return fmt.Errorf("validators at height %v not found", to)
  135. }
  136. paramsInfo := loadConsensusParamsInfo(db, to)
  137. if paramsInfo == nil {
  138. return fmt.Errorf("consensus params at height %v not found", to)
  139. }
  140. keepVals := make(map[int64]bool)
  141. if valInfo.ValidatorSet == nil {
  142. keepVals[valInfo.LastHeightChanged] = true
  143. keepVals[lastStoredHeightFor(to, valInfo.LastHeightChanged)] = true // keep last checkpoint too
  144. }
  145. keepParams := make(map[int64]bool)
  146. if paramsInfo.ConsensusParams.Equal(&tmproto.ConsensusParams{}) {
  147. keepParams[paramsInfo.LastHeightChanged] = true
  148. }
  149. batch := db.NewBatch()
  150. defer batch.Close()
  151. pruned := uint64(0)
  152. var err error
  153. // We have to delete in reverse order, to avoid deleting previous heights that have validator
  154. // sets and consensus params that we may need to retrieve.
  155. for h := to - 1; h >= from; h-- {
  156. // For heights we keep, we must make sure they have the full validator set or consensus
  157. // params, otherwise they will panic if they're retrieved directly (instead of
  158. // indirectly via a LastHeightChanged pointer).
  159. if keepVals[h] {
  160. v := loadValidatorsInfo(db, h)
  161. if v.ValidatorSet == nil {
  162. vip, err := LoadValidators(db, h)
  163. if err != nil {
  164. return err
  165. }
  166. pvi, err := vip.ToProto()
  167. if err != nil {
  168. return err
  169. }
  170. v.ValidatorSet = pvi
  171. v.LastHeightChanged = h
  172. bz, err := v.Marshal()
  173. if err != nil {
  174. return err
  175. }
  176. err = batch.Set(calcValidatorsKey(h), bz)
  177. if err != nil {
  178. return err
  179. }
  180. }
  181. } else {
  182. err = batch.Delete(calcValidatorsKey(h))
  183. if err != nil {
  184. return err
  185. }
  186. }
  187. if keepParams[h] {
  188. p := loadConsensusParamsInfo(db, h)
  189. if p.ConsensusParams.Equal(&tmproto.ConsensusParams{}) {
  190. p.ConsensusParams, err = LoadConsensusParams(db, h)
  191. if err != nil {
  192. return err
  193. }
  194. p.LastHeightChanged = h
  195. bz, err := p.Marshal()
  196. if err != nil {
  197. return err
  198. }
  199. err = batch.Set(calcConsensusParamsKey(h), bz)
  200. if err != nil {
  201. return err
  202. }
  203. }
  204. } else {
  205. err = batch.Delete(calcConsensusParamsKey(h))
  206. if err != nil {
  207. return err
  208. }
  209. }
  210. err = batch.Delete(calcABCIResponsesKey(h))
  211. if err != nil {
  212. return err
  213. }
  214. pruned++
  215. // avoid batches growing too large by flushing to database regularly
  216. if pruned%1000 == 0 && pruned > 0 {
  217. err := batch.Write()
  218. if err != nil {
  219. return err
  220. }
  221. batch.Close()
  222. batch = db.NewBatch()
  223. defer batch.Close()
  224. }
  225. }
  226. err = batch.WriteSync()
  227. if err != nil {
  228. return err
  229. }
  230. return nil
  231. }
  232. //------------------------------------------------------------------------
  233. // ABCIResponsesResultsHash returns the root hash of a Merkle tree of
  234. // ResponseDeliverTx responses (see ABCIResults.Hash)
  235. //
  236. // See merkle.SimpleHashFromByteSlices
  237. func ABCIResponsesResultsHash(ar *tmstate.ABCIResponses) []byte {
  238. return types.NewResults(ar.DeliverTxs).Hash()
  239. }
  240. // LoadABCIResponses loads the ABCIResponses for the given height from the
  241. // database. If not found, ErrNoABCIResponsesForHeight is returned.
  242. //
  243. // This is useful for recovering from crashes where we called app.Commit and
  244. // before we called s.Save(). It can also be used to produce Merkle proofs of
  245. // the result of txs.
  246. func LoadABCIResponses(db dbm.DB, height int64) (*tmstate.ABCIResponses, error) {
  247. buf, err := db.Get(calcABCIResponsesKey(height))
  248. if err != nil {
  249. return nil, err
  250. }
  251. if len(buf) == 0 {
  252. return nil, ErrNoABCIResponsesForHeight{height}
  253. }
  254. abciResponses := new(tmstate.ABCIResponses)
  255. err = abciResponses.Unmarshal(buf)
  256. if err != nil {
  257. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  258. tmos.Exit(fmt.Sprintf(`LoadABCIResponses: Data has been corrupted or its spec has
  259. changed: %v\n`, err))
  260. }
  261. // TODO: ensure that buf is completely read.
  262. return abciResponses, nil
  263. }
  264. // SaveABCIResponses persists the ABCIResponses to the database.
  265. // This is useful in case we crash after app.Commit and before s.Save().
  266. // Responses are indexed by height so they can also be loaded later to produce
  267. // Merkle proofs.
  268. //
  269. // Exposed for testing.
  270. func SaveABCIResponses(db dbm.DB, height int64, abciResponses *tmstate.ABCIResponses) {
  271. var dtxs []*abci.ResponseDeliverTx
  272. //strip nil values,
  273. for _, tx := range abciResponses.DeliverTxs {
  274. if tx != nil {
  275. dtxs = append(dtxs, tx)
  276. }
  277. }
  278. abciResponses.DeliverTxs = dtxs
  279. bz, err := abciResponses.Marshal()
  280. if err != nil {
  281. panic(err)
  282. }
  283. err = db.SetSync(calcABCIResponsesKey(height), bz)
  284. if err != nil {
  285. panic(err)
  286. }
  287. }
  288. //-----------------------------------------------------------------------------
  289. // LoadValidators loads the ValidatorSet for a given height.
  290. // Returns ErrNoValSetForHeight if the validator set can't be found for this height.
  291. func LoadValidators(db dbm.DB, height int64) (*types.ValidatorSet, error) {
  292. valInfo := loadValidatorsInfo(db, height)
  293. if valInfo == nil {
  294. return nil, ErrNoValSetForHeight{height}
  295. }
  296. if valInfo.ValidatorSet == nil {
  297. lastStoredHeight := lastStoredHeightFor(height, valInfo.LastHeightChanged)
  298. valInfo2 := loadValidatorsInfo(db, lastStoredHeight)
  299. if valInfo2 == nil || valInfo2.ValidatorSet == nil {
  300. panic(
  301. fmt.Sprintf("Couldn't find validators at height %d (height %d was originally requested)",
  302. lastStoredHeight,
  303. height,
  304. ),
  305. )
  306. }
  307. vs, err := types.ValidatorSetFromProto(valInfo2.ValidatorSet)
  308. if err != nil {
  309. return nil, err
  310. }
  311. vs.IncrementProposerPriority(tmmath.SafeConvertInt32(height - lastStoredHeight)) // mutate
  312. vi2, err := vs.ToProto()
  313. if err != nil {
  314. return nil, err
  315. }
  316. valInfo2.ValidatorSet = vi2
  317. valInfo = valInfo2
  318. }
  319. vip, err := types.ValidatorSetFromProto(valInfo.ValidatorSet)
  320. if err != nil {
  321. return nil, err
  322. }
  323. return vip, nil
  324. }
  325. func lastStoredHeightFor(height, lastHeightChanged int64) int64 {
  326. checkpointHeight := height - height%valSetCheckpointInterval
  327. return tmmath.MaxInt64(checkpointHeight, lastHeightChanged)
  328. }
  329. // CONTRACT: Returned ValidatorsInfo can be mutated.
  330. func loadValidatorsInfo(db dbm.DB, height int64) *tmstate.ValidatorsInfo {
  331. buf, err := db.Get(calcValidatorsKey(height))
  332. if err != nil {
  333. panic(err)
  334. }
  335. if len(buf) == 0 {
  336. return nil
  337. }
  338. v := new(tmstate.ValidatorsInfo)
  339. err = v.Unmarshal(buf)
  340. if err != nil {
  341. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  342. tmos.Exit(fmt.Sprintf(`LoadValidators: Data has been corrupted or its spec has changed:
  343. %v\n`, err))
  344. }
  345. // TODO: ensure that buf is completely read.
  346. return v
  347. }
  348. // saveValidatorsInfo persists the validator set.
  349. //
  350. // `height` is the effective height for which the validator is responsible for
  351. // signing. It should be called from s.Save(), right before the state itself is
  352. // persisted.
  353. func saveValidatorsInfo(db dbm.DB, height, lastHeightChanged int64, valSet *types.ValidatorSet) {
  354. if lastHeightChanged > height {
  355. panic("LastHeightChanged cannot be greater than ValidatorsInfo height")
  356. }
  357. valInfo := &tmstate.ValidatorsInfo{
  358. LastHeightChanged: lastHeightChanged,
  359. }
  360. // Only persist validator set if it was updated or checkpoint height (see
  361. // valSetCheckpointInterval) is reached.
  362. if height == lastHeightChanged || height%valSetCheckpointInterval == 0 {
  363. pv, err := valSet.ToProto()
  364. if err != nil {
  365. panic(err)
  366. }
  367. valInfo.ValidatorSet = pv
  368. }
  369. bz, err := valInfo.Marshal()
  370. if err != nil {
  371. panic(err)
  372. }
  373. err = db.Set(calcValidatorsKey(height), bz)
  374. if err != nil {
  375. panic(err)
  376. }
  377. }
  378. //-----------------------------------------------------------------------------
  379. // ConsensusParamsInfo represents the latest consensus params, or the last height it changed
  380. // LoadConsensusParams loads the ConsensusParams for a given height.
  381. func LoadConsensusParams(db dbm.DB, height int64) (tmproto.ConsensusParams, error) {
  382. empty := tmproto.ConsensusParams{}
  383. paramsInfo := loadConsensusParamsInfo(db, height)
  384. if paramsInfo == nil {
  385. return empty, ErrNoConsensusParamsForHeight{height}
  386. }
  387. if paramsInfo.ConsensusParams.Equal(&empty) {
  388. paramsInfo2 := loadConsensusParamsInfo(db, paramsInfo.LastHeightChanged)
  389. if paramsInfo2 == nil {
  390. panic(
  391. fmt.Sprintf(
  392. "Couldn't find consensus params at height %d as last changed from height %d",
  393. paramsInfo.LastHeightChanged,
  394. height,
  395. ),
  396. )
  397. }
  398. paramsInfo = paramsInfo2
  399. }
  400. return paramsInfo.ConsensusParams, nil
  401. }
  402. func loadConsensusParamsInfo(db dbm.DB, height int64) *tmstate.ConsensusParamsInfo {
  403. buf, err := db.Get(calcConsensusParamsKey(height))
  404. if err != nil {
  405. panic(err)
  406. }
  407. if len(buf) == 0 {
  408. return nil
  409. }
  410. paramsInfo := new(tmstate.ConsensusParamsInfo)
  411. if err = paramsInfo.Unmarshal(buf); err != nil {
  412. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  413. tmos.Exit(fmt.Sprintf(`LoadConsensusParams: Data has been corrupted or its spec has changed:
  414. %v\n`, err))
  415. }
  416. // TODO: ensure that buf is completely read.
  417. return paramsInfo
  418. }
  419. // saveConsensusParamsInfo persists the consensus params for the next block to disk.
  420. // It should be called from s.Save(), right before the state itself is persisted.
  421. // If the consensus params did not change after processing the latest block,
  422. // only the last height for which they changed is persisted.
  423. func saveConsensusParamsInfo(db dbm.DB, nextHeight, changeHeight int64, params tmproto.ConsensusParams) {
  424. paramsInfo := &tmstate.ConsensusParamsInfo{
  425. LastHeightChanged: changeHeight,
  426. }
  427. if changeHeight == nextHeight {
  428. paramsInfo.ConsensusParams = params
  429. }
  430. bz, err := paramsInfo.Marshal()
  431. if err != nil {
  432. panic(err)
  433. }
  434. err = db.Set(calcConsensusParamsKey(nextHeight), bz)
  435. if err != nil {
  436. panic(err)
  437. }
  438. }