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.

438 lines
13 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
  1. package state
  2. import (
  3. "bytes"
  4. "errors"
  5. "github.com/ebuchman/fail-test"
  6. . "github.com/tendermint/go-common"
  7. cfg "github.com/tendermint/go-config"
  8. "github.com/tendermint/tendermint/proxy"
  9. "github.com/tendermint/tendermint/types"
  10. tmsp "github.com/tendermint/tmsp/types"
  11. )
  12. //--------------------------------------------------
  13. // Execute the block
  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 ErrInvalidBlock(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 ErrProxyAppConn(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. // save state with updated height/blockhash/validators
  40. // but stale apphash, in case we fail between Commit and Save
  41. s.Save()
  42. return nil
  43. }
  44. // Executes block's transactions on proxyAppConn.
  45. // TODO: Generate a bitmap or otherwise store tx validity in state.
  46. func (s *State) execBlockOnProxyApp(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block) error {
  47. var validTxs, invalidTxs = 0, 0
  48. // Execute transactions and get hash
  49. proxyCb := func(req *tmsp.Request, res *tmsp.Response) {
  50. switch r := res.Value.(type) {
  51. case *tmsp.Response_AppendTx:
  52. // TODO: make use of res.Log
  53. // TODO: make use of this info
  54. // Blocks may include invalid txs.
  55. // reqAppendTx := req.(tmsp.RequestAppendTx)
  56. txError := ""
  57. apTx := r.AppendTx
  58. if apTx.Code == tmsp.CodeType_OK {
  59. validTxs += 1
  60. } else {
  61. log.Debug("Invalid tx", "code", r.AppendTx.Code, "log", r.AppendTx.Log)
  62. invalidTxs += 1
  63. txError = apTx.Code.String()
  64. }
  65. // NOTE: if we count we can access the tx from the block instead of
  66. // pulling it from the req
  67. event := types.EventDataTx{
  68. Tx: req.GetAppendTx().Tx,
  69. Result: apTx.Data,
  70. Code: apTx.Code,
  71. Log: apTx.Log,
  72. Error: txError,
  73. }
  74. types.FireEventTx(eventCache, event)
  75. }
  76. }
  77. proxyAppConn.SetResponseCallback(proxyCb)
  78. // Begin block
  79. err := proxyAppConn.BeginBlockSync(block.Hash(), types.TM2PB.Header(block.Header))
  80. if err != nil {
  81. log.Warn("Error in proxyAppConn.BeginBlock", "error", err)
  82. return err
  83. }
  84. fail.Fail() // XXX
  85. // Run txs of block
  86. for _, tx := range block.Txs {
  87. fail.FailRand(len(block.Txs)) // XXX
  88. proxyAppConn.AppendTxAsync(tx)
  89. if err := proxyAppConn.Error(); err != nil {
  90. return err
  91. }
  92. }
  93. fail.Fail() // XXX
  94. // End block
  95. changedValidators, err := proxyAppConn.EndBlockSync(uint64(block.Height))
  96. if err != nil {
  97. log.Warn("Error in proxyAppConn.EndBlock", "error", err)
  98. return err
  99. }
  100. fail.Fail() // XXX
  101. // TODO: Do something with changedValidators
  102. log.Debug("TODO: Do something with changedValidators", "changedValidators", changedValidators)
  103. log.Info(Fmt("ExecBlock got %v valid txs and %v invalid txs", validTxs, invalidTxs))
  104. return nil
  105. }
  106. // Updates the LastCommitHeight of the validators in valSet, in place.
  107. // Assumes that lastValSet matches the valset of block.LastCommit
  108. // CONTRACT: lastValSet is not mutated.
  109. func updateValidatorsWithBlock(lastValSet *types.ValidatorSet, valSet *types.ValidatorSet, block *types.Block) {
  110. for i, precommit := range block.LastCommit.Precommits {
  111. if precommit == nil {
  112. continue
  113. }
  114. _, val := lastValSet.GetByIndex(i)
  115. if val == nil {
  116. PanicCrisis(Fmt("Failed to fetch validator at index %v", i))
  117. }
  118. if _, val_ := valSet.GetByAddress(val.Address); val_ != nil {
  119. val_.LastCommitHeight = block.Height - 1
  120. updated := valSet.Update(val_)
  121. if !updated {
  122. PanicCrisis("Failed to update validator LastCommitHeight")
  123. }
  124. } else {
  125. // XXX This is not an error if validator was removed.
  126. // But, we don't mutate validators yet so go ahead and panic.
  127. PanicCrisis("Could not find validator")
  128. }
  129. }
  130. }
  131. //-----------------------------------------------------
  132. // Validate block
  133. func (s *State) ValidateBlock(block *types.Block) error {
  134. return s.validateBlock(block)
  135. }
  136. func (s *State) validateBlock(block *types.Block) error {
  137. // Basic block validation.
  138. err := block.ValidateBasic(s.ChainID, s.LastBlockHeight, s.LastBlockID, s.LastBlockTime, s.AppHash)
  139. if err != nil {
  140. return err
  141. }
  142. // Validate block LastCommit.
  143. if block.Height == 1 {
  144. if len(block.LastCommit.Precommits) != 0 {
  145. return errors.New("Block at height 1 (first block) should have no LastCommit precommits")
  146. }
  147. } else {
  148. if len(block.LastCommit.Precommits) != s.LastValidators.Size() {
  149. return errors.New(Fmt("Invalid block commit size. Expected %v, got %v",
  150. s.LastValidators.Size(), len(block.LastCommit.Precommits)))
  151. }
  152. err := s.LastValidators.VerifyCommit(
  153. s.ChainID, s.LastBlockID, block.Height-1, block.LastCommit)
  154. if err != nil {
  155. return err
  156. }
  157. }
  158. return nil
  159. }
  160. //-----------------------------------------------------------------------------
  161. // ApplyBlock executes the block, then commits and updates the mempool atomically
  162. // Execute and commit block against app, save block and state
  163. func (s *State) ApplyBlock(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus,
  164. block *types.Block, partsHeader types.PartSetHeader, mempool Mempool) error {
  165. // Run the block on the State:
  166. // + update validator sets
  167. // + run txs on the proxyAppConn
  168. err := s.ExecBlock(eventCache, proxyAppConn, block, partsHeader)
  169. if err != nil {
  170. return errors.New(Fmt("Exec failed for application: %v", err))
  171. }
  172. // lock mempool, commit state, update mempoool
  173. err = s.CommitStateUpdateMempool(proxyAppConn, block, mempool)
  174. if err != nil {
  175. return errors.New(Fmt("Commit failed for application: %v", err))
  176. }
  177. return nil
  178. }
  179. // mempool must be locked during commit and update
  180. // because state is typically reset on Commit and old txs must be replayed
  181. // against committed state before new txs are run in the mempool, lest they be invalid
  182. func (s *State) CommitStateUpdateMempool(proxyAppConn proxy.AppConnConsensus, block *types.Block, mempool Mempool) error {
  183. mempool.Lock()
  184. defer mempool.Unlock()
  185. // Commit block, get hash back
  186. res := proxyAppConn.CommitSync()
  187. if res.IsErr() {
  188. log.Warn("Error in proxyAppConn.CommitSync", "error", res)
  189. return res
  190. }
  191. if res.Log != "" {
  192. log.Debug("Commit.Log: " + res.Log)
  193. }
  194. // Set the state's new AppHash
  195. s.AppHash = res.Data
  196. // Update mempool.
  197. mempool.Update(block.Height, block.Txs)
  198. return nil
  199. }
  200. // Updates to the mempool need to be synchronized with committing a block
  201. // so apps can reset their transient state on Commit
  202. type Mempool interface {
  203. Lock()
  204. Unlock()
  205. Update(height int, txs []types.Tx)
  206. }
  207. type mockMempool struct {
  208. }
  209. func (m mockMempool) Lock() {}
  210. func (m mockMempool) Unlock() {}
  211. func (m mockMempool) Update(height int, txs []types.Tx) {}
  212. //----------------------------------------------------------------
  213. // Handshake with app to sync to latest state of core by replaying blocks
  214. // TODO: Should we move blockchain/store.go to its own package?
  215. type BlockStore interface {
  216. Height() int
  217. LoadBlock(height int) *types.Block
  218. }
  219. type Handshaker struct {
  220. config cfg.Config
  221. state *State
  222. store BlockStore
  223. nBlocks int // number of blocks applied to the state
  224. }
  225. func NewHandshaker(config cfg.Config, state *State, store BlockStore) *Handshaker {
  226. return &Handshaker{config, state, store, 0}
  227. }
  228. // TODO: retry the handshake once if it fails the first time
  229. // ... let Info take an argument determining its behaviour
  230. func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error {
  231. // handshake is done via info request on the query conn
  232. res, tmspInfo, blockInfo, configInfo := proxyApp.Query().InfoSync()
  233. if res.IsErr() {
  234. return errors.New(Fmt("Error calling Info. Code: %v; Data: %X; Log: %s", res.Code, res.Data, res.Log))
  235. }
  236. if blockInfo == nil {
  237. log.Warn("blockInfo is nil, aborting handshake")
  238. return nil
  239. }
  240. log.Notice("TMSP Handshake", "height", blockInfo.BlockHeight, "block_hash", blockInfo.BlockHash, "app_hash", blockInfo.AppHash)
  241. blockHeight := int(blockInfo.BlockHeight) // safe, should be an int32
  242. blockHash := blockInfo.BlockHash
  243. appHash := blockInfo.AppHash
  244. if tmspInfo != nil {
  245. // TODO: check tmsp version (or do this in the tmspcli?)
  246. _ = tmspInfo
  247. }
  248. // last block (nil if we starting from 0)
  249. var header *types.Header
  250. var partsHeader types.PartSetHeader
  251. // replay all blocks after blockHeight
  252. // if blockHeight == 0, we will replay everything
  253. if blockHeight != 0 {
  254. block := h.store.LoadBlock(blockHeight)
  255. if block == nil {
  256. return ErrUnknownBlock{blockHeight}
  257. }
  258. // check block hash
  259. if !bytes.Equal(block.Hash(), blockHash) {
  260. return ErrBlockHashMismatch{block.Hash(), blockHash, blockHeight}
  261. }
  262. // NOTE: app hash should be in the next block ...
  263. // check app hash
  264. /*if !bytes.Equal(block.Header.AppHash, appHash) {
  265. return fmt.Errorf("Handshake error. App hash at height %d does not match. Got %X, expected %X", blockHeight, appHash, block.Header.AppHash)
  266. }*/
  267. header = block.Header
  268. partsHeader = block.MakePartSet(h.config.GetInt("block_part_size")).Header()
  269. }
  270. if configInfo != nil {
  271. // TODO: set config info
  272. _ = configInfo
  273. }
  274. // replay blocks up to the latest in the blockstore
  275. err := h.ReplayBlocks(appHash, header, partsHeader, proxyApp.Consensus())
  276. if err != nil {
  277. return errors.New(Fmt("Error on replay: %v", err))
  278. }
  279. // TODO: (on restart) replay mempool
  280. return nil
  281. }
  282. // Replay all blocks after blockHeight and ensure the result matches the current state.
  283. func (h *Handshaker) ReplayBlocks(appHash []byte, header *types.Header, partsHeader types.PartSetHeader,
  284. appConnConsensus proxy.AppConnConsensus) error {
  285. // NOTE/TODO: tendermint may crash after the app commits
  286. // but before it can save the new state root.
  287. // it should save all eg. valset changes before calling Commit.
  288. // then, if tm state is behind app state, the only thing missing can be app hash
  289. // get a fresh state and reset to the apps latest
  290. stateCopy := h.state.Copy()
  291. // TODO: put validators in iavl tree so we can set the state with an older validator set
  292. lastVals, nextVals := stateCopy.GetValidators()
  293. if header == nil {
  294. stateCopy.LastBlockHeight = 0
  295. stateCopy.LastBlockID = types.BlockID{}
  296. // stateCopy.LastBlockTime = ... doesnt matter
  297. stateCopy.Validators = nextVals
  298. stateCopy.LastValidators = lastVals
  299. } else {
  300. stateCopy.SetBlockAndValidators(header, partsHeader, lastVals, nextVals)
  301. }
  302. stateCopy.Stale = false
  303. stateCopy.AppHash = appHash
  304. appBlockHeight := stateCopy.LastBlockHeight
  305. coreBlockHeight := h.store.Height()
  306. if coreBlockHeight < appBlockHeight {
  307. // if the app is ahead, there's nothing we can do
  308. return ErrAppBlockHeightTooHigh{coreBlockHeight, appBlockHeight}
  309. } else if coreBlockHeight == appBlockHeight {
  310. // if we crashed between Commit and SaveState,
  311. // the state's app hash is stale.
  312. // otherwise we're synced
  313. if h.state.Stale {
  314. h.state.Stale = false
  315. h.state.AppHash = appHash
  316. }
  317. return checkState(h.state, stateCopy)
  318. } else if h.state.LastBlockHeight == appBlockHeight {
  319. // core is ahead of app but core's state height is at apps height
  320. // this happens if we crashed after saving the block,
  321. // but before committing it. We should be 1 ahead
  322. if coreBlockHeight != appBlockHeight+1 {
  323. PanicSanity(Fmt("core.state.height == app.height but core.height (%d) > app.height+1 (%d)", coreBlockHeight, appBlockHeight+1))
  324. }
  325. // check that the blocks last apphash is the states apphash
  326. block := h.store.LoadBlock(coreBlockHeight)
  327. if !bytes.Equal(block.Header.AppHash, appHash) {
  328. return ErrLastStateMismatch{coreBlockHeight, block.Header.AppHash, appHash}
  329. }
  330. // replay the block against the actual tendermint state (not the copy)
  331. return h.loadApplyBlock(coreBlockHeight, h.state, appConnConsensus)
  332. } else {
  333. // either we're caught up or there's blocks to replay
  334. // replay all blocks starting with appBlockHeight+1
  335. for i := appBlockHeight + 1; i <= coreBlockHeight; i++ {
  336. h.loadApplyBlock(i, stateCopy, appConnConsensus)
  337. }
  338. return checkState(h.state, stateCopy)
  339. }
  340. }
  341. func checkState(s, stateCopy *State) error {
  342. // The computed state and the previously set state should be identical
  343. if !s.Equals(stateCopy) {
  344. return ErrStateMismatch{stateCopy, s}
  345. }
  346. return nil
  347. }
  348. func (h *Handshaker) loadApplyBlock(blockIndex int, state *State, appConnConsensus proxy.AppConnConsensus) error {
  349. h.nBlocks += 1
  350. block := h.store.LoadBlock(blockIndex)
  351. panicOnNilBlock(blockIndex, h.store.Height(), block) // XXX
  352. var eventCache types.Fireable // nil
  353. return state.ApplyBlock(eventCache, appConnConsensus, block, block.MakePartSet(h.config.GetInt("block_part_size")).Header(), mockMempool{})
  354. }
  355. func panicOnNilBlock(height, bsHeight int, block *types.Block) {
  356. if block == nil {
  357. // Sanity?
  358. PanicCrisis(Fmt(`
  359. block is nil for height <= blockStore.Height() (%d <= %d).
  360. Block: %v,
  361. `, height, bsHeight, block))
  362. }
  363. }