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.

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