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.

621 lines
19 KiB

cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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
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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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. "github.com/tendermint/tendermint/crypto/encoding"
  9. "github.com/tendermint/tendermint/internal/eventbus"
  10. "github.com/tendermint/tendermint/internal/mempool"
  11. "github.com/tendermint/tendermint/internal/proxy"
  12. "github.com/tendermint/tendermint/libs/log"
  13. tmstate "github.com/tendermint/tendermint/proto/tendermint/state"
  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 mempool.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. pool mempool.Mempool,
  52. evpool EvidencePool,
  53. blockStore BlockStore,
  54. options ...BlockExecutorOption,
  55. ) *BlockExecutor {
  56. res := &BlockExecutor{
  57. store: stateStore,
  58. proxyApp: proxyApp,
  59. eventBus: eventbus.NopEventBus{},
  60. mempool: pool,
  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, error) {
  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. ctx context.Context,
  125. state State,
  126. blockID types.BlockID,
  127. block *types.Block,
  128. ) (State, error) {
  129. // validate the block if we haven't already
  130. if err := blockExec.ValidateBlock(state, block); err != nil {
  131. return state, ErrInvalidBlock(err)
  132. }
  133. startTime := time.Now().UnixNano()
  134. abciResponses, err := execBlockOnProxyApp(ctx,
  135. blockExec.logger, blockExec.proxyApp, block, blockExec.store, state.InitialHeight,
  136. )
  137. endTime := time.Now().UnixNano()
  138. blockExec.metrics.BlockProcessingTime.Observe(float64(endTime-startTime) / 1000000)
  139. if err != nil {
  140. return state, ErrProxyAppConn(err)
  141. }
  142. // Save the results before we commit.
  143. if err := blockExec.store.SaveABCIResponses(block.Height, abciResponses); err != nil {
  144. return state, err
  145. }
  146. // validate the validator updates and convert to tendermint types
  147. abciValUpdates := abciResponses.EndBlock.ValidatorUpdates
  148. err = validateValidatorUpdates(abciValUpdates, state.ConsensusParams.Validator)
  149. if err != nil {
  150. return state, fmt.Errorf("error in validator updates: %w", err)
  151. }
  152. validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciValUpdates)
  153. if err != nil {
  154. return state, err
  155. }
  156. if len(validatorUpdates) > 0 {
  157. blockExec.logger.Debug("updates to validators", "updates", types.ValidatorListString(validatorUpdates))
  158. }
  159. // Update the state with the block and responses.
  160. state, err = updateState(state, blockID, &block.Header, abciResponses, validatorUpdates)
  161. if err != nil {
  162. return state, fmt.Errorf("commit failed for application: %w", err)
  163. }
  164. // Lock mempool, commit app state, update mempoool.
  165. appHash, retainHeight, err := blockExec.Commit(ctx, state, block, abciResponses.DeliverTxs)
  166. if err != nil {
  167. return state, fmt.Errorf("commit failed for application: %w", err)
  168. }
  169. // Update evpool with the latest state.
  170. blockExec.evpool.Update(state, block.Evidence.Evidence)
  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. // Prune old heights, if requested by ABCI app.
  177. if retainHeight > 0 {
  178. pruned, err := blockExec.pruneBlocks(retainHeight)
  179. if err != nil {
  180. blockExec.logger.Error("failed to prune blocks", "retain_height", retainHeight, "err", err)
  181. } else {
  182. blockExec.logger.Debug("pruned blocks", "pruned", pruned, "retain_height", retainHeight)
  183. }
  184. }
  185. // reset the verification cache
  186. blockExec.cache = make(map[string]struct{})
  187. // Events are fired after everything else.
  188. // NOTE: if we crash between Commit and Save, events wont be fired during replay
  189. fireEvents(ctx, blockExec.logger, blockExec.eventBus, block, blockID, abciResponses, validatorUpdates)
  190. return state, nil
  191. }
  192. // Commit locks the mempool, runs the ABCI Commit message, and updates the
  193. // mempool.
  194. // It returns the result of calling abci.Commit (the AppHash) and the height to retain (if any).
  195. // The Mempool must be locked during commit and update because state is
  196. // typically reset on Commit and old txs must be replayed against committed
  197. // state before new txs are run in the mempool, lest they be invalid.
  198. func (blockExec *BlockExecutor) Commit(
  199. ctx context.Context,
  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(ctx)
  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.Commit(ctx)
  215. if err != nil {
  216. blockExec.logger.Error("client error during proxyAppConn.Commit", "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. ctx,
  229. block.Height,
  230. block.Txs,
  231. deliverTxResponses,
  232. TxPreCheck(state),
  233. TxPostCheck(state),
  234. )
  235. return res.Data, res.RetainHeight, err
  236. }
  237. //---------------------------------------------------------
  238. // Helper functions for executing blocks and updating state
  239. // Executes block's transactions on proxyAppConn.
  240. // Returns a list of transaction results and updates to the validator set
  241. func execBlockOnProxyApp(
  242. ctx context.Context,
  243. logger log.Logger,
  244. proxyAppConn proxy.AppConnConsensus,
  245. block *types.Block,
  246. store Store,
  247. initialHeight int64,
  248. ) (*tmstate.ABCIResponses, error) {
  249. var validTxs, invalidTxs = 0, 0
  250. txIndex := 0
  251. abciResponses := new(tmstate.ABCIResponses)
  252. dtxs := make([]*abci.ResponseDeliverTx, len(block.Txs))
  253. abciResponses.DeliverTxs = dtxs
  254. commitInfo := getBeginBlockValidatorInfo(block, store, initialHeight)
  255. byzVals := make([]abci.Evidence, 0)
  256. for _, evidence := range block.Evidence.Evidence {
  257. byzVals = append(byzVals, evidence.ABCI()...)
  258. }
  259. // Begin block
  260. var err error
  261. pbh := block.Header.ToProto()
  262. if pbh == nil {
  263. return nil, errors.New("nil header")
  264. }
  265. abciResponses.BeginBlock, err = proxyAppConn.BeginBlock(
  266. ctx,
  267. abci.RequestBeginBlock{
  268. Hash: block.Hash(),
  269. Header: *pbh,
  270. LastCommitInfo: commitInfo,
  271. ByzantineValidators: byzVals,
  272. },
  273. )
  274. if err != nil {
  275. logger.Error("error in proxyAppConn.BeginBlock", "err", err)
  276. return nil, err
  277. }
  278. // run txs of block
  279. for _, tx := range block.Txs {
  280. resp, err := proxyAppConn.DeliverTx(ctx, abci.RequestDeliverTx{Tx: tx})
  281. if err != nil {
  282. return nil, err
  283. }
  284. if resp.Code == abci.CodeTypeOK {
  285. validTxs++
  286. } else {
  287. logger.Debug("invalid tx", "code", resp.Code, "log", resp.Log)
  288. invalidTxs++
  289. }
  290. abciResponses.DeliverTxs[txIndex] = resp
  291. txIndex++
  292. }
  293. abciResponses.EndBlock, err = proxyAppConn.EndBlock(ctx, abci.RequestEndBlock{Height: block.Height})
  294. if err != nil {
  295. logger.Error("error in proxyAppConn.EndBlock", "err", err)
  296. return nil, err
  297. }
  298. logger.Info("executed block", "height", block.Height, "num_valid_txs", validTxs, "num_invalid_txs", invalidTxs)
  299. return abciResponses, nil
  300. }
  301. func getBeginBlockValidatorInfo(block *types.Block, store Store,
  302. initialHeight int64) abci.LastCommitInfo {
  303. voteInfos := make([]abci.VoteInfo, block.LastCommit.Size())
  304. // Initial block -> LastCommitInfo.Votes are empty.
  305. // Remember that the first LastCommit is intentionally empty, so it makes
  306. // sense for LastCommitInfo.Votes to also be empty.
  307. if block.Height > initialHeight {
  308. lastValSet, err := store.LoadValidators(block.Height - 1)
  309. if err != nil {
  310. panic(err)
  311. }
  312. // Sanity check that commit size matches validator set size - only applies
  313. // after first block.
  314. var (
  315. commitSize = block.LastCommit.Size()
  316. valSetLen = len(lastValSet.Validators)
  317. )
  318. if commitSize != valSetLen {
  319. panic(fmt.Sprintf(
  320. "commit size (%d) doesn't match valset length (%d) at height %d\n\n%v\n\n%v",
  321. commitSize, valSetLen, block.Height, block.LastCommit.Signatures, lastValSet.Validators,
  322. ))
  323. }
  324. for i, val := range lastValSet.Validators {
  325. commitSig := block.LastCommit.Signatures[i]
  326. voteInfos[i] = abci.VoteInfo{
  327. Validator: types.TM2PB.Validator(val),
  328. SignedLastBlock: !commitSig.Absent(),
  329. }
  330. }
  331. }
  332. return abci.LastCommitInfo{
  333. Round: block.LastCommit.Round,
  334. Votes: voteInfos,
  335. }
  336. }
  337. func validateValidatorUpdates(abciUpdates []abci.ValidatorUpdate,
  338. params types.ValidatorParams) error {
  339. for _, valUpdate := range abciUpdates {
  340. if valUpdate.GetPower() < 0 {
  341. return fmt.Errorf("voting power can't be negative %v", valUpdate)
  342. } else if valUpdate.GetPower() == 0 {
  343. // continue, since this is deleting the validator, and thus there is no
  344. // pubkey to check
  345. continue
  346. }
  347. // Check if validator's pubkey matches an ABCI type in the consensus params
  348. pk, err := encoding.PubKeyFromProto(valUpdate.PubKey)
  349. if err != nil {
  350. return err
  351. }
  352. if !params.IsValidPubkeyType(pk.Type()) {
  353. return fmt.Errorf("validator %v is using pubkey %s, which is unsupported for consensus",
  354. valUpdate, pk.Type())
  355. }
  356. }
  357. return nil
  358. }
  359. // updateState returns a new State updated according to the header and responses.
  360. func updateState(
  361. state State,
  362. blockID types.BlockID,
  363. header *types.Header,
  364. abciResponses *tmstate.ABCIResponses,
  365. validatorUpdates []*types.Validator,
  366. ) (State, error) {
  367. // Copy the valset so we can apply changes from EndBlock
  368. // and update s.LastValidators and s.Validators.
  369. nValSet := state.NextValidators.Copy()
  370. // Update the validator set with the latest abciResponses.
  371. lastHeightValsChanged := state.LastHeightValidatorsChanged
  372. if len(validatorUpdates) > 0 {
  373. err := nValSet.UpdateWithChangeSet(validatorUpdates)
  374. if err != nil {
  375. return state, fmt.Errorf("error changing validator set: %w", err)
  376. }
  377. // Change results from this height but only applies to the next next height.
  378. lastHeightValsChanged = header.Height + 1 + 1
  379. }
  380. // Update validator proposer priority and set state variables.
  381. nValSet.IncrementProposerPriority(1)
  382. // Update the params with the latest abciResponses.
  383. nextParams := state.ConsensusParams
  384. lastHeightParamsChanged := state.LastHeightConsensusParamsChanged
  385. if abciResponses.EndBlock.ConsensusParamUpdates != nil {
  386. // NOTE: must not mutate s.ConsensusParams
  387. nextParams = state.ConsensusParams.UpdateConsensusParams(abciResponses.EndBlock.ConsensusParamUpdates)
  388. err := nextParams.ValidateConsensusParams()
  389. if err != nil {
  390. return state, fmt.Errorf("error updating consensus params: %w", err)
  391. }
  392. state.Version.Consensus.App = nextParams.Version.AppVersion
  393. // Change results from this height but only applies to the next height.
  394. lastHeightParamsChanged = header.Height + 1
  395. }
  396. nextVersion := state.Version
  397. // NOTE: the AppHash has not been populated.
  398. // It will be filled on state.Save.
  399. return State{
  400. Version: nextVersion,
  401. ChainID: state.ChainID,
  402. InitialHeight: state.InitialHeight,
  403. LastBlockHeight: header.Height,
  404. LastBlockID: blockID,
  405. LastBlockTime: header.Time,
  406. NextValidators: nValSet,
  407. Validators: state.NextValidators.Copy(),
  408. LastValidators: state.Validators.Copy(),
  409. LastHeightValidatorsChanged: lastHeightValsChanged,
  410. ConsensusParams: nextParams,
  411. LastHeightConsensusParamsChanged: lastHeightParamsChanged,
  412. LastResultsHash: ABCIResponsesResultsHash(abciResponses),
  413. AppHash: nil,
  414. }, nil
  415. }
  416. // Fire NewBlock, NewBlockHeader.
  417. // Fire TxEvent for every tx.
  418. // NOTE: if Tendermint crashes before commit, some or all of these events may be published again.
  419. func fireEvents(
  420. ctx context.Context,
  421. logger log.Logger,
  422. eventBus types.BlockEventPublisher,
  423. block *types.Block,
  424. blockID types.BlockID,
  425. abciResponses *tmstate.ABCIResponses,
  426. validatorUpdates []*types.Validator,
  427. ) {
  428. if err := eventBus.PublishEventNewBlock(ctx, types.EventDataNewBlock{
  429. Block: block,
  430. BlockID: blockID,
  431. ResultBeginBlock: *abciResponses.BeginBlock,
  432. ResultEndBlock: *abciResponses.EndBlock,
  433. }); err != nil {
  434. logger.Error("failed publishing new block", "err", err)
  435. }
  436. if err := eventBus.PublishEventNewBlockHeader(ctx, types.EventDataNewBlockHeader{
  437. Header: block.Header,
  438. NumTxs: int64(len(block.Txs)),
  439. ResultBeginBlock: *abciResponses.BeginBlock,
  440. ResultEndBlock: *abciResponses.EndBlock,
  441. }); err != nil {
  442. logger.Error("failed publishing new block header", "err", err)
  443. }
  444. if len(block.Evidence.Evidence) != 0 {
  445. for _, ev := range block.Evidence.Evidence {
  446. if err := eventBus.PublishEventNewEvidence(ctx, types.EventDataNewEvidence{
  447. Evidence: ev,
  448. Height: block.Height,
  449. }); err != nil {
  450. logger.Error("failed publishing new evidence", "err", err)
  451. }
  452. }
  453. }
  454. for i, tx := range block.Data.Txs {
  455. if err := eventBus.PublishEventTx(ctx, types.EventDataTx{TxResult: abci.TxResult{
  456. Height: block.Height,
  457. Index: uint32(i),
  458. Tx: tx,
  459. Result: *(abciResponses.DeliverTxs[i]),
  460. }}); err != nil {
  461. logger.Error("failed publishing event TX", "err", err)
  462. }
  463. }
  464. if len(validatorUpdates) > 0 {
  465. if err := eventBus.PublishEventValidatorSetUpdates(ctx,
  466. types.EventDataValidatorSetUpdates{ValidatorUpdates: validatorUpdates}); err != nil {
  467. logger.Error("failed publishing event", "err", err)
  468. }
  469. }
  470. }
  471. //----------------------------------------------------------------------------------------------------
  472. // Execute block without state. TODO: eliminate
  473. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  474. // It returns the application root hash (result of abci.Commit).
  475. func ExecCommitBlock(
  476. ctx context.Context,
  477. be *BlockExecutor,
  478. appConnConsensus proxy.AppConnConsensus,
  479. block *types.Block,
  480. logger log.Logger,
  481. store Store,
  482. initialHeight int64,
  483. s State,
  484. ) ([]byte, error) {
  485. abciResponses, err := execBlockOnProxyApp(ctx, logger, appConnConsensus, block, store, initialHeight)
  486. if err != nil {
  487. logger.Error("failed executing block on proxy app", "height", block.Height, "err", err)
  488. return nil, err
  489. }
  490. // the BlockExecutor condition is using for the final block replay process.
  491. if be != nil {
  492. abciValUpdates := abciResponses.EndBlock.ValidatorUpdates
  493. err = validateValidatorUpdates(abciValUpdates, s.ConsensusParams.Validator)
  494. if err != nil {
  495. logger.Error("err", err)
  496. return nil, err
  497. }
  498. validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciValUpdates)
  499. if err != nil {
  500. logger.Error("err", err)
  501. return nil, err
  502. }
  503. bps, err := block.MakePartSet(types.BlockPartSizeBytes)
  504. if err != nil {
  505. return nil, err
  506. }
  507. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  508. fireEvents(ctx, be.logger, be.eventBus, block, blockID, abciResponses, validatorUpdates)
  509. }
  510. // Commit block, get hash back
  511. res, err := appConnConsensus.Commit(ctx)
  512. if err != nil {
  513. logger.Error("client error during proxyAppConn.Commit", "err", res)
  514. return nil, err
  515. }
  516. // ResponseCommit has no error or log, just data
  517. return res.Data, nil
  518. }
  519. func (blockExec *BlockExecutor) pruneBlocks(retainHeight int64) (uint64, error) {
  520. base := blockExec.blockStore.Base()
  521. if retainHeight <= base {
  522. return 0, nil
  523. }
  524. pruned, err := blockExec.blockStore.PruneBlocks(retainHeight)
  525. if err != nil {
  526. return 0, fmt.Errorf("failed to prune block store: %w", err)
  527. }
  528. err = blockExec.Store().PruneStates(retainHeight)
  529. if err != nil {
  530. return 0, fmt.Errorf("failed to prune state store: %w", err)
  531. }
  532. return pruned, nil
  533. }