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.

835 lines
25 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
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
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. "errors"
  5. "fmt"
  6. "time"
  7. "github.com/tendermint/tendermint/account"
  8. "github.com/tendermint/tendermint/binary"
  9. . "github.com/tendermint/tendermint/common"
  10. dbm "github.com/tendermint/tendermint/db"
  11. "github.com/tendermint/tendermint/merkle"
  12. "github.com/tendermint/tendermint/types"
  13. "github.com/tendermint/tendermint/vm"
  14. )
  15. var (
  16. stateKey = []byte("stateKey")
  17. minBondAmount = uint64(1) // TODO adjust
  18. defaultAccountsCacheCapacity = 1000 // TODO adjust
  19. unbondingPeriodBlocks = uint(60 * 24 * 365) // TODO probably better to make it time based.
  20. validatorTimeoutBlocks = uint(10) // TODO adjust
  21. )
  22. //-----------------------------------------------------------------------------
  23. type InvalidTxError struct {
  24. Tx types.Tx
  25. Reason error
  26. }
  27. func (txErr InvalidTxError) Error() string {
  28. return fmt.Sprintf("Invalid tx: [%v] reason: [%v]", txErr.Tx, txErr.Reason)
  29. }
  30. //-----------------------------------------------------------------------------
  31. // NOTE: not goroutine-safe.
  32. type State struct {
  33. DB dbm.DB
  34. LastBlockHeight uint
  35. LastBlockHash []byte
  36. LastBlockParts types.PartSetHeader
  37. LastBlockTime time.Time
  38. BondedValidators *ValidatorSet
  39. LastBondedValidators *ValidatorSet
  40. UnbondingValidators *ValidatorSet
  41. accounts merkle.Tree // Shouldn't be accessed directly.
  42. validatorInfos merkle.Tree // Shouldn't be accessed directly.
  43. }
  44. func LoadState(db dbm.DB) *State {
  45. s := &State{DB: db}
  46. buf := db.Get(stateKey)
  47. if len(buf) == 0 {
  48. return nil
  49. } else {
  50. r, n, err := bytes.NewReader(buf), new(int64), new(error)
  51. s.LastBlockHeight = binary.ReadUvarint(r, n, err)
  52. s.LastBlockHash = binary.ReadByteSlice(r, n, err)
  53. s.LastBlockParts = binary.ReadBinary(types.PartSetHeader{}, r, n, err).(types.PartSetHeader)
  54. s.LastBlockTime = binary.ReadTime(r, n, err)
  55. s.BondedValidators = binary.ReadBinary(&ValidatorSet{}, r, n, err).(*ValidatorSet)
  56. s.LastBondedValidators = binary.ReadBinary(&ValidatorSet{}, r, n, err).(*ValidatorSet)
  57. s.UnbondingValidators = binary.ReadBinary(&ValidatorSet{}, r, n, err).(*ValidatorSet)
  58. accountsHash := binary.ReadByteSlice(r, n, err)
  59. s.accounts = merkle.NewIAVLTree(binary.BasicCodec, account.AccountCodec, defaultAccountsCacheCapacity, db)
  60. s.accounts.Load(accountsHash)
  61. validatorInfosHash := binary.ReadByteSlice(r, n, err)
  62. s.validatorInfos = merkle.NewIAVLTree(binary.BasicCodec, ValidatorInfoCodec, 0, db)
  63. s.validatorInfos.Load(validatorInfosHash)
  64. if *err != nil {
  65. panic(*err)
  66. }
  67. // TODO: ensure that buf is completely read.
  68. }
  69. return s
  70. }
  71. // Save this state into the db.
  72. func (s *State) Save() {
  73. s.accounts.Save()
  74. s.validatorInfos.Save()
  75. buf, n, err := new(bytes.Buffer), new(int64), new(error)
  76. binary.WriteUvarint(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. if *err != nil {
  86. panic(*err)
  87. }
  88. s.DB.Set(stateKey, buf.Bytes())
  89. }
  90. func (s *State) Copy() *State {
  91. return &State{
  92. DB: s.DB,
  93. LastBlockHeight: s.LastBlockHeight,
  94. LastBlockHash: s.LastBlockHash,
  95. LastBlockParts: s.LastBlockParts,
  96. LastBlockTime: s.LastBlockTime,
  97. BondedValidators: s.BondedValidators.Copy(), // TODO remove need for Copy() here.
  98. LastBondedValidators: s.LastBondedValidators.Copy(), // That is, make updates to the validator set
  99. UnbondingValidators: s.UnbondingValidators.Copy(), // copy the valSet lazily.
  100. accounts: s.accounts.Copy(),
  101. validatorInfos: s.validatorInfos.Copy(),
  102. }
  103. }
  104. // The accounts from the TxInputs must either already have
  105. // account.PubKey.(type) != PubKeyNil, (it must be known),
  106. // or it must be specified in the TxInput. If redeclared,
  107. // the TxInput is modified and input.PubKey set to PubKeyNil.
  108. func (s *State) GetOrMakeAccounts(ins []*types.TxInput, outs []*types.TxOutput) (map[string]*account.Account, error) {
  109. accounts := map[string]*account.Account{}
  110. for _, in := range ins {
  111. // Account shouldn't be duplicated
  112. if _, ok := accounts[string(in.Address)]; ok {
  113. return nil, types.ErrTxDuplicateAddress
  114. }
  115. acc := s.GetAccount(in.Address)
  116. if acc == nil {
  117. return nil, types.ErrTxInvalidAddress
  118. }
  119. // PubKey should be present in either "account" or "in"
  120. if err := checkInputPubKey(acc, in); err != nil {
  121. return nil, err
  122. }
  123. accounts[string(in.Address)] = acc
  124. }
  125. for _, out := range outs {
  126. // Account shouldn't be duplicated
  127. if _, ok := accounts[string(out.Address)]; ok {
  128. return nil, types.ErrTxDuplicateAddress
  129. }
  130. acc := s.GetAccount(out.Address)
  131. // output account may be nil (new)
  132. if acc == nil {
  133. acc = &account.Account{
  134. Address: out.Address,
  135. PubKey: account.PubKeyNil{},
  136. Sequence: 0,
  137. Balance: 0,
  138. }
  139. }
  140. accounts[string(out.Address)] = acc
  141. }
  142. return accounts, nil
  143. }
  144. func checkInputPubKey(acc *account.Account, in *types.TxInput) error {
  145. if _, isNil := acc.PubKey.(account.PubKeyNil); isNil {
  146. if _, isNil := in.PubKey.(account.PubKeyNil); isNil {
  147. return types.ErrTxUnknownPubKey
  148. }
  149. if !bytes.Equal(in.PubKey.Address(), acc.Address) {
  150. return types.ErrTxInvalidPubKey
  151. }
  152. acc.PubKey = in.PubKey
  153. } else {
  154. in.PubKey = account.PubKeyNil{}
  155. }
  156. return nil
  157. }
  158. func (s *State) ValidateInputs(accounts map[string]*account.Account, signBytes []byte, ins []*types.TxInput) (total uint64, err error) {
  159. for _, in := range ins {
  160. acc := accounts[string(in.Address)]
  161. if acc == nil {
  162. panic("ValidateInputs() expects account in accounts")
  163. }
  164. err = s.ValidateInput(acc, signBytes, in)
  165. if err != nil {
  166. return
  167. }
  168. // Good. Add amount to total
  169. total += in.Amount
  170. }
  171. return total, nil
  172. }
  173. func (s *State) ValidateInput(acc *account.Account, signBytes []byte, in *types.TxInput) (err error) {
  174. // Check TxInput basic
  175. if err := in.ValidateBasic(); err != nil {
  176. return err
  177. }
  178. // Check signatures
  179. if !acc.PubKey.VerifyBytes(signBytes, in.Signature) {
  180. return types.ErrTxInvalidSignature
  181. }
  182. // Check sequences
  183. if acc.Sequence+1 != in.Sequence {
  184. return types.ErrTxInvalidSequence{
  185. Got: uint64(in.Sequence),
  186. Expected: uint64(acc.Sequence + 1),
  187. }
  188. }
  189. // Check amount
  190. if acc.Balance < in.Amount {
  191. return types.ErrTxInsufficientFunds
  192. }
  193. return nil
  194. }
  195. func (s *State) ValidateOutputs(outs []*types.TxOutput) (total uint64, err error) {
  196. for _, out := range outs {
  197. // Check TxOutput basic
  198. if err := out.ValidateBasic(); err != nil {
  199. return 0, err
  200. }
  201. // Good. Add amount to total
  202. total += out.Amount
  203. }
  204. return total, nil
  205. }
  206. func (s *State) AdjustByInputs(accounts map[string]*account.Account, ins []*types.TxInput) {
  207. for _, in := range ins {
  208. acc := accounts[string(in.Address)]
  209. if acc == nil {
  210. panic("AdjustByInputs() expects account in accounts")
  211. }
  212. if acc.Balance < in.Amount {
  213. panic("AdjustByInputs() expects sufficient funds")
  214. }
  215. acc.Balance -= in.Amount
  216. acc.Sequence += 1
  217. }
  218. }
  219. func (s *State) AdjustByOutputs(accounts map[string]*account.Account, outs []*types.TxOutput) {
  220. for _, out := range outs {
  221. acc := accounts[string(out.Address)]
  222. if acc == nil {
  223. panic("AdjustByOutputs() expects account in accounts")
  224. }
  225. acc.Balance += out.Amount
  226. }
  227. }
  228. // If the tx is invalid, an error will be returned.
  229. // Unlike AppendBlock(), state will not be altered.
  230. func (s *State) ExecTx(tx_ types.Tx, runCall bool) error {
  231. // TODO: do something with fees
  232. fees := uint64(0)
  233. // Exec tx
  234. switch tx := tx_.(type) {
  235. case *types.SendTx:
  236. accounts, err := s.GetOrMakeAccounts(tx.Inputs, tx.Outputs)
  237. if err != nil {
  238. return err
  239. }
  240. signBytes := account.SignBytes(tx)
  241. inTotal, err := s.ValidateInputs(accounts, signBytes, tx.Inputs)
  242. if err != nil {
  243. return err
  244. }
  245. outTotal, err := s.ValidateOutputs(tx.Outputs)
  246. if err != nil {
  247. return err
  248. }
  249. if outTotal > inTotal {
  250. return types.ErrTxInsufficientFunds
  251. }
  252. fee := inTotal - outTotal
  253. fees += fee
  254. // Good! Adjust accounts
  255. s.AdjustByInputs(accounts, tx.Inputs)
  256. s.AdjustByOutputs(accounts, tx.Outputs)
  257. s.UpdateAccounts(accounts)
  258. return nil
  259. case *types.CallTx:
  260. var inAcc, outAcc *account.Account
  261. // Validate input
  262. inAcc = s.GetAccount(tx.Input.Address)
  263. if inAcc == nil {
  264. log.Debug(Fmt("Can't find in account %X", tx.Input.Address))
  265. return types.ErrTxInvalidAddress
  266. }
  267. // pubKey should be present in either "inAcc" or "tx.Input"
  268. if err := checkInputPubKey(inAcc, tx.Input); err != nil {
  269. log.Debug(Fmt("Can't find pubkey for %X", tx.Input.Address))
  270. return err
  271. }
  272. signBytes := account.SignBytes(tx)
  273. err := s.ValidateInput(inAcc, signBytes, tx.Input)
  274. if err != nil {
  275. log.Debug(Fmt("ValidateInput failed on %X:", tx.Input.Address))
  276. return err
  277. }
  278. if tx.Input.Amount < tx.Fee {
  279. log.Debug(Fmt("Sender did not send enough to cover the fee %X", tx.Input.Address))
  280. return types.ErrTxInsufficientFunds
  281. }
  282. createAccount := len(tx.Address) == 0
  283. if !createAccount {
  284. // Validate output
  285. if len(tx.Address) != 20 {
  286. log.Debug(Fmt("Destination address is not 20 bytes %X", tx.Address))
  287. return types.ErrTxInvalidAddress
  288. }
  289. // this may be nil if we are still in mempool and contract was created in same block as this tx
  290. // but that's fine, because the account will be created properly when the create tx runs in the block
  291. // and then this won't return nil. otherwise, we take their fee
  292. outAcc = s.GetAccount(tx.Address)
  293. }
  294. log.Debug(Fmt("Out account: %v", outAcc))
  295. // Good!
  296. value := tx.Input.Amount - tx.Fee
  297. inAcc.Sequence += 1
  298. if runCall {
  299. var (
  300. gas uint64 = tx.GasLimit
  301. err error = nil
  302. caller *vm.Account = toVMAccount(inAcc)
  303. callee *vm.Account = nil
  304. code []byte = nil
  305. appState = NewVMAppState(s) // TODO: confusing.
  306. params = vm.Params{
  307. BlockHeight: uint64(s.LastBlockHeight),
  308. BlockHash: vm.BytesToWord(s.LastBlockHash),
  309. BlockTime: s.LastBlockTime.Unix(),
  310. GasLimit: 10000000,
  311. }
  312. )
  313. // Maybe create a new callee account if
  314. // this transaction is creating a new contract.
  315. if !createAccount {
  316. if outAcc == nil {
  317. // take fees (sorry pal)
  318. inAcc.Balance -= tx.Fee
  319. s.UpdateAccount(inAcc)
  320. log.Debug(Fmt("Cannot find destination address %X. Deducting fee from caller", tx.Address))
  321. return types.ErrTxInvalidAddress
  322. }
  323. callee = toVMAccount(outAcc)
  324. code = callee.Code
  325. log.Debug(Fmt("Calling contract %X with code %X", callee.Address.Address(), callee.Code))
  326. } else {
  327. callee, err = appState.CreateAccount(caller)
  328. if err != nil {
  329. log.Debug(Fmt("Error creating account"))
  330. return err
  331. }
  332. log.Debug(Fmt("Created new account %X", callee.Address.Address()))
  333. code = tx.Data
  334. }
  335. log.Debug(Fmt("Code for this contract: %X", code))
  336. appState.UpdateAccount(caller) // because we adjusted by input above, and bumped nonce maybe.
  337. appState.UpdateAccount(callee) // because we adjusted by input above.
  338. vmach := vm.NewVM(appState, params, caller.Address)
  339. // NOTE: Call() transfers the value from caller to callee iff call succeeds.
  340. ret, err := vmach.Call(caller, callee, code, tx.Data, value, &gas)
  341. if err != nil {
  342. // Failure. Charge the gas fee. The 'value' was otherwise not transferred.
  343. log.Debug(Fmt("Error on execution: %v", err))
  344. inAcc.Balance -= tx.Fee
  345. s.UpdateAccount(inAcc)
  346. // Throw away 'appState' which holds incomplete updates (don't sync it).
  347. } else {
  348. log.Debug("Successful execution")
  349. // Success
  350. if createAccount {
  351. callee.Code = ret
  352. }
  353. appState.Sync()
  354. }
  355. // Create a receipt from the ret and whether errored.
  356. log.Info("VM call complete", "caller", caller, "callee", callee, "return", ret, "err", err)
  357. } else {
  358. // The mempool does not call txs until
  359. // the proposer determines the order of txs.
  360. // So mempool will skip the actual .Call(),
  361. // and only deduct from the caller's balance.
  362. inAcc.Balance -= value
  363. if createAccount {
  364. inAcc.Sequence += 1
  365. }
  366. s.UpdateAccount(inAcc)
  367. }
  368. return nil
  369. case *types.BondTx:
  370. valInfo := s.GetValidatorInfo(tx.PubKey.Address())
  371. if valInfo != nil {
  372. // TODO: In the future, check that the validator wasn't destroyed,
  373. // add funds, merge UnbondTo outputs, and unbond validator.
  374. return errors.New("Adding coins to existing validators not yet supported")
  375. }
  376. accounts, err := s.GetOrMakeAccounts(tx.Inputs, nil)
  377. if err != nil {
  378. return err
  379. }
  380. signBytes := account.SignBytes(tx)
  381. inTotal, err := s.ValidateInputs(accounts, signBytes, tx.Inputs)
  382. if err != nil {
  383. return err
  384. }
  385. if err := tx.PubKey.ValidateBasic(); err != nil {
  386. return err
  387. }
  388. outTotal, err := s.ValidateOutputs(tx.UnbondTo)
  389. if err != nil {
  390. return err
  391. }
  392. if outTotal > inTotal {
  393. return types.ErrTxInsufficientFunds
  394. }
  395. fee := inTotal - outTotal
  396. fees += fee
  397. // Good! Adjust accounts
  398. s.AdjustByInputs(accounts, tx.Inputs)
  399. s.UpdateAccounts(accounts)
  400. // Add ValidatorInfo
  401. s.SetValidatorInfo(&ValidatorInfo{
  402. Address: tx.PubKey.Address(),
  403. PubKey: tx.PubKey,
  404. UnbondTo: tx.UnbondTo,
  405. FirstBondHeight: s.LastBlockHeight + 1,
  406. FirstBondAmount: outTotal,
  407. })
  408. // Add Validator
  409. added := s.BondedValidators.Add(&Validator{
  410. Address: tx.PubKey.Address(),
  411. PubKey: tx.PubKey,
  412. BondHeight: s.LastBlockHeight + 1,
  413. VotingPower: outTotal,
  414. Accum: 0,
  415. })
  416. if !added {
  417. panic("Failed to add validator")
  418. }
  419. return nil
  420. case *types.UnbondTx:
  421. // The validator must be active
  422. _, val := s.BondedValidators.GetByAddress(tx.Address)
  423. if val == nil {
  424. return types.ErrTxInvalidAddress
  425. }
  426. // Verify the signature
  427. signBytes := account.SignBytes(tx)
  428. if !val.PubKey.VerifyBytes(signBytes, tx.Signature) {
  429. return types.ErrTxInvalidSignature
  430. }
  431. // tx.Height must be greater than val.LastCommitHeight
  432. if tx.Height <= val.LastCommitHeight {
  433. return errors.New("Invalid unbond height")
  434. }
  435. // Good!
  436. s.unbondValidator(val)
  437. return nil
  438. case *types.RebondTx:
  439. // The validator must be inactive
  440. _, val := s.UnbondingValidators.GetByAddress(tx.Address)
  441. if val == nil {
  442. return types.ErrTxInvalidAddress
  443. }
  444. // Verify the signature
  445. signBytes := account.SignBytes(tx)
  446. if !val.PubKey.VerifyBytes(signBytes, tx.Signature) {
  447. return types.ErrTxInvalidSignature
  448. }
  449. // tx.Height must be equal to the next height
  450. if tx.Height != s.LastBlockHeight+1 {
  451. return errors.New(Fmt("Invalid rebond height. Expected %v, got %v", s.LastBlockHeight+1, tx.Height))
  452. }
  453. // Good!
  454. s.rebondValidator(val)
  455. return nil
  456. case *types.DupeoutTx:
  457. // Verify the signatures
  458. _, accused := s.BondedValidators.GetByAddress(tx.Address)
  459. if accused == nil {
  460. _, accused = s.UnbondingValidators.GetByAddress(tx.Address)
  461. if accused == nil {
  462. return types.ErrTxInvalidAddress
  463. }
  464. }
  465. voteASignBytes := account.SignBytes(&tx.VoteA)
  466. voteBSignBytes := account.SignBytes(&tx.VoteB)
  467. if !accused.PubKey.VerifyBytes(voteASignBytes, tx.VoteA.Signature) ||
  468. !accused.PubKey.VerifyBytes(voteBSignBytes, tx.VoteB.Signature) {
  469. return types.ErrTxInvalidSignature
  470. }
  471. // Verify equivocation
  472. // TODO: in the future, just require one vote from a previous height that
  473. // doesn't exist on this chain.
  474. if tx.VoteA.Height != tx.VoteB.Height {
  475. return errors.New("DupeoutTx heights don't match")
  476. }
  477. if tx.VoteA.Type == types.VoteTypeCommit && tx.VoteA.Round < tx.VoteB.Round {
  478. // Check special case (not an error, validator must be slashed!)
  479. // Validators should not sign another vote after committing.
  480. } else if tx.VoteB.Type == types.VoteTypeCommit && tx.VoteB.Round < tx.VoteA.Round {
  481. // We need to check both orderings of the votes
  482. } else {
  483. if tx.VoteA.Round != tx.VoteB.Round {
  484. return errors.New("DupeoutTx rounds don't match")
  485. }
  486. if tx.VoteA.Type != tx.VoteB.Type {
  487. return errors.New("DupeoutTx types don't match")
  488. }
  489. if bytes.Equal(tx.VoteA.BlockHash, tx.VoteB.BlockHash) {
  490. return errors.New("DupeoutTx blockhashes shouldn't match")
  491. }
  492. }
  493. // Good! (Bad validator!)
  494. s.destroyValidator(accused)
  495. return nil
  496. default:
  497. panic("Unknown Tx type")
  498. }
  499. }
  500. func (s *State) unbondValidator(val *Validator) {
  501. // Move validator to UnbondingValidators
  502. val, removed := s.BondedValidators.Remove(val.Address)
  503. if !removed {
  504. panic("Couldn't remove validator for unbonding")
  505. }
  506. val.UnbondHeight = s.LastBlockHeight + 1
  507. added := s.UnbondingValidators.Add(val)
  508. if !added {
  509. panic("Couldn't add validator for unbonding")
  510. }
  511. }
  512. func (s *State) rebondValidator(val *Validator) {
  513. // Move validator to BondingValidators
  514. val, removed := s.UnbondingValidators.Remove(val.Address)
  515. if !removed {
  516. panic("Couldn't remove validator for rebonding")
  517. }
  518. val.BondHeight = s.LastBlockHeight + 1
  519. added := s.BondedValidators.Add(val)
  520. if !added {
  521. panic("Couldn't add validator for rebonding")
  522. }
  523. }
  524. func (s *State) releaseValidator(val *Validator) {
  525. // Update validatorInfo
  526. valInfo := s.GetValidatorInfo(val.Address)
  527. if valInfo == nil {
  528. panic("Couldn't find validatorInfo for release")
  529. }
  530. valInfo.ReleasedHeight = s.LastBlockHeight + 1
  531. s.SetValidatorInfo(valInfo)
  532. // Send coins back to UnbondTo outputs
  533. accounts, err := s.GetOrMakeAccounts(nil, valInfo.UnbondTo)
  534. if err != nil {
  535. panic("Couldn't get or make unbondTo accounts")
  536. }
  537. s.AdjustByOutputs(accounts, valInfo.UnbondTo)
  538. s.UpdateAccounts(accounts)
  539. // Remove validator from UnbondingValidators
  540. _, removed := s.UnbondingValidators.Remove(val.Address)
  541. if !removed {
  542. panic("Couldn't remove validator for release")
  543. }
  544. }
  545. func (s *State) destroyValidator(val *Validator) {
  546. // Update validatorInfo
  547. valInfo := s.GetValidatorInfo(val.Address)
  548. if valInfo == nil {
  549. panic("Couldn't find validatorInfo for release")
  550. }
  551. valInfo.DestroyedHeight = s.LastBlockHeight + 1
  552. valInfo.DestroyedAmount = val.VotingPower
  553. s.SetValidatorInfo(valInfo)
  554. // Remove validator
  555. _, removed := s.BondedValidators.Remove(val.Address)
  556. if !removed {
  557. _, removed := s.UnbondingValidators.Remove(val.Address)
  558. if !removed {
  559. panic("Couldn't remove validator for destruction")
  560. }
  561. }
  562. }
  563. // NOTE: If an error occurs during block execution, state will be left
  564. // at an invalid state. Copy the state before calling AppendBlock!
  565. func (s *State) AppendBlock(block *types.Block, blockPartsHeader types.PartSetHeader) error {
  566. err := s.appendBlock(block, blockPartsHeader)
  567. if err != nil {
  568. return err
  569. }
  570. // State.Hash should match block.StateHash
  571. stateHash := s.Hash()
  572. if !bytes.Equal(stateHash, block.StateHash) {
  573. return Errorf("Invalid state hash. Expected %X, got %X",
  574. stateHash, block.StateHash)
  575. }
  576. return nil
  577. }
  578. func (s *State) SetBlockStateHash(block *types.Block) error {
  579. sCopy := s.Copy()
  580. err := sCopy.appendBlock(block, types.PartSetHeader{})
  581. if err != nil {
  582. return err
  583. }
  584. // Set block.StateHash
  585. block.StateHash = sCopy.Hash()
  586. return nil
  587. }
  588. // Appends the block, does not check block.StateHash
  589. // NOTE: If an error occurs during block execution, state will be left
  590. // at an invalid state. Copy the state before calling appendBlock!
  591. func (s *State) appendBlock(block *types.Block, blockPartsHeader types.PartSetHeader) error {
  592. // Basic block validation.
  593. err := block.ValidateBasic(s.LastBlockHeight, s.LastBlockHash, s.LastBlockParts, s.LastBlockTime)
  594. if err != nil {
  595. return err
  596. }
  597. // Validate block Validation.
  598. if block.Height == 1 {
  599. if len(block.Validation.Commits) != 0 {
  600. return errors.New("Block at height 1 (first block) should have no Validation commits")
  601. }
  602. } else {
  603. if uint(len(block.Validation.Commits)) != s.LastBondedValidators.Size() {
  604. return errors.New(Fmt("Invalid block validation size. Expected %v, got %v",
  605. s.LastBondedValidators.Size(), len(block.Validation.Commits)))
  606. }
  607. var sumVotingPower uint64
  608. s.LastBondedValidators.Iterate(func(index uint, val *Validator) bool {
  609. commit := block.Validation.Commits[index]
  610. if commit.IsZero() {
  611. return false
  612. } else {
  613. vote := &types.Vote{
  614. Height: block.Height - 1,
  615. Round: commit.Round,
  616. Type: types.VoteTypeCommit,
  617. BlockHash: block.LastBlockHash,
  618. BlockParts: block.LastBlockParts,
  619. }
  620. if val.PubKey.VerifyBytes(account.SignBytes(vote), commit.Signature) {
  621. sumVotingPower += val.VotingPower
  622. return false
  623. } else {
  624. log.Warn(Fmt("Invalid validation signature.\nval: %v\nvote: %v", val, vote))
  625. err = errors.New("Invalid validation signature")
  626. return true
  627. }
  628. }
  629. })
  630. if err != nil {
  631. return err
  632. }
  633. if sumVotingPower <= s.LastBondedValidators.TotalVotingPower()*2/3 {
  634. return errors.New("Insufficient validation voting power")
  635. }
  636. }
  637. // Update Validator.LastCommitHeight as necessary.
  638. for i, commit := range block.Validation.Commits {
  639. if commit.IsZero() {
  640. continue
  641. }
  642. _, val := s.LastBondedValidators.GetByIndex(uint(i))
  643. if val == nil {
  644. panic(Fmt("Failed to fetch validator at index %v", i))
  645. }
  646. if _, val_ := s.BondedValidators.GetByAddress(val.Address); val_ != nil {
  647. val_.LastCommitHeight = block.Height - 1
  648. updated := s.BondedValidators.Update(val_)
  649. if !updated {
  650. panic("Failed to update bonded validator LastCommitHeight")
  651. }
  652. } else if _, val_ := s.UnbondingValidators.GetByAddress(val.Address); val_ != nil {
  653. val_.LastCommitHeight = block.Height - 1
  654. updated := s.UnbondingValidators.Update(val_)
  655. if !updated {
  656. panic("Failed to update unbonding validator LastCommitHeight")
  657. }
  658. } else {
  659. panic("Could not find validator")
  660. }
  661. }
  662. // Remember LastBondedValidators
  663. s.LastBondedValidators = s.BondedValidators.Copy()
  664. // Commit each tx
  665. for _, tx := range block.Data.Txs {
  666. err := s.ExecTx(tx, true)
  667. if err != nil {
  668. return InvalidTxError{tx, err}
  669. }
  670. }
  671. // If any unbonding periods are over,
  672. // reward account with bonded coins.
  673. toRelease := []*Validator{}
  674. s.UnbondingValidators.Iterate(func(index uint, val *Validator) bool {
  675. if val.UnbondHeight+unbondingPeriodBlocks < block.Height {
  676. toRelease = append(toRelease, val)
  677. }
  678. return false
  679. })
  680. for _, val := range toRelease {
  681. s.releaseValidator(val)
  682. }
  683. // If any validators haven't signed in a while,
  684. // unbond them, they have timed out.
  685. toTimeout := []*Validator{}
  686. s.BondedValidators.Iterate(func(index uint, val *Validator) bool {
  687. lastActivityHeight := MaxUint(val.BondHeight, val.LastCommitHeight)
  688. if lastActivityHeight+validatorTimeoutBlocks < block.Height {
  689. log.Info("Validator timeout", "validator", val, "height", block.Height)
  690. toTimeout = append(toTimeout, val)
  691. }
  692. return false
  693. })
  694. for _, val := range toTimeout {
  695. s.unbondValidator(val)
  696. }
  697. // Increment validator AccumPowers
  698. s.BondedValidators.IncrementAccum(1)
  699. s.LastBlockHeight = block.Height
  700. s.LastBlockHash = block.Hash()
  701. s.LastBlockParts = blockPartsHeader
  702. s.LastBlockTime = block.Time
  703. return nil
  704. }
  705. // The returned Account is a copy, so mutating it
  706. // has no side effects.
  707. func (s *State) GetAccount(address []byte) *account.Account {
  708. _, acc := s.accounts.Get(address)
  709. if acc == nil {
  710. return nil
  711. }
  712. return acc.(*account.Account).Copy()
  713. }
  714. // The returned Account is a copy, so mutating it
  715. // has no side effects.
  716. func (s *State) GetAccounts() merkle.Tree {
  717. return s.accounts.Copy()
  718. }
  719. // The account is copied before setting, so mutating it
  720. // afterwards has no side effects.
  721. func (s *State) UpdateAccount(account *account.Account) {
  722. s.accounts.Set(account.Address, account.Copy())
  723. }
  724. // The accounts are copied before setting, so mutating it
  725. // afterwards has no side effects.
  726. func (s *State) UpdateAccounts(accounts map[string]*account.Account) {
  727. for _, acc := range accounts {
  728. s.accounts.Set(acc.Address, acc.Copy())
  729. }
  730. }
  731. func (s *State) RemoveAccount(address []byte) bool {
  732. _, removed := s.accounts.Remove(address)
  733. return removed
  734. }
  735. // The returned ValidatorInfo is a copy, so mutating it
  736. // has no side effects.
  737. func (s *State) GetValidatorInfo(address []byte) *ValidatorInfo {
  738. _, valInfo := s.validatorInfos.Get(address)
  739. if valInfo == nil {
  740. return nil
  741. }
  742. return valInfo.(*ValidatorInfo).Copy()
  743. }
  744. // Returns false if new, true if updated.
  745. // The valInfo is copied before setting, so mutating it
  746. // afterwards has no side effects.
  747. func (s *State) SetValidatorInfo(valInfo *ValidatorInfo) (updated bool) {
  748. return s.validatorInfos.Set(valInfo.Address, valInfo.Copy())
  749. }
  750. // Returns a hash that represents the state data,
  751. // excluding Last*
  752. func (s *State) Hash() []byte {
  753. hashables := []merkle.Hashable{
  754. s.BondedValidators,
  755. s.UnbondingValidators,
  756. s.accounts,
  757. s.validatorInfos,
  758. }
  759. return merkle.HashFromHashables(hashables)
  760. }