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.

402 lines
14 KiB

7 years ago
6 years ago
8 years ago
8 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
8 years ago
8 years ago
6 years ago
6 years ago
8 years ago
6 years ago
7 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(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(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. if err := blockExec.mempool.Update(block.Height, block.Txs); err != nil {
  119. return nil, err
  120. }
  121. return res.Data, nil
  122. }
  123. //---------------------------------------------------------
  124. // Helper functions for executing blocks and updating state
  125. // Executes block's transactions on proxyAppConn.
  126. // Returns a list of transaction results and updates to the validator set
  127. func execBlockOnProxyApp(logger log.Logger, proxyAppConn proxy.AppConnConsensus,
  128. block *types.Block, lastValSet *types.ValidatorSet, stateDB dbm.DB) (*ABCIResponses, error) {
  129. var validTxs, invalidTxs = 0, 0
  130. txIndex := 0
  131. abciResponses := NewABCIResponses(block)
  132. // Execute transactions and get hash
  133. proxyCb := func(req *abci.Request, res *abci.Response) {
  134. switch r := res.Value.(type) {
  135. case *abci.Response_DeliverTx:
  136. // TODO: make use of res.Log
  137. // TODO: make use of this info
  138. // Blocks may include invalid txs.
  139. txRes := r.DeliverTx
  140. if txRes.Code == abci.CodeTypeOK {
  141. validTxs++
  142. } else {
  143. logger.Debug("Invalid tx", "code", txRes.Code, "log", txRes.Log)
  144. invalidTxs++
  145. }
  146. abciResponses.DeliverTx[txIndex] = txRes
  147. txIndex++
  148. }
  149. }
  150. proxyAppConn.SetResponseCallback(proxyCb)
  151. signVals, byzVals := getBeginBlockValidatorInfo(block, lastValSet, stateDB)
  152. // Begin block
  153. _, err := proxyAppConn.BeginBlockSync(abci.RequestBeginBlock{
  154. Hash: block.Hash(),
  155. Header: types.TM2PB.Header(block.Header),
  156. Validators: signVals,
  157. ByzantineValidators: byzVals,
  158. })
  159. if err != nil {
  160. logger.Error("Error in proxyAppConn.BeginBlock", "err", err)
  161. return nil, err
  162. }
  163. // Run txs of block
  164. for _, tx := range block.Txs {
  165. proxyAppConn.DeliverTxAsync(tx)
  166. if err := proxyAppConn.Error(); err != nil {
  167. return nil, err
  168. }
  169. }
  170. // End block
  171. abciResponses.EndBlock, err = proxyAppConn.EndBlockSync(abci.RequestEndBlock{block.Height})
  172. if err != nil {
  173. logger.Error("Error in proxyAppConn.EndBlock", "err", err)
  174. return nil, err
  175. }
  176. logger.Info("Executed block", "height", block.Height, "validTxs", validTxs, "invalidTxs", invalidTxs)
  177. valUpdates := abciResponses.EndBlock.ValidatorUpdates
  178. if len(valUpdates) > 0 {
  179. logger.Info("Updates to validators", "updates", abci.ValidatorsString(valUpdates))
  180. }
  181. return abciResponses, nil
  182. }
  183. func getBeginBlockValidatorInfo(block *types.Block, lastValSet *types.ValidatorSet, stateDB dbm.DB) ([]abci.SigningValidator, []abci.Evidence) {
  184. // Sanity check that commit length matches validator set size -
  185. // only applies after first block
  186. if block.Height > 1 {
  187. precommitLen := len(block.LastCommit.Precommits)
  188. valSetLen := len(lastValSet.Validators)
  189. if precommitLen != valSetLen {
  190. // sanity check
  191. panic(fmt.Sprintf("precommit length (%d) doesn't match valset length (%d) at height %d\n\n%v\n\n%v",
  192. precommitLen, valSetLen, block.Height, block.LastCommit.Precommits, lastValSet.Validators))
  193. }
  194. }
  195. // determine which validators did not sign last block.
  196. signVals := make([]abci.SigningValidator, len(lastValSet.Validators))
  197. for i, val := range lastValSet.Validators {
  198. var vote *types.Vote
  199. if i < len(block.LastCommit.Precommits) {
  200. vote = block.LastCommit.Precommits[i]
  201. }
  202. val := abci.SigningValidator{
  203. Validator: types.TM2PB.Validator(val),
  204. SignedLastBlock: vote != nil,
  205. }
  206. signVals[i] = val
  207. }
  208. byzVals := make([]abci.Evidence, len(block.Evidence.Evidence))
  209. for i, ev := range block.Evidence.Evidence {
  210. // We need the validator set. We already did this in validateBlock.
  211. // TODO: Should we instead cache the valset in the evidence itself and add
  212. // `SetValidatorSet()` and `ToABCI` methods ?
  213. valset, err := LoadValidators(stateDB, ev.Height())
  214. if err != nil {
  215. panic(err) // shouldn't happen
  216. }
  217. byzVals[i] = types.TM2PB.Evidence(ev, valset, block.Time)
  218. }
  219. return signVals, byzVals
  220. }
  221. // If more or equal than 1/3 of total voting power changed in one block, then
  222. // a light client could never prove the transition externally. See
  223. // ./lite/doc.go for details on how a light client tracks validators.
  224. func updateValidators(currentSet *types.ValidatorSet, abciUpdates []abci.Validator) error {
  225. updates, err := types.PB2TM.Validators(abciUpdates)
  226. if err != nil {
  227. return err
  228. }
  229. // these are tendermint types now
  230. for _, valUpdate := range updates {
  231. if valUpdate.VotingPower < 0 {
  232. return fmt.Errorf("Voting power can't be negative %v", valUpdate)
  233. }
  234. address := valUpdate.Address
  235. _, val := currentSet.GetByAddress(address)
  236. if valUpdate.VotingPower == 0 {
  237. // remove val
  238. _, removed := currentSet.Remove(address)
  239. if !removed {
  240. return fmt.Errorf("Failed to remove validator %X", address)
  241. }
  242. } else if val == nil {
  243. // add val
  244. added := currentSet.Add(valUpdate)
  245. if !added {
  246. return fmt.Errorf("Failed to add new validator %v", valUpdate)
  247. }
  248. } else {
  249. // update val
  250. updated := currentSet.Update(valUpdate)
  251. if !updated {
  252. return fmt.Errorf("Failed to update validator %X to %v", address, valUpdate)
  253. }
  254. }
  255. }
  256. return nil
  257. }
  258. // updateState returns a new State updated according to the header and responses.
  259. func updateState(state State, blockID types.BlockID, header *types.Header,
  260. abciResponses *ABCIResponses) (State, error) {
  261. // copy the valset so we can apply changes from EndBlock
  262. // and update s.LastValidators and s.Validators
  263. prevValSet := state.Validators.Copy()
  264. nextValSet := prevValSet.Copy()
  265. // update the validator set with the latest abciResponses
  266. lastHeightValsChanged := state.LastHeightValidatorsChanged
  267. if len(abciResponses.EndBlock.ValidatorUpdates) > 0 {
  268. err := updateValidators(nextValSet, abciResponses.EndBlock.ValidatorUpdates)
  269. if err != nil {
  270. return state, fmt.Errorf("Error changing validator set: %v", err)
  271. }
  272. // change results from this height but only applies to the next height
  273. lastHeightValsChanged = header.Height + 1
  274. }
  275. // Update validator accums and set state variables
  276. nextValSet.IncrementAccum(1)
  277. // update the params with the latest abciResponses
  278. nextParams := state.ConsensusParams
  279. lastHeightParamsChanged := state.LastHeightConsensusParamsChanged
  280. if abciResponses.EndBlock.ConsensusParamUpdates != nil {
  281. // NOTE: must not mutate s.ConsensusParams
  282. nextParams = state.ConsensusParams.Update(abciResponses.EndBlock.ConsensusParamUpdates)
  283. err := nextParams.Validate()
  284. if err != nil {
  285. return state, fmt.Errorf("Error updating consensus params: %v", err)
  286. }
  287. // change results from this height but only applies to the next height
  288. lastHeightParamsChanged = header.Height + 1
  289. }
  290. // NOTE: the AppHash has not been populated.
  291. // It will be filled on state.Save.
  292. return State{
  293. ChainID: state.ChainID,
  294. LastBlockHeight: header.Height,
  295. LastBlockTotalTx: state.LastBlockTotalTx + header.NumTxs,
  296. LastBlockID: blockID,
  297. LastBlockTime: header.Time,
  298. Validators: nextValSet,
  299. LastValidators: state.Validators.Copy(),
  300. LastHeightValidatorsChanged: lastHeightValsChanged,
  301. ConsensusParams: nextParams,
  302. LastHeightConsensusParamsChanged: lastHeightParamsChanged,
  303. LastResultsHash: abciResponses.ResultsHash(),
  304. AppHash: nil,
  305. }, nil
  306. }
  307. // Fire NewBlock, NewBlockHeader.
  308. // Fire TxEvent for every tx.
  309. // NOTE: if Tendermint crashes before commit, some or all of these events may be published again.
  310. func fireEvents(logger log.Logger, eventBus types.BlockEventPublisher, block *types.Block, abciResponses *ABCIResponses) {
  311. eventBus.PublishEventNewBlock(types.EventDataNewBlock{block})
  312. eventBus.PublishEventNewBlockHeader(types.EventDataNewBlockHeader{block.Header})
  313. for i, tx := range block.Data.Txs {
  314. eventBus.PublishEventTx(types.EventDataTx{types.TxResult{
  315. Height: block.Height,
  316. Index: uint32(i),
  317. Tx: tx,
  318. Result: *(abciResponses.DeliverTx[i]),
  319. }})
  320. }
  321. }
  322. //----------------------------------------------------------------------------------------------------
  323. // Execute block without state. TODO: eliminate
  324. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  325. // It returns the application root hash (result of abci.Commit).
  326. func ExecCommitBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block,
  327. logger log.Logger, lastValSet *types.ValidatorSet, stateDB dbm.DB) ([]byte, error) {
  328. _, err := execBlockOnProxyApp(logger, appConnConsensus, block, lastValSet, stateDB)
  329. if err != nil {
  330. logger.Error("Error executing block on proxy app", "height", block.Height, "err", err)
  331. return nil, err
  332. }
  333. // Commit block, get hash back
  334. res, err := appConnConsensus.CommitSync()
  335. if err != nil {
  336. logger.Error("Client error during proxyAppConn.CommitSync", "err", res)
  337. return nil, err
  338. }
  339. // ResponseCommit has no error or log, just data
  340. return res.Data, nil
  341. }