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.

371 lines
11 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package state
  2. import (
  3. "bytes"
  4. "io"
  5. "time"
  6. acm "github.com/tendermint/tendermint/account"
  7. "github.com/tendermint/tendermint/wire"
  8. . "github.com/tendermint/tendermint/common"
  9. dbm "github.com/tendermint/tendermint/db"
  10. "github.com/tendermint/tendermint/events"
  11. "github.com/tendermint/tendermint/merkle"
  12. "github.com/tendermint/tendermint/types"
  13. )
  14. var (
  15. stateKey = []byte("stateKey")
  16. minBondAmount = int64(1) // TODO adjust
  17. defaultAccountsCacheCapacity = 1000 // TODO adjust
  18. unbondingPeriodBlocks = int(60 * 24 * 365) // TODO probably better to make it time based.
  19. validatorTimeoutBlocks = int(10) // TODO adjust
  20. )
  21. //-----------------------------------------------------------------------------
  22. // NOTE: not goroutine-safe.
  23. type State struct {
  24. DB dbm.DB
  25. ChainID string
  26. LastBlockHeight int
  27. LastBlockHash []byte
  28. LastBlockParts types.PartSetHeader
  29. LastBlockTime time.Time
  30. BondedValidators *ValidatorSet
  31. LastBondedValidators *ValidatorSet
  32. UnbondingValidators *ValidatorSet
  33. accounts merkle.Tree // Shouldn't be accessed directly.
  34. validatorInfos merkle.Tree // Shouldn't be accessed directly.
  35. nameReg merkle.Tree // Shouldn't be accessed directly.
  36. evc events.Fireable // typically an events.EventCache
  37. }
  38. func LoadState(db dbm.DB) *State {
  39. s := &State{DB: db}
  40. buf := db.Get(stateKey)
  41. if len(buf) == 0 {
  42. return nil
  43. } else {
  44. r, n, err := bytes.NewReader(buf), new(int64), new(error)
  45. s.ChainID = wire.ReadString(r, n, err)
  46. s.LastBlockHeight = wire.ReadVarint(r, n, err)
  47. s.LastBlockHash = wire.ReadByteSlice(r, n, err)
  48. s.LastBlockParts = wire.ReadBinary(types.PartSetHeader{}, r, n, err).(types.PartSetHeader)
  49. s.LastBlockTime = wire.ReadTime(r, n, err)
  50. s.BondedValidators = wire.ReadBinary(&ValidatorSet{}, r, n, err).(*ValidatorSet)
  51. s.LastBondedValidators = wire.ReadBinary(&ValidatorSet{}, r, n, err).(*ValidatorSet)
  52. s.UnbondingValidators = wire.ReadBinary(&ValidatorSet{}, r, n, err).(*ValidatorSet)
  53. accountsHash := wire.ReadByteSlice(r, n, err)
  54. s.accounts = merkle.NewIAVLTree(wire.BasicCodec, acm.AccountCodec, defaultAccountsCacheCapacity, db)
  55. s.accounts.Load(accountsHash)
  56. validatorInfosHash := wire.ReadByteSlice(r, n, err)
  57. s.validatorInfos = merkle.NewIAVLTree(wire.BasicCodec, ValidatorInfoCodec, 0, db)
  58. s.validatorInfos.Load(validatorInfosHash)
  59. nameRegHash := wire.ReadByteSlice(r, n, err)
  60. s.nameReg = merkle.NewIAVLTree(wire.BasicCodec, NameRegCodec, 0, db)
  61. s.nameReg.Load(nameRegHash)
  62. if *err != nil {
  63. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  64. Exit(Fmt("Data has been corrupted or its spec has changed: %v\n", *err))
  65. }
  66. // TODO: ensure that buf is completely read.
  67. }
  68. return s
  69. }
  70. func (s *State) Save() {
  71. s.accounts.Save()
  72. s.validatorInfos.Save()
  73. s.nameReg.Save()
  74. buf, n, err := new(bytes.Buffer), new(int64), new(error)
  75. wire.WriteString(s.ChainID, buf, n, err)
  76. wire.WriteVarint(s.LastBlockHeight, buf, n, err)
  77. wire.WriteByteSlice(s.LastBlockHash, buf, n, err)
  78. wire.WriteBinary(s.LastBlockParts, buf, n, err)
  79. wire.WriteTime(s.LastBlockTime, buf, n, err)
  80. wire.WriteBinary(s.BondedValidators, buf, n, err)
  81. wire.WriteBinary(s.LastBondedValidators, buf, n, err)
  82. wire.WriteBinary(s.UnbondingValidators, buf, n, err)
  83. wire.WriteByteSlice(s.accounts.Hash(), buf, n, err)
  84. wire.WriteByteSlice(s.validatorInfos.Hash(), buf, n, err)
  85. wire.WriteByteSlice(s.nameReg.Hash(), buf, n, err)
  86. if *err != nil {
  87. PanicCrisis(*err)
  88. }
  89. s.DB.Set(stateKey, buf.Bytes())
  90. }
  91. // CONTRACT:
  92. // Copy() is a cheap way to take a snapshot,
  93. // as if State were copied by value.
  94. func (s *State) Copy() *State {
  95. return &State{
  96. DB: s.DB,
  97. ChainID: s.ChainID,
  98. LastBlockHeight: s.LastBlockHeight,
  99. LastBlockHash: s.LastBlockHash,
  100. LastBlockParts: s.LastBlockParts,
  101. LastBlockTime: s.LastBlockTime,
  102. BondedValidators: s.BondedValidators.Copy(), // TODO remove need for Copy() here.
  103. LastBondedValidators: s.LastBondedValidators.Copy(), // That is, make updates to the validator set
  104. UnbondingValidators: s.UnbondingValidators.Copy(), // copy the valSet lazily.
  105. accounts: s.accounts.Copy(),
  106. validatorInfos: s.validatorInfos.Copy(),
  107. nameReg: s.nameReg.Copy(),
  108. evc: nil,
  109. }
  110. }
  111. // Returns a hash that represents the state data, excluding Last*
  112. func (s *State) Hash() []byte {
  113. hashables := []merkle.Hashable{
  114. s.BondedValidators,
  115. s.UnbondingValidators,
  116. s.accounts,
  117. s.validatorInfos,
  118. s.nameReg,
  119. }
  120. return merkle.SimpleHashFromHashables(hashables)
  121. }
  122. // Mutates the block in place and updates it with new state hash.
  123. func (s *State) ComputeBlockStateHash(block *types.Block) error {
  124. sCopy := s.Copy()
  125. // sCopy has no event cache in it, so this won't fire events
  126. err := execBlock(sCopy, block, types.PartSetHeader{})
  127. if err != nil {
  128. return err
  129. }
  130. // Set block.StateHash
  131. block.StateHash = sCopy.Hash()
  132. return nil
  133. }
  134. func (s *State) SetDB(db dbm.DB) {
  135. s.DB = db
  136. }
  137. //-------------------------------------
  138. // State.params
  139. func (s *State) GetGasLimit() int64 {
  140. return 1000000 // TODO
  141. }
  142. // State.params
  143. //-------------------------------------
  144. // State.accounts
  145. // Returns nil if account does not exist with given address.
  146. // The returned Account is a copy, so mutating it
  147. // has no side effects.
  148. // Implements Statelike
  149. func (s *State) GetAccount(address []byte) *acm.Account {
  150. _, acc := s.accounts.Get(address)
  151. if acc == nil {
  152. return nil
  153. }
  154. return acc.(*acm.Account).Copy()
  155. }
  156. // The account is copied before setting, so mutating it
  157. // afterwards has no side effects.
  158. // Implements Statelike
  159. func (s *State) UpdateAccount(account *acm.Account) bool {
  160. return s.accounts.Set(account.Address, account.Copy())
  161. }
  162. // Implements Statelike
  163. func (s *State) RemoveAccount(address []byte) bool {
  164. _, removed := s.accounts.Remove(address)
  165. return removed
  166. }
  167. // The returned Account is a copy, so mutating it
  168. // has no side effects.
  169. func (s *State) GetAccounts() merkle.Tree {
  170. return s.accounts.Copy()
  171. }
  172. // Set the accounts tree
  173. func (s *State) SetAccounts(accounts merkle.Tree) {
  174. s.accounts = accounts
  175. }
  176. // State.accounts
  177. //-------------------------------------
  178. // State.validators
  179. // The returned ValidatorInfo is a copy, so mutating it
  180. // has no side effects.
  181. func (s *State) GetValidatorInfo(address []byte) *ValidatorInfo {
  182. _, valInfo := s.validatorInfos.Get(address)
  183. if valInfo == nil {
  184. return nil
  185. }
  186. return valInfo.(*ValidatorInfo).Copy()
  187. }
  188. // Returns false if new, true if updated.
  189. // The valInfo is copied before setting, so mutating it
  190. // afterwards has no side effects.
  191. func (s *State) SetValidatorInfo(valInfo *ValidatorInfo) (updated bool) {
  192. return s.validatorInfos.Set(valInfo.Address, valInfo.Copy())
  193. }
  194. func (s *State) GetValidatorInfos() merkle.Tree {
  195. return s.validatorInfos.Copy()
  196. }
  197. func (s *State) unbondValidator(val *Validator) {
  198. // Move validator to UnbondingValidators
  199. val, removed := s.BondedValidators.Remove(val.Address)
  200. if !removed {
  201. PanicCrisis("Couldn't remove validator for unbonding")
  202. }
  203. val.UnbondHeight = s.LastBlockHeight + 1
  204. added := s.UnbondingValidators.Add(val)
  205. if !added {
  206. PanicCrisis("Couldn't add validator for unbonding")
  207. }
  208. }
  209. func (s *State) rebondValidator(val *Validator) {
  210. // Move validator to BondingValidators
  211. val, removed := s.UnbondingValidators.Remove(val.Address)
  212. if !removed {
  213. PanicCrisis("Couldn't remove validator for rebonding")
  214. }
  215. val.BondHeight = s.LastBlockHeight + 1
  216. added := s.BondedValidators.Add(val)
  217. if !added {
  218. PanicCrisis("Couldn't add validator for rebonding")
  219. }
  220. }
  221. func (s *State) releaseValidator(val *Validator) {
  222. // Update validatorInfo
  223. valInfo := s.GetValidatorInfo(val.Address)
  224. if valInfo == nil {
  225. PanicSanity("Couldn't find validatorInfo for release")
  226. }
  227. valInfo.ReleasedHeight = s.LastBlockHeight + 1
  228. s.SetValidatorInfo(valInfo)
  229. // Send coins back to UnbondTo outputs
  230. accounts, err := getOrMakeOutputs(s, nil, valInfo.UnbondTo)
  231. if err != nil {
  232. PanicSanity("Couldn't get or make unbondTo accounts")
  233. }
  234. adjustByOutputs(accounts, valInfo.UnbondTo)
  235. for _, acc := range accounts {
  236. s.UpdateAccount(acc)
  237. }
  238. // Remove validator from UnbondingValidators
  239. _, removed := s.UnbondingValidators.Remove(val.Address)
  240. if !removed {
  241. PanicCrisis("Couldn't remove validator for release")
  242. }
  243. }
  244. func (s *State) destroyValidator(val *Validator) {
  245. // Update validatorInfo
  246. valInfo := s.GetValidatorInfo(val.Address)
  247. if valInfo == nil {
  248. PanicSanity("Couldn't find validatorInfo for release")
  249. }
  250. valInfo.DestroyedHeight = s.LastBlockHeight + 1
  251. valInfo.DestroyedAmount = val.VotingPower
  252. s.SetValidatorInfo(valInfo)
  253. // Remove validator
  254. _, removed := s.BondedValidators.Remove(val.Address)
  255. if !removed {
  256. _, removed := s.UnbondingValidators.Remove(val.Address)
  257. if !removed {
  258. PanicCrisis("Couldn't remove validator for destruction")
  259. }
  260. }
  261. }
  262. // Set the validator infos tree
  263. func (s *State) SetValidatorInfos(validatorInfos merkle.Tree) {
  264. s.validatorInfos = validatorInfos
  265. }
  266. // State.validators
  267. //-------------------------------------
  268. // State.storage
  269. func (s *State) LoadStorage(hash []byte) (storage merkle.Tree) {
  270. storage = merkle.NewIAVLTree(wire.BasicCodec, wire.BasicCodec, 1024, s.DB)
  271. storage.Load(hash)
  272. return storage
  273. }
  274. // State.storage
  275. //-------------------------------------
  276. // State.nameReg
  277. func (s *State) GetNameRegEntry(name string) *types.NameRegEntry {
  278. _, value := s.nameReg.Get(name)
  279. if value == nil {
  280. return nil
  281. }
  282. entry := value.(*types.NameRegEntry)
  283. return entry.Copy()
  284. }
  285. func (s *State) UpdateNameRegEntry(entry *types.NameRegEntry) bool {
  286. return s.nameReg.Set(entry.Name, entry)
  287. }
  288. func (s *State) RemoveNameRegEntry(name string) bool {
  289. _, removed := s.nameReg.Remove(name)
  290. return removed
  291. }
  292. func (s *State) GetNames() merkle.Tree {
  293. return s.nameReg.Copy()
  294. }
  295. // Set the name reg tree
  296. func (s *State) SetNameReg(nameReg merkle.Tree) {
  297. s.nameReg = nameReg
  298. }
  299. func NameRegEncoder(o interface{}, w io.Writer, n *int64, err *error) {
  300. wire.WriteBinary(o.(*types.NameRegEntry), w, n, err)
  301. }
  302. func NameRegDecoder(r io.Reader, n *int64, err *error) interface{} {
  303. return wire.ReadBinary(&types.NameRegEntry{}, r, n, err)
  304. }
  305. var NameRegCodec = wire.Codec{
  306. Encode: NameRegEncoder,
  307. Decode: NameRegDecoder,
  308. }
  309. // State.nameReg
  310. //-------------------------------------
  311. // Implements events.Eventable. Typically uses events.EventCache
  312. func (s *State) SetFireable(evc events.Fireable) {
  313. s.evc = evc
  314. }
  315. //-----------------------------------------------------------------------------
  316. type InvalidTxError struct {
  317. Tx types.Tx
  318. Reason error
  319. }
  320. func (txErr InvalidTxError) Error() string {
  321. return Fmt("Invalid tx: [%v] reason: [%v]", txErr.Tx, txErr.Reason)
  322. }