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.

583 lines
18 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
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
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
3 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
3 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
3 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
3 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
3 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
3 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
3 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
3 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
3 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
3 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
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
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
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
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
3 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
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
6 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
3 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
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
  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. dbm "github.com/tendermint/tm-db"
  10. abciclient "github.com/tendermint/tendermint/abci/client"
  11. abci "github.com/tendermint/tendermint/abci/types"
  12. abcimocks "github.com/tendermint/tendermint/abci/types/mocks"
  13. "github.com/tendermint/tendermint/crypto"
  14. "github.com/tendermint/tendermint/crypto/ed25519"
  15. "github.com/tendermint/tendermint/crypto/encoding"
  16. "github.com/tendermint/tendermint/crypto/tmhash"
  17. "github.com/tendermint/tendermint/internal/eventbus"
  18. mmock "github.com/tendermint/tendermint/internal/mempool/mock"
  19. "github.com/tendermint/tendermint/internal/proxy"
  20. "github.com/tendermint/tendermint/internal/pubsub"
  21. sm "github.com/tendermint/tendermint/internal/state"
  22. "github.com/tendermint/tendermint/internal/state/mocks"
  23. sf "github.com/tendermint/tendermint/internal/state/test/factory"
  24. "github.com/tendermint/tendermint/internal/store"
  25. "github.com/tendermint/tendermint/internal/test/factory"
  26. "github.com/tendermint/tendermint/libs/log"
  27. "github.com/tendermint/tendermint/types"
  28. "github.com/tendermint/tendermint/version"
  29. )
  30. var (
  31. chainID = "execution_chain"
  32. testPartSize uint32 = 65536
  33. )
  34. func TestApplyBlock(t *testing.T) {
  35. app := &testApp{}
  36. logger := log.TestingLogger()
  37. cc := abciclient.NewLocalClient(logger, app)
  38. proxyApp := proxy.New(cc, logger, proxy.NopMetrics())
  39. ctx, cancel := context.WithCancel(context.Background())
  40. defer cancel()
  41. require.NoError(t, proxyApp.Start(ctx))
  42. eventBus := eventbus.NewDefault(logger)
  43. require.NoError(t, eventBus.Start(ctx))
  44. state, stateDB, _ := makeState(t, 1, 1)
  45. stateStore := sm.NewStore(stateDB)
  46. blockStore := store.NewBlockStore(dbm.NewMemDB())
  47. blockExec := sm.NewBlockExecutor(stateStore, logger, proxyApp, mmock.Mempool{}, sm.EmptyEvidencePool{}, blockStore, eventBus)
  48. block, err := sf.MakeBlock(state, 1, new(types.Commit))
  49. require.NoError(t, err)
  50. bps, err := block.MakePartSet(testPartSize)
  51. require.NoError(t, err)
  52. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  53. state, err = blockExec.ApplyBlock(ctx, state, blockID, block)
  54. require.NoError(t, err)
  55. // TODO check state and mempool
  56. assert.EqualValues(t, 1, state.Version.Consensus.App, "App version wasn't updated")
  57. }
  58. // TestFinalizeBlockDecidedLastCommit ensures we correctly send the DecidedLastCommit to the
  59. // application. The test ensures that the DecidedLastCommit properly reflects
  60. // which validators signed the preceding block.
  61. func TestFinalizeBlockDecidedLastCommit(t *testing.T) {
  62. ctx, cancel := context.WithCancel(context.Background())
  63. defer cancel()
  64. logger := log.TestingLogger()
  65. app := &testApp{}
  66. cc := abciclient.NewLocalClient(logger, app)
  67. appClient := proxy.New(cc, logger, proxy.NopMetrics())
  68. err := appClient.Start(ctx)
  69. require.NoError(t, err)
  70. state, stateDB, privVals := makeState(t, 7, 1)
  71. stateStore := sm.NewStore(stateDB)
  72. absentSig := types.NewCommitSigAbsent()
  73. testCases := []struct {
  74. name string
  75. absentCommitSigs map[int]bool
  76. }{
  77. {"none absent", map[int]bool{}},
  78. {"one absent", map[int]bool{1: true}},
  79. {"multiple absent", map[int]bool{1: true, 3: true}},
  80. }
  81. for _, tc := range testCases {
  82. t.Run(tc.name, func(t *testing.T) {
  83. blockStore := store.NewBlockStore(dbm.NewMemDB())
  84. evpool := &mocks.EvidencePool{}
  85. evpool.On("PendingEvidence", mock.Anything).Return([]types.Evidence{}, 0)
  86. evpool.On("Update", ctx, mock.Anything, mock.Anything).Return()
  87. evpool.On("CheckEvidence", ctx, mock.Anything).Return(nil)
  88. eventBus := eventbus.NewDefault(logger)
  89. require.NoError(t, eventBus.Start(ctx))
  90. blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), appClient, mmock.Mempool{}, evpool, blockStore, eventBus)
  91. state, _, lastCommit := makeAndCommitGoodBlock(ctx, t, state, 1, new(types.Commit), state.NextValidators.Validators[0].Address, blockExec, privVals, nil)
  92. for idx, isAbsent := range tc.absentCommitSigs {
  93. if isAbsent {
  94. lastCommit.Signatures[idx] = absentSig
  95. }
  96. }
  97. // block for height 2
  98. block, err := sf.MakeBlock(state, 2, lastCommit)
  99. require.NoError(t, err)
  100. bps, err := block.MakePartSet(testPartSize)
  101. require.NoError(t, err)
  102. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  103. _, err = blockExec.ApplyBlock(ctx, state, blockID, block)
  104. require.NoError(t, err)
  105. // -> app receives a list of validators with a bool indicating if they signed
  106. for i, v := range app.CommitVotes {
  107. _, absent := tc.absentCommitSigs[i]
  108. assert.Equal(t, !absent, v.SignedLastBlock)
  109. }
  110. })
  111. }
  112. }
  113. // TestFinalizeBlockByzantineValidators ensures we send byzantine validators list.
  114. func TestFinalizeBlockByzantineValidators(t *testing.T) {
  115. ctx, cancel := context.WithCancel(context.Background())
  116. defer cancel()
  117. app := &testApp{}
  118. logger := log.TestingLogger()
  119. cc := abciclient.NewLocalClient(logger, app)
  120. proxyApp := proxy.New(cc, logger, proxy.NopMetrics())
  121. err := proxyApp.Start(ctx)
  122. require.NoError(t, err)
  123. state, stateDB, privVals := makeState(t, 1, 1)
  124. stateStore := sm.NewStore(stateDB)
  125. defaultEvidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
  126. privVal := privVals[state.Validators.Validators[0].Address.String()]
  127. blockID := makeBlockID([]byte("headerhash"), 1000, []byte("partshash"))
  128. header := &types.Header{
  129. Version: version.Consensus{Block: version.BlockProtocol, App: 1},
  130. ChainID: state.ChainID,
  131. Height: 10,
  132. Time: defaultEvidenceTime,
  133. LastBlockID: blockID,
  134. LastCommitHash: crypto.CRandBytes(tmhash.Size),
  135. DataHash: crypto.CRandBytes(tmhash.Size),
  136. ValidatorsHash: state.Validators.Hash(),
  137. NextValidatorsHash: state.Validators.Hash(),
  138. ConsensusHash: crypto.CRandBytes(tmhash.Size),
  139. AppHash: crypto.CRandBytes(tmhash.Size),
  140. LastResultsHash: crypto.CRandBytes(tmhash.Size),
  141. EvidenceHash: crypto.CRandBytes(tmhash.Size),
  142. ProposerAddress: crypto.CRandBytes(crypto.AddressSize),
  143. }
  144. // we don't need to worry about validating the evidence as long as they pass validate basic
  145. dve, err := types.NewMockDuplicateVoteEvidenceWithValidator(ctx, 3, defaultEvidenceTime, privVal, state.ChainID)
  146. require.NoError(t, err)
  147. dve.ValidatorPower = 1000
  148. lcae := &types.LightClientAttackEvidence{
  149. ConflictingBlock: &types.LightBlock{
  150. SignedHeader: &types.SignedHeader{
  151. Header: header,
  152. Commit: types.NewCommit(10, 0, makeBlockID(header.Hash(), 100, []byte("partshash")), []types.CommitSig{{
  153. BlockIDFlag: types.BlockIDFlagNil,
  154. ValidatorAddress: crypto.AddressHash([]byte("validator_address")),
  155. Timestamp: defaultEvidenceTime,
  156. Signature: crypto.CRandBytes(types.MaxSignatureSize),
  157. }}),
  158. },
  159. ValidatorSet: state.Validators,
  160. },
  161. CommonHeight: 8,
  162. ByzantineValidators: []*types.Validator{state.Validators.Validators[0]},
  163. TotalVotingPower: 12,
  164. Timestamp: defaultEvidenceTime,
  165. }
  166. ev := []types.Evidence{dve, lcae}
  167. abciEv := []abci.Evidence{
  168. {
  169. Type: abci.EvidenceType_DUPLICATE_VOTE,
  170. Height: 3,
  171. Time: defaultEvidenceTime,
  172. Validator: types.TM2PB.Validator(state.Validators.Validators[0]),
  173. TotalVotingPower: 10,
  174. },
  175. {
  176. Type: abci.EvidenceType_LIGHT_CLIENT_ATTACK,
  177. Height: 8,
  178. Time: defaultEvidenceTime,
  179. Validator: types.TM2PB.Validator(state.Validators.Validators[0]),
  180. TotalVotingPower: 12,
  181. },
  182. }
  183. evpool := &mocks.EvidencePool{}
  184. evpool.On("PendingEvidence", mock.AnythingOfType("int64")).Return(ev, int64(100))
  185. evpool.On("Update", ctx, mock.AnythingOfType("state.State"), mock.AnythingOfType("types.EvidenceList")).Return()
  186. evpool.On("CheckEvidence", ctx, mock.AnythingOfType("types.EvidenceList")).Return(nil)
  187. eventBus := eventbus.NewDefault(logger)
  188. require.NoError(t, eventBus.Start(ctx))
  189. blockStore := store.NewBlockStore(dbm.NewMemDB())
  190. blockExec := sm.NewBlockExecutor(stateStore, log.TestingLogger(), proxyApp,
  191. mmock.Mempool{}, evpool, blockStore, eventBus)
  192. block, err := sf.MakeBlock(state, 1, new(types.Commit))
  193. require.NoError(t, err)
  194. block.Evidence = ev
  195. block.Header.EvidenceHash = block.Evidence.Hash()
  196. bps, err := block.MakePartSet(testPartSize)
  197. require.NoError(t, err)
  198. blockID = types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  199. _, err = blockExec.ApplyBlock(ctx, state, blockID, block)
  200. require.NoError(t, err)
  201. // TODO check state and mempool
  202. assert.Equal(t, abciEv, app.ByzantineValidators)
  203. }
  204. func TestProcessProposal(t *testing.T) {
  205. const height = 2
  206. txs := factory.MakeTenTxs(height)
  207. ctx, cancel := context.WithCancel(context.Background())
  208. defer cancel()
  209. app := abcimocks.NewBaseMock()
  210. logger := log.TestingLogger()
  211. cc := abciclient.NewLocalClient(logger, app)
  212. proxyApp := proxy.New(cc, logger, proxy.NopMetrics())
  213. err := proxyApp.Start(ctx)
  214. require.NoError(t, err)
  215. state, stateDB, privVals := makeState(t, 1, height)
  216. stateStore := sm.NewStore(stateDB)
  217. blockStore := store.NewBlockStore(dbm.NewMemDB())
  218. eventBus := eventbus.NewDefault(logger)
  219. require.NoError(t, eventBus.Start(ctx))
  220. blockExec := sm.NewBlockExecutor(
  221. stateStore,
  222. logger,
  223. proxyApp,
  224. mmock.Mempool{},
  225. sm.EmptyEvidencePool{},
  226. blockStore,
  227. eventBus,
  228. )
  229. block0, err := sf.MakeBlock(state, height-1, new(types.Commit))
  230. require.NoError(t, err)
  231. lastCommitSig := []types.CommitSig{}
  232. partSet, err := block0.MakePartSet(types.BlockPartSizeBytes)
  233. require.NoError(t, err)
  234. blockID := types.BlockID{Hash: block0.Hash(), PartSetHeader: partSet.Header()}
  235. voteInfos := []abci.VoteInfo{}
  236. for _, privVal := range privVals {
  237. vote, err := factory.MakeVote(ctx, privVal, block0.Header.ChainID, 0, 0, 0, 2, blockID, time.Now())
  238. require.NoError(t, err)
  239. pk, err := privVal.GetPubKey(ctx)
  240. require.NoError(t, err)
  241. addr := pk.Address()
  242. voteInfos = append(voteInfos,
  243. abci.VoteInfo{
  244. SignedLastBlock: true,
  245. Validator: abci.Validator{
  246. Address: addr,
  247. Power: 1000,
  248. },
  249. })
  250. lastCommitSig = append(lastCommitSig, vote.CommitSig())
  251. }
  252. lastCommit := types.NewCommit(height-1, 0, types.BlockID{}, lastCommitSig)
  253. block1, err := sf.MakeBlock(state, height, lastCommit)
  254. require.NoError(t, err)
  255. block1.Txs = txs
  256. expectedRpp := abci.RequestProcessProposal{
  257. Hash: block1.Hash(),
  258. Header: *block1.Header.ToProto(),
  259. Txs: block1.Txs.ToSliceOfBytes(),
  260. ByzantineValidators: block1.Evidence.ToABCI(),
  261. ProposedLastCommit: abci.CommitInfo{
  262. Round: 0,
  263. Votes: voteInfos,
  264. },
  265. }
  266. app.On("ProcessProposal", mock.Anything).Return(abci.ResponseProcessProposal{Accept: true})
  267. acceptBlock, err := blockExec.ProcessProposal(ctx, block1, state)
  268. require.NoError(t, err)
  269. require.True(t, acceptBlock)
  270. app.AssertExpectations(t)
  271. app.AssertCalled(t, "ProcessProposal", expectedRpp)
  272. }
  273. func TestValidateValidatorUpdates(t *testing.T) {
  274. pubkey1 := ed25519.GenPrivKey().PubKey()
  275. pubkey2 := ed25519.GenPrivKey().PubKey()
  276. pk1, err := encoding.PubKeyToProto(pubkey1)
  277. assert.NoError(t, err)
  278. pk2, err := encoding.PubKeyToProto(pubkey2)
  279. assert.NoError(t, err)
  280. defaultValidatorParams := types.ValidatorParams{PubKeyTypes: []string{types.ABCIPubKeyTypeEd25519}}
  281. testCases := []struct {
  282. name string
  283. abciUpdates []abci.ValidatorUpdate
  284. validatorParams types.ValidatorParams
  285. shouldErr bool
  286. }{
  287. {
  288. "adding a validator is OK",
  289. []abci.ValidatorUpdate{{PubKey: pk2, Power: 20}},
  290. defaultValidatorParams,
  291. false,
  292. },
  293. {
  294. "updating a validator is OK",
  295. []abci.ValidatorUpdate{{PubKey: pk1, Power: 20}},
  296. defaultValidatorParams,
  297. false,
  298. },
  299. {
  300. "removing a validator is OK",
  301. []abci.ValidatorUpdate{{PubKey: pk2, Power: 0}},
  302. defaultValidatorParams,
  303. false,
  304. },
  305. {
  306. "adding a validator with negative power results in error",
  307. []abci.ValidatorUpdate{{PubKey: pk2, Power: -100}},
  308. defaultValidatorParams,
  309. true,
  310. },
  311. }
  312. for _, tc := range testCases {
  313. tc := tc
  314. t.Run(tc.name, func(t *testing.T) {
  315. err := sm.ValidateValidatorUpdates(tc.abciUpdates, tc.validatorParams)
  316. if tc.shouldErr {
  317. assert.Error(t, err)
  318. } else {
  319. assert.NoError(t, err)
  320. }
  321. })
  322. }
  323. }
  324. func TestUpdateValidators(t *testing.T) {
  325. pubkey1 := ed25519.GenPrivKey().PubKey()
  326. val1 := types.NewValidator(pubkey1, 10)
  327. pubkey2 := ed25519.GenPrivKey().PubKey()
  328. val2 := types.NewValidator(pubkey2, 20)
  329. pk, err := encoding.PubKeyToProto(pubkey1)
  330. require.NoError(t, err)
  331. pk2, err := encoding.PubKeyToProto(pubkey2)
  332. require.NoError(t, err)
  333. testCases := []struct {
  334. name string
  335. currentSet *types.ValidatorSet
  336. abciUpdates []abci.ValidatorUpdate
  337. resultingSet *types.ValidatorSet
  338. shouldErr bool
  339. }{
  340. {
  341. "adding a validator is OK",
  342. types.NewValidatorSet([]*types.Validator{val1}),
  343. []abci.ValidatorUpdate{{PubKey: pk2, Power: 20}},
  344. types.NewValidatorSet([]*types.Validator{val1, val2}),
  345. false,
  346. },
  347. {
  348. "updating a validator is OK",
  349. types.NewValidatorSet([]*types.Validator{val1}),
  350. []abci.ValidatorUpdate{{PubKey: pk, Power: 20}},
  351. types.NewValidatorSet([]*types.Validator{types.NewValidator(pubkey1, 20)}),
  352. false,
  353. },
  354. {
  355. "removing a validator is OK",
  356. types.NewValidatorSet([]*types.Validator{val1, val2}),
  357. []abci.ValidatorUpdate{{PubKey: pk2, Power: 0}},
  358. types.NewValidatorSet([]*types.Validator{val1}),
  359. false,
  360. },
  361. {
  362. "removing a non-existing validator results in error",
  363. types.NewValidatorSet([]*types.Validator{val1}),
  364. []abci.ValidatorUpdate{{PubKey: pk2, Power: 0}},
  365. types.NewValidatorSet([]*types.Validator{val1}),
  366. true,
  367. },
  368. }
  369. for _, tc := range testCases {
  370. tc := tc
  371. t.Run(tc.name, func(t *testing.T) {
  372. updates, err := types.PB2TM.ValidatorUpdates(tc.abciUpdates)
  373. assert.NoError(t, err)
  374. err = tc.currentSet.UpdateWithChangeSet(updates)
  375. if tc.shouldErr {
  376. assert.Error(t, err)
  377. } else {
  378. assert.NoError(t, err)
  379. require.Equal(t, tc.resultingSet.Size(), tc.currentSet.Size())
  380. assert.Equal(t, tc.resultingSet.TotalVotingPower(), tc.currentSet.TotalVotingPower())
  381. assert.Equal(t, tc.resultingSet.Validators[0].Address, tc.currentSet.Validators[0].Address)
  382. if tc.resultingSet.Size() > 1 {
  383. assert.Equal(t, tc.resultingSet.Validators[1].Address, tc.currentSet.Validators[1].Address)
  384. }
  385. }
  386. })
  387. }
  388. }
  389. // TestFinalizeBlockValidatorUpdates ensures we update validator set and send an event.
  390. func TestFinalizeBlockValidatorUpdates(t *testing.T) {
  391. ctx, cancel := context.WithCancel(context.Background())
  392. defer cancel()
  393. app := &testApp{}
  394. logger := log.TestingLogger()
  395. cc := abciclient.NewLocalClient(logger, app)
  396. proxyApp := proxy.New(cc, logger, proxy.NopMetrics())
  397. err := proxyApp.Start(ctx)
  398. require.NoError(t, err)
  399. state, stateDB, _ := makeState(t, 1, 1)
  400. stateStore := sm.NewStore(stateDB)
  401. blockStore := store.NewBlockStore(dbm.NewMemDB())
  402. eventBus := eventbus.NewDefault(logger)
  403. require.NoError(t, eventBus.Start(ctx))
  404. blockExec := sm.NewBlockExecutor(
  405. stateStore,
  406. logger,
  407. proxyApp,
  408. mmock.Mempool{},
  409. sm.EmptyEvidencePool{},
  410. blockStore,
  411. eventBus,
  412. )
  413. updatesSub, err := eventBus.SubscribeWithArgs(ctx, pubsub.SubscribeArgs{
  414. ClientID: "TestFinalizeBlockValidatorUpdates",
  415. Query: types.EventQueryValidatorSetUpdates,
  416. })
  417. require.NoError(t, err)
  418. block, err := sf.MakeBlock(state, 1, new(types.Commit))
  419. require.NoError(t, err)
  420. bps, err := block.MakePartSet(testPartSize)
  421. require.NoError(t, err)
  422. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  423. pubkey := ed25519.GenPrivKey().PubKey()
  424. pk, err := encoding.PubKeyToProto(pubkey)
  425. require.NoError(t, err)
  426. app.ValidatorUpdates = []abci.ValidatorUpdate{
  427. {PubKey: pk, Power: 10},
  428. }
  429. state, err = blockExec.ApplyBlock(ctx, state, blockID, block)
  430. require.NoError(t, err)
  431. // test new validator was added to NextValidators
  432. if assert.Equal(t, state.Validators.Size()+1, state.NextValidators.Size()) {
  433. idx, _ := state.NextValidators.GetByAddress(pubkey.Address())
  434. if idx < 0 {
  435. t.Fatalf("can't find address %v in the set %v", pubkey.Address(), state.NextValidators)
  436. }
  437. }
  438. // test we threw an event
  439. ctx, cancel = context.WithTimeout(ctx, 1*time.Second)
  440. defer cancel()
  441. msg, err := updatesSub.Next(ctx)
  442. require.NoError(t, err)
  443. event, ok := msg.Data().(types.EventDataValidatorSetUpdates)
  444. require.True(t, ok, "Expected event of type EventDataValidatorSetUpdates, got %T", msg.Data())
  445. if assert.NotEmpty(t, event.ValidatorUpdates) {
  446. assert.Equal(t, pubkey, event.ValidatorUpdates[0].PubKey)
  447. assert.EqualValues(t, 10, event.ValidatorUpdates[0].VotingPower)
  448. }
  449. }
  450. // TestFinalizeBlockValidatorUpdatesResultingInEmptySet checks that processing validator updates that
  451. // would result in empty set causes no panic, an error is raised and NextValidators is not updated
  452. func TestFinalizeBlockValidatorUpdatesResultingInEmptySet(t *testing.T) {
  453. ctx, cancel := context.WithCancel(context.Background())
  454. defer cancel()
  455. app := &testApp{}
  456. logger := log.TestingLogger()
  457. cc := abciclient.NewLocalClient(logger, app)
  458. proxyApp := proxy.New(cc, logger, proxy.NopMetrics())
  459. err := proxyApp.Start(ctx)
  460. require.NoError(t, err)
  461. eventBus := eventbus.NewDefault(logger)
  462. require.NoError(t, eventBus.Start(ctx))
  463. state, stateDB, _ := makeState(t, 1, 1)
  464. stateStore := sm.NewStore(stateDB)
  465. blockStore := store.NewBlockStore(dbm.NewMemDB())
  466. blockExec := sm.NewBlockExecutor(
  467. stateStore,
  468. log.TestingLogger(),
  469. proxyApp,
  470. mmock.Mempool{},
  471. sm.EmptyEvidencePool{},
  472. blockStore,
  473. eventBus,
  474. )
  475. block, err := sf.MakeBlock(state, 1, new(types.Commit))
  476. require.NoError(t, err)
  477. bps, err := block.MakePartSet(testPartSize)
  478. require.NoError(t, err)
  479. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  480. vp, err := encoding.PubKeyToProto(state.Validators.Validators[0].PubKey)
  481. require.NoError(t, err)
  482. // Remove the only validator
  483. app.ValidatorUpdates = []abci.ValidatorUpdate{
  484. {PubKey: vp, Power: 0},
  485. }
  486. assert.NotPanics(t, func() { state, err = blockExec.ApplyBlock(ctx, state, blockID, block) })
  487. assert.Error(t, err)
  488. assert.NotEmpty(t, state.NextValidators.Validators)
  489. }
  490. func makeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) types.BlockID {
  491. var (
  492. h = make([]byte, tmhash.Size)
  493. psH = make([]byte, tmhash.Size)
  494. )
  495. copy(h, hash)
  496. copy(psH, partSetHash)
  497. return types.BlockID{
  498. Hash: h,
  499. PartSetHeader: types.PartSetHeader{
  500. Total: partSetSize,
  501. Hash: psH,
  502. },
  503. }
  504. }