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.

286 lines
8.5 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
  1. package state
  2. import (
  3. "bytes"
  4. "fmt"
  5. "time"
  6. "github.com/tendermint/tendermint/account"
  7. "github.com/tendermint/tendermint/binary"
  8. dbm "github.com/tendermint/tendermint/db"
  9. "github.com/tendermint/tendermint/events"
  10. "github.com/tendermint/tendermint/merkle"
  11. "github.com/tendermint/tendermint/types"
  12. )
  13. var (
  14. stateKey = []byte("stateKey")
  15. minBondAmount = uint64(1) // TODO adjust
  16. defaultAccountsCacheCapacity = 1000 // TODO adjust
  17. unbondingPeriodBlocks = uint(60 * 24 * 365) // TODO probably better to make it time based.
  18. validatorTimeoutBlocks = uint(10) // TODO adjust
  19. )
  20. //-----------------------------------------------------------------------------
  21. // NOTE: not goroutine-safe.
  22. type State struct {
  23. DB dbm.DB
  24. LastBlockHeight uint
  25. LastBlockHash []byte
  26. LastBlockParts types.PartSetHeader
  27. LastBlockTime time.Time
  28. BondedValidators *ValidatorSet
  29. LastBondedValidators *ValidatorSet
  30. UnbondingValidators *ValidatorSet
  31. accounts merkle.Tree // Shouldn't be accessed directly.
  32. validatorInfos merkle.Tree // Shouldn't be accessed directly.
  33. evc events.Fireable // typically an events.EventCache
  34. }
  35. func LoadState(db dbm.DB) *State {
  36. s := &State{DB: db}
  37. buf := db.Get(stateKey)
  38. if len(buf) == 0 {
  39. return nil
  40. } else {
  41. r, n, err := bytes.NewReader(buf), new(int64), new(error)
  42. s.LastBlockHeight = binary.ReadUvarint(r, n, err)
  43. s.LastBlockHash = binary.ReadByteSlice(r, n, err)
  44. s.LastBlockParts = binary.ReadBinary(types.PartSetHeader{}, r, n, err).(types.PartSetHeader)
  45. s.LastBlockTime = binary.ReadTime(r, n, err)
  46. s.BondedValidators = binary.ReadBinary(&ValidatorSet{}, r, n, err).(*ValidatorSet)
  47. s.LastBondedValidators = binary.ReadBinary(&ValidatorSet{}, r, n, err).(*ValidatorSet)
  48. s.UnbondingValidators = binary.ReadBinary(&ValidatorSet{}, r, n, err).(*ValidatorSet)
  49. accountsHash := binary.ReadByteSlice(r, n, err)
  50. s.accounts = merkle.NewIAVLTree(binary.BasicCodec, account.AccountCodec, defaultAccountsCacheCapacity, db)
  51. s.accounts.Load(accountsHash)
  52. validatorInfosHash := binary.ReadByteSlice(r, n, err)
  53. s.validatorInfos = merkle.NewIAVLTree(binary.BasicCodec, ValidatorInfoCodec, 0, db)
  54. s.validatorInfos.Load(validatorInfosHash)
  55. if *err != nil {
  56. panic(*err)
  57. }
  58. // TODO: ensure that buf is completely read.
  59. }
  60. return s
  61. }
  62. func (s *State) Save() {
  63. s.accounts.Save()
  64. s.validatorInfos.Save()
  65. buf, n, err := new(bytes.Buffer), new(int64), new(error)
  66. binary.WriteUvarint(s.LastBlockHeight, buf, n, err)
  67. binary.WriteByteSlice(s.LastBlockHash, buf, n, err)
  68. binary.WriteBinary(s.LastBlockParts, buf, n, err)
  69. binary.WriteTime(s.LastBlockTime, buf, n, err)
  70. binary.WriteBinary(s.BondedValidators, buf, n, err)
  71. binary.WriteBinary(s.LastBondedValidators, buf, n, err)
  72. binary.WriteBinary(s.UnbondingValidators, buf, n, err)
  73. binary.WriteByteSlice(s.accounts.Hash(), buf, n, err)
  74. binary.WriteByteSlice(s.validatorInfos.Hash(), buf, n, err)
  75. if *err != nil {
  76. panic(*err)
  77. }
  78. s.DB.Set(stateKey, buf.Bytes())
  79. }
  80. // CONTRACT:
  81. // Copy() is a cheap way to take a snapshot,
  82. // as if State were copied by value.
  83. func (s *State) Copy() *State {
  84. return &State{
  85. DB: s.DB,
  86. LastBlockHeight: s.LastBlockHeight,
  87. LastBlockHash: s.LastBlockHash,
  88. LastBlockParts: s.LastBlockParts,
  89. LastBlockTime: s.LastBlockTime,
  90. BondedValidators: s.BondedValidators.Copy(), // TODO remove need for Copy() here.
  91. LastBondedValidators: s.LastBondedValidators.Copy(), // That is, make updates to the validator set
  92. UnbondingValidators: s.UnbondingValidators.Copy(), // copy the valSet lazily.
  93. accounts: s.accounts.Copy(),
  94. validatorInfos: s.validatorInfos.Copy(),
  95. evc: nil,
  96. }
  97. }
  98. // Returns a hash that represents the state data, excluding Last*
  99. func (s *State) Hash() []byte {
  100. hashables := []merkle.Hashable{
  101. s.BondedValidators,
  102. s.UnbondingValidators,
  103. s.accounts,
  104. s.validatorInfos,
  105. }
  106. return merkle.HashFromHashables(hashables)
  107. }
  108. // Mutates the block in place and updates it with new state hash.
  109. func (s *State) SetBlockStateHash(block *types.Block) error {
  110. sCopy := s.Copy()
  111. // sCopy has no event cache in it, so this won't fire events
  112. err := execBlock(sCopy, block, types.PartSetHeader{})
  113. if err != nil {
  114. return err
  115. }
  116. // Set block.StateHash
  117. block.StateHash = sCopy.Hash()
  118. return nil
  119. }
  120. //-------------------------------------
  121. // State.accounts
  122. // The returned Account is a copy, so mutating it
  123. // has no side effects.
  124. // Implements Statelike
  125. func (s *State) GetAccount(address []byte) *account.Account {
  126. _, acc := s.accounts.Get(address)
  127. if acc == nil {
  128. return nil
  129. }
  130. return acc.(*account.Account).Copy()
  131. }
  132. // The account is copied before setting, so mutating it
  133. // afterwards has no side effects.
  134. // Implements Statelike
  135. func (s *State) UpdateAccount(account *account.Account) bool {
  136. return s.accounts.Set(account.Address, account.Copy())
  137. }
  138. // Implements Statelike
  139. func (s *State) RemoveAccount(address []byte) bool {
  140. _, removed := s.accounts.Remove(address)
  141. return removed
  142. }
  143. // The returned Account is a copy, so mutating it
  144. // has no side effects.
  145. func (s *State) GetAccounts() merkle.Tree {
  146. return s.accounts.Copy()
  147. }
  148. // State.accounts
  149. //-------------------------------------
  150. // State.validators
  151. // The returned ValidatorInfo is a copy, so mutating it
  152. // has no side effects.
  153. func (s *State) GetValidatorInfo(address []byte) *ValidatorInfo {
  154. _, valInfo := s.validatorInfos.Get(address)
  155. if valInfo == nil {
  156. return nil
  157. }
  158. return valInfo.(*ValidatorInfo).Copy()
  159. }
  160. // Returns false if new, true if updated.
  161. // The valInfo is copied before setting, so mutating it
  162. // afterwards has no side effects.
  163. func (s *State) SetValidatorInfo(valInfo *ValidatorInfo) (updated bool) {
  164. return s.validatorInfos.Set(valInfo.Address, valInfo.Copy())
  165. }
  166. func (s *State) unbondValidator(val *Validator) {
  167. // Move validator to UnbondingValidators
  168. val, removed := s.BondedValidators.Remove(val.Address)
  169. if !removed {
  170. panic("Couldn't remove validator for unbonding")
  171. }
  172. val.UnbondHeight = s.LastBlockHeight + 1
  173. added := s.UnbondingValidators.Add(val)
  174. if !added {
  175. panic("Couldn't add validator for unbonding")
  176. }
  177. }
  178. func (s *State) rebondValidator(val *Validator) {
  179. // Move validator to BondingValidators
  180. val, removed := s.UnbondingValidators.Remove(val.Address)
  181. if !removed {
  182. panic("Couldn't remove validator for rebonding")
  183. }
  184. val.BondHeight = s.LastBlockHeight + 1
  185. added := s.BondedValidators.Add(val)
  186. if !added {
  187. panic("Couldn't add validator for rebonding")
  188. }
  189. }
  190. func (s *State) releaseValidator(val *Validator) {
  191. // Update validatorInfo
  192. valInfo := s.GetValidatorInfo(val.Address)
  193. if valInfo == nil {
  194. panic("Couldn't find validatorInfo for release")
  195. }
  196. valInfo.ReleasedHeight = s.LastBlockHeight + 1
  197. s.SetValidatorInfo(valInfo)
  198. // Send coins back to UnbondTo outputs
  199. accounts, err := getOrMakeAccounts(s, nil, valInfo.UnbondTo)
  200. if err != nil {
  201. panic("Couldn't get or make unbondTo accounts")
  202. }
  203. adjustByOutputs(accounts, valInfo.UnbondTo)
  204. for _, acc := range accounts {
  205. s.UpdateAccount(acc)
  206. }
  207. // Remove validator from UnbondingValidators
  208. _, removed := s.UnbondingValidators.Remove(val.Address)
  209. if !removed {
  210. panic("Couldn't remove validator for release")
  211. }
  212. }
  213. func (s *State) destroyValidator(val *Validator) {
  214. // Update validatorInfo
  215. valInfo := s.GetValidatorInfo(val.Address)
  216. if valInfo == nil {
  217. panic("Couldn't find validatorInfo for release")
  218. }
  219. valInfo.DestroyedHeight = s.LastBlockHeight + 1
  220. valInfo.DestroyedAmount = val.VotingPower
  221. s.SetValidatorInfo(valInfo)
  222. // Remove validator
  223. _, removed := s.BondedValidators.Remove(val.Address)
  224. if !removed {
  225. _, removed := s.UnbondingValidators.Remove(val.Address)
  226. if !removed {
  227. panic("Couldn't remove validator for destruction")
  228. }
  229. }
  230. }
  231. // State.validators
  232. //-------------------------------------
  233. // State.storage
  234. func (s *State) LoadStorage(hash []byte) (storage merkle.Tree) {
  235. storage = merkle.NewIAVLTree(binary.BasicCodec, binary.BasicCodec, 1024, s.DB)
  236. storage.Load(hash)
  237. return storage
  238. }
  239. // State.storage
  240. //-------------------------------------
  241. // Implements events.Eventable. Typically uses events.EventCache
  242. func (s *State) SetFireable(evc events.Fireable) {
  243. s.evc = evc
  244. }
  245. //-----------------------------------------------------------------------------
  246. type InvalidTxError struct {
  247. Tx types.Tx
  248. Reason error
  249. }
  250. func (txErr InvalidTxError) Error() string {
  251. return fmt.Sprintf("Invalid tx: [%v] reason: [%v]", txErr.Tx, txErr.Reason)
  252. }