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.

173 lines
4.9 KiB

  1. package state
  2. import (
  3. "errors"
  4. "fmt"
  5. . "github.com/tendermint/go-common"
  6. "github.com/tendermint/go-events"
  7. "github.com/tendermint/tendermint/proxy"
  8. "github.com/tendermint/tendermint/types"
  9. tmsp "github.com/tendermint/tmsp/types"
  10. )
  11. // Validate block
  12. func (s *State) ValidateBlock(block *types.Block) error {
  13. return s.validateBlock(block)
  14. }
  15. // Execute the block to mutate State.
  16. // Validates block and then executes Data.Txs in the block.
  17. func (s *State) ExecBlock(evsw *events.EventSwitch, proxyAppConn proxy.AppConn, block *types.Block, blockPartsHeader types.PartSetHeader) error {
  18. // Validate the block.
  19. err := s.validateBlock(block)
  20. if err != nil {
  21. return err
  22. }
  23. // Update the validator set
  24. valSet := s.Validators.Copy()
  25. // Update valSet with signatures from block.
  26. updateValidatorsWithBlock(s.LastValidators, valSet, block)
  27. // TODO: Update the validator set (e.g. block.Data.ValidatorUpdates?)
  28. nextValSet := valSet.Copy()
  29. // Execute the block txs
  30. err = s.execBlockOnProxyApp(evsw, proxyAppConn, block)
  31. if err != nil {
  32. // There was some error in proxyApp
  33. // TODO Report error and wait for proxyApp to be available.
  34. return err
  35. }
  36. // All good!
  37. nextValSet.IncrementAccum(1)
  38. s.LastBlockHeight = block.Height
  39. s.LastBlockHash = block.Hash()
  40. s.LastBlockParts = blockPartsHeader
  41. s.LastBlockTime = block.Time
  42. s.Validators = nextValSet
  43. s.LastValidators = valSet
  44. return nil
  45. }
  46. // Executes block's transactions on proxyAppConn.
  47. // TODO: Generate a bitmap or otherwise store tx validity in state.
  48. func (s *State) execBlockOnProxyApp(evsw *events.EventSwitch, proxyAppConn proxy.AppConn, block *types.Block) error {
  49. eventCache := events.NewEventCache(evsw)
  50. var validTxs, invalidTxs = 0, 0
  51. // Execute transactions and get hash
  52. proxyCb := func(req *tmsp.Request, res *tmsp.Response) {
  53. switch r := res.Value.(type) {
  54. case *tmsp.Response_AppendTx:
  55. // TODO: make use of res.Log
  56. // TODO: make use of this info
  57. // Blocks may include invalid txs.
  58. // reqAppendTx := req.(tmsp.RequestAppendTx)
  59. if r.AppendTx.Code == tmsp.CodeType_OK {
  60. validTxs += 1
  61. } else {
  62. log.Debug("Invalid tx", "code", r.AppendTx.Code, "log", r.AppendTx.Log)
  63. invalidTxs += 1
  64. }
  65. // NOTE: if we count we can access the tx from the block instead of
  66. // pulling it from the req
  67. eventCache.FireEvent(types.EventStringTx(req.GetAppendTx().Tx), res)
  68. }
  69. }
  70. proxyAppConn.SetResponseCallback(proxyCb)
  71. // Run txs of block
  72. for _, tx := range block.Txs {
  73. proxyAppConn.AppendTxAsync(tx)
  74. if err := proxyAppConn.Error(); err != nil {
  75. return err
  76. }
  77. }
  78. // End block
  79. changedValidators, err := proxyAppConn.EndBlockSync(uint64(block.Height))
  80. if err != nil {
  81. log.Warn("Error in proxyAppConn.EndBlock", "error", err)
  82. return err
  83. }
  84. // TODO: Do something with changedValidators
  85. log.Info("TODO: Do something with changedValidators", changedValidators)
  86. log.Info(Fmt("ExecBlock got %v valid txs and %v invalid txs", validTxs, invalidTxs))
  87. // fire events
  88. eventCache.Flush()
  89. return nil
  90. }
  91. func (s *State) validateBlock(block *types.Block) error {
  92. // Basic block validation.
  93. err := block.ValidateBasic(s.ChainID, s.LastBlockHeight, s.LastBlockHash, s.LastBlockParts, s.LastBlockTime, s.AppHash)
  94. if err != nil {
  95. return err
  96. }
  97. // Validate block LastCommit.
  98. if block.Height == 1 {
  99. if len(block.LastCommit.Precommits) != 0 {
  100. return errors.New("Block at height 1 (first block) should have no LastCommit precommits")
  101. }
  102. } else {
  103. if len(block.LastCommit.Precommits) != s.LastValidators.Size() {
  104. return fmt.Errorf("Invalid block commit size. Expected %v, got %v",
  105. s.LastValidators.Size(), len(block.LastCommit.Precommits))
  106. }
  107. err := s.LastValidators.VerifyCommit(
  108. s.ChainID, s.LastBlockHash, s.LastBlockParts, block.Height-1, block.LastCommit)
  109. if err != nil {
  110. return err
  111. }
  112. }
  113. return nil
  114. }
  115. // Updates the LastCommitHeight of the validators in valSet, in place.
  116. // Assumes that lastValSet matches the valset of block.LastCommit
  117. // CONTRACT: lastValSet is not mutated.
  118. func updateValidatorsWithBlock(lastValSet *types.ValidatorSet, valSet *types.ValidatorSet, block *types.Block) {
  119. for i, precommit := range block.LastCommit.Precommits {
  120. if precommit == nil {
  121. continue
  122. }
  123. _, val := lastValSet.GetByIndex(i)
  124. if val == nil {
  125. PanicCrisis(Fmt("Failed to fetch validator at index %v", i))
  126. }
  127. if _, val_ := valSet.GetByAddress(val.Address); val_ != nil {
  128. val_.LastCommitHeight = block.Height - 1
  129. updated := valSet.Update(val_)
  130. if !updated {
  131. PanicCrisis("Failed to update validator LastCommitHeight")
  132. }
  133. } else {
  134. // XXX This is not an error if validator was removed.
  135. // But, we don't mutate validators yet so go ahead and panic.
  136. PanicCrisis("Could not find validator")
  137. }
  138. }
  139. }
  140. //-----------------------------------------------------------------------------
  141. type InvalidTxError struct {
  142. Tx types.Tx
  143. Code tmsp.CodeType
  144. }
  145. func (txErr InvalidTxError) Error() string {
  146. return Fmt("Invalid tx: [%v] code: [%v]", txErr.Tx, txErr.Code)
  147. }