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.

374 lines
12 KiB

8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 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
7 years ago
7 years ago
8 years ago
8 years ago
  1. package state
  2. import (
  3. "fmt"
  4. fail "github.com/ebuchman/fail-test"
  5. abci "github.com/tendermint/abci/types"
  6. crypto "github.com/tendermint/go-crypto"
  7. "github.com/tendermint/tendermint/proxy"
  8. "github.com/tendermint/tendermint/types"
  9. dbm "github.com/tendermint/tmlibs/db"
  10. "github.com/tendermint/tmlibs/log"
  11. )
  12. //-----------------------------------------------------------------------------
  13. // BlockExecutor handles block execution and state updates.
  14. // It exposes ApplyBlock(), which validates & executes the block, updates state w/ ABCI responses,
  15. // then commits and updates the mempool atomically, then saves state.
  16. // BlockExecutor provides the context and accessories for properly executing a block.
  17. type BlockExecutor struct {
  18. // save state, validators, consensus params, abci responses here
  19. db dbm.DB
  20. // execute the app against this
  21. proxyApp proxy.AppConnConsensus
  22. // events
  23. eventBus types.BlockEventPublisher
  24. // update these with block results after commit
  25. mempool Mempool
  26. evpool EvidencePool
  27. logger log.Logger
  28. }
  29. // NewBlockExecutor returns a new BlockExecutor with a NopEventBus.
  30. // Call SetEventBus to provide one.
  31. func NewBlockExecutor(db dbm.DB, logger log.Logger, proxyApp proxy.AppConnConsensus,
  32. mempool Mempool, evpool EvidencePool) *BlockExecutor {
  33. return &BlockExecutor{
  34. db: db,
  35. proxyApp: proxyApp,
  36. eventBus: types.NopEventBus{},
  37. mempool: mempool,
  38. evpool: evpool,
  39. logger: logger,
  40. }
  41. }
  42. // SetEventBus - sets the event bus for publishing block related events.
  43. // If not called, it defaults to types.NopEventBus.
  44. func (blockExec *BlockExecutor) SetEventBus(eventBus types.BlockEventPublisher) {
  45. blockExec.eventBus = eventBus
  46. }
  47. // ValidateBlock validates the given block against the given state.
  48. // If the block is invalid, it returns an error.
  49. // Validation does not mutate state, but does require historical information from the stateDB,
  50. // ie. to verify evidence from a validator at an old height.
  51. func (blockExec *BlockExecutor) ValidateBlock(state State, block *types.Block) error {
  52. return validateBlock(blockExec.db, state, block)
  53. }
  54. // ApplyBlock validates the block against the state, executes it against the app,
  55. // fires the relevant events, commits the app, and saves the new state and responses.
  56. // It's the only function that needs to be called
  57. // from outside this package to process and commit an entire block.
  58. // It takes a blockID to avoid recomputing the parts hash.
  59. func (blockExec *BlockExecutor) ApplyBlock(state State, blockID types.BlockID, block *types.Block) (State, error) {
  60. if err := blockExec.ValidateBlock(state, block); err != nil {
  61. return state, ErrInvalidBlock(err)
  62. }
  63. abciResponses, err := execBlockOnProxyApp(blockExec.logger, blockExec.proxyApp, block)
  64. if err != nil {
  65. return state, ErrProxyAppConn(err)
  66. }
  67. fail.Fail() // XXX
  68. // save the results before we commit
  69. saveABCIResponses(blockExec.db, block.Height, abciResponses)
  70. fail.Fail() // XXX
  71. // update the state with the block and responses
  72. state, err = updateState(state, blockID, block.Header, abciResponses)
  73. if err != nil {
  74. return state, fmt.Errorf("Commit failed for application: %v", err)
  75. }
  76. // lock mempool, commit app state, update mempoool
  77. appHash, err := blockExec.Commit(block)
  78. if err != nil {
  79. return state, fmt.Errorf("Commit failed for application: %v", err)
  80. }
  81. // Update evpool with the block and state.
  82. blockExec.evpool.Update(block, state)
  83. fail.Fail() // XXX
  84. // update the app hash and save the state
  85. state.AppHash = appHash
  86. SaveState(blockExec.db, state)
  87. fail.Fail() // XXX
  88. // events are fired after everything else
  89. // NOTE: if we crash between Commit and Save, events wont be fired during replay
  90. fireEvents(blockExec.logger, blockExec.eventBus, block, abciResponses)
  91. return state, nil
  92. }
  93. // Commit locks the mempool, runs the ABCI Commit message, and updates the mempool.
  94. // It returns the result of calling abci.Commit (the AppHash), and an error.
  95. // The Mempool must be locked during commit and update because state is typically reset on Commit and old txs must be replayed
  96. // against committed state before new txs are run in the mempool, lest they be invalid.
  97. func (blockExec *BlockExecutor) Commit(block *types.Block) ([]byte, error) {
  98. blockExec.mempool.Lock()
  99. defer blockExec.mempool.Unlock()
  100. // while mempool is Locked, flush to ensure all async requests have completed
  101. // in the ABCI app before Commit.
  102. err := blockExec.mempool.FlushAppConn()
  103. if err != nil {
  104. blockExec.logger.Error("Client error during mempool.FlushAppConn", "err", err)
  105. return nil, err
  106. }
  107. // Commit block, get hash back
  108. res, err := blockExec.proxyApp.CommitSync()
  109. if err != nil {
  110. blockExec.logger.Error("Client error during proxyAppConn.CommitSync", "err", err)
  111. return nil, err
  112. }
  113. // ResponseCommit has no error code - just data
  114. blockExec.logger.Info("Committed state",
  115. "height", block.Height,
  116. "txs", block.NumTxs,
  117. "appHash", fmt.Sprintf("%X", res.Data))
  118. // Update mempool.
  119. if err := blockExec.mempool.Update(block.Height, block.Txs); err != nil {
  120. return nil, err
  121. }
  122. return res.Data, nil
  123. }
  124. //---------------------------------------------------------
  125. // Helper functions for executing blocks and updating state
  126. // Executes block's transactions on proxyAppConn.
  127. // Returns a list of transaction results and updates to the validator set
  128. func execBlockOnProxyApp(logger log.Logger, proxyAppConn proxy.AppConnConsensus, block *types.Block) (*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. // determine which validators did not sign last block
  152. absentVals := make([]int32, 0)
  153. for valI, vote := range block.LastCommit.Precommits {
  154. if vote == nil {
  155. absentVals = append(absentVals, int32(valI))
  156. }
  157. }
  158. // TODO: determine which validators were byzantine
  159. byzantineVals := make([]abci.Evidence, len(block.Evidence.Evidence))
  160. for i, ev := range block.Evidence.Evidence {
  161. byzantineVals[i] = abci.Evidence{
  162. PubKey: ev.Address(), // XXX
  163. Height: ev.Height(),
  164. }
  165. }
  166. // Begin block
  167. _, err := proxyAppConn.BeginBlockSync(abci.RequestBeginBlock{
  168. Hash: block.Hash(),
  169. Header: types.TM2PB.Header(block.Header),
  170. AbsentValidators: absentVals,
  171. ByzantineValidators: byzantineVals,
  172. })
  173. if err != nil {
  174. logger.Error("Error in proxyAppConn.BeginBlock", "err", err)
  175. return nil, err
  176. }
  177. // Run txs of block
  178. for _, tx := range block.Txs {
  179. proxyAppConn.DeliverTxAsync(tx)
  180. if err := proxyAppConn.Error(); err != nil {
  181. return nil, err
  182. }
  183. }
  184. // End block
  185. abciResponses.EndBlock, err = proxyAppConn.EndBlockSync(abci.RequestEndBlock{block.Height})
  186. if err != nil {
  187. logger.Error("Error in proxyAppConn.EndBlock", "err", err)
  188. return nil, err
  189. }
  190. logger.Info("Executed block", "height", block.Height, "validTxs", validTxs, "invalidTxs", invalidTxs)
  191. valUpdates := abciResponses.EndBlock.ValidatorUpdates
  192. if len(valUpdates) > 0 {
  193. logger.Info("Updates to validators", "updates", abci.ValidatorsString(valUpdates))
  194. }
  195. return abciResponses, nil
  196. }
  197. // If more or equal than 1/3 of total voting power changed in one block, then
  198. // a light client could never prove the transition externally. See
  199. // ./lite/doc.go for details on how a light client tracks validators.
  200. func updateValidators(currentSet *types.ValidatorSet, updates []abci.Validator) error {
  201. for _, v := range updates {
  202. pubkey, err := crypto.PubKeyFromBytes(v.PubKey) // NOTE: expects go-amino encoded pubkey
  203. if err != nil {
  204. return err
  205. }
  206. address := pubkey.Address()
  207. power := int64(v.Power)
  208. // mind the overflow from int64
  209. if power < 0 {
  210. return fmt.Errorf("Power (%d) overflows int64", v.Power)
  211. }
  212. _, val := currentSet.GetByAddress(address)
  213. if val == nil {
  214. // add val
  215. added := currentSet.Add(types.NewValidator(pubkey, power))
  216. if !added {
  217. return fmt.Errorf("Failed to add new validator %X with voting power %d", address, power)
  218. }
  219. } else if v.Power == 0 {
  220. // remove val
  221. _, removed := currentSet.Remove(address)
  222. if !removed {
  223. return fmt.Errorf("Failed to remove validator %X", address)
  224. }
  225. } else {
  226. // update val
  227. val.VotingPower = power
  228. updated := currentSet.Update(val)
  229. if !updated {
  230. return fmt.Errorf("Failed to update validator %X with voting power %d", address, power)
  231. }
  232. }
  233. }
  234. return nil
  235. }
  236. // updateState returns a new State updated according to the header and responses.
  237. func updateState(state State, blockID types.BlockID, header *types.Header,
  238. abciResponses *ABCIResponses) (State, error) {
  239. // copy the valset so we can apply changes from EndBlock
  240. // and update s.LastValidators and s.Validators
  241. prevValSet := state.Validators.Copy()
  242. nextValSet := prevValSet.Copy()
  243. // update the validator set with the latest abciResponses
  244. lastHeightValsChanged := state.LastHeightValidatorsChanged
  245. if len(abciResponses.EndBlock.ValidatorUpdates) > 0 {
  246. err := updateValidators(nextValSet, abciResponses.EndBlock.ValidatorUpdates)
  247. if err != nil {
  248. return state, fmt.Errorf("Error changing validator set: %v", err)
  249. }
  250. // change results from this height but only applies to the next height
  251. lastHeightValsChanged = header.Height + 1
  252. }
  253. // Update validator accums and set state variables
  254. nextValSet.IncrementAccum(1)
  255. // update the params with the latest abciResponses
  256. nextParams := state.ConsensusParams
  257. lastHeightParamsChanged := state.LastHeightConsensusParamsChanged
  258. if abciResponses.EndBlock.ConsensusParamUpdates != nil {
  259. // NOTE: must not mutate s.ConsensusParams
  260. nextParams = state.ConsensusParams.Update(abciResponses.EndBlock.ConsensusParamUpdates)
  261. err := nextParams.Validate()
  262. if err != nil {
  263. return state, fmt.Errorf("Error updating consensus params: %v", err)
  264. }
  265. // change results from this height but only applies to the next height
  266. lastHeightParamsChanged = header.Height + 1
  267. }
  268. // NOTE: the AppHash has not been populated.
  269. // It will be filled on state.Save.
  270. return State{
  271. ChainID: state.ChainID,
  272. LastBlockHeight: header.Height,
  273. LastBlockTotalTx: state.LastBlockTotalTx + header.NumTxs,
  274. LastBlockID: blockID,
  275. LastBlockTime: header.Time,
  276. Validators: nextValSet,
  277. LastValidators: state.Validators.Copy(),
  278. LastHeightValidatorsChanged: lastHeightValsChanged,
  279. ConsensusParams: nextParams,
  280. LastHeightConsensusParamsChanged: lastHeightParamsChanged,
  281. LastResultsHash: abciResponses.ResultsHash(),
  282. AppHash: nil,
  283. }, nil
  284. }
  285. // Fire NewBlock, NewBlockHeader.
  286. // Fire TxEvent for every tx.
  287. // NOTE: if Tendermint crashes before commit, some or all of these events may be published again.
  288. func fireEvents(logger log.Logger, eventBus types.BlockEventPublisher, block *types.Block, abciResponses *ABCIResponses) {
  289. eventBus.PublishEventNewBlock(types.EventDataNewBlock{block})
  290. eventBus.PublishEventNewBlockHeader(types.EventDataNewBlockHeader{block.Header})
  291. for i, tx := range block.Data.Txs {
  292. eventBus.PublishEventTx(types.EventDataTx{types.TxResult{
  293. Height: block.Height,
  294. Index: uint32(i),
  295. Tx: tx,
  296. Result: *(abciResponses.DeliverTx[i]),
  297. }})
  298. }
  299. }
  300. //----------------------------------------------------------------------------------------------------
  301. // Execute block without state. TODO: eliminate
  302. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  303. // It returns the application root hash (result of abci.Commit).
  304. func ExecCommitBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block, logger log.Logger) ([]byte, error) {
  305. _, err := execBlockOnProxyApp(logger, appConnConsensus, block)
  306. if err != nil {
  307. logger.Error("Error executing block on proxy app", "height", block.Height, "err", err)
  308. return nil, err
  309. }
  310. // Commit block, get hash back
  311. res, err := appConnConsensus.CommitSync()
  312. if err != nil {
  313. logger.Error("Client error during proxyAppConn.CommitSync", "err", res)
  314. return nil, err
  315. }
  316. // ResponseCommit has no error or log, just data
  317. return res.Data, nil
  318. }