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.

351 lines
10 KiB

10 years ago
8 years ago
7 years ago
8 years ago
8 years ago
  1. package state
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "time"
  8. "github.com/gogo/protobuf/proto"
  9. tmstate "github.com/tendermint/tendermint/proto/tendermint/state"
  10. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  11. tmversion "github.com/tendermint/tendermint/proto/tendermint/version"
  12. "github.com/tendermint/tendermint/types"
  13. tmtime "github.com/tendermint/tendermint/types/time"
  14. "github.com/tendermint/tendermint/version"
  15. )
  16. // database keys
  17. var (
  18. stateKey = []byte("stateKey")
  19. )
  20. //-----------------------------------------------------------------------------
  21. // InitStateVersion sets the Consensus.Block and Software versions,
  22. // but leaves the Consensus.App version blank.
  23. // The Consensus.App version will be set during the Handshake, once
  24. // we hear from the app what protocol version it is running.
  25. var InitStateVersion = tmstate.Version{
  26. Consensus: tmversion.Consensus{
  27. Block: version.BlockProtocol,
  28. App: 0,
  29. },
  30. Software: version.TMCoreSemVer,
  31. }
  32. //-----------------------------------------------------------------------------
  33. // State is a short description of the latest committed block of the Tendermint consensus.
  34. // It keeps all information necessary to validate new blocks,
  35. // including the last validator set and the consensus params.
  36. // All fields are exposed so the struct can be easily serialized,
  37. // but none of them should be mutated directly.
  38. // Instead, use state.Copy() or state.NextState(...).
  39. // NOTE: not goroutine-safe.
  40. type State struct {
  41. Version tmstate.Version
  42. // immutable
  43. ChainID string
  44. // LastBlockHeight=0 at genesis (ie. block(H=0) does not exist)
  45. LastBlockHeight int64
  46. LastBlockID types.BlockID
  47. LastBlockTime time.Time
  48. // LastValidators is used to validate block.LastCommit.
  49. // Validators are persisted to the database separately every time they change,
  50. // so we can query for historical validator sets.
  51. // Note that if s.LastBlockHeight causes a valset change,
  52. // we set s.LastHeightValidatorsChanged = s.LastBlockHeight + 1 + 1
  53. // Extra +1 due to nextValSet delay.
  54. NextValidators *types.ValidatorSet
  55. Validators *types.ValidatorSet
  56. LastValidators *types.ValidatorSet
  57. LastHeightValidatorsChanged int64
  58. // Consensus parameters used for validating blocks.
  59. // Changes returned by EndBlock and updated after Commit.
  60. ConsensusParams tmproto.ConsensusParams
  61. LastHeightConsensusParamsChanged int64
  62. // Merkle root of the results from executing prev block
  63. LastResultsHash []byte
  64. // the latest AppHash we've received from calling abci.Commit()
  65. AppHash []byte
  66. }
  67. // Copy makes a copy of the State for mutating.
  68. func (state State) Copy() State {
  69. return State{
  70. Version: state.Version,
  71. ChainID: state.ChainID,
  72. LastBlockHeight: state.LastBlockHeight,
  73. LastBlockID: state.LastBlockID,
  74. LastBlockTime: state.LastBlockTime,
  75. NextValidators: state.NextValidators.Copy(),
  76. Validators: state.Validators.Copy(),
  77. LastValidators: state.LastValidators.Copy(),
  78. LastHeightValidatorsChanged: state.LastHeightValidatorsChanged,
  79. ConsensusParams: state.ConsensusParams,
  80. LastHeightConsensusParamsChanged: state.LastHeightConsensusParamsChanged,
  81. AppHash: state.AppHash,
  82. LastResultsHash: state.LastResultsHash,
  83. }
  84. }
  85. // Equals returns true if the States are identical.
  86. func (state State) Equals(state2 State) bool {
  87. sbz, s2bz := state.Bytes(), state2.Bytes()
  88. return bytes.Equal(sbz, s2bz)
  89. }
  90. // Bytes serializes the State using protobuf.
  91. // It panics if either casting to protobuf or serialization fails.
  92. func (state State) Bytes() []byte {
  93. sm, err := state.ToProto()
  94. if err != nil {
  95. panic(err)
  96. }
  97. bz, err := proto.Marshal(sm)
  98. if err != nil {
  99. panic(err)
  100. }
  101. return bz
  102. }
  103. // IsEmpty returns true if the State is equal to the empty State.
  104. func (state State) IsEmpty() bool {
  105. return state.Validators == nil // XXX can't compare to Empty
  106. }
  107. //ToProto takes the local state type and returns the equivalent proto type
  108. func (state *State) ToProto() (*tmstate.State, error) {
  109. if state == nil {
  110. return nil, errors.New("state is nil")
  111. }
  112. sm := new(tmstate.State)
  113. sm.Version = state.Version
  114. sm.ChainID = state.ChainID
  115. sm.LastBlockHeight = state.LastBlockHeight
  116. sm.LastBlockID = state.LastBlockID.ToProto()
  117. sm.LastBlockTime = state.LastBlockTime
  118. vals, err := state.Validators.ToProto()
  119. if err != nil {
  120. return nil, err
  121. }
  122. sm.Validators = vals
  123. nVals, err := state.NextValidators.ToProto()
  124. if err != nil {
  125. return nil, err
  126. }
  127. sm.NextValidators = nVals
  128. if state.LastBlockHeight >= 1 { // At Block 1 LastValidators is nil
  129. lVals, err := state.LastValidators.ToProto()
  130. if err != nil {
  131. return nil, err
  132. }
  133. sm.LastValidators = lVals
  134. }
  135. sm.LastHeightValidatorsChanged = state.LastHeightValidatorsChanged
  136. sm.ConsensusParams = state.ConsensusParams
  137. sm.LastHeightConsensusParamsChanged = state.LastHeightConsensusParamsChanged
  138. sm.LastResultsHash = state.LastResultsHash
  139. sm.AppHash = state.AppHash
  140. return sm, nil
  141. }
  142. // StateFromProto takes a state proto message & returns the local state type
  143. func StateFromProto(pb *tmstate.State) (*State, error) { //nolint:golint
  144. if pb == nil {
  145. return nil, errors.New("nil State")
  146. }
  147. state := new(State)
  148. state.Version = pb.Version
  149. state.ChainID = pb.ChainID
  150. bi, err := types.BlockIDFromProto(&pb.LastBlockID)
  151. if err != nil {
  152. return nil, err
  153. }
  154. state.LastBlockID = *bi
  155. state.LastBlockHeight = pb.LastBlockHeight
  156. state.LastBlockTime = pb.LastBlockTime
  157. vals, err := types.ValidatorSetFromProto(pb.Validators)
  158. if err != nil {
  159. return nil, err
  160. }
  161. state.Validators = vals
  162. nVals, err := types.ValidatorSetFromProto(pb.NextValidators)
  163. if err != nil {
  164. return nil, err
  165. }
  166. state.NextValidators = nVals
  167. if state.LastBlockHeight >= 1 { // At Block 1 LastValidators is nil
  168. lVals, err := types.ValidatorSetFromProto(pb.LastValidators)
  169. if err != nil {
  170. return nil, err
  171. }
  172. state.LastValidators = lVals
  173. } else {
  174. state.LastValidators = types.NewValidatorSet(nil)
  175. }
  176. state.LastHeightValidatorsChanged = pb.LastHeightValidatorsChanged
  177. state.ConsensusParams = pb.ConsensusParams
  178. state.LastHeightConsensusParamsChanged = pb.LastHeightConsensusParamsChanged
  179. state.LastResultsHash = pb.LastResultsHash
  180. state.AppHash = pb.AppHash
  181. return state, nil
  182. }
  183. //------------------------------------------------------------------------
  184. // Create a block from the latest state
  185. // MakeBlock builds a block from the current state with the given txs, commit,
  186. // and evidence. Note it also takes a proposerAddress because the state does not
  187. // track rounds, and hence does not know the correct proposer. TODO: fix this!
  188. func (state State) MakeBlock(
  189. height int64,
  190. txs []types.Tx,
  191. commit *types.Commit,
  192. evidence []types.Evidence,
  193. proposerAddress []byte,
  194. ) (*types.Block, *types.PartSet) {
  195. // Build base block with block data.
  196. block := types.MakeBlock(height, txs, commit, evidence)
  197. // Set time.
  198. var timestamp time.Time
  199. if height == 1 {
  200. timestamp = state.LastBlockTime // genesis time
  201. } else {
  202. timestamp = MedianTime(commit, state.LastValidators)
  203. }
  204. // Fill rest of header with state data.
  205. block.Header.Populate(
  206. state.Version.Consensus, state.ChainID,
  207. timestamp, state.LastBlockID,
  208. state.Validators.Hash(), state.NextValidators.Hash(),
  209. types.HashConsensusParams(state.ConsensusParams), state.AppHash, state.LastResultsHash,
  210. proposerAddress,
  211. )
  212. return block, block.MakePartSet(types.BlockPartSizeBytes)
  213. }
  214. // MedianTime computes a median time for a given Commit (based on Timestamp field of votes messages) and the
  215. // corresponding validator set. The computed time is always between timestamps of
  216. // the votes sent by honest processes, i.e., a faulty processes can not arbitrarily increase or decrease the
  217. // computed value.
  218. func MedianTime(commit *types.Commit, validators *types.ValidatorSet) time.Time {
  219. weightedTimes := make([]*tmtime.WeightedTime, len(commit.Signatures))
  220. totalVotingPower := int64(0)
  221. for i, commitSig := range commit.Signatures {
  222. if commitSig.Absent() {
  223. continue
  224. }
  225. _, validator := validators.GetByAddress(commitSig.ValidatorAddress)
  226. // If there's no condition, TestValidateBlockCommit panics; not needed normally.
  227. if validator != nil {
  228. totalVotingPower += validator.VotingPower
  229. weightedTimes[i] = tmtime.NewWeightedTime(commitSig.Timestamp, validator.VotingPower)
  230. }
  231. }
  232. return tmtime.WeightedMedian(weightedTimes, totalVotingPower)
  233. }
  234. //------------------------------------------------------------------------
  235. // Genesis
  236. // MakeGenesisStateFromFile reads and unmarshals state from the given
  237. // file.
  238. //
  239. // Used during replay and in tests.
  240. func MakeGenesisStateFromFile(genDocFile string) (State, error) {
  241. genDoc, err := MakeGenesisDocFromFile(genDocFile)
  242. if err != nil {
  243. return State{}, err
  244. }
  245. return MakeGenesisState(genDoc)
  246. }
  247. // MakeGenesisDocFromFile reads and unmarshals genesis doc from the given file.
  248. func MakeGenesisDocFromFile(genDocFile string) (*types.GenesisDoc, error) {
  249. genDocJSON, err := ioutil.ReadFile(genDocFile)
  250. if err != nil {
  251. return nil, fmt.Errorf("couldn't read GenesisDoc file: %v", err)
  252. }
  253. genDoc, err := types.GenesisDocFromJSON(genDocJSON)
  254. if err != nil {
  255. return nil, fmt.Errorf("error reading GenesisDoc: %v", err)
  256. }
  257. return genDoc, nil
  258. }
  259. // MakeGenesisState creates state from types.GenesisDoc.
  260. func MakeGenesisState(genDoc *types.GenesisDoc) (State, error) {
  261. err := genDoc.ValidateAndComplete()
  262. if err != nil {
  263. return State{}, fmt.Errorf("error in genesis file: %v", err)
  264. }
  265. var validatorSet, nextValidatorSet *types.ValidatorSet
  266. if genDoc.Validators == nil {
  267. validatorSet = types.NewValidatorSet(nil)
  268. nextValidatorSet = types.NewValidatorSet(nil)
  269. } else {
  270. validators := make([]*types.Validator, len(genDoc.Validators))
  271. for i, val := range genDoc.Validators {
  272. validators[i] = types.NewValidator(val.PubKey, val.Power)
  273. }
  274. validatorSet = types.NewValidatorSet(validators)
  275. nextValidatorSet = types.NewValidatorSet(validators).CopyIncrementProposerPriority(1)
  276. }
  277. return State{
  278. Version: InitStateVersion,
  279. ChainID: genDoc.ChainID,
  280. LastBlockHeight: 0,
  281. LastBlockID: types.BlockID{},
  282. LastBlockTime: genDoc.GenesisTime,
  283. NextValidators: nextValidatorSet,
  284. Validators: validatorSet,
  285. LastValidators: types.NewValidatorSet(nil),
  286. LastHeightValidatorsChanged: 1,
  287. ConsensusParams: *genDoc.ConsensusParams,
  288. LastHeightConsensusParamsChanged: 1,
  289. AppHash: genDoc.AppHash,
  290. }, nil
  291. }