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.

629 lines
19 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
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
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
8 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
  1. package state
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "time"
  7. abci "github.com/tendermint/tendermint/abci/types"
  8. cryptoenc "github.com/tendermint/tendermint/crypto/encoding"
  9. "github.com/tendermint/tendermint/internal/libs/fail"
  10. mempl "github.com/tendermint/tendermint/internal/mempool"
  11. "github.com/tendermint/tendermint/libs/log"
  12. tmstate "github.com/tendermint/tendermint/proto/tendermint/state"
  13. "github.com/tendermint/tendermint/proxy"
  14. "github.com/tendermint/tendermint/types"
  15. )
  16. //-----------------------------------------------------------------------------
  17. // BlockExecutor handles block execution and state updates.
  18. // It exposes ApplyBlock(), which validates & executes the block, updates state w/ ABCI responses,
  19. // then commits and updates the mempool atomically, then saves state.
  20. // BlockExecutor provides the context and accessories for properly executing a block.
  21. type BlockExecutor struct {
  22. // save state, validators, consensus params, abci responses here
  23. store Store
  24. // use blockstore for the pruning functions.
  25. blockStore BlockStore
  26. // execute the app against this
  27. proxyApp proxy.AppConnConsensus
  28. // events
  29. eventBus types.BlockEventPublisher
  30. // manage the mempool lock during commit
  31. // and update both with block results after commit.
  32. mempool mempl.Mempool
  33. evpool EvidencePool
  34. logger log.Logger
  35. metrics *Metrics
  36. // cache the verification results over a single height
  37. cache map[string]struct{}
  38. }
  39. type BlockExecutorOption func(executor *BlockExecutor)
  40. func BlockExecutorWithMetrics(metrics *Metrics) BlockExecutorOption {
  41. return func(blockExec *BlockExecutor) {
  42. blockExec.metrics = metrics
  43. }
  44. }
  45. // NewBlockExecutor returns a new BlockExecutor with a NopEventBus.
  46. // Call SetEventBus to provide one.
  47. func NewBlockExecutor(
  48. stateStore Store,
  49. logger log.Logger,
  50. proxyApp proxy.AppConnConsensus,
  51. mempool mempl.Mempool,
  52. evpool EvidencePool,
  53. blockStore BlockStore,
  54. options ...BlockExecutorOption,
  55. ) *BlockExecutor {
  56. res := &BlockExecutor{
  57. store: stateStore,
  58. proxyApp: proxyApp,
  59. eventBus: types.NopEventBus{},
  60. mempool: mempool,
  61. evpool: evpool,
  62. logger: logger,
  63. metrics: NopMetrics(),
  64. cache: make(map[string]struct{}),
  65. blockStore: blockStore,
  66. }
  67. for _, option := range options {
  68. option(res)
  69. }
  70. return res
  71. }
  72. func (blockExec *BlockExecutor) Store() Store {
  73. return blockExec.store
  74. }
  75. // SetEventBus - sets the event bus for publishing block related events.
  76. // If not called, it defaults to types.NopEventBus.
  77. func (blockExec *BlockExecutor) SetEventBus(eventBus types.BlockEventPublisher) {
  78. blockExec.eventBus = eventBus
  79. }
  80. // CreateProposalBlock calls state.MakeBlock with evidence from the evpool
  81. // and txs from the mempool. The max bytes must be big enough to fit the commit.
  82. // Up to 1/10th of the block space is allcoated for maximum sized evidence.
  83. // The rest is given to txs, up to the max gas.
  84. func (blockExec *BlockExecutor) CreateProposalBlock(
  85. height int64,
  86. state State, commit *types.Commit,
  87. proposerAddr []byte,
  88. ) (*types.Block, *types.PartSet) {
  89. maxBytes := state.ConsensusParams.Block.MaxBytes
  90. maxGas := state.ConsensusParams.Block.MaxGas
  91. evidence, evSize := blockExec.evpool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes)
  92. // Fetch a limited amount of valid txs
  93. maxDataBytes := types.MaxDataBytes(maxBytes, evSize, state.Validators.Size())
  94. txs := blockExec.mempool.ReapMaxBytesMaxGas(maxDataBytes, maxGas)
  95. return state.MakeBlock(height, txs, commit, evidence, proposerAddr)
  96. }
  97. // ValidateBlock validates the given block against the given state.
  98. // If the block is invalid, it returns an error.
  99. // Validation does not mutate state, but does require historical information from the stateDB,
  100. // ie. to verify evidence from a validator at an old height.
  101. func (blockExec *BlockExecutor) ValidateBlock(state State, block *types.Block) error {
  102. hash := block.Hash()
  103. if _, ok := blockExec.cache[hash.String()]; ok {
  104. return nil
  105. }
  106. err := validateBlock(state, block)
  107. if err != nil {
  108. return err
  109. }
  110. err = blockExec.evpool.CheckEvidence(block.Evidence.Evidence)
  111. if err != nil {
  112. return err
  113. }
  114. blockExec.cache[hash.String()] = struct{}{}
  115. return nil
  116. }
  117. // ApplyBlock validates the block against the state, executes it against the app,
  118. // fires the relevant events, commits the app, and saves the new state and responses.
  119. // It returns the new state.
  120. // It's the only function that needs to be called
  121. // from outside this package to process and commit an entire block.
  122. // It takes a blockID to avoid recomputing the parts hash.
  123. func (blockExec *BlockExecutor) ApplyBlock(
  124. state State, blockID types.BlockID, block *types.Block,
  125. ) (State, error) {
  126. // validate the block if we haven't already
  127. if err := blockExec.ValidateBlock(state, block); err != nil {
  128. return state, ErrInvalidBlock(err)
  129. }
  130. startTime := time.Now().UnixNano()
  131. abciResponses, err := execBlockOnProxyApp(
  132. blockExec.logger, blockExec.proxyApp, block, blockExec.store, state.InitialHeight,
  133. )
  134. endTime := time.Now().UnixNano()
  135. blockExec.metrics.BlockProcessingTime.Observe(float64(endTime-startTime) / 1000000)
  136. if err != nil {
  137. return state, ErrProxyAppConn(err)
  138. }
  139. fail.Fail() // XXX
  140. // Save the results before we commit.
  141. if err := blockExec.store.SaveABCIResponses(block.Height, abciResponses); err != nil {
  142. return state, err
  143. }
  144. fail.Fail() // XXX
  145. // validate the validator updates and convert to tendermint types
  146. abciValUpdates := abciResponses.EndBlock.ValidatorUpdates
  147. err = validateValidatorUpdates(abciValUpdates, state.ConsensusParams.Validator)
  148. if err != nil {
  149. return state, fmt.Errorf("error in validator updates: %v", err)
  150. }
  151. validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciValUpdates)
  152. if err != nil {
  153. return state, err
  154. }
  155. if len(validatorUpdates) > 0 {
  156. blockExec.logger.Debug("updates to validators", "updates", types.ValidatorListString(validatorUpdates))
  157. }
  158. // Update the state with the block and responses.
  159. state, err = updateState(state, blockID, &block.Header, abciResponses, validatorUpdates)
  160. if err != nil {
  161. return state, fmt.Errorf("commit failed for application: %v", err)
  162. }
  163. // Lock mempool, commit app state, update mempoool.
  164. appHash, retainHeight, err := blockExec.Commit(state, block, abciResponses.DeliverTxs)
  165. if err != nil {
  166. return state, fmt.Errorf("commit failed for application: %v", err)
  167. }
  168. // Update evpool with the latest state.
  169. blockExec.evpool.Update(state, block.Evidence.Evidence)
  170. fail.Fail() // XXX
  171. // Update the app hash and save the state.
  172. state.AppHash = appHash
  173. if err := blockExec.store.Save(state); err != nil {
  174. return state, err
  175. }
  176. fail.Fail() // XXX
  177. // Prune old heights, if requested by ABCI app.
  178. if retainHeight > 0 {
  179. pruned, err := blockExec.pruneBlocks(retainHeight)
  180. if err != nil {
  181. blockExec.logger.Error("failed to prune blocks", "retain_height", retainHeight, "err", err)
  182. } else {
  183. blockExec.logger.Debug("pruned blocks", "pruned", pruned, "retain_height", retainHeight)
  184. }
  185. }
  186. // reset the verification cache
  187. blockExec.cache = make(map[string]struct{})
  188. // Events are fired after everything else.
  189. // NOTE: if we crash between Commit and Save, events wont be fired during replay
  190. fireEvents(blockExec.logger, blockExec.eventBus, block, blockID, abciResponses, validatorUpdates)
  191. return state, nil
  192. }
  193. // Commit locks the mempool, runs the ABCI Commit message, and updates the
  194. // mempool.
  195. // It returns the result of calling abci.Commit (the AppHash) and the height to retain (if any).
  196. // The Mempool must be locked during commit and update because state is
  197. // typically reset on Commit and old txs must be replayed against committed
  198. // state before new txs are run in the mempool, lest they be invalid.
  199. func (blockExec *BlockExecutor) Commit(
  200. state State,
  201. block *types.Block,
  202. deliverTxResponses []*abci.ResponseDeliverTx,
  203. ) ([]byte, int64, error) {
  204. blockExec.mempool.Lock()
  205. defer blockExec.mempool.Unlock()
  206. // while mempool is Locked, flush to ensure all async requests have completed
  207. // in the ABCI app before Commit.
  208. err := blockExec.mempool.FlushAppConn()
  209. if err != nil {
  210. blockExec.logger.Error("client error during mempool.FlushAppConn", "err", err)
  211. return nil, 0, err
  212. }
  213. // Commit block, get hash back
  214. res, err := blockExec.proxyApp.CommitSync(context.Background())
  215. if err != nil {
  216. blockExec.logger.Error("client error during proxyAppConn.CommitSync", "err", err)
  217. return nil, 0, err
  218. }
  219. // ResponseCommit has no error code - just data
  220. blockExec.logger.Info(
  221. "committed state",
  222. "height", block.Height,
  223. "num_txs", len(block.Txs),
  224. "app_hash", fmt.Sprintf("%X", res.Data),
  225. )
  226. // Update mempool.
  227. err = blockExec.mempool.Update(
  228. block.Height,
  229. block.Txs,
  230. deliverTxResponses,
  231. TxPreCheck(state),
  232. TxPostCheck(state),
  233. )
  234. return res.Data, res.RetainHeight, err
  235. }
  236. //---------------------------------------------------------
  237. // Helper functions for executing blocks and updating state
  238. // Executes block's transactions on proxyAppConn.
  239. // Returns a list of transaction results and updates to the validator set
  240. func execBlockOnProxyApp(
  241. logger log.Logger,
  242. proxyAppConn proxy.AppConnConsensus,
  243. block *types.Block,
  244. store Store,
  245. initialHeight int64,
  246. ) (*tmstate.ABCIResponses, error) {
  247. var validTxs, invalidTxs = 0, 0
  248. txIndex := 0
  249. abciResponses := new(tmstate.ABCIResponses)
  250. dtxs := make([]*abci.ResponseDeliverTx, len(block.Txs))
  251. abciResponses.DeliverTxs = dtxs
  252. // Execute transactions and get hash.
  253. proxyCb := func(req *abci.Request, res *abci.Response) {
  254. if r, ok := res.Value.(*abci.Response_DeliverTx); ok {
  255. // TODO: make use of res.Log
  256. // TODO: make use of this info
  257. // Blocks may include invalid txs.
  258. txRes := r.DeliverTx
  259. if txRes.Code == abci.CodeTypeOK {
  260. validTxs++
  261. } else {
  262. logger.Debug("invalid tx", "code", txRes.Code, "log", txRes.Log)
  263. invalidTxs++
  264. }
  265. abciResponses.DeliverTxs[txIndex] = txRes
  266. txIndex++
  267. }
  268. }
  269. proxyAppConn.SetResponseCallback(proxyCb)
  270. commitInfo := getBeginBlockValidatorInfo(block, store, initialHeight)
  271. byzVals := make([]abci.Evidence, 0)
  272. for _, evidence := range block.Evidence.Evidence {
  273. byzVals = append(byzVals, evidence.ABCI()...)
  274. }
  275. ctx := context.Background()
  276. // Begin block
  277. var err error
  278. pbh := block.Header.ToProto()
  279. if pbh == nil {
  280. return nil, errors.New("nil header")
  281. }
  282. abciResponses.BeginBlock, err = proxyAppConn.BeginBlockSync(
  283. ctx,
  284. abci.RequestBeginBlock{
  285. Hash: block.Hash(),
  286. Header: *pbh,
  287. LastCommitInfo: commitInfo,
  288. ByzantineValidators: byzVals,
  289. },
  290. )
  291. if err != nil {
  292. logger.Error("error in proxyAppConn.BeginBlock", "err", err)
  293. return nil, err
  294. }
  295. // run txs of block
  296. for _, tx := range block.Txs {
  297. _, err = proxyAppConn.DeliverTxAsync(ctx, abci.RequestDeliverTx{Tx: tx})
  298. if err != nil {
  299. return nil, err
  300. }
  301. }
  302. abciResponses.EndBlock, err = proxyAppConn.EndBlockSync(ctx, abci.RequestEndBlock{Height: block.Height})
  303. if err != nil {
  304. logger.Error("error in proxyAppConn.EndBlock", "err", err)
  305. return nil, err
  306. }
  307. logger.Info("executed block", "height", block.Height, "num_valid_txs", validTxs, "num_invalid_txs", invalidTxs)
  308. return abciResponses, nil
  309. }
  310. func getBeginBlockValidatorInfo(block *types.Block, store Store,
  311. initialHeight int64) abci.LastCommitInfo {
  312. voteInfos := make([]abci.VoteInfo, block.LastCommit.Size())
  313. // Initial block -> LastCommitInfo.Votes are empty.
  314. // Remember that the first LastCommit is intentionally empty, so it makes
  315. // sense for LastCommitInfo.Votes to also be empty.
  316. if block.Height > initialHeight {
  317. lastValSet, err := store.LoadValidators(block.Height - 1)
  318. if err != nil {
  319. panic(err)
  320. }
  321. // Sanity check that commit size matches validator set size - only applies
  322. // after first block.
  323. var (
  324. commitSize = block.LastCommit.Size()
  325. valSetLen = len(lastValSet.Validators)
  326. )
  327. if commitSize != valSetLen {
  328. panic(fmt.Sprintf(
  329. "commit size (%d) doesn't match valset length (%d) at height %d\n\n%v\n\n%v",
  330. commitSize, valSetLen, block.Height, block.LastCommit.Signatures, lastValSet.Validators,
  331. ))
  332. }
  333. for i, val := range lastValSet.Validators {
  334. commitSig := block.LastCommit.Signatures[i]
  335. voteInfos[i] = abci.VoteInfo{
  336. Validator: types.TM2PB.Validator(val),
  337. SignedLastBlock: !commitSig.Absent(),
  338. }
  339. }
  340. }
  341. return abci.LastCommitInfo{
  342. Round: block.LastCommit.Round,
  343. Votes: voteInfos,
  344. }
  345. }
  346. func validateValidatorUpdates(abciUpdates []abci.ValidatorUpdate,
  347. params types.ValidatorParams) error {
  348. for _, valUpdate := range abciUpdates {
  349. if valUpdate.GetPower() < 0 {
  350. return fmt.Errorf("voting power can't be negative %v", valUpdate)
  351. } else if valUpdate.GetPower() == 0 {
  352. // continue, since this is deleting the validator, and thus there is no
  353. // pubkey to check
  354. continue
  355. }
  356. // Check if validator's pubkey matches an ABCI type in the consensus params
  357. pk, err := cryptoenc.PubKeyFromProto(valUpdate.PubKey)
  358. if err != nil {
  359. return err
  360. }
  361. if !params.IsValidPubkeyType(pk.Type()) {
  362. return fmt.Errorf("validator %v is using pubkey %s, which is unsupported for consensus",
  363. valUpdate, pk.Type())
  364. }
  365. }
  366. return nil
  367. }
  368. // updateState returns a new State updated according to the header and responses.
  369. func updateState(
  370. state State,
  371. blockID types.BlockID,
  372. header *types.Header,
  373. abciResponses *tmstate.ABCIResponses,
  374. validatorUpdates []*types.Validator,
  375. ) (State, error) {
  376. // Copy the valset so we can apply changes from EndBlock
  377. // and update s.LastValidators and s.Validators.
  378. nValSet := state.NextValidators.Copy()
  379. // Update the validator set with the latest abciResponses.
  380. lastHeightValsChanged := state.LastHeightValidatorsChanged
  381. if len(validatorUpdates) > 0 {
  382. err := nValSet.UpdateWithChangeSet(validatorUpdates)
  383. if err != nil {
  384. return state, fmt.Errorf("error changing validator set: %v", err)
  385. }
  386. // Change results from this height but only applies to the next next height.
  387. lastHeightValsChanged = header.Height + 1 + 1
  388. }
  389. // Update validator proposer priority and set state variables.
  390. nValSet.IncrementProposerPriority(1)
  391. // Update the params with the latest abciResponses.
  392. nextParams := state.ConsensusParams
  393. lastHeightParamsChanged := state.LastHeightConsensusParamsChanged
  394. if abciResponses.EndBlock.ConsensusParamUpdates != nil {
  395. // NOTE: must not mutate s.ConsensusParams
  396. nextParams = state.ConsensusParams.UpdateConsensusParams(abciResponses.EndBlock.ConsensusParamUpdates)
  397. err := nextParams.ValidateConsensusParams()
  398. if err != nil {
  399. return state, fmt.Errorf("error updating consensus params: %v", err)
  400. }
  401. state.Version.Consensus.App = nextParams.Version.AppVersion
  402. // Change results from this height but only applies to the next height.
  403. lastHeightParamsChanged = header.Height + 1
  404. }
  405. nextVersion := state.Version
  406. // NOTE: the AppHash has not been populated.
  407. // It will be filled on state.Save.
  408. return State{
  409. Version: nextVersion,
  410. ChainID: state.ChainID,
  411. InitialHeight: state.InitialHeight,
  412. LastBlockHeight: header.Height,
  413. LastBlockID: blockID,
  414. LastBlockTime: header.Time,
  415. NextValidators: nValSet,
  416. Validators: state.NextValidators.Copy(),
  417. LastValidators: state.Validators.Copy(),
  418. LastHeightValidatorsChanged: lastHeightValsChanged,
  419. ConsensusParams: nextParams,
  420. LastHeightConsensusParamsChanged: lastHeightParamsChanged,
  421. LastResultsHash: ABCIResponsesResultsHash(abciResponses),
  422. AppHash: nil,
  423. }, nil
  424. }
  425. // Fire NewBlock, NewBlockHeader.
  426. // Fire TxEvent for every tx.
  427. // NOTE: if Tendermint crashes before commit, some or all of these events may be published again.
  428. func fireEvents(
  429. logger log.Logger,
  430. eventBus types.BlockEventPublisher,
  431. block *types.Block,
  432. blockID types.BlockID,
  433. abciResponses *tmstate.ABCIResponses,
  434. validatorUpdates []*types.Validator,
  435. ) {
  436. if err := eventBus.PublishEventNewBlock(types.EventDataNewBlock{
  437. Block: block,
  438. BlockID: blockID,
  439. ResultBeginBlock: *abciResponses.BeginBlock,
  440. ResultEndBlock: *abciResponses.EndBlock,
  441. }); err != nil {
  442. logger.Error("failed publishing new block", "err", err)
  443. }
  444. if err := eventBus.PublishEventNewBlockHeader(types.EventDataNewBlockHeader{
  445. Header: block.Header,
  446. NumTxs: int64(len(block.Txs)),
  447. ResultBeginBlock: *abciResponses.BeginBlock,
  448. ResultEndBlock: *abciResponses.EndBlock,
  449. }); err != nil {
  450. logger.Error("failed publishing new block header", "err", err)
  451. }
  452. if len(block.Evidence.Evidence) != 0 {
  453. for _, ev := range block.Evidence.Evidence {
  454. if err := eventBus.PublishEventNewEvidence(types.EventDataNewEvidence{
  455. Evidence: ev,
  456. Height: block.Height,
  457. }); err != nil {
  458. logger.Error("failed publishing new evidence", "err", err)
  459. }
  460. }
  461. }
  462. for i, tx := range block.Data.Txs {
  463. if err := eventBus.PublishEventTx(types.EventDataTx{TxResult: abci.TxResult{
  464. Height: block.Height,
  465. Index: uint32(i),
  466. Tx: tx,
  467. Result: *(abciResponses.DeliverTxs[i]),
  468. }}); err != nil {
  469. logger.Error("failed publishing event TX", "err", err)
  470. }
  471. }
  472. if len(validatorUpdates) > 0 {
  473. if err := eventBus.PublishEventValidatorSetUpdates(
  474. types.EventDataValidatorSetUpdates{ValidatorUpdates: validatorUpdates}); err != nil {
  475. logger.Error("failed publishing event", "err", err)
  476. }
  477. }
  478. }
  479. //----------------------------------------------------------------------------------------------------
  480. // Execute block without state. TODO: eliminate
  481. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  482. // It returns the application root hash (result of abci.Commit).
  483. func ExecCommitBlock(
  484. be *BlockExecutor,
  485. appConnConsensus proxy.AppConnConsensus,
  486. block *types.Block,
  487. logger log.Logger,
  488. store Store,
  489. initialHeight int64,
  490. s State,
  491. ) ([]byte, error) {
  492. abciResponses, err := execBlockOnProxyApp(logger, appConnConsensus, block, store, initialHeight)
  493. if err != nil {
  494. logger.Error("failed executing block on proxy app", "height", block.Height, "err", err)
  495. return nil, err
  496. }
  497. // the BlockExecutor condition is using for the final block replay process.
  498. if be != nil {
  499. abciValUpdates := abciResponses.EndBlock.ValidatorUpdates
  500. err = validateValidatorUpdates(abciValUpdates, s.ConsensusParams.Validator)
  501. if err != nil {
  502. logger.Error("err", err)
  503. return nil, err
  504. }
  505. validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciValUpdates)
  506. if err != nil {
  507. logger.Error("err", err)
  508. return nil, err
  509. }
  510. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(types.BlockPartSizeBytes).Header()}
  511. fireEvents(be.logger, be.eventBus, block, blockID, abciResponses, validatorUpdates)
  512. }
  513. // Commit block, get hash back
  514. res, err := appConnConsensus.CommitSync(context.Background())
  515. if err != nil {
  516. logger.Error("client error during proxyAppConn.CommitSync", "err", res)
  517. return nil, err
  518. }
  519. // ResponseCommit has no error or log, just data
  520. return res.Data, nil
  521. }
  522. func (blockExec *BlockExecutor) pruneBlocks(retainHeight int64) (uint64, error) {
  523. base := blockExec.blockStore.Base()
  524. if retainHeight <= base {
  525. return 0, nil
  526. }
  527. pruned, err := blockExec.blockStore.PruneBlocks(retainHeight)
  528. if err != nil {
  529. return 0, fmt.Errorf("failed to prune block store: %w", err)
  530. }
  531. err = blockExec.Store().PruneStates(retainHeight)
  532. if err != nil {
  533. return 0, fmt.Errorf("failed to prune state store: %w", err)
  534. }
  535. return pruned, nil
  536. }