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.

476 lines
14 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
10 years ago
10 years ago
  1. package state
  2. import (
  3. "bytes"
  4. "io"
  5. "io/ioutil"
  6. "time"
  7. acm "github.com/tendermint/tendermint/account"
  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. ptypes "github.com/tendermint/tendermint/permission/types"
  13. . "github.com/tendermint/tendermint/state/types"
  14. "github.com/tendermint/tendermint/types"
  15. "github.com/tendermint/tendermint/wire"
  16. )
  17. var (
  18. stateKey = []byte("stateKey")
  19. minBondAmount = int64(1) // TODO adjust
  20. defaultAccountsCacheCapacity = 1000 // TODO adjust
  21. unbondingPeriodBlocks = int(60 * 24 * 365) // TODO probably better to make it time based.
  22. validatorTimeoutBlocks = int(10) // TODO adjust
  23. )
  24. //-----------------------------------------------------------------------------
  25. // NOTE: not goroutine-safe.
  26. type State struct {
  27. DB dbm.DB
  28. ChainID string
  29. LastBlockHeight int
  30. LastBlockHash []byte
  31. LastBlockParts types.PartSetHeader
  32. LastBlockTime time.Time
  33. BondedValidators *types.ValidatorSet
  34. LastBondedValidators *types.ValidatorSet
  35. UnbondingValidators *types.ValidatorSet
  36. accounts merkle.Tree // Shouldn't be accessed directly.
  37. validatorInfos merkle.Tree // Shouldn't be accessed directly.
  38. nameReg merkle.Tree // Shouldn't be accessed directly.
  39. evc events.Fireable // typically an events.EventCache
  40. }
  41. func LoadState(db dbm.DB) *State {
  42. s := &State{DB: db}
  43. buf := db.Get(stateKey)
  44. if len(buf) == 0 {
  45. return nil
  46. } else {
  47. r, n, err := bytes.NewReader(buf), new(int64), new(error)
  48. s.ChainID = wire.ReadString(r, n, err)
  49. s.LastBlockHeight = wire.ReadVarint(r, n, err)
  50. s.LastBlockHash = wire.ReadByteSlice(r, n, err)
  51. s.LastBlockParts = wire.ReadBinary(types.PartSetHeader{}, r, n, err).(types.PartSetHeader)
  52. s.LastBlockTime = wire.ReadTime(r, n, err)
  53. s.BondedValidators = wire.ReadBinary(&types.ValidatorSet{}, r, n, err).(*types.ValidatorSet)
  54. s.LastBondedValidators = wire.ReadBinary(&types.ValidatorSet{}, r, n, err).(*types.ValidatorSet)
  55. s.UnbondingValidators = wire.ReadBinary(&types.ValidatorSet{}, r, n, err).(*types.ValidatorSet)
  56. accountsHash := wire.ReadByteSlice(r, n, err)
  57. s.accounts = merkle.NewIAVLTree(wire.BasicCodec, acm.AccountCodec, defaultAccountsCacheCapacity, db)
  58. s.accounts.Load(accountsHash)
  59. validatorInfosHash := wire.ReadByteSlice(r, n, err)
  60. s.validatorInfos = merkle.NewIAVLTree(wire.BasicCodec, types.ValidatorInfoCodec, 0, db)
  61. s.validatorInfos.Load(validatorInfosHash)
  62. nameRegHash := wire.ReadByteSlice(r, n, err)
  63. s.nameReg = merkle.NewIAVLTree(wire.BasicCodec, NameRegCodec, 0, db)
  64. s.nameReg.Load(nameRegHash)
  65. if *err != nil {
  66. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  67. Exit(Fmt("Data has been corrupted or its spec has changed: %v\n", *err))
  68. }
  69. // TODO: ensure that buf is completely read.
  70. }
  71. return s
  72. }
  73. func (s *State) Save() {
  74. s.accounts.Save()
  75. s.validatorInfos.Save()
  76. s.nameReg.Save()
  77. buf, n, err := new(bytes.Buffer), new(int64), new(error)
  78. wire.WriteString(s.ChainID, buf, n, err)
  79. wire.WriteVarint(s.LastBlockHeight, buf, n, err)
  80. wire.WriteByteSlice(s.LastBlockHash, buf, n, err)
  81. wire.WriteBinary(s.LastBlockParts, buf, n, err)
  82. wire.WriteTime(s.LastBlockTime, buf, n, err)
  83. wire.WriteBinary(s.BondedValidators, buf, n, err)
  84. wire.WriteBinary(s.LastBondedValidators, buf, n, err)
  85. wire.WriteBinary(s.UnbondingValidators, buf, n, err)
  86. wire.WriteByteSlice(s.accounts.Hash(), buf, n, err)
  87. wire.WriteByteSlice(s.validatorInfos.Hash(), buf, n, err)
  88. wire.WriteByteSlice(s.nameReg.Hash(), buf, n, err)
  89. if *err != nil {
  90. PanicCrisis(*err)
  91. }
  92. s.DB.Set(stateKey, buf.Bytes())
  93. }
  94. // CONTRACT:
  95. // Copy() is a cheap way to take a snapshot,
  96. // as if State were copied by value.
  97. func (s *State) Copy() *State {
  98. return &State{
  99. DB: s.DB,
  100. ChainID: s.ChainID,
  101. LastBlockHeight: s.LastBlockHeight,
  102. LastBlockHash: s.LastBlockHash,
  103. LastBlockParts: s.LastBlockParts,
  104. LastBlockTime: s.LastBlockTime,
  105. BondedValidators: s.BondedValidators.Copy(), // TODO remove need for Copy() here.
  106. LastBondedValidators: s.LastBondedValidators.Copy(), // That is, make updates to the validator set
  107. UnbondingValidators: s.UnbondingValidators.Copy(), // copy the valSet lazily.
  108. accounts: s.accounts.Copy(),
  109. validatorInfos: s.validatorInfos.Copy(),
  110. nameReg: s.nameReg.Copy(),
  111. evc: nil,
  112. }
  113. }
  114. // Returns a hash that represents the state data, excluding Last*
  115. func (s *State) Hash() []byte {
  116. hashables := []merkle.Hashable{
  117. s.BondedValidators,
  118. s.UnbondingValidators,
  119. s.accounts,
  120. s.validatorInfos,
  121. s.nameReg,
  122. }
  123. return merkle.SimpleHashFromHashables(hashables)
  124. }
  125. // Mutates the block in place and updates it with new state hash.
  126. func (s *State) ComputeBlockStateHash(block *types.Block) error {
  127. sCopy := s.Copy()
  128. // sCopy has no event cache in it, so this won't fire events
  129. err := execBlock(sCopy, block, types.PartSetHeader{})
  130. if err != nil {
  131. return err
  132. }
  133. // Set block.StateHash
  134. block.StateHash = sCopy.Hash()
  135. return nil
  136. }
  137. func (s *State) SetDB(db dbm.DB) {
  138. s.DB = db
  139. }
  140. //-------------------------------------
  141. // State.params
  142. func (s *State) GetGasLimit() int64 {
  143. return 1000000 // TODO
  144. }
  145. // State.params
  146. //-------------------------------------
  147. // State.accounts
  148. // Returns nil if account does not exist with given address.
  149. // The returned Account is a copy, so mutating it
  150. // has no side effects.
  151. // Implements Statelike
  152. func (s *State) GetAccount(address []byte) *acm.Account {
  153. _, acc := s.accounts.Get(address)
  154. if acc == nil {
  155. return nil
  156. }
  157. return acc.(*acm.Account).Copy()
  158. }
  159. // The account is copied before setting, so mutating it
  160. // afterwards has no side effects.
  161. // Implements Statelike
  162. func (s *State) UpdateAccount(account *acm.Account) bool {
  163. return s.accounts.Set(account.Address, account.Copy())
  164. }
  165. // Implements Statelike
  166. func (s *State) RemoveAccount(address []byte) bool {
  167. _, removed := s.accounts.Remove(address)
  168. return removed
  169. }
  170. // The returned Account is a copy, so mutating it
  171. // has no side effects.
  172. func (s *State) GetAccounts() merkle.Tree {
  173. return s.accounts.Copy()
  174. }
  175. // Set the accounts tree
  176. func (s *State) SetAccounts(accounts merkle.Tree) {
  177. s.accounts = accounts
  178. }
  179. // State.accounts
  180. //-------------------------------------
  181. // State.validators
  182. // The returned ValidatorInfo is a copy, so mutating it
  183. // has no side effects.
  184. func (s *State) GetValidatorInfo(address []byte) *types.ValidatorInfo {
  185. _, valInfo := s.validatorInfos.Get(address)
  186. if valInfo == nil {
  187. return nil
  188. }
  189. return valInfo.(*types.ValidatorInfo).Copy()
  190. }
  191. // Returns false if new, true if updated.
  192. // The valInfo is copied before setting, so mutating it
  193. // afterwards has no side effects.
  194. func (s *State) SetValidatorInfo(valInfo *types.ValidatorInfo) (updated bool) {
  195. return s.validatorInfos.Set(valInfo.Address, valInfo.Copy())
  196. }
  197. func (s *State) GetValidatorInfos() merkle.Tree {
  198. return s.validatorInfos.Copy()
  199. }
  200. func (s *State) unbondValidator(val *types.Validator) {
  201. // Move validator to UnbondingValidators
  202. val, removed := s.BondedValidators.Remove(val.Address)
  203. if !removed {
  204. PanicCrisis("Couldn't remove validator for unbonding")
  205. }
  206. val.UnbondHeight = s.LastBlockHeight + 1
  207. added := s.UnbondingValidators.Add(val)
  208. if !added {
  209. PanicCrisis("Couldn't add validator for unbonding")
  210. }
  211. }
  212. func (s *State) rebondValidator(val *types.Validator) {
  213. // Move validator to BondingValidators
  214. val, removed := s.UnbondingValidators.Remove(val.Address)
  215. if !removed {
  216. PanicCrisis("Couldn't remove validator for rebonding")
  217. }
  218. val.BondHeight = s.LastBlockHeight + 1
  219. added := s.BondedValidators.Add(val)
  220. if !added {
  221. PanicCrisis("Couldn't add validator for rebonding")
  222. }
  223. }
  224. func (s *State) releaseValidator(val *types.Validator) {
  225. // Update validatorInfo
  226. valInfo := s.GetValidatorInfo(val.Address)
  227. if valInfo == nil {
  228. PanicSanity("Couldn't find validatorInfo for release")
  229. }
  230. valInfo.ReleasedHeight = s.LastBlockHeight + 1
  231. s.SetValidatorInfo(valInfo)
  232. // Send coins back to UnbondTo outputs
  233. accounts, err := getOrMakeOutputs(s, nil, valInfo.UnbondTo)
  234. if err != nil {
  235. PanicSanity("Couldn't get or make unbondTo accounts")
  236. }
  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. PanicCrisis("Couldn't remove validator for release")
  245. }
  246. }
  247. func (s *State) destroyValidator(val *types.Validator) {
  248. // Update validatorInfo
  249. valInfo := s.GetValidatorInfo(val.Address)
  250. if valInfo == nil {
  251. PanicSanity("Couldn't find validatorInfo for release")
  252. }
  253. valInfo.DestroyedHeight = s.LastBlockHeight + 1
  254. valInfo.DestroyedAmount = val.VotingPower
  255. s.SetValidatorInfo(valInfo)
  256. // Remove validator
  257. _, removed := s.BondedValidators.Remove(val.Address)
  258. if !removed {
  259. _, removed := s.UnbondingValidators.Remove(val.Address)
  260. if !removed {
  261. PanicCrisis("Couldn't remove validator for destruction")
  262. }
  263. }
  264. }
  265. // Set the validator infos tree
  266. func (s *State) SetValidatorInfos(validatorInfos merkle.Tree) {
  267. s.validatorInfos = validatorInfos
  268. }
  269. // State.validators
  270. //-------------------------------------
  271. // State.storage
  272. func (s *State) LoadStorage(hash []byte) (storage merkle.Tree) {
  273. storage = merkle.NewIAVLTree(wire.BasicCodec, wire.BasicCodec, 1024, s.DB)
  274. storage.Load(hash)
  275. return storage
  276. }
  277. // State.storage
  278. //-------------------------------------
  279. // State.nameReg
  280. func (s *State) GetNameRegEntry(name string) *types.NameRegEntry {
  281. _, value := s.nameReg.Get(name)
  282. if value == nil {
  283. return nil
  284. }
  285. entry := value.(*types.NameRegEntry)
  286. return entry.Copy()
  287. }
  288. func (s *State) UpdateNameRegEntry(entry *types.NameRegEntry) bool {
  289. return s.nameReg.Set(entry.Name, entry)
  290. }
  291. func (s *State) RemoveNameRegEntry(name string) bool {
  292. _, removed := s.nameReg.Remove(name)
  293. return removed
  294. }
  295. func (s *State) GetNames() merkle.Tree {
  296. return s.nameReg.Copy()
  297. }
  298. // Set the name reg tree
  299. func (s *State) SetNameReg(nameReg merkle.Tree) {
  300. s.nameReg = nameReg
  301. }
  302. func NameRegEncoder(o interface{}, w io.Writer, n *int64, err *error) {
  303. wire.WriteBinary(o.(*types.NameRegEntry), w, n, err)
  304. }
  305. func NameRegDecoder(r io.Reader, n *int64, err *error) interface{} {
  306. return wire.ReadBinary(&types.NameRegEntry{}, r, n, err)
  307. }
  308. var NameRegCodec = wire.Codec{
  309. Encode: NameRegEncoder,
  310. Decode: NameRegDecoder,
  311. }
  312. // State.nameReg
  313. //-------------------------------------
  314. // Implements events.Eventable. Typically uses events.EventCache
  315. func (s *State) SetFireable(evc events.Fireable) {
  316. s.evc = evc
  317. }
  318. //-----------------------------------------------------------------------------
  319. // Genesis
  320. func MakeGenesisStateFromFile(db dbm.DB, genDocFile string) (*GenesisDoc, *State) {
  321. jsonBlob, err := ioutil.ReadFile(genDocFile)
  322. if err != nil {
  323. Exit(Fmt("Couldn't read GenesisDoc file: %v", err))
  324. }
  325. genDoc := GenesisDocFromJSON(jsonBlob)
  326. return genDoc, MakeGenesisState(db, genDoc)
  327. }
  328. func MakeGenesisState(db dbm.DB, genDoc *GenesisDoc) *State {
  329. if len(genDoc.Validators) == 0 {
  330. Exit(Fmt("The genesis file has no validators"))
  331. }
  332. if genDoc.GenesisTime.IsZero() {
  333. genDoc.GenesisTime = time.Now()
  334. }
  335. // Make accounts state tree
  336. accounts := merkle.NewIAVLTree(wire.BasicCodec, acm.AccountCodec, defaultAccountsCacheCapacity, db)
  337. for _, genAcc := range genDoc.Accounts {
  338. perm := ptypes.ZeroAccountPermissions
  339. if genAcc.Permissions != nil {
  340. perm = *genAcc.Permissions
  341. }
  342. acc := &acm.Account{
  343. Address: genAcc.Address,
  344. PubKey: nil,
  345. Sequence: 0,
  346. Balance: genAcc.Amount,
  347. Permissions: perm,
  348. }
  349. accounts.Set(acc.Address, acc)
  350. }
  351. // global permissions are saved as the 0 address
  352. // so they are included in the accounts tree
  353. globalPerms := ptypes.DefaultAccountPermissions
  354. if genDoc.Params != nil && genDoc.Params.GlobalPermissions != nil {
  355. globalPerms = *genDoc.Params.GlobalPermissions
  356. // XXX: make sure the set bits are all true
  357. // Without it the HasPermission() functions will fail
  358. globalPerms.Base.SetBit = ptypes.AllPermFlags
  359. }
  360. permsAcc := &acm.Account{
  361. Address: ptypes.GlobalPermissionsAddress,
  362. PubKey: nil,
  363. Sequence: 0,
  364. Balance: 1337,
  365. Permissions: globalPerms,
  366. }
  367. accounts.Set(permsAcc.Address, permsAcc)
  368. // Make validatorInfos state tree && validators slice
  369. validatorInfos := merkle.NewIAVLTree(wire.BasicCodec, types.ValidatorInfoCodec, 0, db)
  370. validators := make([]*types.Validator, len(genDoc.Validators))
  371. for i, val := range genDoc.Validators {
  372. pubKey := val.PubKey
  373. address := pubKey.Address()
  374. // Make ValidatorInfo
  375. valInfo := &types.ValidatorInfo{
  376. Address: address,
  377. PubKey: pubKey,
  378. UnbondTo: make([]*types.TxOutput, len(val.UnbondTo)),
  379. FirstBondHeight: 0,
  380. FirstBondAmount: val.Amount,
  381. }
  382. for i, unbondTo := range val.UnbondTo {
  383. valInfo.UnbondTo[i] = &types.TxOutput{
  384. Address: unbondTo.Address,
  385. Amount: unbondTo.Amount,
  386. }
  387. }
  388. validatorInfos.Set(address, valInfo)
  389. // Make validator
  390. validators[i] = &types.Validator{
  391. Address: address,
  392. PubKey: pubKey,
  393. VotingPower: val.Amount,
  394. }
  395. }
  396. // Make namereg tree
  397. nameReg := merkle.NewIAVLTree(wire.BasicCodec, NameRegCodec, 0, db)
  398. // TODO: add names, contracts to genesis.json
  399. // IAVLTrees must be persisted before copy operations.
  400. accounts.Save()
  401. validatorInfos.Save()
  402. nameReg.Save()
  403. return &State{
  404. DB: db,
  405. ChainID: genDoc.ChainID,
  406. LastBlockHeight: 0,
  407. LastBlockHash: nil,
  408. LastBlockParts: types.PartSetHeader{},
  409. LastBlockTime: genDoc.GenesisTime,
  410. BondedValidators: types.NewValidatorSet(validators),
  411. LastBondedValidators: types.NewValidatorSet(nil),
  412. UnbondingValidators: types.NewValidatorSet(nil),
  413. accounts: accounts,
  414. validatorInfos: validatorInfos,
  415. nameReg: nameReg,
  416. }
  417. }