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.

421 lines
14 KiB

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