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.

500 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. dbm "github.com/tendermint/tendermint/libs/db"
  7. "github.com/tendermint/tendermint/libs/fail"
  8. "github.com/tendermint/tendermint/libs/log"
  9. mempl "github.com/tendermint/tendermint/mempool"
  10. "github.com/tendermint/tendermint/proxy"
  11. "github.com/tendermint/tendermint/types"
  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. switch r := res.Value.(type) {
  206. case *abci.Response_DeliverTx:
  207. // TODO: make use of res.Log
  208. // TODO: make use of this info
  209. // Blocks may include invalid txs.
  210. txRes := r.DeliverTx
  211. if txRes.Code == abci.CodeTypeOK {
  212. validTxs++
  213. } else {
  214. logger.Debug("Invalid tx", "code", txRes.Code, "log", txRes.Log)
  215. invalidTxs++
  216. }
  217. abciResponses.DeliverTx[txIndex] = txRes
  218. txIndex++
  219. }
  220. }
  221. proxyAppConn.SetResponseCallback(proxyCb)
  222. commitInfo, byzVals := getBeginBlockValidatorInfo(block, stateDB)
  223. // Begin block
  224. var err error
  225. abciResponses.BeginBlock, err = proxyAppConn.BeginBlockSync(abci.RequestBeginBlock{
  226. Hash: block.Hash(),
  227. Header: types.TM2PB.Header(&block.Header),
  228. LastCommitInfo: commitInfo,
  229. ByzantineValidators: byzVals,
  230. })
  231. if err != nil {
  232. logger.Error("Error in proxyAppConn.BeginBlock", "err", err)
  233. return nil, err
  234. }
  235. // Run txs of block.
  236. for _, tx := range block.Txs {
  237. proxyAppConn.DeliverTxAsync(abci.RequestDeliverTx{Tx: tx})
  238. if err := proxyAppConn.Error(); err != nil {
  239. return nil, err
  240. }
  241. }
  242. // End block.
  243. abciResponses.EndBlock, err = proxyAppConn.EndBlockSync(abci.RequestEndBlock{Height: block.Height})
  244. if err != nil {
  245. logger.Error("Error in proxyAppConn.EndBlock", "err", err)
  246. return nil, err
  247. }
  248. logger.Info("Executed block", "height", block.Height, "validTxs", validTxs, "invalidTxs", invalidTxs)
  249. return abciResponses, nil
  250. }
  251. func getBeginBlockValidatorInfo(block *types.Block, stateDB dbm.DB) (abci.LastCommitInfo, []abci.Evidence) {
  252. voteInfos := make([]abci.VoteInfo, block.LastCommit.Size())
  253. byzVals := make([]abci.Evidence, len(block.Evidence.Evidence))
  254. var lastValSet *types.ValidatorSet
  255. var err error
  256. if block.Height > 1 {
  257. lastValSet, err = LoadValidators(stateDB, block.Height-1)
  258. if err != nil {
  259. panic(err) // shouldn't happen
  260. }
  261. // Sanity check that commit length matches validator set size -
  262. // only applies after first block
  263. precommitLen := block.LastCommit.Size()
  264. valSetLen := len(lastValSet.Validators)
  265. if precommitLen != valSetLen {
  266. // sanity check
  267. panic(fmt.Sprintf("precommit length (%d) doesn't match valset length (%d) at height %d\n\n%v\n\n%v",
  268. precommitLen, valSetLen, block.Height, block.LastCommit.Precommits, lastValSet.Validators))
  269. }
  270. } else {
  271. lastValSet = types.NewValidatorSet(nil)
  272. }
  273. for i, val := range lastValSet.Validators {
  274. var vote *types.CommitSig
  275. if i < len(block.LastCommit.Precommits) {
  276. vote = block.LastCommit.Precommits[i]
  277. }
  278. voteInfo := abci.VoteInfo{
  279. Validator: types.TM2PB.Validator(val),
  280. SignedLastBlock: vote != nil,
  281. }
  282. voteInfos[i] = voteInfo
  283. }
  284. for i, ev := range block.Evidence.Evidence {
  285. // We need the validator set. We already did this in validateBlock.
  286. // TODO: Should we instead cache the valset in the evidence itself and add
  287. // `SetValidatorSet()` and `ToABCI` methods ?
  288. valset, err := LoadValidators(stateDB, ev.Height())
  289. if err != nil {
  290. panic(err) // shouldn't happen
  291. }
  292. byzVals[i] = types.TM2PB.Evidence(ev, valset, block.Time)
  293. }
  294. commitInfo := abci.LastCommitInfo{
  295. Round: int32(block.LastCommit.Round()),
  296. Votes: voteInfos,
  297. }
  298. return commitInfo, byzVals
  299. }
  300. func validateValidatorUpdates(abciUpdates []abci.ValidatorUpdate,
  301. params types.ValidatorParams) error {
  302. for _, valUpdate := range abciUpdates {
  303. if valUpdate.GetPower() < 0 {
  304. return fmt.Errorf("Voting power can't be negative %v", valUpdate)
  305. } else if valUpdate.GetPower() == 0 {
  306. // continue, since this is deleting the validator, and thus there is no
  307. // pubkey to check
  308. continue
  309. }
  310. // Check if validator's pubkey matches an ABCI type in the consensus params
  311. thisKeyType := valUpdate.PubKey.Type
  312. if !params.IsValidPubkeyType(thisKeyType) {
  313. return fmt.Errorf("Validator %v is using pubkey %s, which is unsupported for consensus",
  314. valUpdate, thisKeyType)
  315. }
  316. }
  317. return nil
  318. }
  319. // updateState returns a new State updated according to the header and responses.
  320. func updateState(
  321. state State,
  322. blockID types.BlockID,
  323. header *types.Header,
  324. abciResponses *ABCIResponses,
  325. validatorUpdates []*types.Validator,
  326. ) (State, error) {
  327. // Copy the valset so we can apply changes from EndBlock
  328. // and update s.LastValidators and s.Validators.
  329. nValSet := state.NextValidators.Copy()
  330. // Update the validator set with the latest abciResponses.
  331. lastHeightValsChanged := state.LastHeightValidatorsChanged
  332. if len(validatorUpdates) > 0 {
  333. err := nValSet.UpdateWithChangeSet(validatorUpdates)
  334. if err != nil {
  335. return state, fmt.Errorf("Error changing validator set: %v", err)
  336. }
  337. // Change results from this height but only applies to the next next height.
  338. lastHeightValsChanged = header.Height + 1 + 1
  339. }
  340. // Update validator proposer priority and set state variables.
  341. nValSet.IncrementProposerPriority(1)
  342. // Update the params with the latest abciResponses.
  343. nextParams := state.ConsensusParams
  344. lastHeightParamsChanged := state.LastHeightConsensusParamsChanged
  345. if abciResponses.EndBlock.ConsensusParamUpdates != nil {
  346. // NOTE: must not mutate s.ConsensusParams
  347. nextParams = state.ConsensusParams.Update(abciResponses.EndBlock.ConsensusParamUpdates)
  348. err := nextParams.Validate()
  349. if err != nil {
  350. return state, fmt.Errorf("Error updating consensus params: %v", err)
  351. }
  352. // Change results from this height but only applies to the next height.
  353. lastHeightParamsChanged = header.Height + 1
  354. }
  355. // TODO: allow app to upgrade version
  356. nextVersion := state.Version
  357. // NOTE: the AppHash has not been populated.
  358. // It will be filled on state.Save.
  359. return State{
  360. Version: nextVersion,
  361. ChainID: state.ChainID,
  362. LastBlockHeight: header.Height,
  363. LastBlockTotalTx: state.LastBlockTotalTx + header.NumTxs,
  364. LastBlockID: blockID,
  365. LastBlockTime: header.Time,
  366. NextValidators: nValSet,
  367. Validators: state.NextValidators.Copy(),
  368. LastValidators: state.Validators.Copy(),
  369. LastHeightValidatorsChanged: lastHeightValsChanged,
  370. ConsensusParams: nextParams,
  371. LastHeightConsensusParamsChanged: lastHeightParamsChanged,
  372. LastResultsHash: abciResponses.ResultsHash(),
  373. AppHash: nil,
  374. }, nil
  375. }
  376. // Fire NewBlock, NewBlockHeader.
  377. // Fire TxEvent for every tx.
  378. // NOTE: if Tendermint crashes before commit, some or all of these events may be published again.
  379. func fireEvents(logger log.Logger, eventBus types.BlockEventPublisher, block *types.Block, abciResponses *ABCIResponses, validatorUpdates []*types.Validator) {
  380. eventBus.PublishEventNewBlock(types.EventDataNewBlock{
  381. Block: block,
  382. ResultBeginBlock: *abciResponses.BeginBlock,
  383. ResultEndBlock: *abciResponses.EndBlock,
  384. })
  385. eventBus.PublishEventNewBlockHeader(types.EventDataNewBlockHeader{
  386. Header: block.Header,
  387. ResultBeginBlock: *abciResponses.BeginBlock,
  388. ResultEndBlock: *abciResponses.EndBlock,
  389. })
  390. for i, tx := range block.Data.Txs {
  391. eventBus.PublishEventTx(types.EventDataTx{TxResult: types.TxResult{
  392. Height: block.Height,
  393. Index: uint32(i),
  394. Tx: tx,
  395. Result: *(abciResponses.DeliverTx[i]),
  396. }})
  397. }
  398. if len(validatorUpdates) > 0 {
  399. eventBus.PublishEventValidatorSetUpdates(
  400. types.EventDataValidatorSetUpdates{ValidatorUpdates: validatorUpdates})
  401. }
  402. }
  403. //----------------------------------------------------------------------------------------------------
  404. // Execute block without state. TODO: eliminate
  405. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  406. // It returns the application root hash (result of abci.Commit).
  407. func ExecCommitBlock(
  408. appConnConsensus proxy.AppConnConsensus,
  409. block *types.Block,
  410. logger log.Logger,
  411. stateDB dbm.DB,
  412. ) ([]byte, error) {
  413. _, err := execBlockOnProxyApp(logger, appConnConsensus, block, stateDB)
  414. if err != nil {
  415. logger.Error("Error executing block on proxy app", "height", block.Height, "err", err)
  416. return nil, err
  417. }
  418. // Commit block, get hash back
  419. res, err := appConnConsensus.CommitSync()
  420. if err != nil {
  421. logger.Error("Client error during proxyAppConn.CommitSync", "err", res)
  422. return nil, err
  423. }
  424. // ResponseCommit has no error or log, just data
  425. return res.Data, nil
  426. }