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.

402 lines
12 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)
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)
5 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
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>
4 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)
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>
4 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)
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)
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)
5 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>
4 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
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
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)
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>
4 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/ed25519"
  11. cryptoenc "github.com/tendermint/tendermint/crypto/encoding"
  12. "github.com/tendermint/tendermint/libs/log"
  13. mmock "github.com/tendermint/tendermint/mempool/mock"
  14. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  15. "github.com/tendermint/tendermint/proxy"
  16. sm "github.com/tendermint/tendermint/state"
  17. "github.com/tendermint/tendermint/state/mocks"
  18. "github.com/tendermint/tendermint/types"
  19. tmtime "github.com/tendermint/tendermint/types/time"
  20. )
  21. var (
  22. chainID = "execution_chain"
  23. testPartSize uint32 = 65536
  24. nTxsPerBlock = 10
  25. )
  26. func TestApplyBlock(t *testing.T) {
  27. app := &testApp{}
  28. cc := proxy.NewLocalClientCreator(app)
  29. proxyApp := proxy.NewAppConns(cc)
  30. err := proxyApp.Start()
  31. require.Nil(t, err)
  32. defer proxyApp.Stop() //nolint:errcheck // ignore for tests
  33. state, stateDB, _ := makeState(1, 1)
  34. stateStore := sm.NewStore(stateDB)
  35. blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyApp.Consensus(),
  36. mmock.Mempool{}, sm.EmptyEvidencePool{})
  37. block := makeBlock(state, 1)
  38. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
  39. state, retainHeight, err := blockExec.ApplyBlock(state, blockID, block)
  40. require.Nil(t, err)
  41. assert.EqualValues(t, retainHeight, 1)
  42. // TODO check state and mempool
  43. assert.EqualValues(t, 1, state.Version.Consensus.App, "App version wasn't updated")
  44. }
  45. // TestBeginBlockValidators ensures we send absent validators list.
  46. func TestBeginBlockValidators(t *testing.T) {
  47. app := &testApp{}
  48. cc := proxy.NewLocalClientCreator(app)
  49. proxyApp := proxy.NewAppConns(cc)
  50. err := proxyApp.Start()
  51. require.Nil(t, err)
  52. defer proxyApp.Stop() //nolint:errcheck // no need to check error again
  53. state, stateDB, _ := makeState(2, 2)
  54. stateStore := sm.NewStore(stateDB)
  55. prevHash := state.LastBlockID.Hash
  56. prevParts := types.PartSetHeader{}
  57. prevBlockID := types.BlockID{Hash: prevHash, PartSetHeader: prevParts}
  58. var (
  59. now = tmtime.Now()
  60. commitSig0 = types.NewCommitSigForBlock(
  61. []byte("Signature1"),
  62. state.Validators.Validators[0].Address,
  63. now)
  64. commitSig1 = types.NewCommitSigForBlock(
  65. []byte("Signature2"),
  66. state.Validators.Validators[1].Address,
  67. now)
  68. absentSig = types.NewCommitSigAbsent()
  69. )
  70. testCases := []struct {
  71. desc string
  72. lastCommitSigs []types.CommitSig
  73. expectedAbsentValidators []int
  74. }{
  75. {"none absent", []types.CommitSig{commitSig0, commitSig1}, []int{}},
  76. {"one absent", []types.CommitSig{commitSig0, absentSig}, []int{1}},
  77. {"multiple absent", []types.CommitSig{absentSig, absentSig}, []int{0, 1}},
  78. }
  79. for _, tc := range testCases {
  80. lastCommit := types.NewCommit(1, 0, prevBlockID, tc.lastCommitSigs)
  81. // block for height 2
  82. block, _ := state.MakeBlock(2, makeTxs(2), lastCommit, nil, state.Validators.GetProposer().Address)
  83. _, err = sm.ExecCommitBlock(proxyApp.Consensus(), block, log.TestingLogger(), stateStore, 1)
  84. require.Nil(t, err, tc.desc)
  85. // -> app receives a list of validators with a bool indicating if they signed
  86. ctr := 0
  87. for i, v := range app.CommitVotes {
  88. if ctr < len(tc.expectedAbsentValidators) &&
  89. tc.expectedAbsentValidators[ctr] == i {
  90. assert.False(t, v.SignedLastBlock)
  91. ctr++
  92. } else {
  93. assert.True(t, v.SignedLastBlock)
  94. }
  95. }
  96. }
  97. }
  98. // TestBeginBlockByzantineValidators ensures we send byzantine validators list.
  99. func TestBeginBlockByzantineValidators(t *testing.T) {
  100. app := &testApp{}
  101. cc := proxy.NewLocalClientCreator(app)
  102. proxyApp := proxy.NewAppConns(cc)
  103. err := proxyApp.Start()
  104. require.Nil(t, err)
  105. defer proxyApp.Stop() //nolint:errcheck // ignore for tests
  106. state, stateDB, _ := makeState(1, 1)
  107. stateStore := sm.NewStore(stateDB)
  108. defaultEvidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
  109. abciEv := []abci.Evidence{
  110. {
  111. Type: abci.EvidenceType_DUPLICATE_VOTE,
  112. Height: 3,
  113. Time: defaultEvidenceTime,
  114. Validator: types.TM2PB.Validator(state.Validators.Validators[0]),
  115. TotalVotingPower: 33,
  116. },
  117. {
  118. Type: abci.EvidenceType_LIGHT_CLIENT_ATTACK,
  119. Height: 8,
  120. Time: defaultEvidenceTime,
  121. Validator: types.TM2PB.Validator(state.Validators.Validators[0]),
  122. TotalVotingPower: 12,
  123. },
  124. }
  125. evpool := &mocks.EvidencePool{}
  126. evpool.On("ABCIEvidence", mock.AnythingOfType("int64"), mock.AnythingOfType("[]types.Evidence")).Return(abciEv)
  127. evpool.On("Update", mock.AnythingOfType("state.State")).Return()
  128. evpool.On("CheckEvidence", mock.AnythingOfType("types.EvidenceList")).Return(nil)
  129. blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyApp.Consensus(),
  130. mmock.Mempool{}, evpool)
  131. block := makeBlock(state, 1)
  132. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
  133. state, retainHeight, err := blockExec.ApplyBlock(state, blockID, block)
  134. require.Nil(t, err)
  135. assert.EqualValues(t, retainHeight, 1)
  136. // TODO check state and mempool
  137. assert.Equal(t, abciEv, app.ByzantineValidators)
  138. }
  139. func TestValidateValidatorUpdates(t *testing.T) {
  140. pubkey1 := ed25519.GenPrivKey().PubKey()
  141. pubkey2 := ed25519.GenPrivKey().PubKey()
  142. pk1, err := cryptoenc.PubKeyToProto(pubkey1)
  143. assert.NoError(t, err)
  144. pk2, err := cryptoenc.PubKeyToProto(pubkey2)
  145. assert.NoError(t, err)
  146. defaultValidatorParams := tmproto.ValidatorParams{PubKeyTypes: []string{types.ABCIPubKeyTypeEd25519}}
  147. testCases := []struct {
  148. name string
  149. abciUpdates []abci.ValidatorUpdate
  150. validatorParams tmproto.ValidatorParams
  151. shouldErr bool
  152. }{
  153. {
  154. "adding a validator is OK",
  155. []abci.ValidatorUpdate{{PubKey: pk2, Power: 20}},
  156. defaultValidatorParams,
  157. false,
  158. },
  159. {
  160. "updating a validator is OK",
  161. []abci.ValidatorUpdate{{PubKey: pk1, Power: 20}},
  162. defaultValidatorParams,
  163. false,
  164. },
  165. {
  166. "removing a validator is OK",
  167. []abci.ValidatorUpdate{{PubKey: pk2, Power: 0}},
  168. defaultValidatorParams,
  169. false,
  170. },
  171. {
  172. "adding a validator with negative power results in error",
  173. []abci.ValidatorUpdate{{PubKey: pk2, Power: -100}},
  174. defaultValidatorParams,
  175. true,
  176. },
  177. }
  178. for _, tc := range testCases {
  179. tc := tc
  180. t.Run(tc.name, func(t *testing.T) {
  181. err := sm.ValidateValidatorUpdates(tc.abciUpdates, tc.validatorParams)
  182. if tc.shouldErr {
  183. assert.Error(t, err)
  184. } else {
  185. assert.NoError(t, err)
  186. }
  187. })
  188. }
  189. }
  190. func TestUpdateValidators(t *testing.T) {
  191. pubkey1 := ed25519.GenPrivKey().PubKey()
  192. val1 := types.NewValidator(pubkey1, 10)
  193. pubkey2 := ed25519.GenPrivKey().PubKey()
  194. val2 := types.NewValidator(pubkey2, 20)
  195. pk, err := cryptoenc.PubKeyToProto(pubkey1)
  196. require.NoError(t, err)
  197. pk2, err := cryptoenc.PubKeyToProto(pubkey2)
  198. require.NoError(t, err)
  199. testCases := []struct {
  200. name string
  201. currentSet *types.ValidatorSet
  202. abciUpdates []abci.ValidatorUpdate
  203. resultingSet *types.ValidatorSet
  204. shouldErr bool
  205. }{
  206. {
  207. "adding a validator is OK",
  208. types.NewValidatorSet([]*types.Validator{val1}),
  209. []abci.ValidatorUpdate{{PubKey: pk2, Power: 20}},
  210. types.NewValidatorSet([]*types.Validator{val1, val2}),
  211. false,
  212. },
  213. {
  214. "updating a validator is OK",
  215. types.NewValidatorSet([]*types.Validator{val1}),
  216. []abci.ValidatorUpdate{{PubKey: pk, Power: 20}},
  217. types.NewValidatorSet([]*types.Validator{types.NewValidator(pubkey1, 20)}),
  218. false,
  219. },
  220. {
  221. "removing a validator is OK",
  222. types.NewValidatorSet([]*types.Validator{val1, val2}),
  223. []abci.ValidatorUpdate{{PubKey: pk2, Power: 0}},
  224. types.NewValidatorSet([]*types.Validator{val1}),
  225. false,
  226. },
  227. {
  228. "removing a non-existing validator results in error",
  229. types.NewValidatorSet([]*types.Validator{val1}),
  230. []abci.ValidatorUpdate{{PubKey: pk2, Power: 0}},
  231. types.NewValidatorSet([]*types.Validator{val1}),
  232. true,
  233. },
  234. }
  235. for _, tc := range testCases {
  236. tc := tc
  237. t.Run(tc.name, func(t *testing.T) {
  238. updates, err := types.PB2TM.ValidatorUpdates(tc.abciUpdates)
  239. assert.NoError(t, err)
  240. err = tc.currentSet.UpdateWithChangeSet(updates)
  241. if tc.shouldErr {
  242. assert.Error(t, err)
  243. } else {
  244. assert.NoError(t, err)
  245. require.Equal(t, tc.resultingSet.Size(), tc.currentSet.Size())
  246. assert.Equal(t, tc.resultingSet.TotalVotingPower(), tc.currentSet.TotalVotingPower())
  247. assert.Equal(t, tc.resultingSet.Validators[0].Address, tc.currentSet.Validators[0].Address)
  248. if tc.resultingSet.Size() > 1 {
  249. assert.Equal(t, tc.resultingSet.Validators[1].Address, tc.currentSet.Validators[1].Address)
  250. }
  251. }
  252. })
  253. }
  254. }
  255. // TestEndBlockValidatorUpdates ensures we update validator set and send an event.
  256. func TestEndBlockValidatorUpdates(t *testing.T) {
  257. app := &testApp{}
  258. cc := proxy.NewLocalClientCreator(app)
  259. proxyApp := proxy.NewAppConns(cc)
  260. err := proxyApp.Start()
  261. require.Nil(t, err)
  262. defer proxyApp.Stop() //nolint:errcheck // ignore for tests
  263. state, stateDB, _ := makeState(1, 1)
  264. stateStore := sm.NewStore(stateDB)
  265. blockExec := sm.NewBlockExecutor(
  266. stateStore,
  267. log.TestingLogger(),
  268. proxyApp.Consensus(),
  269. mmock.Mempool{},
  270. sm.EmptyEvidencePool{},
  271. )
  272. eventBus := types.NewEventBus()
  273. err = eventBus.Start()
  274. require.NoError(t, err)
  275. defer eventBus.Stop() //nolint:errcheck // ignore for tests
  276. blockExec.SetEventBus(eventBus)
  277. updatesSub, err := eventBus.Subscribe(
  278. context.Background(),
  279. "TestEndBlockValidatorUpdates",
  280. types.EventQueryValidatorSetUpdates,
  281. )
  282. require.NoError(t, err)
  283. block := makeBlock(state, 1)
  284. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
  285. pubkey := ed25519.GenPrivKey().PubKey()
  286. pk, err := cryptoenc.PubKeyToProto(pubkey)
  287. require.NoError(t, err)
  288. app.ValidatorUpdates = []abci.ValidatorUpdate{
  289. {PubKey: pk, Power: 10},
  290. }
  291. state, _, err = blockExec.ApplyBlock(state, blockID, block)
  292. require.Nil(t, err)
  293. // test new validator was added to NextValidators
  294. if assert.Equal(t, state.Validators.Size()+1, state.NextValidators.Size()) {
  295. idx, _ := state.NextValidators.GetByAddress(pubkey.Address())
  296. if idx < 0 {
  297. t.Fatalf("can't find address %v in the set %v", pubkey.Address(), state.NextValidators)
  298. }
  299. }
  300. // test we threw an event
  301. select {
  302. case msg := <-updatesSub.Out():
  303. event, ok := msg.Data().(types.EventDataValidatorSetUpdates)
  304. require.True(t, ok, "Expected event of type EventDataValidatorSetUpdates, got %T", msg.Data())
  305. if assert.NotEmpty(t, event.ValidatorUpdates) {
  306. assert.Equal(t, pubkey, event.ValidatorUpdates[0].PubKey)
  307. assert.EqualValues(t, 10, event.ValidatorUpdates[0].VotingPower)
  308. }
  309. case <-updatesSub.Cancelled():
  310. t.Fatalf("updatesSub was cancelled (reason: %v)", updatesSub.Err())
  311. case <-time.After(1 * time.Second):
  312. t.Fatal("Did not receive EventValidatorSetUpdates within 1 sec.")
  313. }
  314. }
  315. // TestEndBlockValidatorUpdatesResultingInEmptySet checks that processing validator updates that
  316. // would result in empty set causes no panic, an error is raised and NextValidators is not updated
  317. func TestEndBlockValidatorUpdatesResultingInEmptySet(t *testing.T) {
  318. app := &testApp{}
  319. cc := proxy.NewLocalClientCreator(app)
  320. proxyApp := proxy.NewAppConns(cc)
  321. err := proxyApp.Start()
  322. require.Nil(t, err)
  323. defer proxyApp.Stop() //nolint:errcheck // ignore for tests
  324. state, stateDB, _ := makeState(1, 1)
  325. stateStore := sm.NewStore(stateDB)
  326. blockExec := sm.NewBlockExecutor(
  327. stateStore,
  328. log.TestingLogger(),
  329. proxyApp.Consensus(),
  330. mmock.Mempool{},
  331. sm.EmptyEvidencePool{},
  332. )
  333. block := makeBlock(state, 1)
  334. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: block.MakePartSet(testPartSize).Header()}
  335. vp, err := cryptoenc.PubKeyToProto(state.Validators.Validators[0].PubKey)
  336. require.NoError(t, err)
  337. // Remove the only validator
  338. app.ValidatorUpdates = []abci.ValidatorUpdate{
  339. {PubKey: vp, Power: 0},
  340. }
  341. assert.NotPanics(t, func() { state, _, err = blockExec.ApplyBlock(state, blockID, block) })
  342. assert.NotNil(t, err)
  343. assert.NotEmpty(t, state.NextValidators.Validators)
  344. }