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.

686 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
6 years ago
7 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
8 years ago
8 years ago
8 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cs/replay: execCommitBlock should not read from state.lastValidators (#3067) * execCommitBlock should not read from state.lastValidators * fix height 1 * fix blockchain/reactor_test * fix consensus/mempool_test * fix consensus/reactor_test * fix consensus/replay_test * add CHANGELOG * fix consensus/reactor_test * fix consensus/replay_test * add a test for replay validators change * fix mem_pool test * fix byzantine test * remove a redundant code * reduce validator change blocks to 6 * fix * return peer0 config * seperate testName * seperate testName 1 * seperate testName 2 * seperate app db path * seperate app db path 1 * add a lock before startNet * move the lock to reactor_test * simulate just once * try to find problem * handshake only saveState when app version changed * update gometalinter to 3.0.0 (#3233) in the attempt to fix https://circleci.com/gh/tendermint/tendermint/43165 also code is simplified by running gofmt -s . remove unused vars enable linters we're currently passing remove deprecated linters (cherry picked from commit d47094550315c094512a242445e0dde24b5a03f5) * gofmt code * goimport code * change the bool name to testValidatorsChange * adjust receive kvstore.ProtocolVersion * adjust receive kvstore.ProtocolVersion 1 * adjust receive kvstore.ProtocolVersion 3 * fix merge execution.go * fix merge develop * fix merge develop 1 * fix run cleanupFunc * adjust code according to reviewers' opinion * modify the func name match the convention * simplify simulate a chain containing some validator change txs 1 * test CI error * Merge remote-tracking branch 'upstream/develop' into fixReplay 1 * fix pubsub_test * subscribeUnbuffered vote channel
6 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
8 years ago
7 years ago
8 years ago
  1. package state
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "time"
  7. abci "github.com/tendermint/tendermint/abci/types"
  8. "github.com/tendermint/tendermint/crypto/encoding"
  9. "github.com/tendermint/tendermint/internal/eventbus"
  10. "github.com/tendermint/tendermint/internal/mempool"
  11. "github.com/tendermint/tendermint/internal/proxy"
  12. "github.com/tendermint/tendermint/libs/log"
  13. tmstate "github.com/tendermint/tendermint/proto/tendermint/state"
  14. "github.com/tendermint/tendermint/types"
  15. )
  16. //-----------------------------------------------------------------------------
  17. // BlockExecutor handles block execution and state updates.
  18. // It exposes ApplyBlock(), which validates & executes the block, updates state w/ ABCI responses,
  19. // then commits and updates the mempool atomically, then saves state.
  20. // BlockExecutor provides the context and accessories for properly executing a block.
  21. type BlockExecutor struct {
  22. // save state, validators, consensus params, abci responses here
  23. store Store
  24. // use blockstore for the pruning functions.
  25. blockStore BlockStore
  26. // execute the app against this
  27. proxyApp proxy.AppConnConsensus
  28. // events
  29. eventBus types.BlockEventPublisher
  30. // manage the mempool lock during commit
  31. // and update both with block results after commit.
  32. mempool mempool.Mempool
  33. evpool EvidencePool
  34. logger log.Logger
  35. metrics *Metrics
  36. // cache the verification results over a single height
  37. cache map[string]struct{}
  38. }
  39. type BlockExecutorOption func(executor *BlockExecutor)
  40. func BlockExecutorWithMetrics(metrics *Metrics) BlockExecutorOption {
  41. return func(blockExec *BlockExecutor) {
  42. blockExec.metrics = metrics
  43. }
  44. }
  45. // NewBlockExecutor returns a new BlockExecutor with a NopEventBus.
  46. // Call SetEventBus to provide one.
  47. func NewBlockExecutor(
  48. stateStore Store,
  49. logger log.Logger,
  50. proxyApp proxy.AppConnConsensus,
  51. pool mempool.Mempool,
  52. evpool EvidencePool,
  53. blockStore BlockStore,
  54. options ...BlockExecutorOption,
  55. ) *BlockExecutor {
  56. res := &BlockExecutor{
  57. store: stateStore,
  58. proxyApp: proxyApp,
  59. eventBus: eventbus.NopEventBus{},
  60. mempool: pool,
  61. evpool: evpool,
  62. logger: logger,
  63. metrics: NopMetrics(),
  64. cache: make(map[string]struct{}),
  65. blockStore: blockStore,
  66. }
  67. for _, option := range options {
  68. option(res)
  69. }
  70. return res
  71. }
  72. func (blockExec *BlockExecutor) Store() Store {
  73. return blockExec.store
  74. }
  75. // SetEventBus - sets the event bus for publishing block related events.
  76. // If not called, it defaults to types.NopEventBus.
  77. func (blockExec *BlockExecutor) SetEventBus(eventBus types.BlockEventPublisher) {
  78. blockExec.eventBus = eventBus
  79. }
  80. // CreateProposalBlock calls state.MakeBlock with evidence from the evpool
  81. // and txs from the mempool. The max bytes must be big enough to fit the commit.
  82. // Up to 1/10th of the block space is allcoated for maximum sized evidence.
  83. // The rest is given to txs, up to the max gas.
  84. //
  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. votes []*types.Vote,
  91. ) (*types.Block, *types.PartSet, error) {
  92. maxBytes := state.ConsensusParams.Block.MaxBytes
  93. maxGas := state.ConsensusParams.Block.MaxGas
  94. evidence, evSize := blockExec.evpool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes)
  95. // Fetch a limited amount of valid txs
  96. maxDataBytes := types.MaxDataBytes(maxBytes, evSize, state.Validators.Size())
  97. txs := blockExec.mempool.ReapMaxBytesMaxGas(maxDataBytes, maxGas)
  98. preparedProposal, err := blockExec.proxyApp.PrepareProposal(
  99. context.Background(),
  100. abci.RequestPrepareProposal{
  101. BlockData: txs.ToSliceOfBytes(),
  102. BlockDataSize: maxDataBytes,
  103. Votes: types.VotesToProto(votes),
  104. },
  105. )
  106. if err != nil {
  107. // The App MUST ensure that only valid (and hence 'processable') transactions
  108. // enter the mempool. Hence, at this point, we can't have any non-processable
  109. // transaction causing an error.
  110. //
  111. // Also, the App can simply skip any transaction that could cause any kind of trouble.
  112. // Either way, we can not recover in a meaningful way, unless we skip proposing
  113. // this block, repair what caused the error and try again. Hence, we panic on
  114. // purpose for now.
  115. panic(err)
  116. }
  117. newTxs := preparedProposal.GetBlockData()
  118. var txSize int
  119. for _, tx := range newTxs {
  120. txSize += len(tx)
  121. if maxDataBytes < int64(txSize) {
  122. panic("block data exceeds max amount of allowed bytes")
  123. }
  124. }
  125. modifiedTxs := types.ToTxs(preparedProposal.GetBlockData())
  126. return state.MakeBlock(height, modifiedTxs, commit, evidence, proposerAddr)
  127. }
  128. // ValidateBlock validates the given block against the given state.
  129. // If the block is invalid, it returns an error.
  130. // Validation does not mutate state, but does require historical information from the stateDB,
  131. // ie. to verify evidence from a validator at an old height.
  132. func (blockExec *BlockExecutor) ValidateBlock(state State, block *types.Block) error {
  133. hash := block.Hash()
  134. if _, ok := blockExec.cache[hash.String()]; ok {
  135. return nil
  136. }
  137. err := validateBlock(state, block)
  138. if err != nil {
  139. return err
  140. }
  141. err = blockExec.evpool.CheckEvidence(block.Evidence.Evidence)
  142. if err != nil {
  143. return err
  144. }
  145. blockExec.cache[hash.String()] = struct{}{}
  146. return nil
  147. }
  148. // ApplyBlock validates the block against the state, executes it against the app,
  149. // fires the relevant events, commits the app, and saves the new state and responses.
  150. // It returns the new state.
  151. // It's the only function that needs to be called
  152. // from outside this package to process and commit an entire block.
  153. // It takes a blockID to avoid recomputing the parts hash.
  154. func (blockExec *BlockExecutor) ApplyBlock(
  155. ctx context.Context,
  156. state State,
  157. blockID types.BlockID,
  158. block *types.Block,
  159. ) (State, error) {
  160. // validate the block if we haven't already
  161. if err := blockExec.ValidateBlock(state, block); err != nil {
  162. return state, ErrInvalidBlock(err)
  163. }
  164. startTime := time.Now().UnixNano()
  165. abciResponses, err := execBlockOnProxyApp(ctx,
  166. blockExec.logger, blockExec.proxyApp, block, blockExec.store, state.InitialHeight,
  167. )
  168. endTime := time.Now().UnixNano()
  169. blockExec.metrics.BlockProcessingTime.Observe(float64(endTime-startTime) / 1000000)
  170. if err != nil {
  171. return state, ErrProxyAppConn(err)
  172. }
  173. // Save the results before we commit.
  174. if err := blockExec.store.SaveABCIResponses(block.Height, abciResponses); err != nil {
  175. return state, err
  176. }
  177. // validate the validator updates and convert to tendermint types
  178. abciValUpdates := abciResponses.EndBlock.ValidatorUpdates
  179. err = validateValidatorUpdates(abciValUpdates, state.ConsensusParams.Validator)
  180. if err != nil {
  181. return state, fmt.Errorf("error in validator updates: %w", err)
  182. }
  183. validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciValUpdates)
  184. if err != nil {
  185. return state, err
  186. }
  187. if len(validatorUpdates) > 0 {
  188. blockExec.logger.Debug("updates to validators", "updates", types.ValidatorListString(validatorUpdates))
  189. }
  190. // Update the state with the block and responses.
  191. state, err = updateState(state, blockID, &block.Header, abciResponses, validatorUpdates)
  192. if err != nil {
  193. return state, fmt.Errorf("commit failed for application: %w", err)
  194. }
  195. // Lock mempool, commit app state, update mempoool.
  196. appHash, retainHeight, err := blockExec.Commit(ctx, state, block, abciResponses.DeliverTxs)
  197. if err != nil {
  198. return state, fmt.Errorf("commit failed for application: %w", err)
  199. }
  200. // Update evpool with the latest state.
  201. blockExec.evpool.Update(state, block.Evidence.Evidence)
  202. // Update the app hash and save the state.
  203. state.AppHash = appHash
  204. if err := blockExec.store.Save(state); err != nil {
  205. return state, err
  206. }
  207. // Prune old heights, if requested by ABCI app.
  208. if retainHeight > 0 {
  209. pruned, err := blockExec.pruneBlocks(retainHeight)
  210. if err != nil {
  211. blockExec.logger.Error("failed to prune blocks", "retain_height", retainHeight, "err", err)
  212. } else {
  213. blockExec.logger.Debug("pruned blocks", "pruned", pruned, "retain_height", retainHeight)
  214. }
  215. }
  216. // reset the verification cache
  217. blockExec.cache = make(map[string]struct{})
  218. // Events are fired after everything else.
  219. // NOTE: if we crash between Commit and Save, events wont be fired during replay
  220. fireEvents(ctx, blockExec.logger, blockExec.eventBus, block, blockID, abciResponses, validatorUpdates)
  221. return state, nil
  222. }
  223. func (blockExec *BlockExecutor) ExtendVote(vote *types.Vote) (types.VoteExtension, error) {
  224. ctx := context.Background()
  225. req := abci.RequestExtendVote{
  226. Vote: vote.ToProto(),
  227. }
  228. resp, err := blockExec.proxyApp.ExtendVote(ctx, req)
  229. if err != nil {
  230. return types.VoteExtension{}, err
  231. }
  232. return types.VoteExtensionFromProto(resp.VoteExtension), nil
  233. }
  234. func (blockExec *BlockExecutor) VerifyVoteExtension(vote *types.Vote) error {
  235. ctx := context.Background()
  236. req := abci.RequestVerifyVoteExtension{
  237. Vote: vote.ToProto(),
  238. }
  239. resp, err := blockExec.proxyApp.VerifyVoteExtension(ctx, req)
  240. if err != nil {
  241. return err
  242. }
  243. if resp.IsErr() {
  244. return types.ErrVoteInvalidExtension
  245. }
  246. return nil
  247. }
  248. // Commit locks the mempool, runs the ABCI Commit message, and updates the
  249. // mempool.
  250. // It returns the result of calling abci.Commit (the AppHash) and the height to retain (if any).
  251. // The Mempool must be locked during commit and update because state is
  252. // typically reset on Commit and old txs must be replayed against committed
  253. // state before new txs are run in the mempool, lest they be invalid.
  254. func (blockExec *BlockExecutor) Commit(
  255. ctx context.Context,
  256. state State,
  257. block *types.Block,
  258. deliverTxResponses []*abci.ResponseDeliverTx,
  259. ) ([]byte, int64, error) {
  260. blockExec.mempool.Lock()
  261. defer blockExec.mempool.Unlock()
  262. // while mempool is Locked, flush to ensure all async requests have completed
  263. // in the ABCI app before Commit.
  264. err := blockExec.mempool.FlushAppConn(ctx)
  265. if err != nil {
  266. blockExec.logger.Error("client error during mempool.FlushAppConn", "err", err)
  267. return nil, 0, err
  268. }
  269. // Commit block, get hash back
  270. res, err := blockExec.proxyApp.Commit(ctx)
  271. if err != nil {
  272. blockExec.logger.Error("client error during proxyAppConn.Commit", "err", err)
  273. return nil, 0, err
  274. }
  275. // ResponseCommit has no error code - just data
  276. blockExec.logger.Info(
  277. "committed state",
  278. "height", block.Height,
  279. "num_txs", len(block.Txs),
  280. "app_hash", fmt.Sprintf("%X", res.Data),
  281. )
  282. // Update mempool.
  283. err = blockExec.mempool.Update(
  284. ctx,
  285. block.Height,
  286. block.Txs,
  287. deliverTxResponses,
  288. TxPreCheck(state),
  289. TxPostCheck(state),
  290. )
  291. return res.Data, res.RetainHeight, err
  292. }
  293. //---------------------------------------------------------
  294. // Helper functions for executing blocks and updating state
  295. // Executes block's transactions on proxyAppConn.
  296. // Returns a list of transaction results and updates to the validator set
  297. func execBlockOnProxyApp(
  298. ctx context.Context,
  299. logger log.Logger,
  300. proxyAppConn proxy.AppConnConsensus,
  301. block *types.Block,
  302. store Store,
  303. initialHeight int64,
  304. ) (*tmstate.ABCIResponses, error) {
  305. var validTxs, invalidTxs = 0, 0
  306. txIndex := 0
  307. abciResponses := new(tmstate.ABCIResponses)
  308. dtxs := make([]*abci.ResponseDeliverTx, len(block.Txs))
  309. abciResponses.DeliverTxs = dtxs
  310. commitInfo := getBeginBlockValidatorInfo(block, store, initialHeight)
  311. byzVals := make([]abci.Evidence, 0)
  312. for _, evidence := range block.Evidence.Evidence {
  313. byzVals = append(byzVals, evidence.ABCI()...)
  314. }
  315. // Begin block
  316. var err error
  317. pbh := block.Header.ToProto()
  318. if pbh == nil {
  319. return nil, errors.New("nil header")
  320. }
  321. abciResponses.BeginBlock, err = proxyAppConn.BeginBlock(
  322. ctx,
  323. abci.RequestBeginBlock{
  324. Hash: block.Hash(),
  325. Header: *pbh,
  326. LastCommitInfo: commitInfo,
  327. ByzantineValidators: byzVals,
  328. },
  329. )
  330. if err != nil {
  331. logger.Error("error in proxyAppConn.BeginBlock", "err", err)
  332. return nil, err
  333. }
  334. // run txs of block
  335. for _, tx := range block.Txs {
  336. resp, err := proxyAppConn.DeliverTx(ctx, abci.RequestDeliverTx{Tx: tx})
  337. if err != nil {
  338. return nil, err
  339. }
  340. if resp.Code == abci.CodeTypeOK {
  341. validTxs++
  342. } else {
  343. logger.Debug("invalid tx", "code", resp.Code, "log", resp.Log)
  344. invalidTxs++
  345. }
  346. abciResponses.DeliverTxs[txIndex] = resp
  347. txIndex++
  348. }
  349. abciResponses.EndBlock, err = proxyAppConn.EndBlock(ctx, abci.RequestEndBlock{Height: block.Height})
  350. if err != nil {
  351. logger.Error("error in proxyAppConn.EndBlock", "err", err)
  352. return nil, err
  353. }
  354. logger.Info("executed block", "height", block.Height, "num_valid_txs", validTxs, "num_invalid_txs", invalidTxs)
  355. return abciResponses, nil
  356. }
  357. func getBeginBlockValidatorInfo(block *types.Block, store Store,
  358. initialHeight int64) abci.LastCommitInfo {
  359. voteInfos := make([]abci.VoteInfo, block.LastCommit.Size())
  360. // Initial block -> LastCommitInfo.Votes are empty.
  361. // Remember that the first LastCommit is intentionally empty, so it makes
  362. // sense for LastCommitInfo.Votes to also be empty.
  363. if block.Height > initialHeight {
  364. lastValSet, err := store.LoadValidators(block.Height - 1)
  365. if err != nil {
  366. panic(err)
  367. }
  368. // Sanity check that commit size matches validator set size - only applies
  369. // after first block.
  370. var (
  371. commitSize = block.LastCommit.Size()
  372. valSetLen = len(lastValSet.Validators)
  373. )
  374. if commitSize != valSetLen {
  375. panic(fmt.Sprintf(
  376. "commit size (%d) doesn't match valset length (%d) at height %d\n\n%v\n\n%v",
  377. commitSize, valSetLen, block.Height, block.LastCommit.Signatures, lastValSet.Validators,
  378. ))
  379. }
  380. for i, val := range lastValSet.Validators {
  381. commitSig := block.LastCommit.Signatures[i]
  382. voteInfos[i] = abci.VoteInfo{
  383. Validator: types.TM2PB.Validator(val),
  384. SignedLastBlock: !commitSig.Absent(),
  385. }
  386. }
  387. }
  388. return abci.LastCommitInfo{
  389. Round: block.LastCommit.Round,
  390. Votes: voteInfos,
  391. }
  392. }
  393. func validateValidatorUpdates(abciUpdates []abci.ValidatorUpdate,
  394. params types.ValidatorParams) error {
  395. for _, valUpdate := range abciUpdates {
  396. if valUpdate.GetPower() < 0 {
  397. return fmt.Errorf("voting power can't be negative %v", valUpdate)
  398. } else if valUpdate.GetPower() == 0 {
  399. // continue, since this is deleting the validator, and thus there is no
  400. // pubkey to check
  401. continue
  402. }
  403. // Check if validator's pubkey matches an ABCI type in the consensus params
  404. pk, err := encoding.PubKeyFromProto(valUpdate.PubKey)
  405. if err != nil {
  406. return err
  407. }
  408. if !params.IsValidPubkeyType(pk.Type()) {
  409. return fmt.Errorf("validator %v is using pubkey %s, which is unsupported for consensus",
  410. valUpdate, pk.Type())
  411. }
  412. }
  413. return nil
  414. }
  415. // updateState returns a new State updated according to the header and responses.
  416. func updateState(
  417. state State,
  418. blockID types.BlockID,
  419. header *types.Header,
  420. abciResponses *tmstate.ABCIResponses,
  421. validatorUpdates []*types.Validator,
  422. ) (State, error) {
  423. // Copy the valset so we can apply changes from EndBlock
  424. // and update s.LastValidators and s.Validators.
  425. nValSet := state.NextValidators.Copy()
  426. // Update the validator set with the latest abciResponses.
  427. lastHeightValsChanged := state.LastHeightValidatorsChanged
  428. if len(validatorUpdates) > 0 {
  429. err := nValSet.UpdateWithChangeSet(validatorUpdates)
  430. if err != nil {
  431. return state, fmt.Errorf("error changing validator set: %w", err)
  432. }
  433. // Change results from this height but only applies to the next next height.
  434. lastHeightValsChanged = header.Height + 1 + 1
  435. }
  436. // Update validator proposer priority and set state variables.
  437. nValSet.IncrementProposerPriority(1)
  438. // Update the params with the latest abciResponses.
  439. nextParams := state.ConsensusParams
  440. lastHeightParamsChanged := state.LastHeightConsensusParamsChanged
  441. if abciResponses.EndBlock.ConsensusParamUpdates != nil {
  442. // NOTE: must not mutate s.ConsensusParams
  443. nextParams = state.ConsensusParams.UpdateConsensusParams(abciResponses.EndBlock.ConsensusParamUpdates)
  444. err := nextParams.ValidateConsensusParams()
  445. if err != nil {
  446. return state, fmt.Errorf("error updating consensus params: %w", err)
  447. }
  448. state.Version.Consensus.App = nextParams.Version.AppVersion
  449. // Change results from this height but only applies to the next height.
  450. lastHeightParamsChanged = header.Height + 1
  451. }
  452. nextVersion := state.Version
  453. // NOTE: the AppHash and the VoteExtension has not been populated.
  454. // It will be filled on state.Save.
  455. return State{
  456. Version: nextVersion,
  457. ChainID: state.ChainID,
  458. InitialHeight: state.InitialHeight,
  459. LastBlockHeight: header.Height,
  460. LastBlockID: blockID,
  461. LastBlockTime: header.Time,
  462. NextValidators: nValSet,
  463. Validators: state.NextValidators.Copy(),
  464. LastValidators: state.Validators.Copy(),
  465. LastHeightValidatorsChanged: lastHeightValsChanged,
  466. ConsensusParams: nextParams,
  467. LastHeightConsensusParamsChanged: lastHeightParamsChanged,
  468. LastResultsHash: ABCIResponsesResultsHash(abciResponses),
  469. AppHash: nil,
  470. }, nil
  471. }
  472. // Fire NewBlock, NewBlockHeader.
  473. // Fire TxEvent for every tx.
  474. // NOTE: if Tendermint crashes before commit, some or all of these events may be published again.
  475. func fireEvents(
  476. ctx context.Context,
  477. logger log.Logger,
  478. eventBus types.BlockEventPublisher,
  479. block *types.Block,
  480. blockID types.BlockID,
  481. abciResponses *tmstate.ABCIResponses,
  482. validatorUpdates []*types.Validator,
  483. ) {
  484. if err := eventBus.PublishEventNewBlock(ctx, types.EventDataNewBlock{
  485. Block: block,
  486. BlockID: blockID,
  487. ResultBeginBlock: *abciResponses.BeginBlock,
  488. ResultEndBlock: *abciResponses.EndBlock,
  489. }); err != nil {
  490. logger.Error("failed publishing new block", "err", err)
  491. }
  492. if err := eventBus.PublishEventNewBlockHeader(ctx, types.EventDataNewBlockHeader{
  493. Header: block.Header,
  494. NumTxs: int64(len(block.Txs)),
  495. ResultBeginBlock: *abciResponses.BeginBlock,
  496. ResultEndBlock: *abciResponses.EndBlock,
  497. }); err != nil {
  498. logger.Error("failed publishing new block header", "err", err)
  499. }
  500. if len(block.Evidence.Evidence) != 0 {
  501. for _, ev := range block.Evidence.Evidence {
  502. if err := eventBus.PublishEventNewEvidence(ctx, types.EventDataNewEvidence{
  503. Evidence: ev,
  504. Height: block.Height,
  505. }); err != nil {
  506. logger.Error("failed publishing new evidence", "err", err)
  507. }
  508. }
  509. }
  510. for i, tx := range block.Data.Txs {
  511. if err := eventBus.PublishEventTx(ctx, types.EventDataTx{TxResult: abci.TxResult{
  512. Height: block.Height,
  513. Index: uint32(i),
  514. Tx: tx,
  515. Result: *(abciResponses.DeliverTxs[i]),
  516. }}); err != nil {
  517. logger.Error("failed publishing event TX", "err", err)
  518. }
  519. }
  520. if len(validatorUpdates) > 0 {
  521. if err := eventBus.PublishEventValidatorSetUpdates(ctx,
  522. types.EventDataValidatorSetUpdates{ValidatorUpdates: validatorUpdates}); err != nil {
  523. logger.Error("failed publishing event", "err", err)
  524. }
  525. }
  526. }
  527. //----------------------------------------------------------------------------------------------------
  528. // Execute block without state. TODO: eliminate
  529. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  530. // It returns the application root hash (result of abci.Commit).
  531. func ExecCommitBlock(
  532. ctx context.Context,
  533. be *BlockExecutor,
  534. appConnConsensus proxy.AppConnConsensus,
  535. block *types.Block,
  536. logger log.Logger,
  537. store Store,
  538. initialHeight int64,
  539. s State,
  540. ) ([]byte, error) {
  541. abciResponses, err := execBlockOnProxyApp(ctx, logger, appConnConsensus, block, store, initialHeight)
  542. if err != nil {
  543. logger.Error("failed executing block on proxy app", "height", block.Height, "err", err)
  544. return nil, err
  545. }
  546. // the BlockExecutor condition is using for the final block replay process.
  547. if be != nil {
  548. abciValUpdates := abciResponses.EndBlock.ValidatorUpdates
  549. err = validateValidatorUpdates(abciValUpdates, s.ConsensusParams.Validator)
  550. if err != nil {
  551. logger.Error("err", err)
  552. return nil, err
  553. }
  554. validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciValUpdates)
  555. if err != nil {
  556. logger.Error("err", err)
  557. return nil, err
  558. }
  559. bps, err := block.MakePartSet(types.BlockPartSizeBytes)
  560. if err != nil {
  561. return nil, err
  562. }
  563. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  564. fireEvents(ctx, be.logger, be.eventBus, block, blockID, abciResponses, validatorUpdates)
  565. }
  566. // Commit block, get hash back
  567. res, err := appConnConsensus.Commit(ctx)
  568. if err != nil {
  569. logger.Error("client error during proxyAppConn.Commit", "err", res)
  570. return nil, err
  571. }
  572. // ResponseCommit has no error or log, just data
  573. return res.Data, nil
  574. }
  575. func (blockExec *BlockExecutor) pruneBlocks(retainHeight int64) (uint64, error) {
  576. base := blockExec.blockStore.Base()
  577. if retainHeight <= base {
  578. return 0, nil
  579. }
  580. pruned, err := blockExec.blockStore.PruneBlocks(retainHeight)
  581. if err != nil {
  582. return 0, fmt.Errorf("failed to prune block store: %w", err)
  583. }
  584. err = blockExec.Store().PruneStates(retainHeight)
  585. if err != nil {
  586. return 0, fmt.Errorf("failed to prune state store: %w", err)
  587. }
  588. return pruned, nil
  589. }