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.

301 lines
9.3 KiB

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