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.

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