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.

362 lines
11 KiB

8 years ago
8 years ago
8 years ago
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
8 years ago
  1. package state
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "sync"
  7. "time"
  8. abci "github.com/tendermint/abci/types"
  9. cmn "github.com/tendermint/tmlibs/common"
  10. dbm "github.com/tendermint/tmlibs/db"
  11. "github.com/tendermint/tmlibs/log"
  12. wire "github.com/tendermint/go-wire"
  13. "github.com/tendermint/tendermint/state/txindex"
  14. "github.com/tendermint/tendermint/state/txindex/null"
  15. "github.com/tendermint/tendermint/types"
  16. )
  17. var (
  18. stateKey = []byte("stateKey")
  19. abciResponsesKey = []byte("abciResponsesKey")
  20. )
  21. func calcValidatorsKey(height int) []byte {
  22. return []byte(cmn.Fmt("validatorsKey:%v", height))
  23. }
  24. //-----------------------------------------------------------------------------
  25. // State represents the latest committed state of the Tendermint consensus,
  26. // including the last committed block and validator set.
  27. // Newly committed blocks are validated and executed against the State.
  28. // NOTE: not goroutine-safe.
  29. type State struct {
  30. // mtx for writing to db
  31. mtx sync.Mutex
  32. db dbm.DB
  33. // should not change
  34. GenesisDoc *types.GenesisDoc
  35. ChainID string
  36. // These fields are updated by SetBlockAndValidators.
  37. // LastBlockHeight=0 at genesis (ie. block(H=0) does not exist)
  38. // LastValidators is used to validate block.LastCommit.
  39. LastBlockHeight int
  40. LastBlockID types.BlockID
  41. LastBlockTime time.Time
  42. Validators *types.ValidatorSet
  43. LastValidators *types.ValidatorSet
  44. // AppHash is updated after Commit
  45. AppHash []byte
  46. TxIndexer txindex.TxIndexer `json:"-"` // Transaction indexer
  47. // When a block returns a validator set change via EndBlock,
  48. // the change only applies to the next block.
  49. // So, if s.LastBlockHeight causes a valset change,
  50. // we set s.LastHeightValidatorsChanged = s.LastBlockHeight + 1
  51. LastHeightValidatorsChanged int
  52. logger log.Logger
  53. }
  54. // LoadState loads the State from the database.
  55. func LoadState(db dbm.DB) *State {
  56. return loadState(db, stateKey)
  57. }
  58. func loadState(db dbm.DB, key []byte) *State {
  59. s := &State{db: db, TxIndexer: &null.TxIndex{}}
  60. buf := db.Get(key)
  61. if len(buf) == 0 {
  62. return nil
  63. } else {
  64. r, n, err := bytes.NewReader(buf), new(int), new(error)
  65. wire.ReadBinaryPtr(&s, r, 0, n, err)
  66. if *err != nil {
  67. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  68. cmn.Exit(cmn.Fmt("LoadState: Data has been corrupted or its spec has changed: %v\n", *err))
  69. }
  70. // TODO: ensure that buf is completely read.
  71. }
  72. return s
  73. }
  74. // SetLogger sets the logger on the State.
  75. func (s *State) SetLogger(l log.Logger) {
  76. s.logger = l
  77. }
  78. // Copy makes a copy of the State for mutating.
  79. func (s *State) Copy() *State {
  80. return &State{
  81. db: s.db,
  82. GenesisDoc: s.GenesisDoc,
  83. ChainID: s.ChainID,
  84. LastBlockHeight: s.LastBlockHeight,
  85. LastBlockID: s.LastBlockID,
  86. LastBlockTime: s.LastBlockTime,
  87. Validators: s.Validators.Copy(),
  88. LastValidators: s.LastValidators.Copy(),
  89. AppHash: s.AppHash,
  90. TxIndexer: s.TxIndexer, // pointer here, not value
  91. LastHeightValidatorsChanged: s.LastHeightValidatorsChanged,
  92. logger: s.logger,
  93. }
  94. }
  95. // Save persists the State to the database.
  96. func (s *State) Save() {
  97. s.mtx.Lock()
  98. defer s.mtx.Unlock()
  99. s.saveValidatorsInfo()
  100. s.db.SetSync(stateKey, s.Bytes())
  101. }
  102. // SaveABCIResponses persists the ABCIResponses to the database.
  103. // This is useful in case we crash after app.Commit and before s.Save().
  104. func (s *State) SaveABCIResponses(abciResponses *ABCIResponses) {
  105. s.db.SetSync(abciResponsesKey, abciResponses.Bytes())
  106. }
  107. // LoadABCIResponses loads the ABCIResponses from the database.
  108. func (s *State) LoadABCIResponses() *ABCIResponses {
  109. abciResponses := new(ABCIResponses)
  110. buf := s.db.Get(abciResponsesKey)
  111. if len(buf) != 0 {
  112. r, n, err := bytes.NewReader(buf), new(int), new(error)
  113. wire.ReadBinaryPtr(abciResponses, r, 0, n, err)
  114. if *err != nil {
  115. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  116. cmn.Exit(cmn.Fmt("LoadABCIResponses: Data has been corrupted or its spec has changed: %v\n", *err))
  117. }
  118. // TODO: ensure that buf is completely read.
  119. }
  120. return abciResponses
  121. }
  122. // LoadValidators loads the ValidatorSet for a given height.
  123. func (s *State) LoadValidators(height int) (*types.ValidatorSet, error) {
  124. v := s.loadValidators(height)
  125. if v == nil {
  126. return nil, ErrNoValSetForHeight{height}
  127. }
  128. if v.ValidatorSet == nil {
  129. v = s.loadValidators(v.LastHeightChanged)
  130. if v == nil {
  131. cmn.PanicSanity(fmt.Sprintf(`Couldn't find validators at
  132. height %d as last changed from height %d`, v.LastHeightChanged, height))
  133. }
  134. }
  135. return v.ValidatorSet, nil
  136. }
  137. func (s *State) loadValidators(height int) *ValidatorsInfo {
  138. buf := s.db.Get(calcValidatorsKey(height))
  139. if len(buf) == 0 {
  140. return nil
  141. }
  142. v := new(ValidatorsInfo)
  143. r, n, err := bytes.NewReader(buf), new(int), new(error)
  144. wire.ReadBinaryPtr(v, r, 0, n, err)
  145. if *err != nil {
  146. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  147. cmn.Exit(cmn.Fmt("LoadValidators: Data has been corrupted or its spec has changed: %v\n", *err))
  148. }
  149. // TODO: ensure that buf is completely read.
  150. return v
  151. }
  152. // saveValidatorsInfo persists the validator set for the next block to disk.
  153. // It should be called from s.Save(), right before the state itself is persisted.
  154. // If the validator set did not change after processing the latest block,
  155. // only the last height for which the validators changed is persisted.
  156. func (s *State) saveValidatorsInfo() {
  157. changeHeight := s.LastHeightValidatorsChanged
  158. nextHeight := s.LastBlockHeight + 1
  159. vi := &ValidatorsInfo{
  160. LastHeightChanged: changeHeight,
  161. }
  162. if changeHeight == nextHeight {
  163. vi.ValidatorSet = s.Validators
  164. }
  165. s.db.SetSync(calcValidatorsKey(nextHeight), vi.Bytes())
  166. }
  167. // Equals returns true if the States are identical.
  168. func (s *State) Equals(s2 *State) bool {
  169. return bytes.Equal(s.Bytes(), s2.Bytes())
  170. }
  171. // Bytes serializes the State using go-wire.
  172. func (s *State) Bytes() []byte {
  173. return wire.BinaryBytes(s)
  174. }
  175. // SetBlockAndValidators mutates State variables to update block and validators after running EndBlock.
  176. func (s *State) SetBlockAndValidators(header *types.Header, blockPartsHeader types.PartSetHeader, abciResponses *ABCIResponses) {
  177. // copy the valset so we can apply changes from EndBlock
  178. // and update s.LastValidators and s.Validators
  179. prevValSet := s.Validators.Copy()
  180. nextValSet := prevValSet.Copy()
  181. // update the validator set with the latest abciResponses
  182. if len(abciResponses.EndBlock.Diffs) > 0 {
  183. err := updateValidators(nextValSet, abciResponses.EndBlock.Diffs)
  184. if err != nil {
  185. s.logger.Error("Error changing validator set", "err", err)
  186. // TODO: err or carry on?
  187. }
  188. // change results from this height but only applies to the next height
  189. s.LastHeightValidatorsChanged = header.Height + 1
  190. }
  191. // Update validator accums and set state variables
  192. nextValSet.IncrementAccum(1)
  193. s.setBlockAndValidators(header.Height,
  194. types.BlockID{header.Hash(), blockPartsHeader},
  195. header.Time,
  196. prevValSet, nextValSet)
  197. }
  198. func (s *State) setBlockAndValidators(
  199. height int, blockID types.BlockID, blockTime time.Time,
  200. prevValSet, nextValSet *types.ValidatorSet) {
  201. s.LastBlockHeight = height
  202. s.LastBlockID = blockID
  203. s.LastBlockTime = blockTime
  204. s.Validators = nextValSet
  205. s.LastValidators = prevValSet
  206. }
  207. // GetValidators returns the last and current validator sets.
  208. func (s *State) GetValidators() (*types.ValidatorSet, *types.ValidatorSet) {
  209. return s.LastValidators, s.Validators
  210. }
  211. // GetState loads the most recent state from the database,
  212. // or creates a new one from the given genesisFile and persists the result
  213. // to the database.
  214. func GetState(stateDB dbm.DB, genesisFile string) *State {
  215. state := LoadState(stateDB)
  216. if state == nil {
  217. state = MakeGenesisStateFromFile(stateDB, genesisFile)
  218. state.Save()
  219. }
  220. return state
  221. }
  222. //------------------------------------------------------------------------
  223. // ABCIResponses retains the responses of the various ABCI calls during block processing.
  224. // It is persisted to disk before calling Commit.
  225. type ABCIResponses struct {
  226. Height int
  227. DeliverTx []*abci.ResponseDeliverTx
  228. EndBlock abci.ResponseEndBlock
  229. txs types.Txs // reference for indexing results by hash
  230. }
  231. // NewABCIResponses returns a new ABCIResponses
  232. func NewABCIResponses(block *types.Block) *ABCIResponses {
  233. return &ABCIResponses{
  234. Height: block.Height,
  235. DeliverTx: make([]*abci.ResponseDeliverTx, block.NumTxs),
  236. txs: block.Data.Txs,
  237. }
  238. }
  239. // Bytes serializes the ABCIResponse using go-wire
  240. func (a *ABCIResponses) Bytes() []byte {
  241. return wire.BinaryBytes(*a)
  242. }
  243. //-----------------------------------------------------------------------------
  244. // ValidatorsInfo represents the latest validator set, or the last time it changed
  245. type ValidatorsInfo struct {
  246. ValidatorSet *types.ValidatorSet
  247. LastHeightChanged int
  248. }
  249. // Bytes serializes the ValidatorsInfo using go-wire
  250. func (vi *ValidatorsInfo) Bytes() []byte {
  251. return wire.BinaryBytes(*vi)
  252. }
  253. //------------------------------------------------------------------------
  254. // Genesis
  255. // MakeGenesisStateFromFile reads and unmarshals state from the given
  256. // file.
  257. //
  258. // Used during replay and in tests.
  259. func MakeGenesisStateFromFile(db dbm.DB, genDocFile string) *State {
  260. genDocJSON, err := ioutil.ReadFile(genDocFile)
  261. if err != nil {
  262. cmn.Exit(cmn.Fmt("Couldn't read GenesisDoc file: %v", err))
  263. }
  264. genDoc, err := types.GenesisDocFromJSON(genDocJSON)
  265. if err != nil {
  266. cmn.Exit(cmn.Fmt("Error reading GenesisDoc: %v", err))
  267. }
  268. return MakeGenesisState(db, genDoc)
  269. }
  270. // MakeGenesisState creates state from types.GenesisDoc.
  271. //
  272. // Used in tests.
  273. func MakeGenesisState(db dbm.DB, genDoc *types.GenesisDoc) *State {
  274. if len(genDoc.Validators) == 0 {
  275. cmn.Exit(cmn.Fmt("The genesis file has no validators"))
  276. }
  277. if genDoc.GenesisTime.IsZero() {
  278. genDoc.GenesisTime = time.Now()
  279. }
  280. // Make validators slice
  281. validators := make([]*types.Validator, len(genDoc.Validators))
  282. for i, val := range genDoc.Validators {
  283. pubKey := val.PubKey
  284. address := pubKey.Address()
  285. // Make validator
  286. validators[i] = &types.Validator{
  287. Address: address,
  288. PubKey: pubKey,
  289. VotingPower: val.Amount,
  290. }
  291. }
  292. return &State{
  293. db: db,
  294. GenesisDoc: genDoc,
  295. ChainID: genDoc.ChainID,
  296. LastBlockHeight: 0,
  297. LastBlockID: types.BlockID{},
  298. LastBlockTime: genDoc.GenesisTime,
  299. Validators: types.NewValidatorSet(validators),
  300. LastValidators: types.NewValidatorSet(nil),
  301. AppHash: genDoc.AppHash,
  302. TxIndexer: &null.TxIndex{}, // we do not need indexer during replay and in tests
  303. LastHeightValidatorsChanged: 1,
  304. }
  305. }