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.

363 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
  1. package state
  2. import (
  3. "bytes"
  4. "io"
  5. "time"
  6. acm "github.com/tendermint/tendermint/account"
  7. "github.com/tendermint/tendermint/binary"
  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 = binary.ReadString(r, n, err)
  46. s.LastBlockHeight = binary.ReadVarint(r, n, err)
  47. s.LastBlockHash = binary.ReadByteSlice(r, n, err)
  48. s.LastBlockParts = binary.ReadBinary(types.PartSetHeader{}, r, n, err).(types.PartSetHeader)
  49. s.LastBlockTime = binary.ReadTime(r, n, err)
  50. s.BondedValidators = binary.ReadBinary(&ValidatorSet{}, r, n, err).(*ValidatorSet)
  51. s.LastBondedValidators = binary.ReadBinary(&ValidatorSet{}, r, n, err).(*ValidatorSet)
  52. s.UnbondingValidators = binary.ReadBinary(&ValidatorSet{}, r, n, err).(*ValidatorSet)
  53. accountsHash := binary.ReadByteSlice(r, n, err)
  54. s.accounts = merkle.NewIAVLTree(binary.BasicCodec, acm.AccountCodec, defaultAccountsCacheCapacity, db)
  55. s.accounts.Load(accountsHash)
  56. validatorInfosHash := binary.ReadByteSlice(r, n, err)
  57. s.validatorInfos = merkle.NewIAVLTree(binary.BasicCodec, ValidatorInfoCodec, 0, db)
  58. s.validatorInfos.Load(validatorInfosHash)
  59. nameRegHash := binary.ReadByteSlice(r, n, err)
  60. s.nameReg = merkle.NewIAVLTree(binary.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. binary.WriteString(s.ChainID, buf, n, err)
  76. binary.WriteVarint(s.LastBlockHeight, buf, n, err)
  77. binary.WriteByteSlice(s.LastBlockHash, buf, n, err)
  78. binary.WriteBinary(s.LastBlockParts, buf, n, err)
  79. binary.WriteTime(s.LastBlockTime, buf, n, err)
  80. binary.WriteBinary(s.BondedValidators, buf, n, err)
  81. binary.WriteBinary(s.LastBondedValidators, buf, n, err)
  82. binary.WriteBinary(s.UnbondingValidators, buf, n, err)
  83. binary.WriteByteSlice(s.accounts.Hash(), buf, n, err)
  84. binary.WriteByteSlice(s.validatorInfos.Hash(), buf, n, err)
  85. binary.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.accounts
  139. // Returns nil if account does not exist with given address.
  140. // The returned Account is a copy, so mutating it
  141. // has no side effects.
  142. // Implements Statelike
  143. func (s *State) GetAccount(address []byte) *acm.Account {
  144. _, acc := s.accounts.Get(address)
  145. if acc == nil {
  146. return nil
  147. }
  148. return acc.(*acm.Account).Copy()
  149. }
  150. // The account is copied before setting, so mutating it
  151. // afterwards has no side effects.
  152. // Implements Statelike
  153. func (s *State) UpdateAccount(account *acm.Account) bool {
  154. return s.accounts.Set(account.Address, account.Copy())
  155. }
  156. // Implements Statelike
  157. func (s *State) RemoveAccount(address []byte) bool {
  158. _, removed := s.accounts.Remove(address)
  159. return removed
  160. }
  161. // The returned Account is a copy, so mutating it
  162. // has no side effects.
  163. func (s *State) GetAccounts() merkle.Tree {
  164. return s.accounts.Copy()
  165. }
  166. // Set the accounts tree
  167. func (s *State) SetAccounts(accounts merkle.Tree) {
  168. s.accounts = accounts
  169. }
  170. // State.accounts
  171. //-------------------------------------
  172. // State.validators
  173. // The returned ValidatorInfo is a copy, so mutating it
  174. // has no side effects.
  175. func (s *State) GetValidatorInfo(address []byte) *ValidatorInfo {
  176. _, valInfo := s.validatorInfos.Get(address)
  177. if valInfo == nil {
  178. return nil
  179. }
  180. return valInfo.(*ValidatorInfo).Copy()
  181. }
  182. // Returns false if new, true if updated.
  183. // The valInfo is copied before setting, so mutating it
  184. // afterwards has no side effects.
  185. func (s *State) SetValidatorInfo(valInfo *ValidatorInfo) (updated bool) {
  186. return s.validatorInfos.Set(valInfo.Address, valInfo.Copy())
  187. }
  188. func (s *State) GetValidatorInfos() merkle.Tree {
  189. return s.validatorInfos.Copy()
  190. }
  191. func (s *State) unbondValidator(val *Validator) {
  192. // Move validator to UnbondingValidators
  193. val, removed := s.BondedValidators.Remove(val.Address)
  194. if !removed {
  195. PanicCrisis("Couldn't remove validator for unbonding")
  196. }
  197. val.UnbondHeight = s.LastBlockHeight + 1
  198. added := s.UnbondingValidators.Add(val)
  199. if !added {
  200. PanicCrisis("Couldn't add validator for unbonding")
  201. }
  202. }
  203. func (s *State) rebondValidator(val *Validator) {
  204. // Move validator to BondingValidators
  205. val, removed := s.UnbondingValidators.Remove(val.Address)
  206. if !removed {
  207. PanicCrisis("Couldn't remove validator for rebonding")
  208. }
  209. val.BondHeight = s.LastBlockHeight + 1
  210. added := s.BondedValidators.Add(val)
  211. if !added {
  212. PanicCrisis("Couldn't add validator for rebonding")
  213. }
  214. }
  215. func (s *State) releaseValidator(val *Validator) {
  216. // Update validatorInfo
  217. valInfo := s.GetValidatorInfo(val.Address)
  218. if valInfo == nil {
  219. PanicSanity("Couldn't find validatorInfo for release")
  220. }
  221. valInfo.ReleasedHeight = s.LastBlockHeight + 1
  222. s.SetValidatorInfo(valInfo)
  223. // Send coins back to UnbondTo outputs
  224. accounts, err := getOrMakeOutputs(s, nil, valInfo.UnbondTo)
  225. if err != nil {
  226. PanicSanity("Couldn't get or make unbondTo accounts")
  227. }
  228. adjustByOutputs(accounts, valInfo.UnbondTo)
  229. for _, acc := range accounts {
  230. s.UpdateAccount(acc)
  231. }
  232. // Remove validator from UnbondingValidators
  233. _, removed := s.UnbondingValidators.Remove(val.Address)
  234. if !removed {
  235. PanicCrisis("Couldn't remove validator for release")
  236. }
  237. }
  238. func (s *State) destroyValidator(val *Validator) {
  239. // Update validatorInfo
  240. valInfo := s.GetValidatorInfo(val.Address)
  241. if valInfo == nil {
  242. PanicSanity("Couldn't find validatorInfo for release")
  243. }
  244. valInfo.DestroyedHeight = s.LastBlockHeight + 1
  245. valInfo.DestroyedAmount = val.VotingPower
  246. s.SetValidatorInfo(valInfo)
  247. // Remove validator
  248. _, removed := s.BondedValidators.Remove(val.Address)
  249. if !removed {
  250. _, removed := s.UnbondingValidators.Remove(val.Address)
  251. if !removed {
  252. PanicCrisis("Couldn't remove validator for destruction")
  253. }
  254. }
  255. }
  256. // Set the validator infos tree
  257. func (s *State) SetValidatorInfos(validatorInfos merkle.Tree) {
  258. s.validatorInfos = validatorInfos
  259. }
  260. // State.validators
  261. //-------------------------------------
  262. // State.storage
  263. func (s *State) LoadStorage(hash []byte) (storage merkle.Tree) {
  264. storage = merkle.NewIAVLTree(binary.BasicCodec, binary.BasicCodec, 1024, s.DB)
  265. storage.Load(hash)
  266. return storage
  267. }
  268. // State.storage
  269. //-------------------------------------
  270. // State.nameReg
  271. func (s *State) GetNameRegEntry(name string) *types.NameRegEntry {
  272. _, value := s.nameReg.Get(name)
  273. if value == nil {
  274. return nil
  275. }
  276. entry := value.(*types.NameRegEntry)
  277. return entry.Copy()
  278. }
  279. func (s *State) UpdateNameRegEntry(entry *types.NameRegEntry) bool {
  280. return s.nameReg.Set(entry.Name, entry)
  281. }
  282. func (s *State) RemoveNameRegEntry(name string) bool {
  283. _, removed := s.nameReg.Remove(name)
  284. return removed
  285. }
  286. func (s *State) GetNames() merkle.Tree {
  287. return s.nameReg.Copy()
  288. }
  289. // Set the name reg tree
  290. func (s *State) SetNameReg(nameReg merkle.Tree) {
  291. s.nameReg = nameReg
  292. }
  293. func NameRegEncoder(o interface{}, w io.Writer, n *int64, err *error) {
  294. binary.WriteBinary(o.(*types.NameRegEntry), w, n, err)
  295. }
  296. func NameRegDecoder(r io.Reader, n *int64, err *error) interface{} {
  297. return binary.ReadBinary(&types.NameRegEntry{}, r, n, err)
  298. }
  299. var NameRegCodec = binary.Codec{
  300. Encode: NameRegEncoder,
  301. Decode: NameRegDecoder,
  302. }
  303. // State.nameReg
  304. //-------------------------------------
  305. // Implements events.Eventable. Typically uses events.EventCache
  306. func (s *State) SetFireable(evc events.Fireable) {
  307. s.evc = evc
  308. }
  309. //-----------------------------------------------------------------------------
  310. type InvalidTxError struct {
  311. Tx types.Tx
  312. Reason error
  313. }
  314. func (txErr InvalidTxError) Error() string {
  315. return Fmt("Invalid tx: [%v] reason: [%v]", txErr.Tx, txErr.Reason)
  316. }