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.

484 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
  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/go-common"
  9. dbm "github.com/tendermint/go-db"
  10. "github.com/tendermint/tendermint/events"
  11. "github.com/tendermint/go-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/go-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. return merkle.SimpleHashFromMap(map[string]interface{}{
  117. "BondedValidators": s.BondedValidators,
  118. "UnbondingValidators": s.UnbondingValidators,
  119. "Accounts": s.accounts,
  120. "ValidatorInfos": s.validatorInfos,
  121. "NameRegistry": s.nameReg,
  122. })
  123. }
  124. // Mutates the block in place and updates it with new state hash.
  125. func (s *State) ComputeBlockStateHash(block *types.Block) error {
  126. sCopy := s.Copy()
  127. // sCopy has no event cache in it, so this won't fire events
  128. err := execBlock(sCopy, block, types.PartSetHeader{})
  129. if err != nil {
  130. return err
  131. }
  132. // Set block.StateHash
  133. block.StateHash = sCopy.Hash()
  134. return nil
  135. }
  136. func (s *State) SetDB(db dbm.DB) {
  137. s.DB = db
  138. }
  139. //-------------------------------------
  140. // State.params
  141. func (s *State) GetGasLimit() int64 {
  142. return 1000000 // TODO
  143. }
  144. // State.params
  145. //-------------------------------------
  146. // State.accounts
  147. // Returns nil if account does not exist with given address.
  148. // The returned Account is a copy, so mutating it
  149. // has no side effects.
  150. // Implements Statelike
  151. func (s *State) GetAccount(address []byte) *acm.Account {
  152. _, acc := s.accounts.Get(address)
  153. if acc == nil {
  154. return nil
  155. }
  156. return acc.(*acm.Account).Copy()
  157. }
  158. // The account is copied before setting, so mutating it
  159. // afterwards has no side effects.
  160. // Implements Statelike
  161. func (s *State) UpdateAccount(account *acm.Account) bool {
  162. return s.accounts.Set(account.Address, account.Copy())
  163. }
  164. // Implements Statelike
  165. func (s *State) RemoveAccount(address []byte) bool {
  166. _, removed := s.accounts.Remove(address)
  167. return removed
  168. }
  169. // The returned Account is a copy, so mutating it
  170. // has no side effects.
  171. func (s *State) GetAccounts() merkle.Tree {
  172. return s.accounts.Copy()
  173. }
  174. // Set the accounts tree
  175. func (s *State) SetAccounts(accounts merkle.Tree) {
  176. s.accounts = accounts
  177. }
  178. // State.accounts
  179. //-------------------------------------
  180. // State.validators
  181. // The returned ValidatorInfo is a copy, so mutating it
  182. // has no side effects.
  183. func (s *State) GetValidatorInfo(address []byte) *types.ValidatorInfo {
  184. _, valInfo := s.validatorInfos.Get(address)
  185. if valInfo == nil {
  186. return nil
  187. }
  188. return valInfo.(*types.ValidatorInfo).Copy()
  189. }
  190. // Returns false if new, true if updated.
  191. // The valInfo is copied before setting, so mutating it
  192. // afterwards has no side effects.
  193. func (s *State) SetValidatorInfo(valInfo *types.ValidatorInfo) (updated bool) {
  194. return s.validatorInfos.Set(valInfo.Address, valInfo.Copy())
  195. }
  196. func (s *State) GetValidatorInfos() merkle.Tree {
  197. return s.validatorInfos.Copy()
  198. }
  199. func (s *State) unbondValidator(val *types.Validator) {
  200. // Move validator to UnbondingValidators
  201. val, removed := s.BondedValidators.Remove(val.Address)
  202. if !removed {
  203. PanicCrisis("Couldn't remove validator for unbonding")
  204. }
  205. val.UnbondHeight = s.LastBlockHeight + 1
  206. added := s.UnbondingValidators.Add(val)
  207. if !added {
  208. PanicCrisis("Couldn't add validator for unbonding")
  209. }
  210. }
  211. func (s *State) rebondValidator(val *types.Validator) {
  212. // Move validator to BondingValidators
  213. val, removed := s.UnbondingValidators.Remove(val.Address)
  214. if !removed {
  215. PanicCrisis("Couldn't remove validator for rebonding")
  216. }
  217. val.BondHeight = s.LastBlockHeight + 1
  218. added := s.BondedValidators.Add(val)
  219. if !added {
  220. PanicCrisis("Couldn't add validator for rebonding")
  221. }
  222. }
  223. func (s *State) releaseValidator(val *types.Validator) {
  224. // Update validatorInfo
  225. valInfo := s.GetValidatorInfo(val.Address)
  226. if valInfo == nil {
  227. PanicSanity("Couldn't find validatorInfo for release")
  228. }
  229. valInfo.ReleasedHeight = s.LastBlockHeight + 1
  230. s.SetValidatorInfo(valInfo)
  231. // Send coins back to UnbondTo outputs
  232. accounts, err := getOrMakeOutputs(s, nil, valInfo.UnbondTo)
  233. if err != nil {
  234. PanicSanity("Couldn't get or make unbondTo accounts")
  235. }
  236. adjustByOutputs(accounts, valInfo.UnbondTo)
  237. for _, acc := range accounts {
  238. s.UpdateAccount(acc)
  239. }
  240. // Remove validator from UnbondingValidators
  241. _, removed := s.UnbondingValidators.Remove(val.Address)
  242. if !removed {
  243. PanicCrisis("Couldn't remove validator for release")
  244. }
  245. }
  246. func (s *State) destroyValidator(val *types.Validator) {
  247. // Update validatorInfo
  248. valInfo := s.GetValidatorInfo(val.Address)
  249. if valInfo == nil {
  250. PanicSanity("Couldn't find validatorInfo for release")
  251. }
  252. valInfo.DestroyedHeight = s.LastBlockHeight + 1
  253. valInfo.DestroyedAmount = val.VotingPower
  254. s.SetValidatorInfo(valInfo)
  255. // Remove validator
  256. _, removed := s.BondedValidators.Remove(val.Address)
  257. if !removed {
  258. _, removed := s.UnbondingValidators.Remove(val.Address)
  259. if !removed {
  260. PanicCrisis("Couldn't remove validator for destruction")
  261. }
  262. }
  263. }
  264. // Set the validator infos tree
  265. func (s *State) SetValidatorInfos(validatorInfos merkle.Tree) {
  266. s.validatorInfos = validatorInfos
  267. }
  268. // State.validators
  269. //-------------------------------------
  270. // State.storage
  271. func (s *State) LoadStorage(hash []byte) (storage merkle.Tree) {
  272. storage = merkle.NewIAVLTree(wire.BasicCodec, wire.BasicCodec, 1024, s.DB)
  273. storage.Load(hash)
  274. return storage
  275. }
  276. // State.storage
  277. //-------------------------------------
  278. // State.nameReg
  279. func (s *State) GetNameRegEntry(name string) *types.NameRegEntry {
  280. _, value := s.nameReg.Get(name)
  281. if value == nil {
  282. return nil
  283. }
  284. entry := value.(*types.NameRegEntry)
  285. return entry.Copy()
  286. }
  287. func (s *State) UpdateNameRegEntry(entry *types.NameRegEntry) bool {
  288. return s.nameReg.Set(entry.Name, entry)
  289. }
  290. func (s *State) RemoveNameRegEntry(name string) bool {
  291. _, removed := s.nameReg.Remove(name)
  292. return removed
  293. }
  294. func (s *State) GetNames() merkle.Tree {
  295. return s.nameReg.Copy()
  296. }
  297. // Set the name reg tree
  298. func (s *State) SetNameReg(nameReg merkle.Tree) {
  299. s.nameReg = nameReg
  300. }
  301. func NameRegEncoder(o interface{}, w io.Writer, n *int64, err *error) {
  302. wire.WriteBinary(o.(*types.NameRegEntry), w, n, err)
  303. }
  304. func NameRegDecoder(r io.Reader, n *int64, err *error) interface{} {
  305. return wire.ReadBinary(&types.NameRegEntry{}, r, n, err)
  306. }
  307. var NameRegCodec = wire.Codec{
  308. Encode: NameRegEncoder,
  309. Decode: NameRegDecoder,
  310. }
  311. // State.nameReg
  312. //-------------------------------------
  313. // Implements events.Eventable. Typically uses events.EventCache
  314. func (s *State) SetFireable(evc events.Fireable) {
  315. s.evc = evc
  316. }
  317. //-----------------------------------------------------------------------------
  318. // Genesis
  319. func MakeGenesisStateFromFile(db dbm.DB, genDocFile string) (*GenesisDoc, *State) {
  320. jsonBlob, err := ioutil.ReadFile(genDocFile)
  321. if err != nil {
  322. Exit(Fmt("Couldn't read GenesisDoc file: %v", err))
  323. }
  324. genDoc := GenesisDocFromJSON(jsonBlob)
  325. return genDoc, MakeGenesisState(db, genDoc)
  326. }
  327. func MakeGenesisState(db dbm.DB, genDoc *GenesisDoc) *State {
  328. if len(genDoc.Validators) == 0 {
  329. Exit(Fmt("The genesis file has no validators"))
  330. }
  331. if genDoc.GenesisTime.IsZero() {
  332. genDoc.GenesisTime = time.Now()
  333. }
  334. // Make accounts state tree
  335. accounts := merkle.NewIAVLTree(wire.BasicCodec, acm.AccountCodec, defaultAccountsCacheCapacity, db)
  336. for _, genAcc := range genDoc.Accounts {
  337. perm := ptypes.ZeroAccountPermissions
  338. if genAcc.Permissions != nil {
  339. perm = *genAcc.Permissions
  340. }
  341. acc := &acm.Account{
  342. Address: genAcc.Address,
  343. PubKey: nil,
  344. Sequence: 0,
  345. Balance: genAcc.Amount,
  346. Permissions: perm,
  347. }
  348. accounts.Set(acc.Address, acc)
  349. }
  350. // global permissions are saved as the 0 address
  351. // so they are included in the accounts tree
  352. globalPerms := ptypes.DefaultAccountPermissions
  353. if genDoc.Params != nil && genDoc.Params.GlobalPermissions != nil {
  354. globalPerms = *genDoc.Params.GlobalPermissions
  355. // XXX: make sure the set bits are all true
  356. // Without it the HasPermission() functions will fail
  357. globalPerms.Base.SetBit = ptypes.AllPermFlags
  358. }
  359. permsAcc := &acm.Account{
  360. Address: ptypes.GlobalPermissionsAddress,
  361. PubKey: nil,
  362. Sequence: 0,
  363. Balance: 1337,
  364. Permissions: globalPerms,
  365. }
  366. accounts.Set(permsAcc.Address, permsAcc)
  367. // Make validatorInfos state tree && validators slice
  368. validatorInfos := merkle.NewIAVLTree(wire.BasicCodec, types.ValidatorInfoCodec, 0, db)
  369. validators := make([]*types.Validator, len(genDoc.Validators))
  370. for i, val := range genDoc.Validators {
  371. pubKey := val.PubKey
  372. address := pubKey.Address()
  373. // Make ValidatorInfo
  374. valInfo := &types.ValidatorInfo{
  375. Address: address,
  376. PubKey: pubKey,
  377. UnbondTo: make([]*types.TxOutput, len(val.UnbondTo)),
  378. FirstBondHeight: 0,
  379. FirstBondAmount: val.Amount,
  380. }
  381. for i, unbondTo := range val.UnbondTo {
  382. valInfo.UnbondTo[i] = &types.TxOutput{
  383. Address: unbondTo.Address,
  384. Amount: unbondTo.Amount,
  385. }
  386. }
  387. validatorInfos.Set(address, valInfo)
  388. // Make validator
  389. validators[i] = &types.Validator{
  390. Address: address,
  391. PubKey: pubKey,
  392. VotingPower: val.Amount,
  393. }
  394. }
  395. // Make namereg tree
  396. nameReg := merkle.NewIAVLTree(wire.BasicCodec, NameRegCodec, 0, db)
  397. // TODO: add names, contracts to genesis.json
  398. // IAVLTrees must be persisted before copy operations.
  399. accounts.Save()
  400. validatorInfos.Save()
  401. nameReg.Save()
  402. return &State{
  403. DB: db,
  404. ChainID: genDoc.ChainID,
  405. LastBlockHeight: 0,
  406. LastBlockHash: nil,
  407. LastBlockParts: types.PartSetHeader{},
  408. LastBlockTime: genDoc.GenesisTime,
  409. BondedValidators: types.NewValidatorSet(validators),
  410. LastBondedValidators: types.NewValidatorSet(nil),
  411. UnbondingValidators: types.NewValidatorSet(nil),
  412. accounts: accounts,
  413. validatorInfos: validatorInfos,
  414. nameReg: nameReg,
  415. }
  416. }
  417. func RandGenesisState(numAccounts int, randBalance bool, minBalance int64, numValidators int, randBonded bool, minBonded int64) (*State, []*acm.PrivAccount, []*types.PrivValidator) {
  418. db := dbm.NewMemDB()
  419. genDoc, privAccounts, privValidators := RandGenesisDoc(numAccounts, randBalance, minBalance, numValidators, randBonded, minBonded)
  420. s0 := MakeGenesisState(db, genDoc)
  421. s0.Save()
  422. return s0, privAccounts, privValidators
  423. }