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.

266 lines
7.1 KiB

10 years ago
8 years ago
10 years ago
10 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. package state
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "sync"
  6. "time"
  7. abci "github.com/tendermint/abci/types"
  8. . "github.com/tendermint/go-common"
  9. cfg "github.com/tendermint/go-config"
  10. dbm "github.com/tendermint/go-db"
  11. "github.com/tendermint/go-wire"
  12. "github.com/tendermint/tendermint/state/txindex"
  13. "github.com/tendermint/tendermint/state/txindex/null"
  14. "github.com/tendermint/tendermint/types"
  15. )
  16. var (
  17. stateKey = []byte("stateKey")
  18. abciResponsesKey = []byte("abciResponsesKey")
  19. )
  20. //-----------------------------------------------------------------------------
  21. // NOTE: not goroutine-safe.
  22. type State struct {
  23. // mtx for writing to db
  24. mtx sync.Mutex
  25. db dbm.DB
  26. // should not change
  27. GenesisDoc *types.GenesisDoc
  28. ChainID string
  29. // updated at end of SetBlockAndValidators
  30. LastBlockHeight int // Genesis state has this set to 0. So, Block(H=0) does not exist.
  31. LastBlockID types.BlockID
  32. LastBlockTime time.Time
  33. Validators *types.ValidatorSet
  34. LastValidators *types.ValidatorSet // block.LastCommit validated against this
  35. // AppHash is updated after Commit
  36. AppHash []byte
  37. TxIndexer txindex.TxIndexer `json:"-"` // Transaction indexer.
  38. // Intermediate results from processing
  39. // Persisted separately from the state
  40. abciResponses *ABCIResponses
  41. }
  42. func LoadState(db dbm.DB) *State {
  43. return loadState(db, stateKey)
  44. }
  45. func loadState(db dbm.DB, key []byte) *State {
  46. s := &State{db: db, TxIndexer: &null.TxIndex{}}
  47. buf := db.Get(key)
  48. if len(buf) == 0 {
  49. return nil
  50. } else {
  51. r, n, err := bytes.NewReader(buf), new(int), new(error)
  52. wire.ReadBinaryPtr(&s, r, 0, n, err)
  53. if *err != nil {
  54. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  55. Exit(Fmt("LoadState: Data has been corrupted or its spec has changed: %v\n", *err))
  56. }
  57. // TODO: ensure that buf is completely read.
  58. }
  59. return s
  60. }
  61. func (s *State) Copy() *State {
  62. return &State{
  63. db: s.db,
  64. GenesisDoc: s.GenesisDoc,
  65. ChainID: s.ChainID,
  66. LastBlockHeight: s.LastBlockHeight,
  67. LastBlockID: s.LastBlockID,
  68. LastBlockTime: s.LastBlockTime,
  69. Validators: s.Validators.Copy(),
  70. LastValidators: s.LastValidators.Copy(),
  71. AppHash: s.AppHash,
  72. TxIndexer: s.TxIndexer, // pointer here, not value
  73. }
  74. }
  75. func (s *State) Save() {
  76. s.mtx.Lock()
  77. defer s.mtx.Unlock()
  78. s.db.SetSync(stateKey, s.Bytes())
  79. }
  80. // Sets the ABCIResponses in the state and writes them to disk
  81. // in case we crash after app.Commit and before s.Save()
  82. func (s *State) SaveABCIResponses(abciResponses *ABCIResponses) {
  83. // save the validators to the db
  84. s.db.SetSync(abciResponsesKey, abciResponses.Bytes())
  85. }
  86. func (s *State) LoadABCIResponses() *ABCIResponses {
  87. abciResponses := new(ABCIResponses)
  88. buf := s.db.Get(abciResponsesKey)
  89. if len(buf) != 0 {
  90. r, n, err := bytes.NewReader(buf), new(int), new(error)
  91. wire.ReadBinaryPtr(abciResponses, r, 0, n, err)
  92. if *err != nil {
  93. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  94. Exit(Fmt("LoadABCIResponses: Data has been corrupted or its spec has changed: %v\n", *err))
  95. }
  96. // TODO: ensure that buf is completely read.
  97. }
  98. return abciResponses
  99. }
  100. func (s *State) Equals(s2 *State) bool {
  101. return bytes.Equal(s.Bytes(), s2.Bytes())
  102. }
  103. func (s *State) Bytes() []byte {
  104. buf, n, err := new(bytes.Buffer), new(int), new(error)
  105. wire.WriteBinary(s, buf, n, err)
  106. if *err != nil {
  107. PanicCrisis(*err)
  108. }
  109. return buf.Bytes()
  110. }
  111. // Mutate state variables to match block and validators
  112. // after running EndBlock
  113. func (s *State) SetBlockAndValidators(header *types.Header, blockPartsHeader types.PartSetHeader, abciResponses *ABCIResponses) {
  114. // copy the valset
  115. prevValSet := s.Validators.Copy()
  116. nextValSet := prevValSet.Copy()
  117. // update the validator set with the latest abciResponses
  118. err := updateValidators(nextValSet, abciResponses.EndBlock.Diffs)
  119. if err != nil {
  120. log.Warn("Error changing validator set", "error", err)
  121. // TODO: err or carry on?
  122. }
  123. // Update validator accums and set state variables
  124. nextValSet.IncrementAccum(1)
  125. s.setBlockAndValidators(header.Height,
  126. types.BlockID{header.Hash(), blockPartsHeader}, header.Time,
  127. prevValSet, nextValSet)
  128. }
  129. func (s *State) setBlockAndValidators(
  130. height int, blockID types.BlockID, blockTime time.Time,
  131. prevValSet, nextValSet *types.ValidatorSet) {
  132. s.LastBlockHeight = height
  133. s.LastBlockID = blockID
  134. s.LastBlockTime = blockTime
  135. s.Validators = nextValSet
  136. s.LastValidators = prevValSet
  137. }
  138. func (s *State) GetValidators() (*types.ValidatorSet, *types.ValidatorSet) {
  139. return s.LastValidators, s.Validators
  140. }
  141. // Load the most recent state from "state" db,
  142. // or create a new one (and save) from genesis.
  143. func GetState(config cfg.Config, stateDB dbm.DB) *State {
  144. state := LoadState(stateDB)
  145. if state == nil {
  146. state = MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file"))
  147. state.Save()
  148. }
  149. return state
  150. }
  151. //--------------------------------------------------
  152. // ABCIResponses holds intermediate state during block processing
  153. type ABCIResponses struct {
  154. Height int
  155. DeliverTx []*abci.ResponseDeliverTx
  156. EndBlock abci.ResponseEndBlock
  157. txs types.Txs // reference for indexing results by hash
  158. }
  159. func NewABCIResponses(block *types.Block) *ABCIResponses {
  160. return &ABCIResponses{
  161. Height: block.Height,
  162. DeliverTx: make([]*abci.ResponseDeliverTx, block.NumTxs),
  163. txs: block.Data.Txs,
  164. }
  165. }
  166. // Serialize the ABCIResponse
  167. func (a *ABCIResponses) Bytes() []byte {
  168. buf, n, err := new(bytes.Buffer), new(int), new(error)
  169. wire.WriteBinary(*a, buf, n, err)
  170. if *err != nil {
  171. PanicCrisis(*err)
  172. }
  173. return buf.Bytes()
  174. }
  175. //-----------------------------------------------------------------------------
  176. // Genesis
  177. // MakeGenesisStateFromFile reads and unmarshals state from the given file.
  178. //
  179. // Used during replay and in tests.
  180. func MakeGenesisStateFromFile(db dbm.DB, genDocFile string) *State {
  181. genDocJSON, err := ioutil.ReadFile(genDocFile)
  182. if err != nil {
  183. Exit(Fmt("Couldn't read GenesisDoc file: %v", err))
  184. }
  185. genDoc, err := types.GenesisDocFromJSON(genDocJSON)
  186. if err != nil {
  187. Exit(Fmt("Error reading GenesisDoc: %v", err))
  188. }
  189. return MakeGenesisState(db, genDoc)
  190. }
  191. // MakeGenesisState creates state from types.GenesisDoc.
  192. //
  193. // Used in tests.
  194. func MakeGenesisState(db dbm.DB, genDoc *types.GenesisDoc) *State {
  195. if len(genDoc.Validators) == 0 {
  196. Exit(Fmt("The genesis file has no validators"))
  197. }
  198. if genDoc.GenesisTime.IsZero() {
  199. genDoc.GenesisTime = time.Now()
  200. }
  201. // Make validators slice
  202. validators := make([]*types.Validator, len(genDoc.Validators))
  203. for i, val := range genDoc.Validators {
  204. pubKey := val.PubKey
  205. address := pubKey.Address()
  206. // Make validator
  207. validators[i] = &types.Validator{
  208. Address: address,
  209. PubKey: pubKey,
  210. VotingPower: val.Amount,
  211. }
  212. }
  213. return &State{
  214. db: db,
  215. GenesisDoc: genDoc,
  216. ChainID: genDoc.ChainID,
  217. LastBlockHeight: 0,
  218. LastBlockID: types.BlockID{},
  219. LastBlockTime: genDoc.GenesisTime,
  220. Validators: types.NewValidatorSet(validators),
  221. LastValidators: types.NewValidatorSet(nil),
  222. AppHash: genDoc.AppHash,
  223. TxIndexer: &null.TxIndex{}, // we do not need indexer during replay and in tests
  224. }
  225. }