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.

353 lines
10 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
  1. package state
  2. import (
  3. "bytes"
  4. "io"
  5. "time"
  6. "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, account.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. // SOMETHING HAS GONE HORRIBLY WRONG
  88. panic(*err)
  89. }
  90. s.DB.Set(stateKey, buf.Bytes())
  91. }
  92. // CONTRACT:
  93. // Copy() is a cheap way to take a snapshot,
  94. // as if State were copied by value.
  95. func (s *State) Copy() *State {
  96. return &State{
  97. DB: s.DB,
  98. ChainID: s.ChainID,
  99. LastBlockHeight: s.LastBlockHeight,
  100. LastBlockHash: s.LastBlockHash,
  101. LastBlockParts: s.LastBlockParts,
  102. LastBlockTime: s.LastBlockTime,
  103. BondedValidators: s.BondedValidators.Copy(), // TODO remove need for Copy() here.
  104. LastBondedValidators: s.LastBondedValidators.Copy(), // That is, make updates to the validator set
  105. UnbondingValidators: s.UnbondingValidators.Copy(), // copy the valSet lazily.
  106. accounts: s.accounts.Copy(),
  107. validatorInfos: s.validatorInfos.Copy(),
  108. nameReg: s.nameReg.Copy(),
  109. evc: nil,
  110. }
  111. }
  112. // Returns a hash that represents the state data, excluding Last*
  113. func (s *State) Hash() []byte {
  114. hashables := []merkle.Hashable{
  115. s.BondedValidators,
  116. s.UnbondingValidators,
  117. s.accounts,
  118. s.validatorInfos,
  119. s.nameReg,
  120. }
  121. return merkle.SimpleHashFromHashables(hashables)
  122. }
  123. // Mutates the block in place and updates it with new state hash.
  124. func (s *State) ComputeBlockStateHash(block *types.Block) error {
  125. sCopy := s.Copy()
  126. // sCopy has no event cache in it, so this won't fire events
  127. err := execBlock(sCopy, block, types.PartSetHeader{})
  128. if err != nil {
  129. return err
  130. }
  131. // Set block.StateHash
  132. block.StateHash = sCopy.Hash()
  133. return nil
  134. }
  135. //-------------------------------------
  136. // State.accounts
  137. // Returns nil if account does not exist with given address.
  138. // The returned Account is a copy, so mutating it
  139. // has no side effects.
  140. // Implements Statelike
  141. func (s *State) GetAccount(address []byte) *account.Account {
  142. _, acc := s.accounts.Get(address)
  143. if acc == nil {
  144. return nil
  145. }
  146. return acc.(*account.Account).Copy()
  147. }
  148. // The account is copied before setting, so mutating it
  149. // afterwards has no side effects.
  150. // Implements Statelike
  151. func (s *State) UpdateAccount(account *account.Account) bool {
  152. return s.accounts.Set(account.Address, account.Copy())
  153. }
  154. // Implements Statelike
  155. func (s *State) RemoveAccount(address []byte) bool {
  156. _, removed := s.accounts.Remove(address)
  157. return removed
  158. }
  159. // The returned Account is a copy, so mutating it
  160. // has no side effects.
  161. func (s *State) GetAccounts() merkle.Tree {
  162. return s.accounts.Copy()
  163. }
  164. // State.accounts
  165. //-------------------------------------
  166. // State.validators
  167. // The returned ValidatorInfo is a copy, so mutating it
  168. // has no side effects.
  169. func (s *State) GetValidatorInfo(address []byte) *ValidatorInfo {
  170. _, valInfo := s.validatorInfos.Get(address)
  171. if valInfo == nil {
  172. return nil
  173. }
  174. return valInfo.(*ValidatorInfo).Copy()
  175. }
  176. // Returns false if new, true if updated.
  177. // The valInfo is copied before setting, so mutating it
  178. // afterwards has no side effects.
  179. func (s *State) SetValidatorInfo(valInfo *ValidatorInfo) (updated bool) {
  180. return s.validatorInfos.Set(valInfo.Address, valInfo.Copy())
  181. }
  182. func (s *State) unbondValidator(val *Validator) {
  183. // Move validator to UnbondingValidators
  184. val, removed := s.BondedValidators.Remove(val.Address)
  185. if !removed {
  186. // SOMETHING HAS GONE HORRIBLY WRONG
  187. panic("Couldn't remove validator for unbonding")
  188. }
  189. val.UnbondHeight = s.LastBlockHeight + 1
  190. added := s.UnbondingValidators.Add(val)
  191. if !added {
  192. // SOMETHING HAS GONE HORRIBLY WRONG
  193. panic("Couldn't add validator for unbonding")
  194. }
  195. }
  196. func (s *State) rebondValidator(val *Validator) {
  197. // Move validator to BondingValidators
  198. val, removed := s.UnbondingValidators.Remove(val.Address)
  199. if !removed {
  200. // SOMETHING HAS GONE HORRIBLY WRONG
  201. panic("Couldn't remove validator for rebonding")
  202. }
  203. val.BondHeight = s.LastBlockHeight + 1
  204. added := s.BondedValidators.Add(val)
  205. if !added {
  206. // SOMETHING HAS GONE HORRIBLY WRONG
  207. panic("Couldn't add validator for rebonding")
  208. }
  209. }
  210. func (s *State) releaseValidator(val *Validator) {
  211. // Update validatorInfo
  212. valInfo := s.GetValidatorInfo(val.Address)
  213. // SANITY CHECK
  214. if valInfo == nil {
  215. panic("Couldn't find validatorInfo for release")
  216. }
  217. // SANITY CHECK END
  218. valInfo.ReleasedHeight = s.LastBlockHeight + 1
  219. s.SetValidatorInfo(valInfo)
  220. // Send coins back to UnbondTo outputs
  221. // SANITY CHECK
  222. accounts, err := getOrMakeOutputs(s, nil, valInfo.UnbondTo)
  223. if err != nil {
  224. panic("Couldn't get or make unbondTo accounts")
  225. }
  226. // SANITY CHECK END
  227. adjustByOutputs(accounts, valInfo.UnbondTo)
  228. for _, acc := range accounts {
  229. s.UpdateAccount(acc)
  230. }
  231. // Remove validator from UnbondingValidators
  232. _, removed := s.UnbondingValidators.Remove(val.Address)
  233. if !removed {
  234. // SOMETHING HAS GONE HORRIBLY WRONG
  235. panic("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. // SANITY CHECK
  242. if valInfo == nil {
  243. panic("Couldn't find validatorInfo for release")
  244. }
  245. // SANITY CHECK END
  246. valInfo.DestroyedHeight = s.LastBlockHeight + 1
  247. valInfo.DestroyedAmount = val.VotingPower
  248. s.SetValidatorInfo(valInfo)
  249. // Remove validator
  250. _, removed := s.BondedValidators.Remove(val.Address)
  251. if !removed {
  252. _, removed := s.UnbondingValidators.Remove(val.Address)
  253. if !removed {
  254. // SOMETHING HAS GONE HORRIBLY WRONG
  255. panic("Couldn't remove validator for destruction")
  256. }
  257. }
  258. }
  259. // State.validators
  260. //-------------------------------------
  261. // State.storage
  262. func (s *State) LoadStorage(hash []byte) (storage merkle.Tree) {
  263. storage = merkle.NewIAVLTree(binary.BasicCodec, binary.BasicCodec, 1024, s.DB)
  264. storage.Load(hash)
  265. return storage
  266. }
  267. // State.storage
  268. //-------------------------------------
  269. // State.nameReg
  270. func (s *State) GetNameRegEntry(name string) *types.NameRegEntry {
  271. _, value := s.nameReg.Get(name)
  272. if value == nil {
  273. return nil
  274. }
  275. entry := value.(*types.NameRegEntry)
  276. return entry.Copy()
  277. }
  278. func (s *State) UpdateNameRegEntry(entry *types.NameRegEntry) bool {
  279. return s.nameReg.Set(entry.Name, entry)
  280. }
  281. func (s *State) RemoveNameRegEntry(name string) bool {
  282. _, removed := s.nameReg.Remove(name)
  283. return removed
  284. }
  285. func (s *State) GetNames() merkle.Tree {
  286. return s.nameReg.Copy()
  287. }
  288. func NameRegEncoder(o interface{}, w io.Writer, n *int64, err *error) {
  289. binary.WriteBinary(o.(*types.NameRegEntry), w, n, err)
  290. }
  291. func NameRegDecoder(r io.Reader, n *int64, err *error) interface{} {
  292. return binary.ReadBinary(&types.NameRegEntry{}, r, n, err)
  293. }
  294. var NameRegCodec = binary.Codec{
  295. Encode: NameRegEncoder,
  296. Decode: NameRegDecoder,
  297. }
  298. // State.nameReg
  299. //-------------------------------------
  300. // Implements events.Eventable. Typically uses events.EventCache
  301. func (s *State) SetFireable(evc events.Fireable) {
  302. s.evc = evc
  303. }
  304. //-----------------------------------------------------------------------------
  305. type InvalidTxError struct {
  306. Tx types.Tx
  307. Reason error
  308. }
  309. func (txErr InvalidTxError) Error() string {
  310. return Fmt("Invalid tx: [%v] reason: [%v]", txErr.Tx, txErr.Reason)
  311. }