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.

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