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.

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