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.

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