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.

183 lines
5.2 KiB

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