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.

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