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.

630 lines
19 KiB

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