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.

512 lines
16 KiB

mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
7 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
8 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
8 years ago
8 years ago
8 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
8 years ago
7 years ago
8 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
8 years ago
  1. package state
  2. import (
  3. "fmt"
  4. "time"
  5. abci "github.com/tendermint/tendermint/abci/types"
  6. "github.com/tendermint/tendermint/libs/fail"
  7. "github.com/tendermint/tendermint/libs/log"
  8. mempl "github.com/tendermint/tendermint/mempool"
  9. "github.com/tendermint/tendermint/proxy"
  10. "github.com/tendermint/tendermint/types"
  11. dbm "github.com/tendermint/tm-db"
  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. // manage the mempool lock during commit
  26. // and update both with block results after commit.
  27. mempool mempl.Mempool
  28. evpool EvidencePool
  29. logger log.Logger
  30. metrics *Metrics
  31. }
  32. type BlockExecutorOption func(executor *BlockExecutor)
  33. func BlockExecutorWithMetrics(metrics *Metrics) BlockExecutorOption {
  34. return func(blockExec *BlockExecutor) {
  35. blockExec.metrics = metrics
  36. }
  37. }
  38. // NewBlockExecutor returns a new BlockExecutor with a NopEventBus.
  39. // Call SetEventBus to provide one.
  40. func NewBlockExecutor(
  41. db dbm.DB,
  42. logger log.Logger,
  43. proxyApp proxy.AppConnConsensus,
  44. mempool mempl.Mempool,
  45. evpool EvidencePool,
  46. options ...BlockExecutorOption,
  47. ) *BlockExecutor {
  48. res := &BlockExecutor{
  49. db: db,
  50. proxyApp: proxyApp,
  51. eventBus: types.NopEventBus{},
  52. mempool: mempool,
  53. evpool: evpool,
  54. logger: logger,
  55. metrics: NopMetrics(),
  56. }
  57. for _, option := range options {
  58. option(res)
  59. }
  60. return res
  61. }
  62. func (blockExec *BlockExecutor) DB() dbm.DB {
  63. return blockExec.db
  64. }
  65. // SetEventBus - sets the event bus for publishing block related events.
  66. // If not called, it defaults to types.NopEventBus.
  67. func (blockExec *BlockExecutor) SetEventBus(eventBus types.BlockEventPublisher) {
  68. blockExec.eventBus = eventBus
  69. }
  70. // CreateProposalBlock calls state.MakeBlock with evidence from the evpool
  71. // and txs from the mempool. The max bytes must be big enough to fit the commit.
  72. // Up to 1/10th of the block space is allcoated for maximum sized evidence.
  73. // The rest is given to txs, up to the max gas.
  74. func (blockExec *BlockExecutor) CreateProposalBlock(
  75. height int64,
  76. state State, commit *types.Commit,
  77. proposerAddr []byte,
  78. ) (*types.Block, *types.PartSet) {
  79. maxBytes := state.ConsensusParams.Block.MaxBytes
  80. maxGas := state.ConsensusParams.Block.MaxGas
  81. // Fetch a limited amount of valid evidence
  82. maxNumEvidence, _ := types.MaxEvidencePerBlock(maxBytes)
  83. evidence := blockExec.evpool.PendingEvidence(maxNumEvidence)
  84. // Fetch a limited amount of valid txs
  85. maxDataBytes := types.MaxDataBytes(maxBytes, state.Validators.Size(), len(evidence))
  86. txs := blockExec.mempool.ReapMaxBytesMaxGas(maxDataBytes, maxGas)
  87. return state.MakeBlock(height, txs, commit, evidence, proposerAddr)
  88. }
  89. // ValidateBlock validates the given block against the given state.
  90. // If the block is invalid, it returns an error.
  91. // Validation does not mutate state, but does require historical information from the stateDB,
  92. // ie. to verify evidence from a validator at an old height.
  93. func (blockExec *BlockExecutor) ValidateBlock(state State, block *types.Block) error {
  94. return validateBlock(blockExec.evpool, blockExec.db, state, block)
  95. }
  96. // ApplyBlock validates the block against the state, executes it against the app,
  97. // fires the relevant events, commits the app, and saves the new state and responses.
  98. // It's the only function that needs to be called
  99. // from outside this package to process and commit an entire block.
  100. // It takes a blockID to avoid recomputing the parts hash.
  101. func (blockExec *BlockExecutor) ApplyBlock(state State, blockID types.BlockID, block *types.Block) (State, error) {
  102. if err := blockExec.ValidateBlock(state, block); err != nil {
  103. return state, ErrInvalidBlock(err)
  104. }
  105. startTime := time.Now().UnixNano()
  106. abciResponses, err := execBlockOnProxyApp(blockExec.logger, blockExec.proxyApp, block, blockExec.db)
  107. endTime := time.Now().UnixNano()
  108. blockExec.metrics.BlockProcessingTime.Observe(float64(endTime-startTime) / 1000000)
  109. if err != nil {
  110. return state, ErrProxyAppConn(err)
  111. }
  112. fail.Fail() // XXX
  113. // Save the results before we commit.
  114. SaveABCIResponses(blockExec.db, block.Height, abciResponses)
  115. fail.Fail() // XXX
  116. // validate the validator updates and convert to tendermint types
  117. abciValUpdates := abciResponses.EndBlock.ValidatorUpdates
  118. err = validateValidatorUpdates(abciValUpdates, state.ConsensusParams.Validator)
  119. if err != nil {
  120. return state, fmt.Errorf("error in validator updates: %v", err)
  121. }
  122. validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciValUpdates)
  123. if err != nil {
  124. return state, err
  125. }
  126. if len(validatorUpdates) > 0 {
  127. blockExec.logger.Info("Updates to validators", "updates", types.ValidatorListString(validatorUpdates))
  128. }
  129. // Update the state with the block and responses.
  130. state, err = updateState(state, blockID, &block.Header, abciResponses, validatorUpdates)
  131. if err != nil {
  132. return state, fmt.Errorf("commit failed for application: %v", err)
  133. }
  134. // Lock mempool, commit app state, update mempoool.
  135. appHash, err := blockExec.Commit(state, block, abciResponses.DeliverTxs)
  136. if err != nil {
  137. return state, fmt.Errorf("commit failed for application: %v", err)
  138. }
  139. // Update evpool with the block and state.
  140. blockExec.evpool.Update(block, state)
  141. fail.Fail() // XXX
  142. // Update the app hash and save the state.
  143. state.AppHash = appHash
  144. SaveState(blockExec.db, state)
  145. fail.Fail() // XXX
  146. // Events are fired after everything else.
  147. // NOTE: if we crash between Commit and Save, events wont be fired during replay
  148. fireEvents(blockExec.logger, blockExec.eventBus, block, abciResponses, validatorUpdates)
  149. return state, nil
  150. }
  151. // Commit locks the mempool, runs the ABCI Commit message, and updates the
  152. // mempool.
  153. // It returns the result of calling abci.Commit (the AppHash), and an error.
  154. // The Mempool must be locked during commit and update because state is
  155. // typically reset on Commit and old txs must be replayed against committed
  156. // state before new txs are run in the mempool, lest they be invalid.
  157. func (blockExec *BlockExecutor) Commit(
  158. state State,
  159. block *types.Block,
  160. deliverTxResponses []*abci.ResponseDeliverTx,
  161. ) ([]byte, error) {
  162. blockExec.mempool.Lock()
  163. defer blockExec.mempool.Unlock()
  164. // while mempool is Locked, flush to ensure all async requests have completed
  165. // in the ABCI app before Commit.
  166. err := blockExec.mempool.FlushAppConn()
  167. if err != nil {
  168. blockExec.logger.Error("Client error during mempool.FlushAppConn", "err", err)
  169. return nil, err
  170. }
  171. // Commit block, get hash back
  172. res, err := blockExec.proxyApp.CommitSync()
  173. if err != nil {
  174. blockExec.logger.Error(
  175. "Client error during proxyAppConn.CommitSync",
  176. "err", err,
  177. )
  178. return nil, err
  179. }
  180. // ResponseCommit has no error code - just data
  181. blockExec.logger.Info(
  182. "Committed state",
  183. "height", block.Height,
  184. "txs", len(block.Txs),
  185. "appHash", fmt.Sprintf("%X", res.Data),
  186. )
  187. // Update mempool.
  188. err = blockExec.mempool.Update(
  189. block.Height,
  190. block.Txs,
  191. deliverTxResponses,
  192. TxPreCheck(state),
  193. TxPostCheck(state),
  194. )
  195. return res.Data, err
  196. }
  197. //---------------------------------------------------------
  198. // Helper functions for executing blocks and updating state
  199. // Executes block's transactions on proxyAppConn.
  200. // Returns a list of transaction results and updates to the validator set
  201. func execBlockOnProxyApp(
  202. logger log.Logger,
  203. proxyAppConn proxy.AppConnConsensus,
  204. block *types.Block,
  205. stateDB dbm.DB,
  206. ) (*ABCIResponses, error) {
  207. var validTxs, invalidTxs = 0, 0
  208. txIndex := 0
  209. abciResponses := NewABCIResponses(block)
  210. // Execute transactions and get hash.
  211. proxyCb := func(req *abci.Request, res *abci.Response) {
  212. if r, ok := res.Value.(*abci.Response_DeliverTx); ok {
  213. // TODO: make use of res.Log
  214. // TODO: make use of this info
  215. // Blocks may include invalid txs.
  216. txRes := r.DeliverTx
  217. if txRes.Code == abci.CodeTypeOK {
  218. validTxs++
  219. } else {
  220. logger.Debug("Invalid tx", "code", txRes.Code, "log", txRes.Log)
  221. invalidTxs++
  222. }
  223. abciResponses.DeliverTxs[txIndex] = txRes
  224. txIndex++
  225. }
  226. }
  227. proxyAppConn.SetResponseCallback(proxyCb)
  228. commitInfo, byzVals := getBeginBlockValidatorInfo(block, stateDB)
  229. // Begin block
  230. var err error
  231. abciResponses.BeginBlock, err = proxyAppConn.BeginBlockSync(abci.RequestBeginBlock{
  232. Hash: block.Hash(),
  233. Header: types.TM2PB.Header(&block.Header),
  234. LastCommitInfo: commitInfo,
  235. ByzantineValidators: byzVals,
  236. })
  237. if err != nil {
  238. logger.Error("Error in proxyAppConn.BeginBlock", "err", err)
  239. return nil, err
  240. }
  241. // Run txs of block.
  242. for _, tx := range block.Txs {
  243. proxyAppConn.DeliverTxAsync(abci.RequestDeliverTx{Tx: tx})
  244. if err := proxyAppConn.Error(); err != nil {
  245. return nil, err
  246. }
  247. }
  248. // End block.
  249. abciResponses.EndBlock, err = proxyAppConn.EndBlockSync(abci.RequestEndBlock{Height: block.Height})
  250. if err != nil {
  251. logger.Error("Error in proxyAppConn.EndBlock", "err", err)
  252. return nil, err
  253. }
  254. logger.Info("Executed block", "height", block.Height, "validTxs", validTxs, "invalidTxs", invalidTxs)
  255. return abciResponses, nil
  256. }
  257. func getBeginBlockValidatorInfo(block *types.Block, stateDB dbm.DB) (abci.LastCommitInfo, []abci.Evidence) {
  258. voteInfos := make([]abci.VoteInfo, block.LastCommit.Size())
  259. byzVals := make([]abci.Evidence, len(block.Evidence.Evidence))
  260. var lastValSet *types.ValidatorSet
  261. var err error
  262. if block.Height > 1 {
  263. lastValSet, err = LoadValidators(stateDB, block.Height-1)
  264. if err != nil {
  265. panic(err) // shouldn't happen
  266. }
  267. // Sanity check that commit length matches validator set size -
  268. // only applies after first block
  269. precommitLen := block.LastCommit.Size()
  270. valSetLen := len(lastValSet.Validators)
  271. if precommitLen != valSetLen {
  272. // sanity check
  273. panic(fmt.Sprintf("precommit length (%d) doesn't match valset length (%d) at height %d\n\n%v\n\n%v",
  274. precommitLen, valSetLen, block.Height, block.LastCommit.Precommits, lastValSet.Validators))
  275. }
  276. } else {
  277. lastValSet = types.NewValidatorSet(nil)
  278. }
  279. for i, val := range lastValSet.Validators {
  280. var vote *types.CommitSig
  281. if i < len(block.LastCommit.Precommits) {
  282. vote = block.LastCommit.Precommits[i]
  283. }
  284. voteInfo := abci.VoteInfo{
  285. Validator: types.TM2PB.Validator(val),
  286. SignedLastBlock: vote != nil,
  287. }
  288. voteInfos[i] = voteInfo
  289. }
  290. for i, ev := range block.Evidence.Evidence {
  291. // We need the validator set. We already did this in validateBlock.
  292. // TODO: Should we instead cache the valset in the evidence itself and add
  293. // `SetValidatorSet()` and `ToABCI` methods ?
  294. valset, err := LoadValidators(stateDB, ev.Height())
  295. if err != nil {
  296. panic(err) // shouldn't happen
  297. }
  298. byzVals[i] = types.TM2PB.Evidence(ev, valset, block.Time)
  299. }
  300. commitInfo := abci.LastCommitInfo{
  301. Round: int32(block.LastCommit.Round()),
  302. Votes: voteInfos,
  303. }
  304. return commitInfo, byzVals
  305. }
  306. func validateValidatorUpdates(abciUpdates []abci.ValidatorUpdate,
  307. params types.ValidatorParams) error {
  308. for _, valUpdate := range abciUpdates {
  309. if valUpdate.GetPower() < 0 {
  310. return fmt.Errorf("voting power can't be negative %v", valUpdate)
  311. } else if valUpdate.GetPower() == 0 {
  312. // continue, since this is deleting the validator, and thus there is no
  313. // pubkey to check
  314. continue
  315. }
  316. // Check if validator's pubkey matches an ABCI type in the consensus params
  317. thisKeyType := valUpdate.PubKey.Type
  318. if !params.IsValidPubkeyType(thisKeyType) {
  319. return fmt.Errorf("validator %v is using pubkey %s, which is unsupported for consensus",
  320. valUpdate, thisKeyType)
  321. }
  322. }
  323. return nil
  324. }
  325. // updateState returns a new State updated according to the header and responses.
  326. func updateState(
  327. state State,
  328. blockID types.BlockID,
  329. header *types.Header,
  330. abciResponses *ABCIResponses,
  331. validatorUpdates []*types.Validator,
  332. ) (State, error) {
  333. // Copy the valset so we can apply changes from EndBlock
  334. // and update s.LastValidators and s.Validators.
  335. nValSet := state.NextValidators.Copy()
  336. // Update the validator set with the latest abciResponses.
  337. lastHeightValsChanged := state.LastHeightValidatorsChanged
  338. if len(validatorUpdates) > 0 {
  339. err := nValSet.UpdateWithChangeSet(validatorUpdates)
  340. if err != nil {
  341. return state, fmt.Errorf("error changing validator set: %v", err)
  342. }
  343. // Change results from this height but only applies to the next next height.
  344. lastHeightValsChanged = header.Height + 1 + 1
  345. }
  346. // Update validator proposer priority and set state variables.
  347. nValSet.IncrementProposerPriority(1)
  348. // Update the params with the latest abciResponses.
  349. nextParams := state.ConsensusParams
  350. lastHeightParamsChanged := state.LastHeightConsensusParamsChanged
  351. if abciResponses.EndBlock.ConsensusParamUpdates != nil {
  352. // NOTE: must not mutate s.ConsensusParams
  353. nextParams = state.ConsensusParams.Update(abciResponses.EndBlock.ConsensusParamUpdates)
  354. err := nextParams.Validate()
  355. if err != nil {
  356. return state, fmt.Errorf("error updating consensus params: %v", err)
  357. }
  358. // Change results from this height but only applies to the next height.
  359. lastHeightParamsChanged = header.Height + 1
  360. }
  361. // TODO: allow app to upgrade version
  362. nextVersion := state.Version
  363. // NOTE: the AppHash has not been populated.
  364. // It will be filled on state.Save.
  365. return State{
  366. Version: nextVersion,
  367. ChainID: state.ChainID,
  368. LastBlockHeight: header.Height,
  369. LastBlockID: blockID,
  370. LastBlockTime: header.Time,
  371. NextValidators: nValSet,
  372. Validators: state.NextValidators.Copy(),
  373. LastValidators: state.Validators.Copy(),
  374. LastHeightValidatorsChanged: lastHeightValsChanged,
  375. ConsensusParams: nextParams,
  376. LastHeightConsensusParamsChanged: lastHeightParamsChanged,
  377. LastResultsHash: abciResponses.ResultsHash(),
  378. AppHash: nil,
  379. }, nil
  380. }
  381. // Fire NewBlock, NewBlockHeader.
  382. // Fire TxEvent for every tx.
  383. // NOTE: if Tendermint crashes before commit, some or all of these events may be published again.
  384. func fireEvents(
  385. logger log.Logger,
  386. eventBus types.BlockEventPublisher,
  387. block *types.Block,
  388. abciResponses *ABCIResponses,
  389. validatorUpdates []*types.Validator,
  390. ) {
  391. eventBus.PublishEventNewBlock(types.EventDataNewBlock{
  392. Block: block,
  393. ResultBeginBlock: *abciResponses.BeginBlock,
  394. ResultEndBlock: *abciResponses.EndBlock,
  395. })
  396. eventBus.PublishEventNewBlockHeader(types.EventDataNewBlockHeader{
  397. Header: block.Header,
  398. NumTxs: int64(len(block.Txs)),
  399. ResultBeginBlock: *abciResponses.BeginBlock,
  400. ResultEndBlock: *abciResponses.EndBlock,
  401. })
  402. for i, tx := range block.Data.Txs {
  403. eventBus.PublishEventTx(types.EventDataTx{TxResult: types.TxResult{
  404. Height: block.Height,
  405. Index: uint32(i),
  406. Tx: tx,
  407. Result: *(abciResponses.DeliverTxs[i]),
  408. }})
  409. }
  410. if len(validatorUpdates) > 0 {
  411. eventBus.PublishEventValidatorSetUpdates(
  412. types.EventDataValidatorSetUpdates{ValidatorUpdates: validatorUpdates})
  413. }
  414. }
  415. //----------------------------------------------------------------------------------------------------
  416. // Execute block without state. TODO: eliminate
  417. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  418. // It returns the application root hash (result of abci.Commit).
  419. func ExecCommitBlock(
  420. appConnConsensus proxy.AppConnConsensus,
  421. block *types.Block,
  422. logger log.Logger,
  423. stateDB dbm.DB,
  424. ) ([]byte, error) {
  425. _, err := execBlockOnProxyApp(logger, appConnConsensus, block, stateDB)
  426. if err != nil {
  427. logger.Error("Error executing block on proxy app", "height", block.Height, "err", err)
  428. return nil, err
  429. }
  430. // Commit block, get hash back
  431. res, err := appConnConsensus.CommitSync()
  432. if err != nil {
  433. logger.Error("Client error during proxyAppConn.CommitSync", "err", res)
  434. return nil, err
  435. }
  436. // ResponseCommit has no error or log, just data
  437. return res.Data, nil
  438. }