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.

310 lines
9.8 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(fmt.Sprintf("validatorsKey:%v", height))
  12. }
  13. func calcConsensusParamsKey(height int64) []byte {
  14. return []byte(fmt.Sprintf("consensusParamsKey:%v", height))
  15. }
  16. func calcABCIResponsesKey(height int64) []byte {
  17. return []byte(fmt.Sprintf("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(fmt.Sprintf(`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. // This extra logic due to Tendermint validator set changes being delayed 1 block.
  77. // It may get overwritten due to InitChain validator updates.
  78. lastHeightVoteChanged := int64(1)
  79. saveValidatorsInfo(db, nextHeight, lastHeightVoteChanged, state.Validators)
  80. }
  81. // Save next validators.
  82. saveValidatorsInfo(db, nextHeight+1, state.LastHeightValidatorsChanged, state.NextValidators)
  83. // Save next consensus params.
  84. saveConsensusParamsInfo(db, nextHeight, state.LastHeightConsensusParamsChanged, state.ConsensusParams)
  85. db.SetSync(key, state.Bytes())
  86. }
  87. //------------------------------------------------------------------------
  88. // ABCIResponses retains the responses
  89. // of the various ABCI calls during block processing.
  90. // It is persisted to disk for each height before calling Commit.
  91. type ABCIResponses struct {
  92. DeliverTx []*abci.ResponseDeliverTx
  93. EndBlock *abci.ResponseEndBlock
  94. BeginBlock *abci.ResponseBeginBlock
  95. }
  96. // NewABCIResponses returns a new ABCIResponses
  97. func NewABCIResponses(block *types.Block) *ABCIResponses {
  98. resDeliverTxs := make([]*abci.ResponseDeliverTx, block.NumTxs)
  99. if block.NumTxs == 0 {
  100. // This makes Amino encoding/decoding consistent.
  101. resDeliverTxs = nil
  102. }
  103. return &ABCIResponses{
  104. DeliverTx: resDeliverTxs,
  105. }
  106. }
  107. // Bytes serializes the ABCIResponse using go-amino.
  108. func (arz *ABCIResponses) Bytes() []byte {
  109. return cdc.MustMarshalBinaryBare(arz)
  110. }
  111. func (arz *ABCIResponses) ResultsHash() []byte {
  112. results := types.NewResults(arz.DeliverTx)
  113. return results.Hash()
  114. }
  115. // LoadABCIResponses loads the ABCIResponses for the given height from the database.
  116. // This is useful for recovering from crashes where we called app.Commit and before we called
  117. // s.Save(). It can also be used to produce Merkle proofs of the result of txs.
  118. func LoadABCIResponses(db dbm.DB, height int64) (*ABCIResponses, error) {
  119. buf := db.Get(calcABCIResponsesKey(height))
  120. if len(buf) == 0 {
  121. return nil, ErrNoABCIResponsesForHeight{height}
  122. }
  123. abciResponses := new(ABCIResponses)
  124. err := cdc.UnmarshalBinaryBare(buf, abciResponses)
  125. if err != nil {
  126. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  127. cmn.Exit(fmt.Sprintf(`LoadABCIResponses: Data has been corrupted or its spec has
  128. changed: %v\n`, err))
  129. }
  130. // TODO: ensure that buf is completely read.
  131. return abciResponses, nil
  132. }
  133. // SaveABCIResponses persists the ABCIResponses to the database.
  134. // This is useful in case we crash after app.Commit and before s.Save().
  135. // Responses are indexed by height so they can also be loaded later to produce Merkle proofs.
  136. func saveABCIResponses(db dbm.DB, height int64, abciResponses *ABCIResponses) {
  137. db.SetSync(calcABCIResponsesKey(height), abciResponses.Bytes())
  138. }
  139. //-----------------------------------------------------------------------------
  140. // ValidatorsInfo represents the latest validator set, or the last height it changed
  141. type ValidatorsInfo struct {
  142. ValidatorSet *types.ValidatorSet
  143. LastHeightChanged int64
  144. }
  145. // Bytes serializes the ValidatorsInfo using go-amino.
  146. func (valInfo *ValidatorsInfo) Bytes() []byte {
  147. return cdc.MustMarshalBinaryBare(valInfo)
  148. }
  149. // LoadValidators loads the ValidatorSet for a given height.
  150. // Returns ErrNoValSetForHeight if the validator set can't be found for this height.
  151. func LoadValidators(db dbm.DB, height int64) (*types.ValidatorSet, error) {
  152. valInfo := loadValidatorsInfo(db, height)
  153. if valInfo == nil {
  154. return nil, ErrNoValSetForHeight{height}
  155. }
  156. if valInfo.ValidatorSet == nil {
  157. valInfo2 := loadValidatorsInfo(db, valInfo.LastHeightChanged)
  158. if valInfo2 == nil {
  159. panic(
  160. fmt.Sprintf(
  161. "Couldn't find validators at height %d as last changed from height %d",
  162. valInfo.LastHeightChanged,
  163. height,
  164. ),
  165. )
  166. }
  167. valInfo2.ValidatorSet.IncrementProposerPriority(int(height - valInfo.LastHeightChanged)) // mutate
  168. valInfo = valInfo2
  169. }
  170. return valInfo.ValidatorSet, nil
  171. }
  172. // CONTRACT: Returned ValidatorsInfo can be mutated.
  173. func loadValidatorsInfo(db dbm.DB, height int64) *ValidatorsInfo {
  174. buf := db.Get(calcValidatorsKey(height))
  175. if len(buf) == 0 {
  176. return nil
  177. }
  178. v := new(ValidatorsInfo)
  179. err := cdc.UnmarshalBinaryBare(buf, v)
  180. if err != nil {
  181. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  182. cmn.Exit(fmt.Sprintf(`LoadValidators: Data has been corrupted or its spec has changed:
  183. %v\n`, err))
  184. }
  185. // TODO: ensure that buf is completely read.
  186. return v
  187. }
  188. // saveValidatorsInfo persists the validator set.
  189. // `height` is the effective height for which the validator is responsible for signing.
  190. // It should be called from s.Save(), right before the state itself is persisted.
  191. // If the validator set did not change after processing the latest block,
  192. // only the last height for which the validators changed is persisted.
  193. func saveValidatorsInfo(db dbm.DB, height, lastHeightChanged int64, valSet *types.ValidatorSet) {
  194. if lastHeightChanged > height {
  195. panic("LastHeightChanged cannot be greater than ValidatorsInfo height")
  196. }
  197. valInfo := &ValidatorsInfo{
  198. LastHeightChanged: lastHeightChanged,
  199. }
  200. if lastHeightChanged == height {
  201. valInfo.ValidatorSet = valSet
  202. }
  203. db.Set(calcValidatorsKey(height), valInfo.Bytes())
  204. }
  205. //-----------------------------------------------------------------------------
  206. // ConsensusParamsInfo represents the latest consensus params, or the last height it changed
  207. type ConsensusParamsInfo struct {
  208. ConsensusParams types.ConsensusParams
  209. LastHeightChanged int64
  210. }
  211. // Bytes serializes the ConsensusParamsInfo using go-amino.
  212. func (params ConsensusParamsInfo) Bytes() []byte {
  213. return cdc.MustMarshalBinaryBare(params)
  214. }
  215. // LoadConsensusParams loads the ConsensusParams for a given height.
  216. func LoadConsensusParams(db dbm.DB, height int64) (types.ConsensusParams, error) {
  217. empty := types.ConsensusParams{}
  218. paramsInfo := loadConsensusParamsInfo(db, height)
  219. if paramsInfo == nil {
  220. return empty, ErrNoConsensusParamsForHeight{height}
  221. }
  222. if paramsInfo.ConsensusParams.Equals(&empty) {
  223. paramsInfo2 := loadConsensusParamsInfo(db, paramsInfo.LastHeightChanged)
  224. if paramsInfo2 == nil {
  225. panic(
  226. fmt.Sprintf(
  227. "Couldn't find consensus params at height %d as last changed from height %d",
  228. paramsInfo.LastHeightChanged,
  229. height,
  230. ),
  231. )
  232. }
  233. paramsInfo = paramsInfo2
  234. }
  235. return paramsInfo.ConsensusParams, nil
  236. }
  237. func loadConsensusParamsInfo(db dbm.DB, height int64) *ConsensusParamsInfo {
  238. buf := db.Get(calcConsensusParamsKey(height))
  239. if len(buf) == 0 {
  240. return nil
  241. }
  242. paramsInfo := new(ConsensusParamsInfo)
  243. err := cdc.UnmarshalBinaryBare(buf, paramsInfo)
  244. if err != nil {
  245. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  246. cmn.Exit(fmt.Sprintf(`LoadConsensusParams: Data has been corrupted or its spec has changed:
  247. %v\n`, err))
  248. }
  249. // TODO: ensure that buf is completely read.
  250. return paramsInfo
  251. }
  252. // saveConsensusParamsInfo persists the consensus params for the next block to disk.
  253. // It should be called from s.Save(), right before the state itself is persisted.
  254. // If the consensus params did not change after processing the latest block,
  255. // only the last height for which they changed is persisted.
  256. func saveConsensusParamsInfo(db dbm.DB, nextHeight, changeHeight int64, params types.ConsensusParams) {
  257. paramsInfo := &ConsensusParamsInfo{
  258. LastHeightChanged: changeHeight,
  259. }
  260. if changeHeight == nextHeight {
  261. paramsInfo.ConsensusParams = params
  262. }
  263. db.Set(calcConsensusParamsKey(nextHeight), paramsInfo.Bytes())
  264. }