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.

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