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.

474 lines
15 KiB

7 years ago
8 years ago
8 years ago
8 years ago
6 years ago
6 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
7 years ago
6 years ago
6 years ago
8 years ago
8 years ago
  1. package state
  2. import (
  3. "fmt"
  4. "time"
  5. abci "github.com/tendermint/tendermint/abci/types"
  6. dbm "github.com/tendermint/tendermint/libs/db"
  7. "github.com/tendermint/tendermint/libs/fail"
  8. "github.com/tendermint/tendermint/libs/log"
  9. "github.com/tendermint/tendermint/mempool"
  10. "github.com/tendermint/tendermint/proxy"
  11. "github.com/tendermint/tendermint/types"
  12. )
  13. //-----------------------------------------------------------------------------
  14. // BlockExecutor handles block execution and state updates.
  15. // It exposes ApplyBlock(), which validates & executes the block, updates state w/ ABCI responses,
  16. // then commits and updates the mempool atomically, then saves state.
  17. // BlockExecutor provides the context and accessories for properly executing a block.
  18. type BlockExecutor struct {
  19. // save state, validators, consensus params, abci responses here
  20. db dbm.DB
  21. // execute the app against this
  22. proxyApp proxy.AppConnConsensus
  23. // events
  24. eventBus types.BlockEventPublisher
  25. // update these with block results after commit
  26. mempool Mempool
  27. evpool EvidencePool
  28. logger log.Logger
  29. metrics *Metrics
  30. }
  31. type BlockExecutorOption func(executor *BlockExecutor)
  32. func BlockExecutorWithMetrics(metrics *Metrics) BlockExecutorOption {
  33. return func(blockExec *BlockExecutor) {
  34. blockExec.metrics = metrics
  35. }
  36. }
  37. // NewBlockExecutor returns a new BlockExecutor with a NopEventBus.
  38. // Call SetEventBus to provide one.
  39. func NewBlockExecutor(db dbm.DB, logger log.Logger, proxyApp proxy.AppConnConsensus,
  40. mempool Mempool, evpool EvidencePool, options ...BlockExecutorOption) *BlockExecutor {
  41. res := &BlockExecutor{
  42. db: db,
  43. proxyApp: proxyApp,
  44. eventBus: types.NopEventBus{},
  45. mempool: mempool,
  46. evpool: evpool,
  47. logger: logger,
  48. metrics: NopMetrics(),
  49. }
  50. for _, option := range options {
  51. option(res)
  52. }
  53. return res
  54. }
  55. // SetEventBus - sets the event bus for publishing block related events.
  56. // If not called, it defaults to types.NopEventBus.
  57. func (blockExec *BlockExecutor) SetEventBus(eventBus types.BlockEventPublisher) {
  58. blockExec.eventBus = eventBus
  59. }
  60. // ValidateBlock validates the given block against the given state.
  61. // If the block is invalid, it returns an error.
  62. // Validation does not mutate state, but does require historical information from the stateDB,
  63. // ie. to verify evidence from a validator at an old height.
  64. func (blockExec *BlockExecutor) ValidateBlock(state State, block *types.Block) error {
  65. return validateBlock(blockExec.db, state, block)
  66. }
  67. // ApplyBlock validates the block against the state, executes it against the app,
  68. // fires the relevant events, commits the app, and saves the new state and responses.
  69. // It's the only function that needs to be called
  70. // from outside this package to process and commit an entire block.
  71. // It takes a blockID to avoid recomputing the parts hash.
  72. func (blockExec *BlockExecutor) ApplyBlock(state State, blockID types.BlockID, block *types.Block) (State, error) {
  73. if err := blockExec.ValidateBlock(state, block); err != nil {
  74. return state, ErrInvalidBlock(err)
  75. }
  76. startTime := time.Now().UnixNano()
  77. abciResponses, err := execBlockOnProxyApp(blockExec.logger, blockExec.proxyApp, block, state.LastValidators, blockExec.db)
  78. endTime := time.Now().UnixNano()
  79. blockExec.metrics.BlockProcessingTime.Observe(float64(endTime-startTime) / 1000000)
  80. if err != nil {
  81. return state, ErrProxyAppConn(err)
  82. }
  83. fail.Fail() // XXX
  84. // Save the results before we commit.
  85. saveABCIResponses(blockExec.db, block.Height, abciResponses)
  86. fail.Fail() // XXX
  87. // Update the state with the block and responses.
  88. state, err = updateState(state, blockID, &block.Header, abciResponses)
  89. if err != nil {
  90. return state, fmt.Errorf("Commit failed for application: %v", err)
  91. }
  92. // Lock mempool, commit app state, update mempoool.
  93. appHash, err := blockExec.Commit(state, block)
  94. if err != nil {
  95. return state, fmt.Errorf("Commit failed for application: %v", err)
  96. }
  97. // Update evpool with the block and state.
  98. blockExec.evpool.Update(block, state)
  99. fail.Fail() // XXX
  100. // Update the app hash and save the state.
  101. state.AppHash = appHash
  102. SaveState(blockExec.db, state)
  103. fail.Fail() // XXX
  104. // Events are fired after everything else.
  105. // NOTE: if we crash between Commit and Save, events wont be fired during replay
  106. fireEvents(blockExec.logger, blockExec.eventBus, block, abciResponses)
  107. return state, nil
  108. }
  109. // Commit locks the mempool, runs the ABCI Commit message, and updates the
  110. // mempool.
  111. // It returns the result of calling abci.Commit (the AppHash), and an error.
  112. // The Mempool must be locked during commit and update because state is
  113. // typically reset on Commit and old txs must be replayed against committed
  114. // state before new txs are run in the mempool, lest they be invalid.
  115. func (blockExec *BlockExecutor) Commit(
  116. state State,
  117. block *types.Block,
  118. ) ([]byte, error) {
  119. blockExec.mempool.Lock()
  120. defer blockExec.mempool.Unlock()
  121. // while mempool is Locked, flush to ensure all async requests have completed
  122. // in the ABCI app before Commit.
  123. err := blockExec.mempool.FlushAppConn()
  124. if err != nil {
  125. blockExec.logger.Error("Client error during mempool.FlushAppConn", "err", err)
  126. return nil, err
  127. }
  128. // Commit block, get hash back
  129. res, err := blockExec.proxyApp.CommitSync()
  130. if err != nil {
  131. blockExec.logger.Error(
  132. "Client error during proxyAppConn.CommitSync",
  133. "err", err,
  134. )
  135. return nil, err
  136. }
  137. // ResponseCommit has no error code - just data
  138. blockExec.logger.Info(
  139. "Committed state",
  140. "height", block.Height,
  141. "txs", block.NumTxs,
  142. "appHash", fmt.Sprintf("%X", res.Data),
  143. )
  144. // Update mempool.
  145. err = blockExec.mempool.Update(
  146. block.Height,
  147. block.Txs,
  148. mempool.PreCheckAminoMaxBytes(
  149. types.MaxDataBytesUnknownEvidence(
  150. state.ConsensusParams.BlockSize.MaxBytes,
  151. state.Validators.Size(),
  152. ),
  153. ),
  154. mempool.PostCheckMaxGas(state.ConsensusParams.BlockSize.MaxGas),
  155. )
  156. return res.Data, err
  157. }
  158. //---------------------------------------------------------
  159. // Helper functions for executing blocks and updating state
  160. // Executes block's transactions on proxyAppConn.
  161. // Returns a list of transaction results and updates to the validator set
  162. func execBlockOnProxyApp(
  163. logger log.Logger,
  164. proxyAppConn proxy.AppConnConsensus,
  165. block *types.Block,
  166. lastValSet *types.ValidatorSet,
  167. stateDB dbm.DB,
  168. ) (*ABCIResponses, error) {
  169. var validTxs, invalidTxs = 0, 0
  170. txIndex := 0
  171. abciResponses := NewABCIResponses(block)
  172. // Execute transactions and get hash.
  173. proxyCb := func(req *abci.Request, res *abci.Response) {
  174. switch r := res.Value.(type) {
  175. case *abci.Response_DeliverTx:
  176. // TODO: make use of res.Log
  177. // TODO: make use of this info
  178. // Blocks may include invalid txs.
  179. txRes := r.DeliverTx
  180. if txRes.Code == abci.CodeTypeOK {
  181. validTxs++
  182. } else {
  183. logger.Debug("Invalid tx", "code", txRes.Code, "log", txRes.Log)
  184. invalidTxs++
  185. }
  186. abciResponses.DeliverTx[txIndex] = txRes
  187. txIndex++
  188. }
  189. }
  190. proxyAppConn.SetResponseCallback(proxyCb)
  191. commitInfo, byzVals := getBeginBlockValidatorInfo(block, lastValSet, stateDB)
  192. // Begin block.
  193. _, err := proxyAppConn.BeginBlockSync(abci.RequestBeginBlock{
  194. Hash: block.Hash(),
  195. Header: types.TM2PB.Header(&block.Header),
  196. LastCommitInfo: commitInfo,
  197. ByzantineValidators: byzVals,
  198. })
  199. if err != nil {
  200. logger.Error("Error in proxyAppConn.BeginBlock", "err", err)
  201. return nil, err
  202. }
  203. // Run txs of block.
  204. for _, tx := range block.Txs {
  205. proxyAppConn.DeliverTxAsync(tx)
  206. if err := proxyAppConn.Error(); err != nil {
  207. return nil, err
  208. }
  209. }
  210. // End block.
  211. abciResponses.EndBlock, err = proxyAppConn.EndBlockSync(abci.RequestEndBlock{Height: block.Height})
  212. if err != nil {
  213. logger.Error("Error in proxyAppConn.EndBlock", "err", err)
  214. return nil, err
  215. }
  216. logger.Info("Executed block", "height", block.Height, "validTxs", validTxs, "invalidTxs", invalidTxs)
  217. valUpdates := abciResponses.EndBlock.ValidatorUpdates
  218. if len(valUpdates) > 0 {
  219. // TODO: cleanup the formatting
  220. logger.Info("Updates to validators", "updates", valUpdates)
  221. }
  222. return abciResponses, nil
  223. }
  224. func getBeginBlockValidatorInfo(block *types.Block, lastValSet *types.ValidatorSet, stateDB dbm.DB) (abci.LastCommitInfo, []abci.Evidence) {
  225. // Sanity check that commit length matches validator set size -
  226. // only applies after first block
  227. if block.Height > 1 {
  228. precommitLen := len(block.LastCommit.Precommits)
  229. valSetLen := len(lastValSet.Validators)
  230. if precommitLen != valSetLen {
  231. // sanity check
  232. panic(fmt.Sprintf("precommit length (%d) doesn't match valset length (%d) at height %d\n\n%v\n\n%v",
  233. precommitLen, valSetLen, block.Height, block.LastCommit.Precommits, lastValSet.Validators))
  234. }
  235. }
  236. // Collect the vote info (list of validators and whether or not they signed).
  237. voteInfos := make([]abci.VoteInfo, len(lastValSet.Validators))
  238. for i, val := range lastValSet.Validators {
  239. var vote *types.Vote
  240. if i < len(block.LastCommit.Precommits) {
  241. vote = block.LastCommit.Precommits[i]
  242. }
  243. voteInfo := abci.VoteInfo{
  244. Validator: types.TM2PB.Validator(val),
  245. SignedLastBlock: vote != nil,
  246. }
  247. voteInfos[i] = voteInfo
  248. }
  249. commitInfo := abci.LastCommitInfo{
  250. Round: int32(block.LastCommit.Round()),
  251. Votes: voteInfos,
  252. }
  253. byzVals := make([]abci.Evidence, len(block.Evidence.Evidence))
  254. for i, ev := range block.Evidence.Evidence {
  255. // We need the validator set. We already did this in validateBlock.
  256. // TODO: Should we instead cache the valset in the evidence itself and add
  257. // `SetValidatorSet()` and `ToABCI` methods ?
  258. valset, err := LoadValidators(stateDB, ev.Height())
  259. if err != nil {
  260. panic(err) // shouldn't happen
  261. }
  262. byzVals[i] = types.TM2PB.Evidence(ev, valset, block.Time)
  263. }
  264. return commitInfo, byzVals
  265. }
  266. // If more or equal than 1/3 of total voting power changed in one block, then
  267. // a light client could never prove the transition externally. See
  268. // ./lite/doc.go for details on how a light client tracks validators.
  269. func updateValidators(currentSet *types.ValidatorSet, abciUpdates []abci.ValidatorUpdate) error {
  270. updates, err := types.PB2TM.ValidatorUpdates(abciUpdates)
  271. if err != nil {
  272. return err
  273. }
  274. // these are tendermint types now
  275. for _, valUpdate := range updates {
  276. if valUpdate.VotingPower < 0 {
  277. return fmt.Errorf("Voting power can't be negative %v", valUpdate)
  278. }
  279. address := valUpdate.Address
  280. _, val := currentSet.GetByAddress(address)
  281. if valUpdate.VotingPower == 0 {
  282. // remove val
  283. _, removed := currentSet.Remove(address)
  284. if !removed {
  285. return fmt.Errorf("Failed to remove validator %X", address)
  286. }
  287. } else if val == nil {
  288. // add val
  289. added := currentSet.Add(valUpdate)
  290. if !added {
  291. return fmt.Errorf("Failed to add new validator %v", valUpdate)
  292. }
  293. } else {
  294. // update val
  295. updated := currentSet.Update(valUpdate)
  296. if !updated {
  297. return fmt.Errorf("Failed to update validator %X to %v", address, valUpdate)
  298. }
  299. }
  300. }
  301. return nil
  302. }
  303. // updateState returns a new State updated according to the header and responses.
  304. func updateState(
  305. state State,
  306. blockID types.BlockID,
  307. header *types.Header,
  308. abciResponses *ABCIResponses,
  309. ) (State, error) {
  310. // Copy the valset so we can apply changes from EndBlock
  311. // and update s.LastValidators and s.Validators.
  312. nValSet := state.NextValidators.Copy()
  313. // Update the validator set with the latest abciResponses.
  314. lastHeightValsChanged := state.LastHeightValidatorsChanged
  315. if len(abciResponses.EndBlock.ValidatorUpdates) > 0 {
  316. err := updateValidators(nValSet, abciResponses.EndBlock.ValidatorUpdates)
  317. if err != nil {
  318. return state, fmt.Errorf("Error changing validator set: %v", err)
  319. }
  320. // Change results from this height but only applies to the next next height.
  321. lastHeightValsChanged = header.Height + 1 + 1
  322. }
  323. // Update validator accums and set state variables.
  324. nValSet.IncrementAccum(1)
  325. // Update the params with the latest abciResponses.
  326. nextParams := state.ConsensusParams
  327. lastHeightParamsChanged := state.LastHeightConsensusParamsChanged
  328. if abciResponses.EndBlock.ConsensusParamUpdates != nil {
  329. // NOTE: must not mutate s.ConsensusParams
  330. nextParams = state.ConsensusParams.Update(abciResponses.EndBlock.ConsensusParamUpdates)
  331. err := nextParams.Validate()
  332. if err != nil {
  333. return state, fmt.Errorf("Error updating consensus params: %v", err)
  334. }
  335. // Change results from this height but only applies to the next height.
  336. lastHeightParamsChanged = header.Height + 1
  337. }
  338. // TODO: allow app to upgrade version
  339. nextVersion := state.Version
  340. // NOTE: the AppHash has not been populated.
  341. // It will be filled on state.Save.
  342. return State{
  343. Version: nextVersion,
  344. ChainID: state.ChainID,
  345. LastBlockHeight: header.Height,
  346. LastBlockTotalTx: state.LastBlockTotalTx + header.NumTxs,
  347. LastBlockID: blockID,
  348. LastBlockTime: header.Time,
  349. NextValidators: nValSet,
  350. Validators: state.NextValidators.Copy(),
  351. LastValidators: state.Validators.Copy(),
  352. LastHeightValidatorsChanged: lastHeightValsChanged,
  353. ConsensusParams: nextParams,
  354. LastHeightConsensusParamsChanged: lastHeightParamsChanged,
  355. LastResultsHash: abciResponses.ResultsHash(),
  356. AppHash: nil,
  357. }, nil
  358. }
  359. // Fire NewBlock, NewBlockHeader.
  360. // Fire TxEvent for every tx.
  361. // NOTE: if Tendermint crashes before commit, some or all of these events may be published again.
  362. func fireEvents(logger log.Logger, eventBus types.BlockEventPublisher, block *types.Block, abciResponses *ABCIResponses) {
  363. eventBus.PublishEventNewBlock(types.EventDataNewBlock{block})
  364. eventBus.PublishEventNewBlockHeader(types.EventDataNewBlockHeader{block.Header})
  365. for i, tx := range block.Data.Txs {
  366. eventBus.PublishEventTx(types.EventDataTx{types.TxResult{
  367. Height: block.Height,
  368. Index: uint32(i),
  369. Tx: tx,
  370. Result: *(abciResponses.DeliverTx[i]),
  371. }})
  372. }
  373. abciValUpdates := abciResponses.EndBlock.ValidatorUpdates
  374. if len(abciValUpdates) > 0 {
  375. // if there were an error, we would've stopped in updateValidators
  376. updates, _ := types.PB2TM.ValidatorUpdates(abciValUpdates)
  377. eventBus.PublishEventValidatorSetUpdates(
  378. types.EventDataValidatorSetUpdates{ValidatorUpdates: updates})
  379. }
  380. }
  381. //----------------------------------------------------------------------------------------------------
  382. // Execute block without state. TODO: eliminate
  383. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  384. // It returns the application root hash (result of abci.Commit).
  385. func ExecCommitBlock(
  386. appConnConsensus proxy.AppConnConsensus,
  387. block *types.Block,
  388. logger log.Logger,
  389. lastValSet *types.ValidatorSet,
  390. stateDB dbm.DB,
  391. ) ([]byte, error) {
  392. _, err := execBlockOnProxyApp(logger, appConnConsensus, block, lastValSet, stateDB)
  393. if err != nil {
  394. logger.Error("Error executing block on proxy app", "height", block.Height, "err", err)
  395. return nil, err
  396. }
  397. // Commit block, get hash back
  398. res, err := appConnConsensus.CommitSync()
  399. if err != nil {
  400. logger.Error("Client error during proxyAppConn.CommitSync", "err", res)
  401. return nil, err
  402. }
  403. // ResponseCommit has no error or log, just data
  404. return res.Data, nil
  405. }