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.

303 lines
8.9 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. "encoding/hex"
  4. "errors"
  5. "fmt"
  6. fail "github.com/ebuchman/fail-test"
  7. abci "github.com/tendermint/abci/types"
  8. . "github.com/tendermint/go-common"
  9. crypto "github.com/tendermint/go-crypto"
  10. "github.com/tendermint/tendermint/proxy"
  11. txindexer "github.com/tendermint/tendermint/state/tx/indexer"
  12. "github.com/tendermint/tendermint/types"
  13. )
  14. // ExecBlock executes the block to mutate State.
  15. // + validates the block
  16. // + executes block.Txs on the proxyAppConn
  17. // + updates validator sets
  18. // + returns block.Txs results
  19. func (s *State) ExecBlock(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block, blockPartsHeader types.PartSetHeader) ([]*types.TxResult, error) {
  20. // Validate the block.
  21. if err := s.validateBlock(block); err != nil {
  22. return nil, ErrInvalidBlock(err)
  23. }
  24. // compute bitarray of validators that signed
  25. signed := commitBitArrayFromBlock(block)
  26. _ = signed // TODO send on begin block
  27. // copy the valset
  28. valSet := s.Validators.Copy()
  29. nextValSet := valSet.Copy()
  30. // Execute the block txs
  31. txResults, changedValidators, err := execBlockOnProxyApp(eventCache, proxyAppConn, block)
  32. if err != nil {
  33. // There was some error in proxyApp
  34. // TODO Report error and wait for proxyApp to be available.
  35. return nil, ErrProxyAppConn(err)
  36. }
  37. // update the validator set
  38. err = updateValidators(nextValSet, changedValidators)
  39. if err != nil {
  40. log.Warn("Error changing validator set", "error", err)
  41. // TODO: err or carry on?
  42. }
  43. // All good!
  44. // Update validator accums and set state variables
  45. nextValSet.IncrementAccum(1)
  46. s.SetBlockAndValidators(block.Header, blockPartsHeader, valSet, nextValSet)
  47. fail.Fail() // XXX
  48. return txResults, nil
  49. }
  50. // Executes block's transactions on proxyAppConn.
  51. // Returns a list of transaction results and updates to the validator set
  52. // TODO: Generate a bitmap or otherwise store tx validity in state.
  53. func execBlockOnProxyApp(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block) ([]*types.TxResult, []*abci.Validator, error) {
  54. var validTxs, invalidTxs = 0, 0
  55. txResults := make([]*types.TxResult, len(block.Txs))
  56. txIndex := 0
  57. // Execute transactions and get hash
  58. proxyCb := func(req *abci.Request, res *abci.Response) {
  59. switch r := res.Value.(type) {
  60. case *abci.Response_DeliverTx:
  61. // TODO: make use of res.Log
  62. // TODO: make use of this info
  63. // Blocks may include invalid txs.
  64. // reqDeliverTx := req.(abci.RequestDeliverTx)
  65. txError := ""
  66. txResult := r.DeliverTx
  67. if txResult.Code == abci.CodeType_OK {
  68. validTxs++
  69. } else {
  70. log.Debug("Invalid tx", "code", txResult.Code, "log", txResult.Log)
  71. invalidTxs++
  72. txError = txResult.Code.String()
  73. }
  74. txResults[txIndex] = &types.TxResult{uint64(block.Height), uint32(txIndex), *txResult}
  75. txIndex++
  76. // NOTE: if we count we can access the tx from the block instead of
  77. // pulling it from the req
  78. event := types.EventDataTx{
  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. if r != nil {
  211. tx := block.Txs[i]
  212. // dd2e325f79f7e5f77788759d278c1d4b370c842e => {"height":2405, "index":0, ...}
  213. batch.Index(hex.EncodeToString(tx.Hash()), *r)
  214. }
  215. }
  216. s.TxIndexer.Batch(batch)
  217. return nil
  218. }
  219. // mempool must be locked during commit and update
  220. // because state is typically reset on Commit and old txs must be replayed
  221. // against committed state before new txs are run in the mempool, lest they be invalid
  222. func (s *State) CommitStateUpdateMempool(proxyAppConn proxy.AppConnConsensus, block *types.Block, mempool types.Mempool) error {
  223. mempool.Lock()
  224. defer mempool.Unlock()
  225. // Commit block, get hash back
  226. res := proxyAppConn.CommitSync()
  227. if res.IsErr() {
  228. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  229. return res
  230. }
  231. if res.Log != "" {
  232. log.Debug("Commit.Log: " + res.Log)
  233. }
  234. log.Info("Committed state", "hash", res.Data)
  235. // Set the state's new AppHash
  236. s.AppHash = res.Data
  237. // Update mempool.
  238. mempool.Update(block.Height, block.Txs)
  239. return nil
  240. }
  241. // Apply and commit a block, but without all the state validation.
  242. // Returns the application root hash (result of abci.Commit)
  243. func ApplyBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block) ([]byte, error) {
  244. var eventCache types.Fireable // nil
  245. _, _, err := execBlockOnProxyApp(eventCache, appConnConsensus, block)
  246. if err != nil {
  247. log.Warn("Error executing block on proxy app", "height", block.Height, "err", err)
  248. return nil, err
  249. }
  250. // Commit block, get hash back
  251. res := appConnConsensus.CommitSync()
  252. if res.IsErr() {
  253. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  254. return nil, res
  255. }
  256. if res.Log != "" {
  257. log.Info("Commit.Log: " + res.Log)
  258. }
  259. return res.Data, nil
  260. }