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.

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