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.

299 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. Tx: types.Tx(req.GetDeliverTx().Tx),
  79. Data: txResult.Data,
  80. Code: txResult.Code,
  81. Log: txResult.Log,
  82. Error: txError,
  83. }
  84. types.FireEventTx(eventCache, event)
  85. }
  86. }
  87. proxyAppConn.SetResponseCallback(proxyCb)
  88. // Begin block
  89. err := proxyAppConn.BeginBlockSync(block.Hash(), types.TM2PB.Header(block.Header))
  90. if err != nil {
  91. log.Warn("Error in proxyAppConn.BeginBlock", "error", err)
  92. return nil, nil, err
  93. }
  94. fail.Fail() // XXX
  95. // Run txs of block
  96. for _, tx := range block.Txs {
  97. fail.FailRand(len(block.Txs)) // XXX
  98. proxyAppConn.DeliverTxAsync(tx)
  99. if err := proxyAppConn.Error(); err != nil {
  100. return nil, nil, err
  101. }
  102. }
  103. fail.Fail() // XXX
  104. // End block
  105. respEndBlock, err := proxyAppConn.EndBlockSync(uint64(block.Height))
  106. if err != nil {
  107. log.Warn("Error in proxyAppConn.EndBlock", "error", err)
  108. return nil, nil, err
  109. }
  110. fail.Fail() // XXX
  111. log.Info("Executed block", "height", block.Height, "valid txs", validTxs, "invalid txs", invalidTxs)
  112. if len(respEndBlock.Diffs) > 0 {
  113. log.Info("Update to validator set", "updates", abci.ValidatorsString(respEndBlock.Diffs))
  114. }
  115. return txResults, respEndBlock.Diffs, nil
  116. }
  117. func updateValidators(validators *types.ValidatorSet, changedValidators []*abci.Validator) error {
  118. // TODO: prevent change of 1/3+ at once
  119. for _, v := range changedValidators {
  120. pubkey, err := crypto.PubKeyFromBytes(v.PubKey) // NOTE: expects go-wire encoded pubkey
  121. if err != nil {
  122. return err
  123. }
  124. address := pubkey.Address()
  125. power := int64(v.Power)
  126. // mind the overflow from uint64
  127. if power < 0 {
  128. return errors.New(Fmt("Power (%d) overflows int64", v.Power))
  129. }
  130. _, val := validators.GetByAddress(address)
  131. if val == nil {
  132. // add val
  133. added := validators.Add(types.NewValidator(pubkey, power))
  134. if !added {
  135. return errors.New(Fmt("Failed to add new validator %X with voting power %d", address, power))
  136. }
  137. } else if v.Power == 0 {
  138. // remove val
  139. _, removed := validators.Remove(address)
  140. if !removed {
  141. return errors.New(Fmt("Failed to remove validator %X)"))
  142. }
  143. } else {
  144. // update val
  145. val.VotingPower = power
  146. updated := validators.Update(val)
  147. if !updated {
  148. return errors.New(Fmt("Failed to update validator %X with voting power %d", address, power))
  149. }
  150. }
  151. }
  152. return nil
  153. }
  154. // return a bit array of validators that signed the last commit
  155. // NOTE: assumes commits have already been authenticated
  156. func commitBitArrayFromBlock(block *types.Block) *BitArray {
  157. signed := NewBitArray(len(block.LastCommit.Precommits))
  158. for i, precommit := range block.LastCommit.Precommits {
  159. if precommit != nil {
  160. signed.SetIndex(i, true) // val_.LastCommitHeight = block.Height - 1
  161. }
  162. }
  163. return signed
  164. }
  165. //-----------------------------------------------------
  166. // Validate block
  167. func (s *State) ValidateBlock(block *types.Block) error {
  168. return s.validateBlock(block)
  169. }
  170. func (s *State) validateBlock(block *types.Block) error {
  171. // Basic block validation.
  172. err := block.ValidateBasic(s.ChainID, s.LastBlockHeight, s.LastBlockID, s.LastBlockTime, s.AppHash)
  173. if err != nil {
  174. return err
  175. }
  176. // Validate block LastCommit.
  177. if block.Height == 1 {
  178. if len(block.LastCommit.Precommits) != 0 {
  179. return errors.New("Block at height 1 (first block) should have no LastCommit precommits")
  180. }
  181. } else {
  182. if len(block.LastCommit.Precommits) != s.LastValidators.Size() {
  183. return errors.New(Fmt("Invalid block commit size. Expected %v, got %v",
  184. s.LastValidators.Size(), len(block.LastCommit.Precommits)))
  185. }
  186. err := s.LastValidators.VerifyCommit(
  187. s.ChainID, s.LastBlockID, block.Height-1, block.LastCommit)
  188. if err != nil {
  189. return err
  190. }
  191. }
  192. return nil
  193. }
  194. // ApplyBlock executes the block, then commits and updates the mempool
  195. // atomically, optionally indexing transaction results.
  196. func (s *State) ApplyBlock(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus,
  197. block *types.Block, partsHeader types.PartSetHeader, mempool types.Mempool) error {
  198. txResults, err := s.ExecBlock(eventCache, proxyAppConn, block, partsHeader)
  199. if err != nil {
  200. return fmt.Errorf("Exec failed for application: %v", err)
  201. }
  202. // lock mempool, commit state, update mempoool
  203. err = s.CommitStateUpdateMempool(proxyAppConn, block, mempool)
  204. if err != nil {
  205. return fmt.Errorf("Commit failed for application: %v", err)
  206. }
  207. batch := txindexer.NewBatch()
  208. for i, r := range txResults {
  209. tx := block.Txs[i]
  210. batch.Index(tx.Hash(), *r)
  211. }
  212. s.TxIndexer.Batch(batch)
  213. return nil
  214. }
  215. // mempool must be locked during commit and update
  216. // because state is typically reset on Commit and old txs must be replayed
  217. // against committed state before new txs are run in the mempool, lest they be invalid
  218. func (s *State) CommitStateUpdateMempool(proxyAppConn proxy.AppConnConsensus, block *types.Block, mempool types.Mempool) error {
  219. mempool.Lock()
  220. defer mempool.Unlock()
  221. // Commit block, get hash back
  222. res := proxyAppConn.CommitSync()
  223. if res.IsErr() {
  224. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  225. return res
  226. }
  227. if res.Log != "" {
  228. log.Debug("Commit.Log: " + res.Log)
  229. }
  230. log.Info("Committed state", "hash", res.Data)
  231. // Set the state's new AppHash
  232. s.AppHash = res.Data
  233. // Update mempool.
  234. mempool.Update(block.Height, block.Txs)
  235. return nil
  236. }
  237. // Apply and commit a block, but without all the state validation.
  238. // Returns the application root hash (result of abci.Commit)
  239. func ApplyBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block) ([]byte, error) {
  240. var eventCache types.Fireable // nil
  241. _, _, err := execBlockOnProxyApp(eventCache, appConnConsensus, block)
  242. if err != nil {
  243. log.Warn("Error executing block on proxy app", "height", block.Height, "err", err)
  244. return nil, err
  245. }
  246. // Commit block, get hash back
  247. res := appConnConsensus.CommitSync()
  248. if res.IsErr() {
  249. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  250. return nil, res
  251. }
  252. if res.Log != "" {
  253. log.Info("Commit.Log: " + res.Log)
  254. }
  255. return res.Data, nil
  256. }