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.

379 lines
13 KiB

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
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. "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 types.Mempool
  26. evpool types.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 types.Mempool, evpool types.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(s State, block *types.Block) error {
  52. return validateBlock(blockExec.db, s, 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(s State, blockID types.BlockID, block *types.Block) (State, error) {
  60. if err := blockExec.ValidateBlock(s, block); err != nil {
  61. return s, ErrInvalidBlock(err)
  62. }
  63. abciResponses, err := execBlockOnProxyApp(blockExec.logger, blockExec.proxyApp, block)
  64. if err != nil {
  65. return s, 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. s, err = updateState(s, blockID, block.Header, abciResponses)
  73. if err != nil {
  74. return s, fmt.Errorf("Commit failed for application: %v", err)
  75. }
  76. // lock mempool, commit state, update mempoool
  77. appHash, err := blockExec.Commit(block)
  78. if err != nil {
  79. return s, fmt.Errorf("Commit failed for application: %v", err)
  80. }
  81. fail.Fail() // XXX
  82. // update the app hash and save the state
  83. s.AppHash = appHash
  84. SaveState(blockExec.db, s)
  85. fail.Fail() // XXX
  86. // Update evpool now that state is saved
  87. // TODO: handle the crash/recover scenario
  88. // ie. (may need to call Update for last block)
  89. blockExec.evpool.Update(block)
  90. // events are fired after everything else
  91. // NOTE: if we crash between Commit and Save, events wont be fired during replay
  92. fireEvents(blockExec.logger, blockExec.eventBus, block, abciResponses)
  93. return s, nil
  94. }
  95. // Commit locks the mempool, runs the ABCI Commit message, and updates the mempool.
  96. // It returns the result of calling abci.Commit (the AppHash), and an error.
  97. // The Mempool must be locked during commit and update because state is typically reset on Commit and old txs must be replayed
  98. // against committed state before new txs are run in the mempool, lest they be invalid.
  99. func (blockExec *BlockExecutor) Commit(block *types.Block) ([]byte, error) {
  100. blockExec.mempool.Lock()
  101. defer blockExec.mempool.Unlock()
  102. // while mempool is Locked, flush to ensure all async requests have completed
  103. // in the ABCI app before Commit.
  104. err := blockExec.mempool.FlushAppConn()
  105. if err != nil {
  106. blockExec.logger.Error("Client error during mempool.FlushAppConn", "err", err)
  107. return nil, err
  108. }
  109. // Commit block, get hash back
  110. res, err := blockExec.proxyApp.CommitSync()
  111. if err != nil {
  112. blockExec.logger.Error("Client error during proxyAppConn.CommitSync", "err", err)
  113. return nil, err
  114. }
  115. // ResponseCommit has no error code - just data
  116. blockExec.logger.Info("Committed state", "height", block.Height, "txs", block.NumTxs, "appHash", 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, block *types.Block) (*ABCIResponses, error) {
  128. var validTxs, invalidTxs = 0, 0
  129. txIndex := 0
  130. abciResponses := NewABCIResponses(block)
  131. // Execute transactions and get hash
  132. proxyCb := func(req *abci.Request, res *abci.Response) {
  133. switch r := res.Value.(type) {
  134. case *abci.Response_DeliverTx:
  135. // TODO: make use of res.Log
  136. // TODO: make use of this info
  137. // Blocks may include invalid txs.
  138. txRes := r.DeliverTx
  139. if txRes.Code == abci.CodeTypeOK {
  140. validTxs++
  141. } else {
  142. logger.Debug("Invalid tx", "code", txRes.Code, "log", txRes.Log)
  143. invalidTxs++
  144. }
  145. abciResponses.DeliverTx[txIndex] = txRes
  146. txIndex++
  147. }
  148. }
  149. proxyAppConn.SetResponseCallback(proxyCb)
  150. // determine which validators did not sign last block
  151. absentVals := make([]int32, 0)
  152. for valI, vote := range block.LastCommit.Precommits {
  153. if vote == nil {
  154. absentVals = append(absentVals, int32(valI))
  155. }
  156. }
  157. // TODO: determine which validators were byzantine
  158. byzantineVals := make([]abci.Evidence, len(block.Evidence.Evidence))
  159. for i, ev := range block.Evidence.Evidence {
  160. byzantineVals[i] = abci.Evidence{
  161. PubKey: ev.Address(), // XXX
  162. Height: ev.Height(),
  163. }
  164. }
  165. // Begin block
  166. _, err := proxyAppConn.BeginBlockSync(abci.RequestBeginBlock{
  167. Hash: block.Hash(),
  168. Header: types.TM2PB.Header(block.Header),
  169. AbsentValidators: absentVals,
  170. ByzantineValidators: byzantineVals,
  171. })
  172. if err != nil {
  173. logger.Error("Error in proxyAppConn.BeginBlock", "err", err)
  174. return nil, err
  175. }
  176. // Run txs of block
  177. for _, tx := range block.Txs {
  178. proxyAppConn.DeliverTxAsync(tx)
  179. if err := proxyAppConn.Error(); err != nil {
  180. return nil, err
  181. }
  182. }
  183. // End block
  184. abciResponses.EndBlock, err = proxyAppConn.EndBlockSync(abci.RequestEndBlock{block.Height})
  185. if err != nil {
  186. logger.Error("Error in proxyAppConn.EndBlock", "err", err)
  187. return nil, err
  188. }
  189. logger.Info("Executed block", "height", block.Height, "validTxs", validTxs, "invalidTxs", invalidTxs)
  190. valUpdates := abciResponses.EndBlock.ValidatorUpdates
  191. if len(valUpdates) > 0 {
  192. logger.Info("Updates to validators", "updates", abci.ValidatorsString(valUpdates))
  193. }
  194. return abciResponses, nil
  195. }
  196. // If more or equal than 1/3 of total voting power changed in one block, then
  197. // a light client could never prove the transition externally. See
  198. // ./lite/doc.go for details on how a light client tracks validators.
  199. func updateValidators(currentSet *types.ValidatorSet, updates []abci.Validator) error {
  200. for _, v := range updates {
  201. pubkey, err := crypto.PubKeyFromBytes(v.PubKey) // NOTE: expects go-wire encoded pubkey
  202. if err != nil {
  203. return err
  204. }
  205. address := pubkey.Address()
  206. power := int64(v.Power)
  207. // mind the overflow from int64
  208. if power < 0 {
  209. return fmt.Errorf("Power (%d) overflows int64", v.Power)
  210. }
  211. _, val := currentSet.GetByAddress(address)
  212. if val == nil {
  213. // add val
  214. added := currentSet.Add(types.NewValidator(pubkey, power))
  215. if !added {
  216. return fmt.Errorf("Failed to add new validator %X with voting power %d", address, power)
  217. }
  218. } else if v.Power == 0 {
  219. // remove val
  220. _, removed := currentSet.Remove(address)
  221. if !removed {
  222. return fmt.Errorf("Failed to remove validator %X", address)
  223. }
  224. } else {
  225. // update val
  226. val.VotingPower = power
  227. updated := currentSet.Update(val)
  228. if !updated {
  229. return fmt.Errorf("Failed to update validator %X with voting power %d", address, power)
  230. }
  231. }
  232. }
  233. return nil
  234. }
  235. // updateState returns a new State updated according to the header and responses.
  236. func updateState(s State, blockID types.BlockID, header *types.Header,
  237. abciResponses *ABCIResponses) (State, error) {
  238. // copy the valset so we can apply changes from EndBlock
  239. // and update s.LastValidators and s.Validators
  240. prevValSet := s.Validators.Copy()
  241. nextValSet := prevValSet.Copy()
  242. // update the validator set with the latest abciResponses
  243. lastHeightValsChanged := s.LastHeightValidatorsChanged
  244. if len(abciResponses.EndBlock.ValidatorUpdates) > 0 {
  245. err := updateValidators(nextValSet, abciResponses.EndBlock.ValidatorUpdates)
  246. if err != nil {
  247. return s, fmt.Errorf("Error changing validator set: %v", err)
  248. }
  249. // change results from this height but only applies to the next height
  250. lastHeightValsChanged = header.Height + 1
  251. }
  252. // Update validator accums and set state variables
  253. nextValSet.IncrementAccum(1)
  254. // update the params with the latest abciResponses
  255. nextParams := s.ConsensusParams
  256. lastHeightParamsChanged := s.LastHeightConsensusParamsChanged
  257. if abciResponses.EndBlock.ConsensusParamUpdates != nil {
  258. // NOTE: must not mutate s.ConsensusParams
  259. nextParams = s.ConsensusParams.Update(abciResponses.EndBlock.ConsensusParamUpdates)
  260. err := nextParams.Validate()
  261. if err != nil {
  262. return s, fmt.Errorf("Error updating consensus params: %v", err)
  263. }
  264. // change results from this height but only applies to the next height
  265. lastHeightParamsChanged = header.Height + 1
  266. }
  267. // NOTE: the AppHash has not been populated.
  268. // It will be filled on state.Save.
  269. return State{
  270. ChainID: s.ChainID,
  271. LastBlockHeight: header.Height,
  272. LastBlockTotalTx: s.LastBlockTotalTx + header.NumTxs,
  273. LastBlockID: blockID,
  274. LastBlockTime: header.Time,
  275. Validators: nextValSet,
  276. LastValidators: s.Validators.Copy(),
  277. LastHeightValidatorsChanged: lastHeightValsChanged,
  278. ConsensusParams: nextParams,
  279. LastHeightConsensusParamsChanged: lastHeightParamsChanged,
  280. LastResultsHash: abciResponses.ResultsHash(),
  281. AppHash: nil,
  282. }, nil
  283. }
  284. // Fire NewBlock, NewBlockHeader.
  285. // Fire TxEvent for every tx.
  286. // NOTE: if Tendermint crashes before commit, some or all of these events may be published again.
  287. func fireEvents(logger log.Logger, eventBus types.BlockEventPublisher, block *types.Block, abciResponses *ABCIResponses) {
  288. // NOTE: do we still need this buffer ?
  289. txEventBuffer := types.NewTxEventBuffer(eventBus, int(block.NumTxs))
  290. for i, tx := range block.Data.Txs {
  291. txEventBuffer.PublishEventTx(types.EventDataTx{types.TxResult{
  292. Height: block.Height,
  293. Index: uint32(i),
  294. Tx: tx,
  295. Result: *(abciResponses.DeliverTx[i]),
  296. }})
  297. }
  298. eventBus.PublishEventNewBlock(types.EventDataNewBlock{block})
  299. eventBus.PublishEventNewBlockHeader(types.EventDataNewBlockHeader{block.Header})
  300. err := txEventBuffer.Flush()
  301. if err != nil {
  302. logger.Error("Failed to flush event buffer", "err", err)
  303. }
  304. }
  305. //----------------------------------------------------------------------------------------------------
  306. // Execute block without state. TODO: eliminate
  307. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  308. // It returns the application root hash (result of abci.Commit).
  309. func ExecCommitBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block, logger log.Logger) ([]byte, error) {
  310. _, err := execBlockOnProxyApp(logger, appConnConsensus, block)
  311. if err != nil {
  312. logger.Error("Error executing block on proxy app", "height", block.Height, "err", err)
  313. return nil, err
  314. }
  315. // Commit block, get hash back
  316. res, err := appConnConsensus.CommitSync()
  317. if err != nil {
  318. logger.Error("Client error during proxyAppConn.CommitSync", "err", res)
  319. return nil, err
  320. }
  321. // ResponseCommit has no error or log, just data
  322. return res.Data, nil
  323. }