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.

682 lines
21 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
5 years ago
6 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>
4 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>
4 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>
4 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>
4 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>
4 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
5 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
5 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
5 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
5 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
6 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. //
  85. // Contract: application will not return more bytes than are sent over the wire.
  86. func (blockExec *BlockExecutor) CreateProposalBlock(
  87. height int64,
  88. state State, commit *types.Commit,
  89. proposerAddr []byte,
  90. ) (*types.Block, *types.PartSet, error) {
  91. maxBytes := state.ConsensusParams.Block.MaxBytes
  92. maxGas := state.ConsensusParams.Block.MaxGas
  93. evidence, evSize := blockExec.evpool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes)
  94. // Fetch a limited amount of valid txs
  95. maxDataBytes := types.MaxDataBytes(maxBytes, evSize, state.Validators.Size())
  96. txs := blockExec.mempool.ReapMaxBytesMaxGas(maxDataBytes, maxGas)
  97. preparedProposal, err := blockExec.proxyApp.PrepareProposal(
  98. context.Background(),
  99. abci.RequestPrepareProposal{BlockData: txs.ToSliceOfBytes(), BlockDataSize: maxDataBytes},
  100. )
  101. if err != nil {
  102. // The App MUST ensure that only valid (and hence 'processable') transactions
  103. // enter the mempool. Hence, at this point, we can't have any non-processable
  104. // transaction causing an error.
  105. //
  106. // Also, the App can simply skip any transaction that could cause any kind of trouble.
  107. // Either way, we can not recover in a meaningful way, unless we skip proposing
  108. // this block, repair what caused the error and try again. Hence, we panic on
  109. // purpose for now.
  110. panic(err)
  111. }
  112. newTxs := preparedProposal.GetBlockData()
  113. var txSize int
  114. for _, tx := range newTxs {
  115. txSize += len(tx)
  116. if maxDataBytes < int64(txSize) {
  117. panic("block data exceeds max amount of allowed bytes")
  118. }
  119. }
  120. modifiedTxs := types.ToTxs(preparedProposal.GetBlockData())
  121. return state.MakeBlock(height, modifiedTxs, commit, evidence, proposerAddr)
  122. }
  123. // ValidateBlock validates the given block against the given state.
  124. // If the block is invalid, it returns an error.
  125. // Validation does not mutate state, but does require historical information from the stateDB,
  126. // ie. to verify evidence from a validator at an old height.
  127. func (blockExec *BlockExecutor) ValidateBlock(state State, block *types.Block) error {
  128. hash := block.Hash()
  129. if _, ok := blockExec.cache[hash.String()]; ok {
  130. return nil
  131. }
  132. err := validateBlock(state, block)
  133. if err != nil {
  134. return err
  135. }
  136. err = blockExec.evpool.CheckEvidence(block.Evidence.Evidence)
  137. if err != nil {
  138. return err
  139. }
  140. blockExec.cache[hash.String()] = struct{}{}
  141. return nil
  142. }
  143. // ApplyBlock validates the block against the state, executes it against the app,
  144. // fires the relevant events, commits the app, and saves the new state and responses.
  145. // It returns the new state.
  146. // It's the only function that needs to be called
  147. // from outside this package to process and commit an entire block.
  148. // It takes a blockID to avoid recomputing the parts hash.
  149. func (blockExec *BlockExecutor) ApplyBlock(
  150. ctx context.Context,
  151. state State,
  152. blockID types.BlockID,
  153. block *types.Block,
  154. ) (State, error) {
  155. // validate the block if we haven't already
  156. if err := blockExec.ValidateBlock(state, block); err != nil {
  157. return state, ErrInvalidBlock(err)
  158. }
  159. startTime := time.Now().UnixNano()
  160. abciResponses, err := execBlockOnProxyApp(ctx,
  161. blockExec.logger, blockExec.proxyApp, block, blockExec.store, state.InitialHeight,
  162. )
  163. endTime := time.Now().UnixNano()
  164. blockExec.metrics.BlockProcessingTime.Observe(float64(endTime-startTime) / 1000000)
  165. if err != nil {
  166. return state, ErrProxyAppConn(err)
  167. }
  168. // Save the results before we commit.
  169. if err := blockExec.store.SaveABCIResponses(block.Height, abciResponses); err != nil {
  170. return state, err
  171. }
  172. // validate the validator updates and convert to tendermint types
  173. abciValUpdates := abciResponses.EndBlock.ValidatorUpdates
  174. err = validateValidatorUpdates(abciValUpdates, state.ConsensusParams.Validator)
  175. if err != nil {
  176. return state, fmt.Errorf("error in validator updates: %w", err)
  177. }
  178. validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciValUpdates)
  179. if err != nil {
  180. return state, err
  181. }
  182. if len(validatorUpdates) > 0 {
  183. blockExec.logger.Debug("updates to validators", "updates", types.ValidatorListString(validatorUpdates))
  184. }
  185. // Update the state with the block and responses.
  186. state, err = updateState(state, blockID, &block.Header, abciResponses, validatorUpdates)
  187. if err != nil {
  188. return state, fmt.Errorf("commit failed for application: %w", err)
  189. }
  190. // Lock mempool, commit app state, update mempoool.
  191. appHash, retainHeight, err := blockExec.Commit(ctx, state, block, abciResponses.DeliverTxs)
  192. if err != nil {
  193. return state, fmt.Errorf("commit failed for application: %w", err)
  194. }
  195. // Update evpool with the latest state.
  196. blockExec.evpool.Update(state, block.Evidence.Evidence)
  197. // Update the app hash and save the state.
  198. state.AppHash = appHash
  199. if err := blockExec.store.Save(state); err != nil {
  200. return state, err
  201. }
  202. // Prune old heights, if requested by ABCI app.
  203. if retainHeight > 0 {
  204. pruned, err := blockExec.pruneBlocks(retainHeight)
  205. if err != nil {
  206. blockExec.logger.Error("failed to prune blocks", "retain_height", retainHeight, "err", err)
  207. } else {
  208. blockExec.logger.Debug("pruned blocks", "pruned", pruned, "retain_height", retainHeight)
  209. }
  210. }
  211. // reset the verification cache
  212. blockExec.cache = make(map[string]struct{})
  213. // Events are fired after everything else.
  214. // NOTE: if we crash between Commit and Save, events wont be fired during replay
  215. fireEvents(ctx, blockExec.logger, blockExec.eventBus, block, blockID, abciResponses, validatorUpdates)
  216. return state, nil
  217. }
  218. func (blockExec *BlockExecutor) ExtendVote(vote *types.Vote) (types.VoteExtension, error) {
  219. ctx := context.Background()
  220. req := abci.RequestExtendVote{
  221. Vote: vote.ToProto(),
  222. }
  223. resp, err := blockExec.proxyApp.ExtendVote(ctx, req)
  224. if err != nil {
  225. return types.VoteExtension{}, err
  226. }
  227. return types.VoteExtensionFromProto(resp.VoteExtension), nil
  228. }
  229. func (blockExec *BlockExecutor) VerifyVoteExtension(vote *types.Vote) error {
  230. ctx := context.Background()
  231. req := abci.RequestVerifyVoteExtension{
  232. Vote: vote.ToProto(),
  233. }
  234. resp, err := blockExec.proxyApp.VerifyVoteExtension(ctx, req)
  235. if err != nil {
  236. return err
  237. }
  238. if resp.IsErr() {
  239. return types.ErrVoteInvalidExtension
  240. }
  241. return nil
  242. }
  243. // Commit locks the mempool, runs the ABCI Commit message, and updates the
  244. // mempool.
  245. // It returns the result of calling abci.Commit (the AppHash) and the height to retain (if any).
  246. // The Mempool must be locked during commit and update because state is
  247. // typically reset on Commit and old txs must be replayed against committed
  248. // state before new txs are run in the mempool, lest they be invalid.
  249. func (blockExec *BlockExecutor) Commit(
  250. ctx context.Context,
  251. state State,
  252. block *types.Block,
  253. deliverTxResponses []*abci.ResponseDeliverTx,
  254. ) ([]byte, int64, error) {
  255. blockExec.mempool.Lock()
  256. defer blockExec.mempool.Unlock()
  257. // while mempool is Locked, flush to ensure all async requests have completed
  258. // in the ABCI app before Commit.
  259. err := blockExec.mempool.FlushAppConn(ctx)
  260. if err != nil {
  261. blockExec.logger.Error("client error during mempool.FlushAppConn", "err", err)
  262. return nil, 0, err
  263. }
  264. // Commit block, get hash back
  265. res, err := blockExec.proxyApp.Commit(ctx)
  266. if err != nil {
  267. blockExec.logger.Error("client error during proxyAppConn.Commit", "err", err)
  268. return nil, 0, err
  269. }
  270. // ResponseCommit has no error code - just data
  271. blockExec.logger.Info(
  272. "committed state",
  273. "height", block.Height,
  274. "num_txs", len(block.Txs),
  275. "app_hash", fmt.Sprintf("%X", res.Data),
  276. )
  277. // Update mempool.
  278. err = blockExec.mempool.Update(
  279. ctx,
  280. block.Height,
  281. block.Txs,
  282. deliverTxResponses,
  283. TxPreCheck(state),
  284. TxPostCheck(state),
  285. )
  286. return res.Data, res.RetainHeight, err
  287. }
  288. //---------------------------------------------------------
  289. // Helper functions for executing blocks and updating state
  290. // Executes block's transactions on proxyAppConn.
  291. // Returns a list of transaction results and updates to the validator set
  292. func execBlockOnProxyApp(
  293. ctx context.Context,
  294. logger log.Logger,
  295. proxyAppConn proxy.AppConnConsensus,
  296. block *types.Block,
  297. store Store,
  298. initialHeight int64,
  299. ) (*tmstate.ABCIResponses, error) {
  300. var validTxs, invalidTxs = 0, 0
  301. txIndex := 0
  302. abciResponses := new(tmstate.ABCIResponses)
  303. dtxs := make([]*abci.ResponseDeliverTx, len(block.Txs))
  304. abciResponses.DeliverTxs = dtxs
  305. commitInfo := getBeginBlockValidatorInfo(block, store, initialHeight)
  306. byzVals := make([]abci.Evidence, 0)
  307. for _, evidence := range block.Evidence.Evidence {
  308. byzVals = append(byzVals, evidence.ABCI()...)
  309. }
  310. // Begin block
  311. var err error
  312. pbh := block.Header.ToProto()
  313. if pbh == nil {
  314. return nil, errors.New("nil header")
  315. }
  316. abciResponses.BeginBlock, err = proxyAppConn.BeginBlock(
  317. ctx,
  318. abci.RequestBeginBlock{
  319. Hash: block.Hash(),
  320. Header: *pbh,
  321. LastCommitInfo: commitInfo,
  322. ByzantineValidators: byzVals,
  323. },
  324. )
  325. if err != nil {
  326. logger.Error("error in proxyAppConn.BeginBlock", "err", err)
  327. return nil, err
  328. }
  329. // run txs of block
  330. for _, tx := range block.Txs {
  331. resp, err := proxyAppConn.DeliverTx(ctx, abci.RequestDeliverTx{Tx: tx})
  332. if err != nil {
  333. return nil, err
  334. }
  335. if resp.Code == abci.CodeTypeOK {
  336. validTxs++
  337. } else {
  338. logger.Debug("invalid tx", "code", resp.Code, "log", resp.Log)
  339. invalidTxs++
  340. }
  341. abciResponses.DeliverTxs[txIndex] = resp
  342. txIndex++
  343. }
  344. abciResponses.EndBlock, err = proxyAppConn.EndBlock(ctx, abci.RequestEndBlock{Height: block.Height})
  345. if err != nil {
  346. logger.Error("error in proxyAppConn.EndBlock", "err", err)
  347. return nil, err
  348. }
  349. logger.Info("executed block", "height", block.Height, "num_valid_txs", validTxs, "num_invalid_txs", invalidTxs)
  350. return abciResponses, nil
  351. }
  352. func getBeginBlockValidatorInfo(block *types.Block, store Store,
  353. initialHeight int64) abci.LastCommitInfo {
  354. voteInfos := make([]abci.VoteInfo, block.LastCommit.Size())
  355. // Initial block -> LastCommitInfo.Votes are empty.
  356. // Remember that the first LastCommit is intentionally empty, so it makes
  357. // sense for LastCommitInfo.Votes to also be empty.
  358. if block.Height > initialHeight {
  359. lastValSet, err := store.LoadValidators(block.Height - 1)
  360. if err != nil {
  361. panic(err)
  362. }
  363. // Sanity check that commit size matches validator set size - only applies
  364. // after first block.
  365. var (
  366. commitSize = block.LastCommit.Size()
  367. valSetLen = len(lastValSet.Validators)
  368. )
  369. if commitSize != valSetLen {
  370. panic(fmt.Sprintf(
  371. "commit size (%d) doesn't match valset length (%d) at height %d\n\n%v\n\n%v",
  372. commitSize, valSetLen, block.Height, block.LastCommit.Signatures, lastValSet.Validators,
  373. ))
  374. }
  375. for i, val := range lastValSet.Validators {
  376. commitSig := block.LastCommit.Signatures[i]
  377. voteInfos[i] = abci.VoteInfo{
  378. Validator: types.TM2PB.Validator(val),
  379. SignedLastBlock: !commitSig.Absent(),
  380. }
  381. }
  382. }
  383. return abci.LastCommitInfo{
  384. Round: block.LastCommit.Round,
  385. Votes: voteInfos,
  386. }
  387. }
  388. func validateValidatorUpdates(abciUpdates []abci.ValidatorUpdate,
  389. params types.ValidatorParams) error {
  390. for _, valUpdate := range abciUpdates {
  391. if valUpdate.GetPower() < 0 {
  392. return fmt.Errorf("voting power can't be negative %v", valUpdate)
  393. } else if valUpdate.GetPower() == 0 {
  394. // continue, since this is deleting the validator, and thus there is no
  395. // pubkey to check
  396. continue
  397. }
  398. // Check if validator's pubkey matches an ABCI type in the consensus params
  399. pk, err := encoding.PubKeyFromProto(valUpdate.PubKey)
  400. if err != nil {
  401. return err
  402. }
  403. if !params.IsValidPubkeyType(pk.Type()) {
  404. return fmt.Errorf("validator %v is using pubkey %s, which is unsupported for consensus",
  405. valUpdate, pk.Type())
  406. }
  407. }
  408. return nil
  409. }
  410. // updateState returns a new State updated according to the header and responses.
  411. func updateState(
  412. state State,
  413. blockID types.BlockID,
  414. header *types.Header,
  415. abciResponses *tmstate.ABCIResponses,
  416. validatorUpdates []*types.Validator,
  417. ) (State, error) {
  418. // Copy the valset so we can apply changes from EndBlock
  419. // and update s.LastValidators and s.Validators.
  420. nValSet := state.NextValidators.Copy()
  421. // Update the validator set with the latest abciResponses.
  422. lastHeightValsChanged := state.LastHeightValidatorsChanged
  423. if len(validatorUpdates) > 0 {
  424. err := nValSet.UpdateWithChangeSet(validatorUpdates)
  425. if err != nil {
  426. return state, fmt.Errorf("error changing validator set: %w", err)
  427. }
  428. // Change results from this height but only applies to the next next height.
  429. lastHeightValsChanged = header.Height + 1 + 1
  430. }
  431. // Update validator proposer priority and set state variables.
  432. nValSet.IncrementProposerPriority(1)
  433. // Update the params with the latest abciResponses.
  434. nextParams := state.ConsensusParams
  435. lastHeightParamsChanged := state.LastHeightConsensusParamsChanged
  436. if abciResponses.EndBlock.ConsensusParamUpdates != nil {
  437. // NOTE: must not mutate s.ConsensusParams
  438. nextParams = state.ConsensusParams.UpdateConsensusParams(abciResponses.EndBlock.ConsensusParamUpdates)
  439. err := nextParams.ValidateConsensusParams()
  440. if err != nil {
  441. return state, fmt.Errorf("error updating consensus params: %w", err)
  442. }
  443. state.Version.Consensus.App = nextParams.Version.AppVersion
  444. // Change results from this height but only applies to the next height.
  445. lastHeightParamsChanged = header.Height + 1
  446. }
  447. nextVersion := state.Version
  448. // NOTE: the AppHash and the VoteExtension has not been populated.
  449. // It will be filled on state.Save.
  450. return State{
  451. Version: nextVersion,
  452. ChainID: state.ChainID,
  453. InitialHeight: state.InitialHeight,
  454. LastBlockHeight: header.Height,
  455. LastBlockID: blockID,
  456. LastBlockTime: header.Time,
  457. NextValidators: nValSet,
  458. Validators: state.NextValidators.Copy(),
  459. LastValidators: state.Validators.Copy(),
  460. LastHeightValidatorsChanged: lastHeightValsChanged,
  461. ConsensusParams: nextParams,
  462. LastHeightConsensusParamsChanged: lastHeightParamsChanged,
  463. LastResultsHash: ABCIResponsesResultsHash(abciResponses),
  464. AppHash: nil,
  465. }, nil
  466. }
  467. // Fire NewBlock, NewBlockHeader.
  468. // Fire TxEvent for every tx.
  469. // NOTE: if Tendermint crashes before commit, some or all of these events may be published again.
  470. func fireEvents(
  471. ctx context.Context,
  472. logger log.Logger,
  473. eventBus types.BlockEventPublisher,
  474. block *types.Block,
  475. blockID types.BlockID,
  476. abciResponses *tmstate.ABCIResponses,
  477. validatorUpdates []*types.Validator,
  478. ) {
  479. if err := eventBus.PublishEventNewBlock(ctx, types.EventDataNewBlock{
  480. Block: block,
  481. BlockID: blockID,
  482. ResultBeginBlock: *abciResponses.BeginBlock,
  483. ResultEndBlock: *abciResponses.EndBlock,
  484. }); err != nil {
  485. logger.Error("failed publishing new block", "err", err)
  486. }
  487. if err := eventBus.PublishEventNewBlockHeader(ctx, types.EventDataNewBlockHeader{
  488. Header: block.Header,
  489. NumTxs: int64(len(block.Txs)),
  490. ResultBeginBlock: *abciResponses.BeginBlock,
  491. ResultEndBlock: *abciResponses.EndBlock,
  492. }); err != nil {
  493. logger.Error("failed publishing new block header", "err", err)
  494. }
  495. if len(block.Evidence.Evidence) != 0 {
  496. for _, ev := range block.Evidence.Evidence {
  497. if err := eventBus.PublishEventNewEvidence(ctx, types.EventDataNewEvidence{
  498. Evidence: ev,
  499. Height: block.Height,
  500. }); err != nil {
  501. logger.Error("failed publishing new evidence", "err", err)
  502. }
  503. }
  504. }
  505. for i, tx := range block.Data.Txs {
  506. if err := eventBus.PublishEventTx(ctx, types.EventDataTx{TxResult: abci.TxResult{
  507. Height: block.Height,
  508. Index: uint32(i),
  509. Tx: tx,
  510. Result: *(abciResponses.DeliverTxs[i]),
  511. }}); err != nil {
  512. logger.Error("failed publishing event TX", "err", err)
  513. }
  514. }
  515. if len(validatorUpdates) > 0 {
  516. if err := eventBus.PublishEventValidatorSetUpdates(ctx,
  517. types.EventDataValidatorSetUpdates{ValidatorUpdates: validatorUpdates}); err != nil {
  518. logger.Error("failed publishing event", "err", err)
  519. }
  520. }
  521. }
  522. //----------------------------------------------------------------------------------------------------
  523. // Execute block without state. TODO: eliminate
  524. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  525. // It returns the application root hash (result of abci.Commit).
  526. func ExecCommitBlock(
  527. ctx context.Context,
  528. be *BlockExecutor,
  529. appConnConsensus proxy.AppConnConsensus,
  530. block *types.Block,
  531. logger log.Logger,
  532. store Store,
  533. initialHeight int64,
  534. s State,
  535. ) ([]byte, error) {
  536. abciResponses, err := execBlockOnProxyApp(ctx, logger, appConnConsensus, block, store, initialHeight)
  537. if err != nil {
  538. logger.Error("failed executing block on proxy app", "height", block.Height, "err", err)
  539. return nil, err
  540. }
  541. // the BlockExecutor condition is using for the final block replay process.
  542. if be != nil {
  543. abciValUpdates := abciResponses.EndBlock.ValidatorUpdates
  544. err = validateValidatorUpdates(abciValUpdates, s.ConsensusParams.Validator)
  545. if err != nil {
  546. logger.Error("err", err)
  547. return nil, err
  548. }
  549. validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciValUpdates)
  550. if err != nil {
  551. logger.Error("err", err)
  552. return nil, err
  553. }
  554. bps, err := block.MakePartSet(types.BlockPartSizeBytes)
  555. if err != nil {
  556. return nil, err
  557. }
  558. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  559. fireEvents(ctx, be.logger, be.eventBus, block, blockID, abciResponses, validatorUpdates)
  560. }
  561. // Commit block, get hash back
  562. res, err := appConnConsensus.Commit(ctx)
  563. if err != nil {
  564. logger.Error("client error during proxyAppConn.Commit", "err", res)
  565. return nil, err
  566. }
  567. // ResponseCommit has no error or log, just data
  568. return res.Data, nil
  569. }
  570. func (blockExec *BlockExecutor) pruneBlocks(retainHeight int64) (uint64, error) {
  571. base := blockExec.blockStore.Base()
  572. if retainHeight <= base {
  573. return 0, nil
  574. }
  575. pruned, err := blockExec.blockStore.PruneBlocks(retainHeight)
  576. if err != nil {
  577. return 0, fmt.Errorf("failed to prune block store: %w", err)
  578. }
  579. err = blockExec.Store().PruneStates(retainHeight)
  580. if err != nil {
  581. return 0, fmt.Errorf("failed to prune state store: %w", err)
  582. }
  583. return pruned, nil
  584. }