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.

338 lines
9.9 KiB

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