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.

300 lines
8.8 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. package state
  2. import (
  3. "errors"
  4. "fmt"
  5. fail "github.com/ebuchman/fail-test"
  6. abci "github.com/tendermint/abci/types"
  7. . "github.com/tendermint/go-common"
  8. crypto "github.com/tendermint/go-crypto"
  9. "github.com/tendermint/tendermint/proxy"
  10. txindexer "github.com/tendermint/tendermint/state/tx/indexer"
  11. "github.com/tendermint/tendermint/types"
  12. )
  13. // ExecBlock executes the block to mutate State.
  14. // + validates the block
  15. // + executes block.Txs on the proxyAppConn
  16. // + updates validator sets
  17. // + returns block.Txs results
  18. func (s *State) ExecBlock(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block, blockPartsHeader types.PartSetHeader) ([]*types.TxResult, error) {
  19. // Validate the block.
  20. if err := s.validateBlock(block); err != nil {
  21. return nil, ErrInvalidBlock(err)
  22. }
  23. // compute bitarray of validators that signed
  24. signed := commitBitArrayFromBlock(block)
  25. _ = signed // TODO send on begin block
  26. // copy the valset
  27. valSet := s.Validators.Copy()
  28. nextValSet := valSet.Copy()
  29. // Execute the block txs
  30. txResults, changedValidators, err := execBlockOnProxyApp(eventCache, 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 nil, ErrProxyAppConn(err)
  35. }
  36. // update the validator set
  37. err = updateValidators(nextValSet, changedValidators)
  38. if err != nil {
  39. log.Warn("Error changing validator set", "error", err)
  40. // TODO: err or carry on?
  41. }
  42. // All good!
  43. // Update validator accums and set state variables
  44. nextValSet.IncrementAccum(1)
  45. s.SetBlockAndValidators(block.Header, blockPartsHeader, valSet, nextValSet)
  46. fail.Fail() // XXX
  47. return txResults, nil
  48. }
  49. // Executes block's transactions on proxyAppConn.
  50. // Returns a list of transaction results and updates to the validator set
  51. // TODO: Generate a bitmap or otherwise store tx validity in state.
  52. func execBlockOnProxyApp(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block) ([]*types.TxResult, []*abci.Validator, error) {
  53. var validTxs, invalidTxs = 0, 0
  54. txResults := make([]*types.TxResult, len(block.Txs))
  55. txIndex := 0
  56. // Execute transactions and get hash
  57. proxyCb := func(req *abci.Request, res *abci.Response) {
  58. switch r := res.Value.(type) {
  59. case *abci.Response_DeliverTx:
  60. // TODO: make use of res.Log
  61. // TODO: make use of this info
  62. // Blocks may include invalid txs.
  63. // reqDeliverTx := req.(abci.RequestDeliverTx)
  64. txError := ""
  65. txResult := r.DeliverTx
  66. if txResult.Code == abci.CodeType_OK {
  67. validTxs++
  68. } else {
  69. log.Debug("Invalid tx", "code", txResult.Code, "log", txResult.Log)
  70. invalidTxs++
  71. txError = txResult.Code.String()
  72. }
  73. txResults[txIndex] = &types.TxResult{uint64(block.Height), uint32(txIndex), *txResult}
  74. txIndex++
  75. // NOTE: if we count we can access the tx from the block instead of
  76. // pulling it from the req
  77. event := types.EventDataTx{
  78. Height: block.Height,
  79. Tx: types.Tx(req.GetDeliverTx().Tx),
  80. Data: txResult.Data,
  81. Code: txResult.Code,
  82. Log: txResult.Log,
  83. Error: txError,
  84. }
  85. types.FireEventTx(eventCache, event)
  86. }
  87. }
  88. proxyAppConn.SetResponseCallback(proxyCb)
  89. // Begin block
  90. err := proxyAppConn.BeginBlockSync(block.Hash(), types.TM2PB.Header(block.Header))
  91. if err != nil {
  92. log.Warn("Error in proxyAppConn.BeginBlock", "error", err)
  93. return nil, nil, err
  94. }
  95. fail.Fail() // XXX
  96. // Run txs of block
  97. for _, tx := range block.Txs {
  98. fail.FailRand(len(block.Txs)) // XXX
  99. proxyAppConn.DeliverTxAsync(tx)
  100. if err := proxyAppConn.Error(); err != nil {
  101. return nil, nil, err
  102. }
  103. }
  104. fail.Fail() // XXX
  105. // End block
  106. respEndBlock, err := proxyAppConn.EndBlockSync(uint64(block.Height))
  107. if err != nil {
  108. log.Warn("Error in proxyAppConn.EndBlock", "error", err)
  109. return nil, nil, err
  110. }
  111. fail.Fail() // XXX
  112. log.Info("Executed block", "height", block.Height, "valid txs", validTxs, "invalid txs", invalidTxs)
  113. if len(respEndBlock.Diffs) > 0 {
  114. log.Info("Update to validator set", "updates", abci.ValidatorsString(respEndBlock.Diffs))
  115. }
  116. return txResults, respEndBlock.Diffs, nil
  117. }
  118. func updateValidators(validators *types.ValidatorSet, changedValidators []*abci.Validator) error {
  119. // TODO: prevent change of 1/3+ at once
  120. for _, v := range changedValidators {
  121. pubkey, err := crypto.PubKeyFromBytes(v.PubKey) // NOTE: expects go-wire encoded pubkey
  122. if err != nil {
  123. return err
  124. }
  125. address := pubkey.Address()
  126. power := int64(v.Power)
  127. // mind the overflow from uint64
  128. if power < 0 {
  129. return errors.New(Fmt("Power (%d) overflows int64", v.Power))
  130. }
  131. _, val := validators.GetByAddress(address)
  132. if val == nil {
  133. // add val
  134. added := validators.Add(types.NewValidator(pubkey, power))
  135. if !added {
  136. return errors.New(Fmt("Failed to add new validator %X with voting power %d", address, power))
  137. }
  138. } else if v.Power == 0 {
  139. // remove val
  140. _, removed := validators.Remove(address)
  141. if !removed {
  142. return errors.New(Fmt("Failed to remove validator %X)"))
  143. }
  144. } else {
  145. // update val
  146. val.VotingPower = power
  147. updated := validators.Update(val)
  148. if !updated {
  149. return errors.New(Fmt("Failed to update validator %X with voting power %d", address, power))
  150. }
  151. }
  152. }
  153. return nil
  154. }
  155. // return a bit array of validators that signed the last commit
  156. // NOTE: assumes commits have already been authenticated
  157. func commitBitArrayFromBlock(block *types.Block) *BitArray {
  158. signed := NewBitArray(len(block.LastCommit.Precommits))
  159. for i, precommit := range block.LastCommit.Precommits {
  160. if precommit != nil {
  161. signed.SetIndex(i, true) // val_.LastCommitHeight = block.Height - 1
  162. }
  163. }
  164. return signed
  165. }
  166. //-----------------------------------------------------
  167. // Validate block
  168. func (s *State) ValidateBlock(block *types.Block) error {
  169. return s.validateBlock(block)
  170. }
  171. func (s *State) validateBlock(block *types.Block) error {
  172. // Basic block validation.
  173. err := block.ValidateBasic(s.ChainID, s.LastBlockHeight, s.LastBlockID, s.LastBlockTime, s.AppHash)
  174. if err != nil {
  175. return err
  176. }
  177. // Validate block LastCommit.
  178. if block.Height == 1 {
  179. if len(block.LastCommit.Precommits) != 0 {
  180. return errors.New("Block at height 1 (first block) should have no LastCommit precommits")
  181. }
  182. } else {
  183. if len(block.LastCommit.Precommits) != s.LastValidators.Size() {
  184. return errors.New(Fmt("Invalid block commit size. Expected %v, got %v",
  185. s.LastValidators.Size(), len(block.LastCommit.Precommits)))
  186. }
  187. err := s.LastValidators.VerifyCommit(
  188. s.ChainID, s.LastBlockID, block.Height-1, block.LastCommit)
  189. if err != nil {
  190. return err
  191. }
  192. }
  193. return nil
  194. }
  195. // ApplyBlock executes the block, then commits and updates the mempool
  196. // atomically, optionally indexing transaction results.
  197. func (s *State) ApplyBlock(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus,
  198. block *types.Block, partsHeader types.PartSetHeader, mempool types.Mempool) error {
  199. txResults, err := s.ExecBlock(eventCache, proxyAppConn, block, partsHeader)
  200. if err != nil {
  201. return fmt.Errorf("Exec failed for application: %v", err)
  202. }
  203. // lock mempool, commit state, update mempoool
  204. err = s.CommitStateUpdateMempool(proxyAppConn, block, mempool)
  205. if err != nil {
  206. return fmt.Errorf("Commit failed for application: %v", err)
  207. }
  208. batch := txindexer.NewBatch()
  209. for i, r := range txResults {
  210. tx := block.Txs[i]
  211. batch.Index(tx.Hash(), *r)
  212. }
  213. s.TxIndexer.Batch(batch)
  214. return nil
  215. }
  216. // mempool must be locked during commit and update
  217. // because state is typically reset on Commit and old txs must be replayed
  218. // against committed state before new txs are run in the mempool, lest they be invalid
  219. func (s *State) CommitStateUpdateMempool(proxyAppConn proxy.AppConnConsensus, block *types.Block, mempool types.Mempool) error {
  220. mempool.Lock()
  221. defer mempool.Unlock()
  222. // Commit block, get hash back
  223. res := proxyAppConn.CommitSync()
  224. if res.IsErr() {
  225. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  226. return res
  227. }
  228. if res.Log != "" {
  229. log.Debug("Commit.Log: " + res.Log)
  230. }
  231. log.Info("Committed state", "hash", res.Data)
  232. // Set the state's new AppHash
  233. s.AppHash = res.Data
  234. // Update mempool.
  235. mempool.Update(block.Height, block.Txs)
  236. return nil
  237. }
  238. // Apply and commit a block, but without all the state validation.
  239. // Returns the application root hash (result of abci.Commit)
  240. func ApplyBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block) ([]byte, error) {
  241. var eventCache types.Fireable // nil
  242. _, _, err := execBlockOnProxyApp(eventCache, appConnConsensus, block)
  243. if err != nil {
  244. log.Warn("Error executing block on proxy app", "height", block.Height, "err", err)
  245. return nil, err
  246. }
  247. // Commit block, get hash back
  248. res := appConnConsensus.CommitSync()
  249. if res.IsErr() {
  250. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  251. return nil, res
  252. }
  253. if res.Log != "" {
  254. log.Info("Commit.Log: " + res.Log)
  255. }
  256. return res.Data, nil
  257. }