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.

282 lines
8.9 KiB

  1. package state
  2. import (
  3. "bytes"
  4. "fmt"
  5. abci "github.com/tendermint/abci/types"
  6. wire "github.com/tendermint/go-wire"
  7. "github.com/tendermint/tendermint/types"
  8. cmn "github.com/tendermint/tmlibs/common"
  9. dbm "github.com/tendermint/tmlibs/db"
  10. )
  11. //------------------------------------------------------------------------
  12. func calcValidatorsKey(height int64) []byte {
  13. return []byte(cmn.Fmt("validatorsKey:%v", height))
  14. }
  15. func calcConsensusParamsKey(height int64) []byte {
  16. return []byte(cmn.Fmt("consensusParamsKey:%v", height))
  17. }
  18. func calcABCIResponsesKey(height int64) []byte {
  19. return []byte(cmn.Fmt("abciResponsesKey:%v", height))
  20. }
  21. // LoadStateFromDBOrGenesisFile loads the most recent state from the database,
  22. // or creates a new one from the given genesisFilePath and persists the result
  23. // to the database.
  24. func LoadStateFromDBOrGenesisFile(stateDB dbm.DB, genesisFilePath string) (State, error) {
  25. state := LoadState(stateDB)
  26. if state.IsEmpty() {
  27. var err error
  28. state, err = MakeGenesisStateFromFile(genesisFilePath)
  29. if err != nil {
  30. return state, err
  31. }
  32. SaveState(stateDB, state)
  33. }
  34. return state, nil
  35. }
  36. // LoadStateFromDBOrGenesisDoc loads the most recent state from the database,
  37. // or creates a new one from the given genesisDoc and persists the result
  38. // to the database.
  39. func LoadStateFromDBOrGenesisDoc(stateDB dbm.DB, genesisDoc *types.GenesisDoc) (State, error) {
  40. state := LoadState(stateDB)
  41. if state.IsEmpty() {
  42. var err error
  43. state, err = MakeGenesisState(genesisDoc)
  44. if err != nil {
  45. return state, err
  46. }
  47. SaveState(stateDB, state)
  48. }
  49. return state, nil
  50. }
  51. // LoadState loads the State from the database.
  52. func LoadState(db dbm.DB) State {
  53. return loadState(db, stateKey)
  54. }
  55. func loadState(db dbm.DB, key []byte) (state State) {
  56. buf := db.Get(key)
  57. if len(buf) == 0 {
  58. return state
  59. }
  60. r, n, err := bytes.NewReader(buf), new(int), new(error)
  61. wire.ReadBinaryPtr(&state, r, 0, n, err)
  62. if *err != nil {
  63. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  64. cmn.Exit(cmn.Fmt(`LoadState: Data has been corrupted or its spec has changed:
  65. %v\n`, *err))
  66. }
  67. // TODO: ensure that buf is completely read.
  68. return state
  69. }
  70. // SaveState persists the State, the ValidatorsInfo, and the ConsensusParamsInfo to the database.
  71. func SaveState(db dbm.DB, s State) {
  72. saveState(db, s, stateKey)
  73. }
  74. func saveState(db dbm.DB, s State, key []byte) {
  75. nextHeight := s.LastBlockHeight + 1
  76. saveValidatorsInfo(db, nextHeight, s.LastHeightValidatorsChanged, s.Validators)
  77. saveConsensusParamsInfo(db, nextHeight, s.LastHeightConsensusParamsChanged, s.ConsensusParams)
  78. db.SetSync(stateKey, s.Bytes())
  79. }
  80. //------------------------------------------------------------------------
  81. // ABCIResponses retains the responses
  82. // of the various ABCI calls during block processing.
  83. // It is persisted to disk for each height before calling Commit.
  84. type ABCIResponses struct {
  85. DeliverTx []*abci.ResponseDeliverTx
  86. EndBlock *abci.ResponseEndBlock
  87. }
  88. // NewABCIResponses returns a new ABCIResponses
  89. func NewABCIResponses(block *types.Block) *ABCIResponses {
  90. return &ABCIResponses{
  91. DeliverTx: make([]*abci.ResponseDeliverTx, block.NumTxs),
  92. }
  93. }
  94. // Bytes serializes the ABCIResponse using go-wire
  95. func (a *ABCIResponses) Bytes() []byte {
  96. return wire.BinaryBytes(*a)
  97. }
  98. func (a *ABCIResponses) ResultsHash() []byte {
  99. results := types.NewResults(a.DeliverTx)
  100. return results.Hash()
  101. }
  102. // LoadABCIResponses loads the ABCIResponses for the given height from the database.
  103. // This is useful for recovering from crashes where we called app.Commit and before we called
  104. // s.Save(). It can also be used to produce Merkle proofs of the result of txs.
  105. func LoadABCIResponses(db dbm.DB, height int64) (*ABCIResponses, error) {
  106. buf := db.Get(calcABCIResponsesKey(height))
  107. if len(buf) == 0 {
  108. return nil, ErrNoABCIResponsesForHeight{height}
  109. }
  110. abciResponses := new(ABCIResponses)
  111. r, n, err := bytes.NewReader(buf), new(int), new(error)
  112. wire.ReadBinaryPtr(abciResponses, r, 0, n, err)
  113. if *err != nil {
  114. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  115. cmn.Exit(cmn.Fmt(`LoadABCIResponses: Data has been corrupted or its spec has
  116. changed: %v\n`, *err))
  117. }
  118. // TODO: ensure that buf is completely read.
  119. return abciResponses, nil
  120. }
  121. // SaveABCIResponses persists the ABCIResponses to the database.
  122. // This is useful in case we crash after app.Commit and before s.Save().
  123. // Responses are indexed by height so they can also be loaded later to produce Merkle proofs.
  124. func saveABCIResponses(db dbm.DB, height int64, abciResponses *ABCIResponses) {
  125. db.SetSync(calcABCIResponsesKey(height), abciResponses.Bytes())
  126. }
  127. //-----------------------------------------------------------------------------
  128. // ValidatorsInfo represents the latest validator set, or the last height it changed
  129. type ValidatorsInfo struct {
  130. ValidatorSet *types.ValidatorSet
  131. LastHeightChanged int64
  132. }
  133. // Bytes serializes the ValidatorsInfo using go-wire
  134. func (valInfo *ValidatorsInfo) Bytes() []byte {
  135. return wire.BinaryBytes(*valInfo)
  136. }
  137. // LoadValidators loads the ValidatorSet for a given height.
  138. // Returns ErrNoValSetForHeight if the validator set can't be found for this height.
  139. func LoadValidators(db dbm.DB, height int64) (*types.ValidatorSet, error) {
  140. valInfo := loadValidatorsInfo(db, height)
  141. if valInfo == nil {
  142. return nil, ErrNoValSetForHeight{height}
  143. }
  144. if valInfo.ValidatorSet == nil {
  145. valInfo = loadValidatorsInfo(db, valInfo.LastHeightChanged)
  146. if valInfo == nil {
  147. cmn.PanicSanity(fmt.Sprintf(`Couldn't find validators at height %d as
  148. last changed from height %d`, valInfo.LastHeightChanged, height))
  149. }
  150. }
  151. return valInfo.ValidatorSet, nil
  152. }
  153. func loadValidatorsInfo(db dbm.DB, height int64) *ValidatorsInfo {
  154. buf := db.Get(calcValidatorsKey(height))
  155. if len(buf) == 0 {
  156. return nil
  157. }
  158. v := new(ValidatorsInfo)
  159. r, n, err := bytes.NewReader(buf), new(int), new(error)
  160. wire.ReadBinaryPtr(v, r, 0, n, err)
  161. if *err != nil {
  162. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  163. cmn.Exit(cmn.Fmt(`LoadValidators: Data has been corrupted or its spec has changed:
  164. %v\n`, *err))
  165. }
  166. // TODO: ensure that buf is completely read.
  167. return v
  168. }
  169. // saveValidatorsInfo persists the validator set for the next block to disk.
  170. // It should be called from s.Save(), right before the state itself is persisted.
  171. // If the validator set did not change after processing the latest block,
  172. // only the last height for which the validators changed is persisted.
  173. func saveValidatorsInfo(db dbm.DB, nextHeight, changeHeight int64, valSet *types.ValidatorSet) {
  174. valInfo := &ValidatorsInfo{
  175. LastHeightChanged: changeHeight,
  176. }
  177. if changeHeight == nextHeight {
  178. valInfo.ValidatorSet = valSet
  179. }
  180. db.SetSync(calcValidatorsKey(nextHeight), valInfo.Bytes())
  181. }
  182. //-----------------------------------------------------------------------------
  183. // ConsensusParamsInfo represents the latest consensus params, or the last height it changed
  184. type ConsensusParamsInfo struct {
  185. ConsensusParams types.ConsensusParams
  186. LastHeightChanged int64
  187. }
  188. // Bytes serializes the ConsensusParamsInfo using go-wire
  189. func (params ConsensusParamsInfo) Bytes() []byte {
  190. return wire.BinaryBytes(params)
  191. }
  192. // LoadConsensusParams loads the ConsensusParams for a given height.
  193. func LoadConsensusParams(db dbm.DB, height int64) (types.ConsensusParams, error) {
  194. empty := types.ConsensusParams{}
  195. paramsInfo := loadConsensusParamsInfo(db, height)
  196. if paramsInfo == nil {
  197. return empty, ErrNoConsensusParamsForHeight{height}
  198. }
  199. if paramsInfo.ConsensusParams == empty {
  200. paramsInfo = loadConsensusParamsInfo(db, paramsInfo.LastHeightChanged)
  201. if paramsInfo == nil {
  202. cmn.PanicSanity(fmt.Sprintf(`Couldn't find consensus params at height %d as
  203. last changed from height %d`, paramsInfo.LastHeightChanged, height))
  204. }
  205. }
  206. return paramsInfo.ConsensusParams, nil
  207. }
  208. func loadConsensusParamsInfo(db dbm.DB, height int64) *ConsensusParamsInfo {
  209. buf := db.Get(calcConsensusParamsKey(height))
  210. if len(buf) == 0 {
  211. return nil
  212. }
  213. paramsInfo := new(ConsensusParamsInfo)
  214. r, n, err := bytes.NewReader(buf), new(int), new(error)
  215. wire.ReadBinaryPtr(paramsInfo, r, 0, n, err)
  216. if *err != nil {
  217. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  218. cmn.Exit(cmn.Fmt(`LoadConsensusParams: Data has been corrupted or its spec has changed:
  219. %v\n`, *err))
  220. }
  221. // TODO: ensure that buf is completely read.
  222. return paramsInfo
  223. }
  224. // saveConsensusParamsInfo persists the consensus params for the next block to disk.
  225. // It should be called from s.Save(), right before the state itself is persisted.
  226. // If the consensus params did not change after processing the latest block,
  227. // only the last height for which they changed is persisted.
  228. func saveConsensusParamsInfo(db dbm.DB, nextHeight, changeHeight int64, params types.ConsensusParams) {
  229. paramsInfo := &ConsensusParamsInfo{
  230. LastHeightChanged: changeHeight,
  231. }
  232. if changeHeight == nextHeight {
  233. paramsInfo.ConsensusParams = params
  234. }
  235. db.SetSync(calcConsensusParamsKey(nextHeight), paramsInfo.Bytes())
  236. }