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.

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