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.

308 lines
9.1 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
7 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. func (s *State) ValidateBlock(block *types.Block) error {
  150. return s.validateBlock(block)
  151. }
  152. func (s *State) validateBlock(block *types.Block) error {
  153. // Basic block validation.
  154. err := block.ValidateBasic(s.ChainID, s.LastBlockHeight, s.LastBlockID, s.LastBlockTime, s.AppHash)
  155. if err != nil {
  156. return err
  157. }
  158. // Validate block LastCommit.
  159. if block.Height == 1 {
  160. if len(block.LastCommit.Precommits) != 0 {
  161. return errors.New("Block at height 1 (first block) should have no LastCommit precommits")
  162. }
  163. } else {
  164. if len(block.LastCommit.Precommits) != s.LastValidators.Size() {
  165. return errors.New(cmn.Fmt("Invalid block commit size. Expected %v, got %v",
  166. s.LastValidators.Size(), len(block.LastCommit.Precommits)))
  167. }
  168. err := s.LastValidators.VerifyCommit(
  169. s.ChainID, s.LastBlockID, block.Height-1, block.LastCommit)
  170. if err != nil {
  171. return err
  172. }
  173. }
  174. return nil
  175. }
  176. //-----------------------------------------------------------------------------
  177. // ApplyBlock validates & executes the block, updates state w/ ABCI responses,
  178. // then commits and updates the mempool atomically, then saves state.
  179. // Transaction results are optionally indexed.
  180. // Validate, execute, and commit block against app, save block and state
  181. func (s *State) ApplyBlock(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus,
  182. block *types.Block, partsHeader types.PartSetHeader, mempool types.Mempool) error {
  183. abciResponses, err := s.ValExecBlock(eventCache, proxyAppConn, block)
  184. if err != nil {
  185. return fmt.Errorf("Exec failed for application: %v", err)
  186. }
  187. fail.Fail() // XXX
  188. // index txs. This could run in the background
  189. s.indexTxs(abciResponses)
  190. // save the results before we commit
  191. s.SaveABCIResponses(abciResponses)
  192. fail.Fail() // XXX
  193. // now update the block and validators
  194. s.SetBlockAndValidators(block.Header, partsHeader, abciResponses)
  195. // lock mempool, commit state, update mempoool
  196. err = s.CommitStateUpdateMempool(proxyAppConn, block, mempool)
  197. if err != nil {
  198. return fmt.Errorf("Commit failed for application: %v", err)
  199. }
  200. fail.Fail() // XXX
  201. // save the state
  202. s.Save()
  203. return nil
  204. }
  205. // mempool must be locked during commit and update
  206. // because state is typically reset on Commit and old txs must be replayed
  207. // against committed state before new txs are run in the mempool, lest they be invalid
  208. func (s *State) CommitStateUpdateMempool(proxyAppConn proxy.AppConnConsensus, block *types.Block, mempool types.Mempool) error {
  209. mempool.Lock()
  210. defer mempool.Unlock()
  211. // Commit block, get hash back
  212. res := proxyAppConn.CommitSync()
  213. if res.IsErr() {
  214. s.logger.Error("Error in proxyAppConn.CommitSync", "err", res)
  215. return res
  216. }
  217. if res.Log != "" {
  218. s.logger.Debug("Commit.Log: " + res.Log)
  219. }
  220. s.logger.Info("Committed state", "height", block.Height, "txs", block.NumTxs, "hash", res.Data)
  221. // Set the state's new AppHash
  222. s.AppHash = res.Data
  223. // Update mempool.
  224. mempool.Update(block.Height, block.Txs)
  225. return nil
  226. }
  227. func (s *State) indexTxs(abciResponses *ABCIResponses) {
  228. // save the tx results using the TxIndexer
  229. // NOTE: these may be overwriting, but the values should be the same.
  230. batch := txindex.NewBatch(len(abciResponses.DeliverTx))
  231. for i, d := range abciResponses.DeliverTx {
  232. tx := abciResponses.txs[i]
  233. batch.Add(types.TxResult{
  234. Height: uint64(abciResponses.Height),
  235. Index: uint32(i),
  236. Tx: tx,
  237. Result: *d,
  238. })
  239. }
  240. s.TxIndexer.AddBatch(batch)
  241. }
  242. // Exec and commit a block on the proxyApp without validating or mutating the state
  243. // Returns the application root hash (result of abci.Commit)
  244. func ExecCommitBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block, logger log.Logger) ([]byte, error) {
  245. var eventCache types.Fireable // nil
  246. _, err := execBlockOnProxyApp(eventCache, appConnConsensus, block, logger)
  247. if err != nil {
  248. logger.Error("Error executing block on proxy app", "height", block.Height, "err", err)
  249. return nil, err
  250. }
  251. // Commit block, get hash back
  252. res := appConnConsensus.CommitSync()
  253. if res.IsErr() {
  254. logger.Error("Error in proxyAppConn.CommitSync", "err", res)
  255. return nil, res
  256. }
  257. if res.Log != "" {
  258. logger.Info("Commit.Log: " + res.Log)
  259. }
  260. return res.Data, nil
  261. }