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.

481 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>
4 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>
4 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>
4 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>
4 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>
4 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>
4 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>
4 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/state"
  10. tmproto "github.com/tendermint/tendermint/proto/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. //------------------------------------------------------------------------
  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. batch.Set(calcValidatorsKey(h), bz)
  178. }
  179. } else {
  180. batch.Delete(calcValidatorsKey(h))
  181. }
  182. if keepParams[h] {
  183. p := loadConsensusParamsInfo(db, h)
  184. if p.ConsensusParams.Equal(&tmproto.ConsensusParams{}) {
  185. p.ConsensusParams, err = LoadConsensusParams(db, h)
  186. if err != nil {
  187. return err
  188. }
  189. p.LastHeightChanged = h
  190. bz, err := p.Marshal()
  191. if err != nil {
  192. return err
  193. }
  194. batch.Set(calcConsensusParamsKey(h), bz)
  195. }
  196. } else {
  197. batch.Delete(calcConsensusParamsKey(h))
  198. }
  199. batch.Delete(calcABCIResponsesKey(h))
  200. pruned++
  201. // avoid batches growing too large by flushing to database regularly
  202. if pruned%1000 == 0 && pruned > 0 {
  203. err := batch.Write()
  204. if err != nil {
  205. return err
  206. }
  207. batch.Close()
  208. batch = db.NewBatch()
  209. defer batch.Close()
  210. }
  211. }
  212. err = batch.WriteSync()
  213. if err != nil {
  214. return err
  215. }
  216. return nil
  217. }
  218. // ABCIResponsesResultsHash returns the merkle hash of the deliverTxs within ABCIResponses
  219. func ABCIResponsesResultsHash(ar tmstate.ABCIResponses) []byte {
  220. results := types.NewResults(ar.DeliverTxs)
  221. return results.Hash()
  222. }
  223. // LoadABCIResponses loads the ABCIResponses for the given height from the database.
  224. // This is useful for recovering from crashes where we called app.Commit and before we called
  225. // s.Save(). It can also be used to produce Merkle proofs of the result of txs.
  226. func LoadABCIResponses(db dbm.DB, height int64) (*tmstate.ABCIResponses, error) {
  227. buf, err := db.Get(calcABCIResponsesKey(height))
  228. if err != nil {
  229. return nil, err
  230. }
  231. if len(buf) == 0 {
  232. return nil, ErrNoABCIResponsesForHeight{height}
  233. }
  234. abciResponses := new(tmstate.ABCIResponses)
  235. err = abciResponses.Unmarshal(buf)
  236. if err != nil {
  237. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  238. tmos.Exit(fmt.Sprintf(`LoadABCIResponses: Data has been corrupted or its spec has
  239. changed: %v\n`, err))
  240. }
  241. // TODO: ensure that buf is completely read.
  242. return abciResponses, nil
  243. }
  244. // SaveABCIResponses persists the ABCIResponses to the database.
  245. // This is useful in case we crash after app.Commit and before s.Save().
  246. // Responses are indexed by height so they can also be loaded later to produce
  247. // Merkle proofs.
  248. //
  249. // Exposed for testing.
  250. func SaveABCIResponses(db dbm.DB, height int64, abciResponses *tmstate.ABCIResponses) {
  251. var dtxs []*abci.ResponseDeliverTx
  252. //strip nil values,
  253. for _, tx := range abciResponses.DeliverTxs {
  254. if tx != nil {
  255. dtxs = append(dtxs, tx)
  256. }
  257. }
  258. abciResponses.DeliverTxs = dtxs
  259. bz, err := abciResponses.Marshal()
  260. if err != nil {
  261. panic(err)
  262. }
  263. db.SetSync(calcABCIResponsesKey(height), bz)
  264. }
  265. //-----------------------------------------------------------------------------
  266. // LoadValidators loads the ValidatorSet for a given height.
  267. // Returns ErrNoValSetForHeight if the validator set can't be found for this height.
  268. func LoadValidators(db dbm.DB, height int64) (*types.ValidatorSet, error) {
  269. valInfo := loadValidatorsInfo(db, height)
  270. if valInfo == nil {
  271. return nil, ErrNoValSetForHeight{height}
  272. }
  273. if valInfo.ValidatorSet == nil {
  274. lastStoredHeight := lastStoredHeightFor(height, valInfo.LastHeightChanged)
  275. valInfo2 := loadValidatorsInfo(db, lastStoredHeight)
  276. if valInfo2 == nil || valInfo2.ValidatorSet == nil {
  277. panic(
  278. fmt.Sprintf("Couldn't find validators at height %d (height %d was originally requested)",
  279. lastStoredHeight,
  280. height,
  281. ),
  282. )
  283. }
  284. vs, err := types.ValidatorSetFromProto(valInfo2.ValidatorSet)
  285. if err != nil {
  286. return nil, err
  287. }
  288. vs.IncrementProposerPriority(tmmath.SafeConvertInt32(height - lastStoredHeight)) // mutate
  289. vi2, err := vs.ToProto()
  290. if err != nil {
  291. return nil, err
  292. }
  293. valInfo2.ValidatorSet = vi2
  294. valInfo = valInfo2
  295. }
  296. vip, err := types.ValidatorSetFromProto(valInfo.ValidatorSet)
  297. if err != nil {
  298. return nil, err
  299. }
  300. return vip, nil
  301. }
  302. func lastStoredHeightFor(height, lastHeightChanged int64) int64 {
  303. checkpointHeight := height - height%valSetCheckpointInterval
  304. return tmmath.MaxInt64(checkpointHeight, lastHeightChanged)
  305. }
  306. // CONTRACT: Returned ValidatorsInfo can be mutated.
  307. func loadValidatorsInfo(db dbm.DB, height int64) *tmstate.ValidatorsInfo {
  308. buf, err := db.Get(calcValidatorsKey(height))
  309. if err != nil {
  310. panic(err)
  311. }
  312. if len(buf) == 0 {
  313. return nil
  314. }
  315. v := new(tmstate.ValidatorsInfo)
  316. err = v.Unmarshal(buf)
  317. if err != nil {
  318. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  319. tmos.Exit(fmt.Sprintf(`LoadValidators: Data has been corrupted or its spec has changed:
  320. %v\n`, err))
  321. }
  322. // TODO: ensure that buf is completely read.
  323. return v
  324. }
  325. // saveValidatorsInfo persists the validator set.
  326. //
  327. // `height` is the effective height for which the validator is responsible for
  328. // signing. It should be called from s.Save(), right before the state itself is
  329. // persisted.
  330. func saveValidatorsInfo(db dbm.DB, height, lastHeightChanged int64, valSet *types.ValidatorSet) {
  331. if lastHeightChanged > height {
  332. panic("LastHeightChanged cannot be greater than ValidatorsInfo height")
  333. }
  334. valInfo := &tmstate.ValidatorsInfo{
  335. LastHeightChanged: lastHeightChanged,
  336. }
  337. // Only persist validator set if it was updated or checkpoint height (see
  338. // valSetCheckpointInterval) is reached.
  339. if height == lastHeightChanged || height%valSetCheckpointInterval == 0 {
  340. pv, err := valSet.ToProto()
  341. if err != nil {
  342. panic(err)
  343. }
  344. valInfo.ValidatorSet = pv
  345. }
  346. bz, err := valInfo.Marshal()
  347. if err != nil {
  348. panic(err)
  349. }
  350. db.Set(calcValidatorsKey(height), bz)
  351. }
  352. //-----------------------------------------------------------------------------
  353. // ConsensusParamsInfo represents the latest consensus params, or the last height it changed
  354. // LoadConsensusParams loads the ConsensusParams for a given height.
  355. func LoadConsensusParams(db dbm.DB, height int64) (tmproto.ConsensusParams, error) {
  356. empty := tmproto.ConsensusParams{}
  357. paramsInfo := loadConsensusParamsInfo(db, height)
  358. if paramsInfo == nil {
  359. return empty, ErrNoConsensusParamsForHeight{height}
  360. }
  361. if paramsInfo.ConsensusParams.Equal(&empty) {
  362. paramsInfo2 := loadConsensusParamsInfo(db, paramsInfo.LastHeightChanged)
  363. if paramsInfo2 == nil {
  364. panic(
  365. fmt.Sprintf(
  366. "Couldn't find consensus params at height %d as last changed from height %d",
  367. paramsInfo.LastHeightChanged,
  368. height,
  369. ),
  370. )
  371. }
  372. paramsInfo = paramsInfo2
  373. }
  374. return paramsInfo.ConsensusParams, nil
  375. }
  376. func loadConsensusParamsInfo(db dbm.DB, height int64) *tmstate.ConsensusParamsInfo {
  377. buf, err := db.Get(calcConsensusParamsKey(height))
  378. if err != nil {
  379. panic(err)
  380. }
  381. if len(buf) == 0 {
  382. return nil
  383. }
  384. paramsInfo := new(tmstate.ConsensusParamsInfo)
  385. if err = paramsInfo.Unmarshal(buf); err != nil {
  386. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  387. tmos.Exit(fmt.Sprintf(`LoadConsensusParams: Data has been corrupted or its spec has changed:
  388. %v\n`, err))
  389. }
  390. // TODO: ensure that buf is completely read.
  391. return paramsInfo
  392. }
  393. // saveConsensusParamsInfo persists the consensus params for the next block to disk.
  394. // It should be called from s.Save(), right before the state itself is persisted.
  395. // If the consensus params did not change after processing the latest block,
  396. // only the last height for which they changed is persisted.
  397. func saveConsensusParamsInfo(db dbm.DB, nextHeight, changeHeight int64, params tmproto.ConsensusParams) {
  398. paramsInfo := &tmstate.ConsensusParamsInfo{
  399. LastHeightChanged: changeHeight,
  400. }
  401. if changeHeight == nextHeight {
  402. paramsInfo.ConsensusParams = params
  403. }
  404. bz, err := paramsInfo.Marshal()
  405. if err != nil {
  406. panic(err)
  407. }
  408. db.Set(calcConsensusParamsKey(nextHeight), bz)
  409. }