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
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
  1. package state
  2. import (
  3. "errors"
  4. "fmt"
  5. . "github.com/tendermint/go-common"
  6. "github.com/tendermint/tendermint/proxy"
  7. "github.com/tendermint/tendermint/types"
  8. tmsp "github.com/tendermint/tmsp/types"
  9. )
  10. // Validate block
  11. func (s *State) ValidateBlock(block *types.Block) error {
  12. return s.validateBlock(block)
  13. }
  14. // Execute the block to mutate State.
  15. // Validates block and then executes Data.Txs in the block.
  16. func (s *State) ExecBlock(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block, blockPartsHeader types.PartSetHeader) error {
  17. // Validate the block.
  18. err := s.validateBlock(block)
  19. if err != nil {
  20. return err
  21. }
  22. // Update the validator set
  23. valSet := s.Validators.Copy()
  24. // Update valSet with signatures from block.
  25. updateValidatorsWithBlock(s.LastValidators, valSet, block)
  26. // TODO: Update the validator set (e.g. block.Data.ValidatorUpdates?)
  27. nextValSet := valSet.Copy()
  28. // Execute the block txs
  29. err = s.execBlockOnProxyApp(eventCache, proxyAppConn, block)
  30. if err != nil {
  31. // There was some error in proxyApp
  32. // TODO Report error and wait for proxyApp to be available.
  33. return err
  34. }
  35. // All good!
  36. // Update validator accums and set state variables
  37. nextValSet.IncrementAccum(1)
  38. s.SetBlockAndValidators(block.Header, blockPartsHeader, valSet, nextValSet)
  39. return nil
  40. }
  41. // Executes block's transactions on proxyAppConn.
  42. // TODO: Generate a bitmap or otherwise store tx validity in state.
  43. func (s *State) execBlockOnProxyApp(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block) error {
  44. var validTxs, invalidTxs = 0, 0
  45. // Execute transactions and get hash
  46. proxyCb := func(req *tmsp.Request, res *tmsp.Response) {
  47. switch r := res.Value.(type) {
  48. case *tmsp.Response_AppendTx:
  49. // TODO: make use of res.Log
  50. // TODO: make use of this info
  51. // Blocks may include invalid txs.
  52. // reqAppendTx := req.(tmsp.RequestAppendTx)
  53. txError := ""
  54. apTx := r.AppendTx
  55. if apTx.Code == tmsp.CodeType_OK {
  56. validTxs += 1
  57. } else {
  58. log.Debug("Invalid tx", "code", r.AppendTx.Code, "log", r.AppendTx.Log)
  59. invalidTxs += 1
  60. txError = apTx.Code.String()
  61. }
  62. // NOTE: if we count we can access the tx from the block instead of
  63. // pulling it from the req
  64. event := types.EventDataTx{
  65. Tx: req.GetAppendTx().Tx,
  66. Result: apTx.Data,
  67. Code: apTx.Code,
  68. Log: apTx.Log,
  69. Error: txError,
  70. }
  71. types.FireEventTx(eventCache, event)
  72. }
  73. }
  74. proxyAppConn.SetResponseCallback(proxyCb)
  75. // Begin block
  76. err := proxyAppConn.BeginBlockSync(block.Hash(), types.TM2PB.Header(block.Header))
  77. if err != nil {
  78. log.Warn("Error in proxyAppConn.BeginBlock", "error", err)
  79. return err
  80. }
  81. // Run txs of block
  82. for _, tx := range block.Txs {
  83. proxyAppConn.AppendTxAsync(tx)
  84. if err := proxyAppConn.Error(); err != nil {
  85. return err
  86. }
  87. }
  88. // End block
  89. changedValidators, err := proxyAppConn.EndBlockSync(uint64(block.Height))
  90. if err != nil {
  91. log.Warn("Error in proxyAppConn.EndBlock", "error", err)
  92. return err
  93. }
  94. // TODO: Do something with changedValidators
  95. log.Debug("TODO: Do something with changedValidators", "changedValidators", changedValidators)
  96. log.Info(Fmt("ExecBlock got %v valid txs and %v invalid txs", validTxs, invalidTxs))
  97. return nil
  98. }
  99. func (s *State) validateBlock(block *types.Block) error {
  100. // Basic block validation.
  101. err := block.ValidateBasic(s.ChainID, s.LastBlockHeight, s.LastBlockID, s.LastBlockTime, s.AppHash)
  102. if err != nil {
  103. return err
  104. }
  105. // Validate block LastCommit.
  106. if block.Height == 1 {
  107. if len(block.LastCommit.Precommits) != 0 {
  108. return errors.New("Block at height 1 (first block) should have no LastCommit precommits")
  109. }
  110. } else {
  111. if len(block.LastCommit.Precommits) != s.LastValidators.Size() {
  112. return fmt.Errorf("Invalid block commit size. Expected %v, got %v",
  113. s.LastValidators.Size(), len(block.LastCommit.Precommits))
  114. }
  115. err := s.LastValidators.VerifyCommit(
  116. s.ChainID, s.LastBlockID, block.Height-1, block.LastCommit)
  117. if err != nil {
  118. return err
  119. }
  120. }
  121. return nil
  122. }
  123. // Updates the LastCommitHeight of the validators in valSet, in place.
  124. // Assumes that lastValSet matches the valset of block.LastCommit
  125. // CONTRACT: lastValSet is not mutated.
  126. func updateValidatorsWithBlock(lastValSet *types.ValidatorSet, valSet *types.ValidatorSet, block *types.Block) {
  127. for i, precommit := range block.LastCommit.Precommits {
  128. if precommit == nil {
  129. continue
  130. }
  131. _, val := lastValSet.GetByIndex(i)
  132. if val == nil {
  133. PanicCrisis(Fmt("Failed to fetch validator at index %v", i))
  134. }
  135. if _, val_ := valSet.GetByAddress(val.Address); val_ != nil {
  136. val_.LastCommitHeight = block.Height - 1
  137. updated := valSet.Update(val_)
  138. if !updated {
  139. PanicCrisis("Failed to update validator LastCommitHeight")
  140. }
  141. } else {
  142. // XXX This is not an error if validator was removed.
  143. // But, we don't mutate validators yet so go ahead and panic.
  144. PanicCrisis("Could not find validator")
  145. }
  146. }
  147. }
  148. //-----------------------------------------------------------------------------
  149. type InvalidTxError struct {
  150. Tx types.Tx
  151. Code tmsp.CodeType
  152. }
  153. func (txErr InvalidTxError) Error() string {
  154. return Fmt("Invalid tx: [%v] code: [%v]", txErr.Tx, txErr.Code)
  155. }
  156. //-----------------------------------------------------------------------------
  157. // mempool must be locked during commit and update
  158. // because state is typically reset on Commit and old txs must be replayed
  159. // against committed state before new txs are run in the mempool, lest they be invalid
  160. func (s *State) CommitStateUpdateMempool(proxyAppConn proxy.AppConnConsensus, block *types.Block, mempool Mempool) error {
  161. mempool.Lock()
  162. defer mempool.Unlock()
  163. // flush out any CheckTx that have already started
  164. // cs.proxyAppConn.FlushSync() // ?! XXX
  165. // Commit block, get hash back
  166. res := proxyAppConn.CommitSync()
  167. if res.IsErr() {
  168. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  169. return res
  170. }
  171. if res.Log != "" {
  172. log.Debug("Commit.Log: " + res.Log)
  173. }
  174. // Set the state's new AppHash
  175. s.AppHash = res.Data
  176. // Update mempool.
  177. mempool.Update(block.Height, block.Txs)
  178. return nil
  179. }
  180. // Execute and commit block against app, save block and state
  181. func (s *State) ApplyBlock(eventCache events.Fireable, proxyAppConn proxy.AppConnConsensus,
  182. block *types.Block, partsHeader types.PartSetHeader, mempool Mempool) {
  183. // Run the block on the State:
  184. // + update validator sets
  185. // + run txs on the proxyAppConn
  186. err := s.ExecBlock(eventCache, proxyAppConn, block, partsHeader)
  187. if err != nil {
  188. // TODO: handle this gracefully.
  189. PanicQ(Fmt("Exec failed for application: %v", err))
  190. }
  191. // lock mempool, commit state, update mempoool
  192. err = s.CommitStateUpdateMempool(proxyAppConn, block, mempool)
  193. if err != nil {
  194. // TODO: handle this gracefully.
  195. PanicQ(Fmt("Commit failed for application: %v", err))
  196. }
  197. }
  198. // Replay all blocks after blockHeight and ensure the result matches the current state.
  199. // XXX: blockStore must guarantee to have blocks for height <= blockStore.Height()
  200. func (s *State) ReplayBlocks(appHash []byte, header *types.Header, partsHeader types.PartSetHeader,
  201. appConnConsensus proxy.AppConnConsensus, blockStore proxy.BlockStore) error {
  202. // NOTE/TODO: tendermint may crash after the app commits
  203. // but before it can save the new state root.
  204. // it should save all eg. valset changes before calling Commit.
  205. // then, if tm state is behind app state, the only thing missing can be app hash
  206. // fresh state to work on
  207. stateCopy := s.Copy()
  208. // reset to this height (do nothing if its 0)
  209. var blockHeight int
  210. if header != nil {
  211. blockHeight = header.Height
  212. // TODO: put validators in iavl tree so we can set the state with an older validator set
  213. lastVals, nextVals := stateCopy.GetValidators()
  214. stateCopy.SetBlockAndValidators(header, partsHeader, lastVals, nextVals)
  215. stateCopy.AppHash = appHash
  216. }
  217. // run the transactions
  218. var eventCache events.Fireable // nil
  219. // replay all blocks starting with blockHeight+1
  220. for i := blockHeight + 1; i <= blockStore.Height(); i++ {
  221. blockMeta := blockStore.LoadBlockMeta(i)
  222. block := blockStore.LoadBlock(i)
  223. panicOnNilBlock(i, blockStore.Height(), block, blockMeta) // XXX
  224. stateCopy.ApplyBlock(eventCache, appConnConsensus, block, blockMeta.PartsHeader, mockMempool{})
  225. }
  226. // The computed state and the previously set state should be identical
  227. if !s.Equals(stateCopy) {
  228. return fmt.Errorf("State after replay does not match saved state. Got ----\n%v\nExpected ----\n%v\n", stateCopy, s)
  229. }
  230. return nil
  231. }
  232. func panicOnNilBlock(height, bsHeight int, block *types.Block, blockMeta *types.BlockMeta) {
  233. if block == nil || blockMeta == nil {
  234. // Sanity?
  235. PanicCrisis(Fmt(`
  236. block/blockMeta is nil for height <= blockStore.Height() (%d <= %d).
  237. Block: %v,
  238. BlockMeta: %v
  239. `, height, bsHeight, block, blockMeta))
  240. }
  241. }
  242. //------------------------------------------------
  243. // Updates to the mempool need to be synchronized with committing a block
  244. // so apps can reset their transient state on Commit
  245. type Mempool interface {
  246. Lock()
  247. Unlock()
  248. Update(height int, txs []types.Tx)
  249. }
  250. type mockMempool struct {
  251. }
  252. func (m mockMempool) Lock() {}
  253. func (m mockMempool) Unlock() {}
  254. func (m mockMempool) Update(height int, txs []types.Tx) {}