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.

437 lines
14 KiB

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