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.

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