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.

464 lines
14 KiB

state: add more tests for block validation (#3674) * Expose priv validators for use in testing * Generalize block header validation test past height 1 * Remove ineffectual assignment * Remove redundant SaveState call * Reorder comment for clarity * Use the block executor ApplyBlock function instead of implementing a stripped-down version of it * Remove commented-out code * Remove unnecessary test The required tests already appear to be implemented (implicitly) through the TestValidateBlockHeader test. * Allow for catching of specific error types during TestValidateBlockCommit * Make return error testable * Clean up and add TestValidateBlockCommit code * Fix formatting * Extract function to create a new mock test app * Update comment for clarity * Fix comment * Add skeleton code for evidence-related test * Allow for addressing priv val by address * Generalize test beyond a single validator * Generalize TestValidateBlockEvidence past first height * Reorder code to clearly separate tests and utility code * Use a common constant for stop height for testing in state/validation_test.go * Refactor errors to resemble existing conventions * Fix formatting * Extract common helper functions Having the tests littered with helper functions makes them less easily readable imho, so I've pulled them out into a separate file. This also makes it easier to see what helper functions are available during testing, so we minimize the chance of duplication when writing new tests. * Remove unused parameter * Remove unused parameters * Add field keys * Remove unused height constant * Fix typo * Fix incorrect return error * Add field keys * Use separate package for tests This refactors all of the state package's tests into a state_test package, so as to keep any usage of the state package's internal methods explicit. Any internal methods/constants used by tests are now explicitly exported in state/export_test.go * Refactor: extract helper function to make, validate, execute and commit a block * Rename state function to makeState * Remove redundant constant for number of validators * Refactor mock evidence registration into TestMain * Remove extraneous nVals variable * Replace function-level TODOs with file-level TODO and explanation * Remove extraneous comment * Fix linting issues brought up by GolangCI (pulled in from latest merge from develop)
6 years ago
state: add more tests for block validation (#3674) * Expose priv validators for use in testing * Generalize block header validation test past height 1 * Remove ineffectual assignment * Remove redundant SaveState call * Reorder comment for clarity * Use the block executor ApplyBlock function instead of implementing a stripped-down version of it * Remove commented-out code * Remove unnecessary test The required tests already appear to be implemented (implicitly) through the TestValidateBlockHeader test. * Allow for catching of specific error types during TestValidateBlockCommit * Make return error testable * Clean up and add TestValidateBlockCommit code * Fix formatting * Extract function to create a new mock test app * Update comment for clarity * Fix comment * Add skeleton code for evidence-related test * Allow for addressing priv val by address * Generalize test beyond a single validator * Generalize TestValidateBlockEvidence past first height * Reorder code to clearly separate tests and utility code * Use a common constant for stop height for testing in state/validation_test.go * Refactor errors to resemble existing conventions * Fix formatting * Extract common helper functions Having the tests littered with helper functions makes them less easily readable imho, so I've pulled them out into a separate file. This also makes it easier to see what helper functions are available during testing, so we minimize the chance of duplication when writing new tests. * Remove unused parameter * Remove unused parameters * Add field keys * Remove unused height constant * Fix typo * Fix incorrect return error * Add field keys * Use separate package for tests This refactors all of the state package's tests into a state_test package, so as to keep any usage of the state package's internal methods explicit. Any internal methods/constants used by tests are now explicitly exported in state/export_test.go * Refactor: extract helper function to make, validate, execute and commit a block * Rename state function to makeState * Remove redundant constant for number of validators * Refactor mock evidence registration into TestMain * Remove extraneous nVals variable * Replace function-level TODOs with file-level TODO and explanation * Remove extraneous comment * Fix linting issues brought up by GolangCI (pulled in from latest merge from develop)
6 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
state: add more tests for block validation (#3674) * Expose priv validators for use in testing * Generalize block header validation test past height 1 * Remove ineffectual assignment * Remove redundant SaveState call * Reorder comment for clarity * Use the block executor ApplyBlock function instead of implementing a stripped-down version of it * Remove commented-out code * Remove unnecessary test The required tests already appear to be implemented (implicitly) through the TestValidateBlockHeader test. * Allow for catching of specific error types during TestValidateBlockCommit * Make return error testable * Clean up and add TestValidateBlockCommit code * Fix formatting * Extract function to create a new mock test app * Update comment for clarity * Fix comment * Add skeleton code for evidence-related test * Allow for addressing priv val by address * Generalize test beyond a single validator * Generalize TestValidateBlockEvidence past first height * Reorder code to clearly separate tests and utility code * Use a common constant for stop height for testing in state/validation_test.go * Refactor errors to resemble existing conventions * Fix formatting * Extract common helper functions Having the tests littered with helper functions makes them less easily readable imho, so I've pulled them out into a separate file. This also makes it easier to see what helper functions are available during testing, so we minimize the chance of duplication when writing new tests. * Remove unused parameter * Remove unused parameters * Add field keys * Remove unused height constant * Fix typo * Fix incorrect return error * Add field keys * Use separate package for tests This refactors all of the state package's tests into a state_test package, so as to keep any usage of the state package's internal methods explicit. Any internal methods/constants used by tests are now explicitly exported in state/export_test.go * Refactor: extract helper function to make, validate, execute and commit a block * Rename state function to makeState * Remove redundant constant for number of validators * Refactor mock evidence registration into TestMain * Remove extraneous nVals variable * Replace function-level TODOs with file-level TODO and explanation * Remove extraneous comment * Fix linting issues brought up by GolangCI (pulled in from latest merge from develop)
6 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
state: add more tests for block validation (#3674) * Expose priv validators for use in testing * Generalize block header validation test past height 1 * Remove ineffectual assignment * Remove redundant SaveState call * Reorder comment for clarity * Use the block executor ApplyBlock function instead of implementing a stripped-down version of it * Remove commented-out code * Remove unnecessary test The required tests already appear to be implemented (implicitly) through the TestValidateBlockHeader test. * Allow for catching of specific error types during TestValidateBlockCommit * Make return error testable * Clean up and add TestValidateBlockCommit code * Fix formatting * Extract function to create a new mock test app * Update comment for clarity * Fix comment * Add skeleton code for evidence-related test * Allow for addressing priv val by address * Generalize test beyond a single validator * Generalize TestValidateBlockEvidence past first height * Reorder code to clearly separate tests and utility code * Use a common constant for stop height for testing in state/validation_test.go * Refactor errors to resemble existing conventions * Fix formatting * Extract common helper functions Having the tests littered with helper functions makes them less easily readable imho, so I've pulled them out into a separate file. This also makes it easier to see what helper functions are available during testing, so we minimize the chance of duplication when writing new tests. * Remove unused parameter * Remove unused parameters * Add field keys * Remove unused height constant * Fix typo * Fix incorrect return error * Add field keys * Use separate package for tests This refactors all of the state package's tests into a state_test package, so as to keep any usage of the state package's internal methods explicit. Any internal methods/constants used by tests are now explicitly exported in state/export_test.go * Refactor: extract helper function to make, validate, execute and commit a block * Rename state function to makeState * Remove redundant constant for number of validators * Refactor mock evidence registration into TestMain * Remove extraneous nVals variable * Replace function-level TODOs with file-level TODO and explanation * Remove extraneous comment * Fix linting issues brought up by GolangCI (pulled in from latest merge from develop)
6 years ago
state: add more tests for block validation (#3674) * Expose priv validators for use in testing * Generalize block header validation test past height 1 * Remove ineffectual assignment * Remove redundant SaveState call * Reorder comment for clarity * Use the block executor ApplyBlock function instead of implementing a stripped-down version of it * Remove commented-out code * Remove unnecessary test The required tests already appear to be implemented (implicitly) through the TestValidateBlockHeader test. * Allow for catching of specific error types during TestValidateBlockCommit * Make return error testable * Clean up and add TestValidateBlockCommit code * Fix formatting * Extract function to create a new mock test app * Update comment for clarity * Fix comment * Add skeleton code for evidence-related test * Allow for addressing priv val by address * Generalize test beyond a single validator * Generalize TestValidateBlockEvidence past first height * Reorder code to clearly separate tests and utility code * Use a common constant for stop height for testing in state/validation_test.go * Refactor errors to resemble existing conventions * Fix formatting * Extract common helper functions Having the tests littered with helper functions makes them less easily readable imho, so I've pulled them out into a separate file. This also makes it easier to see what helper functions are available during testing, so we minimize the chance of duplication when writing new tests. * Remove unused parameter * Remove unused parameters * Add field keys * Remove unused height constant * Fix typo * Fix incorrect return error * Add field keys * Use separate package for tests This refactors all of the state package's tests into a state_test package, so as to keep any usage of the state package's internal methods explicit. Any internal methods/constants used by tests are now explicitly exported in state/export_test.go * Refactor: extract helper function to make, validate, execute and commit a block * Rename state function to makeState * Remove redundant constant for number of validators * Refactor mock evidence registration into TestMain * Remove extraneous nVals variable * Replace function-level TODOs with file-level TODO and explanation * Remove extraneous comment * Fix linting issues brought up by GolangCI (pulled in from latest merge from develop)
6 years ago
state: add more tests for block validation (#3674) * Expose priv validators for use in testing * Generalize block header validation test past height 1 * Remove ineffectual assignment * Remove redundant SaveState call * Reorder comment for clarity * Use the block executor ApplyBlock function instead of implementing a stripped-down version of it * Remove commented-out code * Remove unnecessary test The required tests already appear to be implemented (implicitly) through the TestValidateBlockHeader test. * Allow for catching of specific error types during TestValidateBlockCommit * Make return error testable * Clean up and add TestValidateBlockCommit code * Fix formatting * Extract function to create a new mock test app * Update comment for clarity * Fix comment * Add skeleton code for evidence-related test * Allow for addressing priv val by address * Generalize test beyond a single validator * Generalize TestValidateBlockEvidence past first height * Reorder code to clearly separate tests and utility code * Use a common constant for stop height for testing in state/validation_test.go * Refactor errors to resemble existing conventions * Fix formatting * Extract common helper functions Having the tests littered with helper functions makes them less easily readable imho, so I've pulled them out into a separate file. This also makes it easier to see what helper functions are available during testing, so we minimize the chance of duplication when writing new tests. * Remove unused parameter * Remove unused parameters * Add field keys * Remove unused height constant * Fix typo * Fix incorrect return error * Add field keys * Use separate package for tests This refactors all of the state package's tests into a state_test package, so as to keep any usage of the state package's internal methods explicit. Any internal methods/constants used by tests are now explicitly exported in state/export_test.go * Refactor: extract helper function to make, validate, execute and commit a block * Rename state function to makeState * Remove redundant constant for number of validators * Refactor mock evidence registration into TestMain * Remove extraneous nVals variable * Replace function-level TODOs with file-level TODO and explanation * Remove extraneous comment * Fix linting issues brought up by GolangCI (pulled in from latest merge from develop)
6 years ago
6 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
pubsub 2.0 (#3227) * green pubsub tests :OK: * get rid of clientToQueryMap * Subscribe and SubscribeUnbuffered * start adapting other pkgs to new pubsub * nope * rename MsgAndTags to Message * remove TagMap it does not bring any additional benefits * bring back EventSubscriber * fix test * fix data race in TestStartNextHeightCorrectly ``` Write at 0x00c0001c7418 by goroutine 796: github.com/tendermint/tendermint/consensus.TestStartNextHeightCorrectly() /go/src/github.com/tendermint/tendermint/consensus/state_test.go:1296 +0xad testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Previous read at 0x00c0001c7418 by goroutine 858: github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1631 +0x1366 github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1476 +0x8f github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg() /go/src/github.com/tendermint/tendermint/consensus/state.go:667 +0xa1e github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:628 +0x794 Goroutine 796 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 testing.runTests.func1() /usr/local/go/src/testing/testing.go:1119 +0xa8 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 testing.runTests() /usr/local/go/src/testing/testing.go:1117 +0x4ee testing.(*M).Run() /usr/local/go/src/testing/testing.go:1034 +0x2ee main.main() _testmain.go:214 +0x332 Goroutine 858 (running) created at: github.com/tendermint/tendermint/consensus.(*ConsensusState).startRoutines() /go/src/github.com/tendermint/tendermint/consensus/state.go:334 +0x221 github.com/tendermint/tendermint/consensus.startTestRound() /go/src/github.com/tendermint/tendermint/consensus/common_test.go:122 +0x63 github.com/tendermint/tendermint/consensus.TestStateFullRound1() /go/src/github.com/tendermint/tendermint/consensus/state_test.go:255 +0x397 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ``` * fixes after my own review * fix formatting * wait 100ms before kicking a subscriber out + a test for indexer_service * fixes after my second review * no timeout * add changelog entries * fix merge conflicts * fix typos after Thane's review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * reformat code * rewrite indexer service in the attempt to fix failing test https://github.com/tendermint/tendermint/pull/3227/#issuecomment-462316527 * Revert "rewrite indexer service in the attempt to fix failing test" This reverts commit 0d9107a098230de7138abb1c201877c246e89ed1. * another attempt to fix indexer * fixes after Ethan's review * use unbuffered channel when indexing transactions Refs https://github.com/tendermint/tendermint/pull/3227#discussion_r258786716 * add a comment for EventBus#SubscribeUnbuffered * format code
6 years ago
state: add more tests for block validation (#3674) * Expose priv validators for use in testing * Generalize block header validation test past height 1 * Remove ineffectual assignment * Remove redundant SaveState call * Reorder comment for clarity * Use the block executor ApplyBlock function instead of implementing a stripped-down version of it * Remove commented-out code * Remove unnecessary test The required tests already appear to be implemented (implicitly) through the TestValidateBlockHeader test. * Allow for catching of specific error types during TestValidateBlockCommit * Make return error testable * Clean up and add TestValidateBlockCommit code * Fix formatting * Extract function to create a new mock test app * Update comment for clarity * Fix comment * Add skeleton code for evidence-related test * Allow for addressing priv val by address * Generalize test beyond a single validator * Generalize TestValidateBlockEvidence past first height * Reorder code to clearly separate tests and utility code * Use a common constant for stop height for testing in state/validation_test.go * Refactor errors to resemble existing conventions * Fix formatting * Extract common helper functions Having the tests littered with helper functions makes them less easily readable imho, so I've pulled them out into a separate file. This also makes it easier to see what helper functions are available during testing, so we minimize the chance of duplication when writing new tests. * Remove unused parameter * Remove unused parameters * Add field keys * Remove unused height constant * Fix typo * Fix incorrect return error * Add field keys * Use separate package for tests This refactors all of the state package's tests into a state_test package, so as to keep any usage of the state package's internal methods explicit. Any internal methods/constants used by tests are now explicitly exported in state/export_test.go * Refactor: extract helper function to make, validate, execute and commit a block * Rename state function to makeState * Remove redundant constant for number of validators * Refactor mock evidence registration into TestMain * Remove extraneous nVals variable * Replace function-level TODOs with file-level TODO and explanation * Remove extraneous comment * Fix linting issues brought up by GolangCI (pulled in from latest merge from develop)
6 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 years ago
  1. package state_test
  2. import (
  3. "context"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/assert"
  7. "github.com/stretchr/testify/mock"
  8. "github.com/stretchr/testify/require"
  9. abci "github.com/tendermint/tendermint/abci/types"
  10. "github.com/tendermint/tendermint/crypto"
  11. "github.com/tendermint/tendermint/crypto/ed25519"
  12. cryptoenc "github.com/tendermint/tendermint/crypto/encoding"
  13. "github.com/tendermint/tendermint/crypto/tmhash"
  14. mmock "github.com/tendermint/tendermint/internal/mempool/mock"
  15. "github.com/tendermint/tendermint/libs/log"
  16. "github.com/tendermint/tendermint/proxy"
  17. sm "github.com/tendermint/tendermint/state"
  18. "github.com/tendermint/tendermint/state/mocks"
  19. "github.com/tendermint/tendermint/types"
  20. tmtime "github.com/tendermint/tendermint/types/time"
  21. "github.com/tendermint/tendermint/version"
  22. )
  23. var (
  24. chainID = "execution_chain"
  25. testPartSize uint32 = 65536
  26. nTxsPerBlock = 10
  27. )
  28. func TestApplyBlock(t *testing.T) {
  29. app := &testApp{}
  30. cc := proxy.NewLocalClientCreator(app)
  31. proxyApp := proxy.NewAppConns(cc)
  32. err := proxyApp.Start()
  33. require.Nil(t, err)
  34. defer proxyApp.Stop() //nolint:errcheck // ignore for tests
  35. state, stateDB, _ := makeState(1, 1)
  36. stateStore := sm.NewStore(stateDB)
  37. blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyApp.Consensus(),
  38. mmock.Mempool{}, sm.EmptyEvidencePool{})
  39. block := makeBlock(state, 1)
  40. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
  41. state, retainHeight, err := blockExec.ApplyBlock(state, blockID, block)
  42. require.Nil(t, err)
  43. assert.EqualValues(t, retainHeight, 1)
  44. // TODO check state and mempool
  45. assert.EqualValues(t, 1, state.Version.Consensus.App, "App version wasn't updated")
  46. }
  47. // TestBeginBlockValidators ensures we send absent validators list.
  48. func TestBeginBlockValidators(t *testing.T) {
  49. app := &testApp{}
  50. cc := proxy.NewLocalClientCreator(app)
  51. proxyApp := proxy.NewAppConns(cc)
  52. err := proxyApp.Start()
  53. require.Nil(t, err)
  54. defer proxyApp.Stop() //nolint:errcheck // no need to check error again
  55. state, stateDB, _ := makeState(2, 2)
  56. stateStore := sm.NewStore(stateDB)
  57. prevHash := state.LastBlockID.Hash
  58. prevParts := types.PartSetHeader{}
  59. prevBlockID := types.BlockID{Hash: prevHash, PartSetHeader: prevParts}
  60. var (
  61. now = tmtime.Now()
  62. commitSig0 = types.NewCommitSigForBlock(
  63. []byte("Signature1"),
  64. state.Validators.Validators[0].Address,
  65. now)
  66. commitSig1 = types.NewCommitSigForBlock(
  67. []byte("Signature2"),
  68. state.Validators.Validators[1].Address,
  69. now)
  70. absentSig = types.NewCommitSigAbsent()
  71. )
  72. testCases := []struct {
  73. desc string
  74. lastCommitSigs []types.CommitSig
  75. expectedAbsentValidators []int
  76. }{
  77. {"none absent", []types.CommitSig{commitSig0, commitSig1}, []int{}},
  78. {"one absent", []types.CommitSig{commitSig0, absentSig}, []int{1}},
  79. {"multiple absent", []types.CommitSig{absentSig, absentSig}, []int{0, 1}},
  80. }
  81. for _, tc := range testCases {
  82. lastCommit := types.NewCommit(1, 0, prevBlockID, tc.lastCommitSigs)
  83. // block for height 2
  84. block, _ := state.MakeBlock(2, makeTxs(2), lastCommit, nil, state.Validators.GetProposer().Address)
  85. _, err = sm.ExecCommitBlock(nil, proxyApp.Consensus(), block, log.TestingLogger(), stateStore, 1, state)
  86. require.Nil(t, err, tc.desc)
  87. // -> app receives a list of validators with a bool indicating if they signed
  88. ctr := 0
  89. for i, v := range app.CommitVotes {
  90. if ctr < len(tc.expectedAbsentValidators) &&
  91. tc.expectedAbsentValidators[ctr] == i {
  92. assert.False(t, v.SignedLastBlock)
  93. ctr++
  94. } else {
  95. assert.True(t, v.SignedLastBlock)
  96. }
  97. }
  98. }
  99. }
  100. // TestBeginBlockByzantineValidators ensures we send byzantine validators list.
  101. func TestBeginBlockByzantineValidators(t *testing.T) {
  102. app := &testApp{}
  103. cc := proxy.NewLocalClientCreator(app)
  104. proxyApp := proxy.NewAppConns(cc)
  105. err := proxyApp.Start()
  106. require.Nil(t, err)
  107. defer proxyApp.Stop() //nolint:errcheck // ignore for tests
  108. state, stateDB, privVals := makeState(1, 1)
  109. stateStore := sm.NewStore(stateDB)
  110. defaultEvidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
  111. privVal := privVals[state.Validators.Validators[0].Address.String()]
  112. blockID := makeBlockID([]byte("headerhash"), 1000, []byte("partshash"))
  113. header := &types.Header{
  114. Version: version.Consensus{Block: version.BlockProtocol, App: 1},
  115. ChainID: state.ChainID,
  116. Height: 10,
  117. Time: defaultEvidenceTime,
  118. LastBlockID: blockID,
  119. LastCommitHash: crypto.CRandBytes(tmhash.Size),
  120. DataHash: crypto.CRandBytes(tmhash.Size),
  121. ValidatorsHash: state.Validators.Hash(),
  122. NextValidatorsHash: state.Validators.Hash(),
  123. ConsensusHash: crypto.CRandBytes(tmhash.Size),
  124. AppHash: crypto.CRandBytes(tmhash.Size),
  125. LastResultsHash: crypto.CRandBytes(tmhash.Size),
  126. EvidenceHash: crypto.CRandBytes(tmhash.Size),
  127. ProposerAddress: crypto.CRandBytes(crypto.AddressSize),
  128. }
  129. // we don't need to worry about validating the evidence as long as they pass validate basic
  130. dve := types.NewMockDuplicateVoteEvidenceWithValidator(3, defaultEvidenceTime, privVal, state.ChainID)
  131. dve.ValidatorPower = 1000
  132. lcae := &types.LightClientAttackEvidence{
  133. ConflictingBlock: &types.LightBlock{
  134. SignedHeader: &types.SignedHeader{
  135. Header: header,
  136. Commit: types.NewCommit(10, 0, makeBlockID(header.Hash(), 100, []byte("partshash")), []types.CommitSig{{
  137. BlockIDFlag: types.BlockIDFlagNil,
  138. ValidatorAddress: crypto.AddressHash([]byte("validator_address")),
  139. Timestamp: defaultEvidenceTime,
  140. Signature: crypto.CRandBytes(types.MaxSignatureSize),
  141. }}),
  142. },
  143. ValidatorSet: state.Validators,
  144. },
  145. CommonHeight: 8,
  146. ByzantineValidators: []*types.Validator{state.Validators.Validators[0]},
  147. TotalVotingPower: 12,
  148. Timestamp: defaultEvidenceTime,
  149. }
  150. ev := []types.Evidence{dve, lcae}
  151. abciEv := []abci.Evidence{
  152. {
  153. Type: abci.EvidenceType_DUPLICATE_VOTE,
  154. Height: 3,
  155. Time: defaultEvidenceTime,
  156. Validator: types.TM2PB.Validator(state.Validators.Validators[0]),
  157. TotalVotingPower: 10,
  158. },
  159. {
  160. Type: abci.EvidenceType_LIGHT_CLIENT_ATTACK,
  161. Height: 8,
  162. Time: defaultEvidenceTime,
  163. Validator: types.TM2PB.Validator(state.Validators.Validators[0]),
  164. TotalVotingPower: 12,
  165. },
  166. }
  167. evpool := &mocks.EvidencePool{}
  168. evpool.On("PendingEvidence", mock.AnythingOfType("int64")).Return(ev, int64(100))
  169. evpool.On("Update", mock.AnythingOfType("state.State"), mock.AnythingOfType("types.EvidenceList")).Return()
  170. evpool.On("CheckEvidence", mock.AnythingOfType("types.EvidenceList")).Return(nil)
  171. blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyApp.Consensus(),
  172. mmock.Mempool{}, evpool)
  173. block := makeBlock(state, 1)
  174. block.Evidence = types.EvidenceData{Evidence: ev}
  175. block.Header.EvidenceHash = block.Evidence.Hash()
  176. blockID = types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
  177. state, retainHeight, err := blockExec.ApplyBlock(state, blockID, block)
  178. require.Nil(t, err)
  179. assert.EqualValues(t, retainHeight, 1)
  180. // TODO check state and mempool
  181. assert.Equal(t, abciEv, app.ByzantineValidators)
  182. }
  183. func TestValidateValidatorUpdates(t *testing.T) {
  184. pubkey1 := ed25519.GenPrivKey().PubKey()
  185. pubkey2 := ed25519.GenPrivKey().PubKey()
  186. pk1, err := cryptoenc.PubKeyToProto(pubkey1)
  187. assert.NoError(t, err)
  188. pk2, err := cryptoenc.PubKeyToProto(pubkey2)
  189. assert.NoError(t, err)
  190. defaultValidatorParams := types.ValidatorParams{PubKeyTypes: []string{types.ABCIPubKeyTypeEd25519}}
  191. testCases := []struct {
  192. name string
  193. abciUpdates []abci.ValidatorUpdate
  194. validatorParams types.ValidatorParams
  195. shouldErr bool
  196. }{
  197. {
  198. "adding a validator is OK",
  199. []abci.ValidatorUpdate{{PubKey: pk2, Power: 20}},
  200. defaultValidatorParams,
  201. false,
  202. },
  203. {
  204. "updating a validator is OK",
  205. []abci.ValidatorUpdate{{PubKey: pk1, Power: 20}},
  206. defaultValidatorParams,
  207. false,
  208. },
  209. {
  210. "removing a validator is OK",
  211. []abci.ValidatorUpdate{{PubKey: pk2, Power: 0}},
  212. defaultValidatorParams,
  213. false,
  214. },
  215. {
  216. "adding a validator with negative power results in error",
  217. []abci.ValidatorUpdate{{PubKey: pk2, Power: -100}},
  218. defaultValidatorParams,
  219. true,
  220. },
  221. }
  222. for _, tc := range testCases {
  223. tc := tc
  224. t.Run(tc.name, func(t *testing.T) {
  225. err := sm.ValidateValidatorUpdates(tc.abciUpdates, tc.validatorParams)
  226. if tc.shouldErr {
  227. assert.Error(t, err)
  228. } else {
  229. assert.NoError(t, err)
  230. }
  231. })
  232. }
  233. }
  234. func TestUpdateValidators(t *testing.T) {
  235. pubkey1 := ed25519.GenPrivKey().PubKey()
  236. val1 := types.NewValidator(pubkey1, 10)
  237. pubkey2 := ed25519.GenPrivKey().PubKey()
  238. val2 := types.NewValidator(pubkey2, 20)
  239. pk, err := cryptoenc.PubKeyToProto(pubkey1)
  240. require.NoError(t, err)
  241. pk2, err := cryptoenc.PubKeyToProto(pubkey2)
  242. require.NoError(t, err)
  243. testCases := []struct {
  244. name string
  245. currentSet *types.ValidatorSet
  246. abciUpdates []abci.ValidatorUpdate
  247. resultingSet *types.ValidatorSet
  248. shouldErr bool
  249. }{
  250. {
  251. "adding a validator is OK",
  252. types.NewValidatorSet([]*types.Validator{val1}),
  253. []abci.ValidatorUpdate{{PubKey: pk2, Power: 20}},
  254. types.NewValidatorSet([]*types.Validator{val1, val2}),
  255. false,
  256. },
  257. {
  258. "updating a validator is OK",
  259. types.NewValidatorSet([]*types.Validator{val1}),
  260. []abci.ValidatorUpdate{{PubKey: pk, Power: 20}},
  261. types.NewValidatorSet([]*types.Validator{types.NewValidator(pubkey1, 20)}),
  262. false,
  263. },
  264. {
  265. "removing a validator is OK",
  266. types.NewValidatorSet([]*types.Validator{val1, val2}),
  267. []abci.ValidatorUpdate{{PubKey: pk2, Power: 0}},
  268. types.NewValidatorSet([]*types.Validator{val1}),
  269. false,
  270. },
  271. {
  272. "removing a non-existing validator results in error",
  273. types.NewValidatorSet([]*types.Validator{val1}),
  274. []abci.ValidatorUpdate{{PubKey: pk2, Power: 0}},
  275. types.NewValidatorSet([]*types.Validator{val1}),
  276. true,
  277. },
  278. }
  279. for _, tc := range testCases {
  280. tc := tc
  281. t.Run(tc.name, func(t *testing.T) {
  282. updates, err := types.PB2TM.ValidatorUpdates(tc.abciUpdates)
  283. assert.NoError(t, err)
  284. err = tc.currentSet.UpdateWithChangeSet(updates)
  285. if tc.shouldErr {
  286. assert.Error(t, err)
  287. } else {
  288. assert.NoError(t, err)
  289. require.Equal(t, tc.resultingSet.Size(), tc.currentSet.Size())
  290. assert.Equal(t, tc.resultingSet.TotalVotingPower(), tc.currentSet.TotalVotingPower())
  291. assert.Equal(t, tc.resultingSet.Validators[0].Address, tc.currentSet.Validators[0].Address)
  292. if tc.resultingSet.Size() > 1 {
  293. assert.Equal(t, tc.resultingSet.Validators[1].Address, tc.currentSet.Validators[1].Address)
  294. }
  295. }
  296. })
  297. }
  298. }
  299. // TestEndBlockValidatorUpdates ensures we update validator set and send an event.
  300. func TestEndBlockValidatorUpdates(t *testing.T) {
  301. app := &testApp{}
  302. cc := proxy.NewLocalClientCreator(app)
  303. proxyApp := proxy.NewAppConns(cc)
  304. err := proxyApp.Start()
  305. require.Nil(t, err)
  306. defer proxyApp.Stop() //nolint:errcheck // ignore for tests
  307. state, stateDB, _ := makeState(1, 1)
  308. stateStore := sm.NewStore(stateDB)
  309. blockExec := sm.NewBlockExecutor(
  310. stateStore,
  311. log.TestingLogger(),
  312. proxyApp.Consensus(),
  313. mmock.Mempool{},
  314. sm.EmptyEvidencePool{},
  315. )
  316. eventBus := types.NewEventBus()
  317. err = eventBus.Start()
  318. require.NoError(t, err)
  319. defer eventBus.Stop() //nolint:errcheck // ignore for tests
  320. blockExec.SetEventBus(eventBus)
  321. updatesSub, err := eventBus.Subscribe(
  322. context.Background(),
  323. "TestEndBlockValidatorUpdates",
  324. types.EventQueryValidatorSetUpdates,
  325. )
  326. require.NoError(t, err)
  327. block := makeBlock(state, 1)
  328. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
  329. pubkey := ed25519.GenPrivKey().PubKey()
  330. pk, err := cryptoenc.PubKeyToProto(pubkey)
  331. require.NoError(t, err)
  332. app.ValidatorUpdates = []abci.ValidatorUpdate{
  333. {PubKey: pk, Power: 10},
  334. }
  335. state, _, err = blockExec.ApplyBlock(state, blockID, block)
  336. require.Nil(t, err)
  337. // test new validator was added to NextValidators
  338. if assert.Equal(t, state.Validators.Size()+1, state.NextValidators.Size()) {
  339. idx, _ := state.NextValidators.GetByAddress(pubkey.Address())
  340. if idx < 0 {
  341. t.Fatalf("can't find address %v in the set %v", pubkey.Address(), state.NextValidators)
  342. }
  343. }
  344. // test we threw an event
  345. select {
  346. case msg := <-updatesSub.Out():
  347. event, ok := msg.Data().(types.EventDataValidatorSetUpdates)
  348. require.True(t, ok, "Expected event of type EventDataValidatorSetUpdates, got %T", msg.Data())
  349. if assert.NotEmpty(t, event.ValidatorUpdates) {
  350. assert.Equal(t, pubkey, event.ValidatorUpdates[0].PubKey)
  351. assert.EqualValues(t, 10, event.ValidatorUpdates[0].VotingPower)
  352. }
  353. case <-updatesSub.Canceled():
  354. t.Fatalf("updatesSub was canceled (reason: %v)", updatesSub.Err())
  355. case <-time.After(1 * time.Second):
  356. t.Fatal("Did not receive EventValidatorSetUpdates within 1 sec.")
  357. }
  358. }
  359. // TestEndBlockValidatorUpdatesResultingInEmptySet checks that processing validator updates that
  360. // would result in empty set causes no panic, an error is raised and NextValidators is not updated
  361. func TestEndBlockValidatorUpdatesResultingInEmptySet(t *testing.T) {
  362. app := &testApp{}
  363. cc := proxy.NewLocalClientCreator(app)
  364. proxyApp := proxy.NewAppConns(cc)
  365. err := proxyApp.Start()
  366. require.Nil(t, err)
  367. defer proxyApp.Stop() //nolint:errcheck // ignore for tests
  368. state, stateDB, _ := makeState(1, 1)
  369. stateStore := sm.NewStore(stateDB)
  370. blockExec := sm.NewBlockExecutor(
  371. stateStore,
  372. log.TestingLogger(),
  373. proxyApp.Consensus(),
  374. mmock.Mempool{},
  375. sm.EmptyEvidencePool{},
  376. )
  377. block := makeBlock(state, 1)
  378. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
  379. vp, err := cryptoenc.PubKeyToProto(state.Validators.Validators[0].PubKey)
  380. require.NoError(t, err)
  381. // Remove the only validator
  382. app.ValidatorUpdates = []abci.ValidatorUpdate{
  383. {PubKey: vp, Power: 0},
  384. }
  385. assert.NotPanics(t, func() { state, _, err = blockExec.ApplyBlock(state, blockID, block) })
  386. assert.NotNil(t, err)
  387. assert.NotEmpty(t, state.NextValidators.Validators)
  388. }
  389. func makeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) types.BlockID {
  390. var (
  391. h = make([]byte, tmhash.Size)
  392. psH = make([]byte, tmhash.Size)
  393. )
  394. copy(h, hash)
  395. copy(psH, partSetHash)
  396. return types.BlockID{
  397. Hash: h,
  398. PartSetHeader: types.PartSetHeader{
  399. Total: partSetSize,
  400. Hash: psH,
  401. },
  402. }
  403. }