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.

1174 lines
41 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
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
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
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
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
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
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: Refactor tagging events using list of lists (#3643) ## PR This PR introduces a fundamental breaking change to the structure of ABCI response and tx tags and the way they're processed. Namely, the SDK can support more complex and aggregated events for distribution and slashing. In addition, block responses can include duplicate keys in events. Implement new Event type. An event has a type and a list of KV pairs (ie. list-of-lists). Typical events may look like: "rewards": [{"amount": "5000uatom", "validator": "...", "recipient": "..."}] "sender": [{"address": "...", "balance": "100uatom"}] The events are indexed by {even.type}.{even.attribute[i].key}/.... In this case a client would subscribe or query for rewards.recipient='...' ABCI response types and related types now include Events []Event instead of Tags []cmn.KVPair. PubSub logic now publishes/matches against map[string][]string instead of map[string]string to support duplicate keys in response events (from #1385). A match is successful if the value is found in the slice of strings. closes: #1859 closes: #2905 ## Commits: * Implement Event ABCI type and updates responses to use events * Update messages_test.go * Update kvstore.go * Update event_bus.go * Update subscription.go * Update pubsub.go * Update kvstore.go * Update query logic to handle slice of strings in events * Update Empty#Matches and unit tests * Update pubsub logic * Update EventBus#Publish * Update kv tx indexer * Update godocs * Update ResultEvent to use slice of strings; update RPC * Update more tests * Update abci.md * Check for key in validateAndStringifyEvents * Fix KV indexer to skip empty keys * Fix linting errors * Update CHANGELOG_PENDING.md * Update docs/spec/abci/abci.md Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update abci/types/types.proto Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update docs/spec/abci/abci.md Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update libs/pubsub/query/query.go Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update match function to match if ANY value matches * Implement TestSubscribeDuplicateKeys * Update TestMatches to include multi-key test cases * Update events.go * Update Query interface godoc * Update match godoc * Add godoc for matchValue * DRY-up tx indexing * Return error from PublishWithEvents in EventBus#Publish * Update PublishEventNewBlockHeader to return an error * Fix build * Update events doc in ABCI * Update ABCI events godoc * Implement TestEventBusPublishEventTxDuplicateKeys * Update TestSubscribeDuplicateKeys to be table-driven * Remove mod file * Remove markdown from events godoc * Implement TestTxSearchDeprecatedIndexing test
6 years ago
abci: Refactor tagging events using list of lists (#3643) ## PR This PR introduces a fundamental breaking change to the structure of ABCI response and tx tags and the way they're processed. Namely, the SDK can support more complex and aggregated events for distribution and slashing. In addition, block responses can include duplicate keys in events. Implement new Event type. An event has a type and a list of KV pairs (ie. list-of-lists). Typical events may look like: "rewards": [{"amount": "5000uatom", "validator": "...", "recipient": "..."}] "sender": [{"address": "...", "balance": "100uatom"}] The events are indexed by {even.type}.{even.attribute[i].key}/.... In this case a client would subscribe or query for rewards.recipient='...' ABCI response types and related types now include Events []Event instead of Tags []cmn.KVPair. PubSub logic now publishes/matches against map[string][]string instead of map[string]string to support duplicate keys in response events (from #1385). A match is successful if the value is found in the slice of strings. closes: #1859 closes: #2905 ## Commits: * Implement Event ABCI type and updates responses to use events * Update messages_test.go * Update kvstore.go * Update event_bus.go * Update subscription.go * Update pubsub.go * Update kvstore.go * Update query logic to handle slice of strings in events * Update Empty#Matches and unit tests * Update pubsub logic * Update EventBus#Publish * Update kv tx indexer * Update godocs * Update ResultEvent to use slice of strings; update RPC * Update more tests * Update abci.md * Check for key in validateAndStringifyEvents * Fix KV indexer to skip empty keys * Fix linting errors * Update CHANGELOG_PENDING.md * Update docs/spec/abci/abci.md Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com> * Update abci/types/types.proto Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update docs/spec/abci/abci.md Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update libs/pubsub/query/query.go Co-Authored-By: Ethan Buchman <ethan@coinculture.info> * Update match function to match if ANY value matches * Implement TestSubscribeDuplicateKeys * Update TestMatches to include multi-key test cases * Update events.go * Update Query interface godoc * Update match godoc * Add godoc for matchValue * DRY-up tx indexing * Return error from PublishWithEvents in EventBus#Publish * Update PublishEventNewBlockHeader to return an error * Fix build * Update events doc in ABCI * Update ABCI events godoc * Implement TestEventBusPublishEventTxDuplicateKeys * Update TestSubscribeDuplicateKeys to be table-driven * Remove mod file * Remove markdown from events godoc * Implement TestTxSearchDeprecatedIndexing test
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
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
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
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
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
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
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
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
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
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
Normalize priorities to not exceed total voting power (#3049) * more proposer priority tests - test that we don't reset to zero when updating / adding - test that same power validators alternate * add another test to track / simulate similar behaviour as in #2960 * address some of Chris' review comments * address some more of Chris' review comments * temporarily pushing branch with the following changes: The total power might change if: - a validator is added - a validator is removed - a validator is updated Decrement the accums (of all validators) directly after any of these events (by the inverse of the change) * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * Fix 2960 by re-normalizing / scaling priorities to be in bounds of total power, additionally: - remove heap where it doesn't make sense - avg. only at the end of IncrementProposerPriority instead of each iteration - update (and slightly improve) TestAveragingInIncrementProposerPriorityWithVotingPower to reflect above changes * fix tests * add comment * update changelog pending & some minor changes * comment about division will floor the result & fix typo * Update TestLargeGenesisValidator: - remove TODO and increase large genesis validator's voting power accordingly * move changelog entry to P2P Protocol * Ceil instead of flooring when dividing & update test * quickly fix failing TestProposerPriorityDoesNotGetResetToZero: - divide by Ceil((maxPriority - minPriority) / 2*totalVotingPower) * fix typo: rename getValWitMostPriority -> getValWithMostPriority * test proposer frequencies * return absolute value for diff. keep testing * use for loop for div * cleanup, more tests * spellcheck * get rid of using floats: manually ceil where necessary * Remove float, simplify, fix tests to match chris's proof (#3157)
6 years ago
  1. package state_test
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "math"
  7. "math/big"
  8. mrand "math/rand"
  9. "os"
  10. "testing"
  11. "github.com/stretchr/testify/assert"
  12. "github.com/stretchr/testify/require"
  13. dbm "github.com/tendermint/tm-db"
  14. abci "github.com/tendermint/tendermint/abci/types"
  15. "github.com/tendermint/tendermint/config"
  16. "github.com/tendermint/tendermint/crypto/ed25519"
  17. "github.com/tendermint/tendermint/crypto/encoding"
  18. "github.com/tendermint/tendermint/crypto/merkle"
  19. sm "github.com/tendermint/tendermint/internal/state"
  20. statefactory "github.com/tendermint/tendermint/internal/state/test/factory"
  21. tmstate "github.com/tendermint/tendermint/proto/tendermint/state"
  22. "github.com/tendermint/tendermint/types"
  23. )
  24. // setupTestCase does setup common to all test cases.
  25. func setupTestCase(t *testing.T) (func(t *testing.T), dbm.DB, sm.State) {
  26. cfg, err := config.ResetTestRoot(t.TempDir(), "state_")
  27. require.NoError(t, err)
  28. dbType := dbm.BackendType(cfg.DBBackend)
  29. stateDB, err := dbm.NewDB("state", dbType, cfg.DBDir())
  30. require.NoError(t, err)
  31. stateStore := sm.NewStore(stateDB)
  32. state, err := stateStore.Load()
  33. require.NoError(t, err)
  34. require.Empty(t, state)
  35. state, err = sm.MakeGenesisStateFromFile(cfg.GenesisFile())
  36. assert.NoError(t, err)
  37. assert.NotNil(t, state)
  38. err = stateStore.Save(state)
  39. require.NoError(t, err)
  40. tearDown := func(t *testing.T) { os.RemoveAll(cfg.RootDir) }
  41. return tearDown, stateDB, state
  42. }
  43. // TestStateCopy tests the correct copying behavior of State.
  44. func TestStateCopy(t *testing.T) {
  45. tearDown, _, state := setupTestCase(t)
  46. defer tearDown(t)
  47. stateCopy := state.Copy()
  48. seq, err := state.Equals(stateCopy)
  49. require.NoError(t, err)
  50. assert.True(t, seq,
  51. "expected state and its copy to be identical.\ngot: %v\nexpected: %v",
  52. stateCopy, state)
  53. stateCopy.LastBlockHeight++
  54. stateCopy.LastValidators = state.Validators
  55. seq, err = state.Equals(stateCopy)
  56. require.NoError(t, err)
  57. assert.False(t, seq, "expected states to be different. got same %v", state)
  58. }
  59. // TestMakeGenesisStateNilValidators tests state's consistency when genesis file's validators field is nil.
  60. func TestMakeGenesisStateNilValidators(t *testing.T) {
  61. doc := types.GenesisDoc{
  62. ChainID: "dummy",
  63. Validators: nil,
  64. }
  65. require.Nil(t, doc.ValidateAndComplete())
  66. state, err := sm.MakeGenesisState(&doc)
  67. require.NoError(t, err)
  68. require.Equal(t, 0, len(state.Validators.Validators))
  69. require.Equal(t, 0, len(state.NextValidators.Validators))
  70. }
  71. // TestStateSaveLoad tests saving and loading State from a db.
  72. func TestStateSaveLoad(t *testing.T) {
  73. tearDown, stateDB, state := setupTestCase(t)
  74. defer tearDown(t)
  75. stateStore := sm.NewStore(stateDB)
  76. state.LastBlockHeight++
  77. state.LastValidators = state.Validators
  78. err := stateStore.Save(state)
  79. require.NoError(t, err)
  80. loadedState, err := stateStore.Load()
  81. require.NoError(t, err)
  82. seq, err := state.Equals(loadedState)
  83. require.NoError(t, err)
  84. assert.True(t, seq,
  85. "expected state and its copy to be identical.\ngot: %v\nexpected: %v",
  86. loadedState, state)
  87. }
  88. // TestABCIResponsesSaveLoad tests saving and loading ABCIResponses.
  89. func TestABCIResponsesSaveLoad1(t *testing.T) {
  90. tearDown, stateDB, state := setupTestCase(t)
  91. defer tearDown(t)
  92. stateStore := sm.NewStore(stateDB)
  93. state.LastBlockHeight++
  94. // Build mock responses.
  95. block := statefactory.MakeBlock(state, 2, new(types.Commit))
  96. abciResponses := new(tmstate.ABCIResponses)
  97. dtxs := make([]*abci.ExecTxResult, 2)
  98. abciResponses.FinalizeBlock = new(abci.ResponseFinalizeBlock)
  99. abciResponses.FinalizeBlock.TxResults = dtxs
  100. abciResponses.FinalizeBlock.TxResults[0] = &abci.ExecTxResult{Data: []byte("foo"), Events: nil}
  101. abciResponses.FinalizeBlock.TxResults[1] = &abci.ExecTxResult{Data: []byte("bar"), Log: "ok", Events: nil}
  102. pbpk, err := encoding.PubKeyToProto(ed25519.GenPrivKey().PubKey())
  103. require.NoError(t, err)
  104. abciResponses.FinalizeBlock.ValidatorUpdates = []abci.ValidatorUpdate{{PubKey: pbpk, Power: 10}}
  105. err = stateStore.SaveABCIResponses(block.Height, abciResponses)
  106. require.NoError(t, err)
  107. loadedABCIResponses, err := stateStore.LoadABCIResponses(block.Height)
  108. require.NoError(t, err)
  109. assert.Equal(t, abciResponses, loadedABCIResponses,
  110. "ABCIResponses don't match:\ngot: %v\nexpected: %v\n",
  111. loadedABCIResponses, abciResponses)
  112. }
  113. // TestResultsSaveLoad tests saving and loading ABCI results.
  114. func TestABCIResponsesSaveLoad2(t *testing.T) {
  115. tearDown, stateDB, _ := setupTestCase(t)
  116. defer tearDown(t)
  117. stateStore := sm.NewStore(stateDB)
  118. cases := [...]struct {
  119. // Height is implied to equal index+2,
  120. // as block 1 is created from genesis.
  121. added []*abci.ExecTxResult
  122. expected []*abci.ExecTxResult
  123. }{
  124. 0: {
  125. nil,
  126. nil,
  127. },
  128. 1: {
  129. []*abci.ExecTxResult{
  130. {Code: 32, Data: []byte("Hello"), Log: "Huh?"},
  131. },
  132. []*abci.ExecTxResult{
  133. {Code: 32, Data: []byte("Hello")},
  134. },
  135. },
  136. 2: {
  137. []*abci.ExecTxResult{
  138. {Code: 383},
  139. {
  140. Data: []byte("Gotcha!"),
  141. Events: []abci.Event{
  142. {Type: "type1", Attributes: []abci.EventAttribute{{Key: "a", Value: "1"}}},
  143. {Type: "type2", Attributes: []abci.EventAttribute{{Key: "build", Value: "stuff"}}},
  144. },
  145. },
  146. },
  147. []*abci.ExecTxResult{
  148. {Code: 383, Data: nil},
  149. {Code: 0, Data: []byte("Gotcha!"), Events: []abci.Event{
  150. {Type: "type1", Attributes: []abci.EventAttribute{{Key: "a", Value: "1"}}},
  151. {Type: "type2", Attributes: []abci.EventAttribute{{Key: "build", Value: "stuff"}}},
  152. }},
  153. },
  154. },
  155. 3: {
  156. nil,
  157. nil,
  158. },
  159. 4: {
  160. []*abci.ExecTxResult{nil},
  161. nil,
  162. },
  163. }
  164. // Query all before, this should return error.
  165. for i := range cases {
  166. h := int64(i + 1)
  167. res, err := stateStore.LoadABCIResponses(h)
  168. assert.Error(t, err, "%d: %#v", i, res)
  169. }
  170. // Add all cases.
  171. for i, tc := range cases {
  172. h := int64(i + 1) // last block height, one below what we save
  173. responses := &tmstate.ABCIResponses{
  174. FinalizeBlock: &abci.ResponseFinalizeBlock{
  175. TxResults: tc.added,
  176. },
  177. }
  178. err := stateStore.SaveABCIResponses(h, responses)
  179. require.NoError(t, err)
  180. }
  181. // Query all before, should return expected value.
  182. for i, tc := range cases {
  183. h := int64(i + 1)
  184. res, err := stateStore.LoadABCIResponses(h)
  185. if assert.NoError(t, err, "%d", i) {
  186. t.Log(res)
  187. e, err := abci.MarshalTxResults(tc.expected)
  188. require.NoError(t, err)
  189. he := merkle.HashFromByteSlices(e)
  190. rs, err := abci.MarshalTxResults(res.FinalizeBlock.TxResults)
  191. hrs := merkle.HashFromByteSlices(rs)
  192. require.NoError(t, err)
  193. assert.Equal(t, he, hrs, "%d", i)
  194. }
  195. }
  196. }
  197. // TestValidatorSimpleSaveLoad tests saving and loading validators.
  198. func TestValidatorSimpleSaveLoad(t *testing.T) {
  199. tearDown, stateDB, state := setupTestCase(t)
  200. defer tearDown(t)
  201. statestore := sm.NewStore(stateDB)
  202. // Can't load anything for height 0.
  203. _, err := statestore.LoadValidators(0)
  204. assert.IsType(t, sm.ErrNoValSetForHeight{}, err, "expected err at height 0")
  205. // Should be able to load for height 1.
  206. v, err := statestore.LoadValidators(1)
  207. require.NoError(t, err, "expected no err at height 1")
  208. assert.Equal(t, v.Hash(), state.Validators.Hash(), "expected validator hashes to match")
  209. // Should be able to load for height 2.
  210. v, err = statestore.LoadValidators(2)
  211. require.NoError(t, err, "expected no err at height 2")
  212. assert.Equal(t, v.Hash(), state.NextValidators.Hash(), "expected validator hashes to match")
  213. // Increment height, save; should be able to load for next & next next height.
  214. state.LastBlockHeight++
  215. nextHeight := state.LastBlockHeight + 1
  216. err = statestore.Save(state)
  217. require.NoError(t, err)
  218. vp0, err := statestore.LoadValidators(nextHeight + 0)
  219. assert.NoError(t, err)
  220. vp1, err := statestore.LoadValidators(nextHeight + 1)
  221. assert.NoError(t, err)
  222. assert.Equal(t, vp0.Hash(), state.Validators.Hash(), "expected validator hashes to match")
  223. assert.Equal(t, vp1.Hash(), state.NextValidators.Hash(), "expected next validator hashes to match")
  224. }
  225. // TestValidatorChangesSaveLoad tests saving and loading a validator set with changes.
  226. func TestOneValidatorChangesSaveLoad(t *testing.T) {
  227. tearDown, stateDB, state := setupTestCase(t)
  228. defer tearDown(t)
  229. stateStore := sm.NewStore(stateDB)
  230. // Change vals at these heights.
  231. changeHeights := []int64{1, 2, 4, 5, 10, 15, 16, 17, 20}
  232. N := len(changeHeights)
  233. // Build the validator history by running updateState
  234. // with the right validator set for each height.
  235. highestHeight := changeHeights[N-1] + 5
  236. changeIndex := 0
  237. _, val := state.Validators.GetByIndex(0)
  238. power := val.VotingPower
  239. var err error
  240. var validatorUpdates []*types.Validator
  241. for i := int64(1); i < highestHeight; i++ {
  242. // When we get to a change height, use the next pubkey.
  243. if changeIndex < len(changeHeights) && i == changeHeights[changeIndex] {
  244. changeIndex++
  245. power++
  246. }
  247. header, blockID, responses := makeHeaderPartsResponsesValPowerChange(t, state, power)
  248. validatorUpdates, err = types.PB2TM.ValidatorUpdates(responses.FinalizeBlock.ValidatorUpdates)
  249. require.NoError(t, err)
  250. rs, err := abci.MarshalTxResults(responses.FinalizeBlock.TxResults)
  251. require.NoError(t, err)
  252. h := merkle.HashFromByteSlices(rs)
  253. state, err = state.Update(blockID, &header, h, responses.FinalizeBlock.ConsensusParamUpdates, validatorUpdates)
  254. require.NoError(t, err)
  255. err = stateStore.Save(state)
  256. require.NoError(t, err)
  257. }
  258. // On each height change, increment the power by one.
  259. testCases := make([]int64, highestHeight)
  260. changeIndex = 0
  261. power = val.VotingPower
  262. for i := int64(1); i < highestHeight+1; i++ {
  263. // We get to the height after a change height use the next pubkey (note
  264. // our counter starts at 0 this time).
  265. if changeIndex < len(changeHeights) && i == changeHeights[changeIndex]+1 {
  266. changeIndex++
  267. power++
  268. }
  269. testCases[i-1] = power
  270. }
  271. for i, power := range testCases {
  272. v, err := stateStore.LoadValidators(int64(i + 1 + 1)) // +1 because vset changes delayed by 1 block.
  273. assert.NoError(t, err, fmt.Sprintf("expected no err at height %d", i))
  274. assert.Equal(t, v.Size(), 1, "validator set size is greater than 1: %d", v.Size())
  275. _, val := v.GetByIndex(0)
  276. assert.Equal(t, val.VotingPower, power, fmt.Sprintf(`unexpected powerat
  277. height %d`, i))
  278. }
  279. }
  280. func TestProposerFrequency(t *testing.T) {
  281. ctx, cancel := context.WithCancel(context.Background())
  282. defer cancel()
  283. // some explicit test cases
  284. testCases := []struct {
  285. powers []int64
  286. }{
  287. // 2 vals
  288. {[]int64{1, 1}},
  289. {[]int64{1, 2}},
  290. {[]int64{1, 100}},
  291. {[]int64{5, 5}},
  292. {[]int64{5, 100}},
  293. {[]int64{50, 50}},
  294. {[]int64{50, 100}},
  295. {[]int64{1, 1000}},
  296. // 3 vals
  297. {[]int64{1, 1, 1}},
  298. {[]int64{1, 2, 3}},
  299. {[]int64{1, 2, 3}},
  300. {[]int64{1, 1, 10}},
  301. {[]int64{1, 1, 100}},
  302. {[]int64{1, 10, 100}},
  303. {[]int64{1, 1, 1000}},
  304. {[]int64{1, 10, 1000}},
  305. {[]int64{1, 100, 1000}},
  306. // 4 vals
  307. {[]int64{1, 1, 1, 1}},
  308. {[]int64{1, 2, 3, 4}},
  309. {[]int64{1, 1, 1, 10}},
  310. {[]int64{1, 1, 1, 100}},
  311. {[]int64{1, 1, 1, 1000}},
  312. {[]int64{1, 1, 10, 100}},
  313. {[]int64{1, 1, 10, 1000}},
  314. {[]int64{1, 1, 100, 1000}},
  315. {[]int64{1, 10, 100, 1000}},
  316. }
  317. for caseNum, testCase := range testCases {
  318. // run each case 5 times to sample different
  319. // initial priorities
  320. for i := 0; i < 5; i++ {
  321. valSet := genValSetWithPowers(testCase.powers)
  322. testProposerFreq(t, caseNum, valSet)
  323. }
  324. }
  325. // some random test cases with up to 100 validators
  326. maxVals := 100
  327. maxPower := 1000
  328. nTestCases := 5
  329. for i := 0; i < nTestCases; i++ {
  330. N := mrand.Int()%maxVals + 1
  331. vals := make([]*types.Validator, N)
  332. totalVotePower := int64(0)
  333. for j := 0; j < N; j++ {
  334. // make sure votePower > 0
  335. votePower := int64(mrand.Int()%maxPower) + 1
  336. totalVotePower += votePower
  337. privVal := types.NewMockPV()
  338. pubKey, err := privVal.GetPubKey(ctx)
  339. require.NoError(t, err)
  340. val := types.NewValidator(pubKey, votePower)
  341. val.ProposerPriority = mrand.Int63()
  342. vals[j] = val
  343. }
  344. valSet := types.NewValidatorSet(vals)
  345. valSet.RescalePriorities(totalVotePower)
  346. testProposerFreq(t, i, valSet)
  347. }
  348. }
  349. // new val set with given powers and random initial priorities
  350. func genValSetWithPowers(powers []int64) *types.ValidatorSet {
  351. size := len(powers)
  352. vals := make([]*types.Validator, size)
  353. totalVotePower := int64(0)
  354. for i := 0; i < size; i++ {
  355. totalVotePower += powers[i]
  356. val := types.NewValidator(ed25519.GenPrivKey().PubKey(), powers[i])
  357. val.ProposerPriority = mrand.Int63()
  358. vals[i] = val
  359. }
  360. valSet := types.NewValidatorSet(vals)
  361. valSet.RescalePriorities(totalVotePower)
  362. return valSet
  363. }
  364. // test a proposer appears as frequently as expected
  365. func testProposerFreq(t *testing.T, caseNum int, valSet *types.ValidatorSet) {
  366. N := valSet.Size()
  367. totalPower := valSet.TotalVotingPower()
  368. // run the proposer selection and track frequencies
  369. runMult := 1
  370. runs := int(totalPower) * runMult
  371. freqs := make([]int, N)
  372. for i := 0; i < runs; i++ {
  373. prop := valSet.GetProposer()
  374. idx, _ := valSet.GetByAddress(prop.Address)
  375. freqs[idx]++
  376. valSet.IncrementProposerPriority(1)
  377. }
  378. // assert frequencies match expected (max off by 1)
  379. for i, freq := range freqs {
  380. _, val := valSet.GetByIndex(int32(i))
  381. expectFreq := int(val.VotingPower) * runMult
  382. gotFreq := freq
  383. abs := int(math.Abs(float64(expectFreq - gotFreq)))
  384. // max bound on expected vs seen freq was proven
  385. // to be 1 for the 2 validator case in
  386. // https://github.com/cwgoes/tm-proposer-idris
  387. // and inferred to generalize to N-1
  388. bound := N - 1
  389. require.True(
  390. t,
  391. abs <= bound,
  392. fmt.Sprintf("Case %d val %d (%d): got %d, expected %d", caseNum, i, N, gotFreq, expectFreq),
  393. )
  394. }
  395. }
  396. // TestProposerPriorityDoesNotGetResetToZero assert that we preserve accum when calling updateState
  397. // see https://github.com/tendermint/tendermint/issues/2718
  398. func TestProposerPriorityDoesNotGetResetToZero(t *testing.T) {
  399. tearDown, _, state := setupTestCase(t)
  400. defer tearDown(t)
  401. val1VotingPower := int64(10)
  402. val1PubKey := ed25519.GenPrivKey().PubKey()
  403. val1 := &types.Validator{Address: val1PubKey.Address(), PubKey: val1PubKey, VotingPower: val1VotingPower}
  404. state.Validators = types.NewValidatorSet([]*types.Validator{val1})
  405. state.NextValidators = state.Validators
  406. // NewValidatorSet calls IncrementProposerPriority but uses on a copy of val1
  407. assert.EqualValues(t, 0, val1.ProposerPriority)
  408. block := statefactory.MakeBlock(state, state.LastBlockHeight+1, new(types.Commit))
  409. bps, err := block.MakePartSet(testPartSize)
  410. require.NoError(t, err)
  411. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  412. fb := &abci.ResponseFinalizeBlock{
  413. ValidatorUpdates: nil,
  414. }
  415. validatorUpdates, err := types.PB2TM.ValidatorUpdates(fb.ValidatorUpdates)
  416. require.NoError(t, err)
  417. rs, err := abci.MarshalTxResults(fb.TxResults)
  418. require.NoError(t, err)
  419. h := merkle.HashFromByteSlices(rs)
  420. updatedState, err := state.Update(blockID, &block.Header, h, fb.ConsensusParamUpdates, validatorUpdates)
  421. assert.NoError(t, err)
  422. curTotal := val1VotingPower
  423. // one increment step and one validator: 0 + power - total_power == 0
  424. assert.Equal(t, 0+val1VotingPower-curTotal, updatedState.NextValidators.Validators[0].ProposerPriority)
  425. // add a validator
  426. val2PubKey := ed25519.GenPrivKey().PubKey()
  427. val2VotingPower := int64(100)
  428. fvp, err := encoding.PubKeyToProto(val2PubKey)
  429. require.NoError(t, err)
  430. updateAddVal := abci.ValidatorUpdate{PubKey: fvp, Power: val2VotingPower}
  431. validatorUpdates, err = types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{updateAddVal})
  432. assert.NoError(t, err)
  433. rs, err = abci.MarshalTxResults(fb.TxResults)
  434. require.NoError(t, err)
  435. h = merkle.HashFromByteSlices(rs)
  436. updatedState2, err := updatedState.Update(blockID, &block.Header, h, fb.ConsensusParamUpdates, validatorUpdates)
  437. assert.NoError(t, err)
  438. require.Equal(t, len(updatedState2.NextValidators.Validators), 2)
  439. _, updatedVal1 := updatedState2.NextValidators.GetByAddress(val1PubKey.Address())
  440. _, addedVal2 := updatedState2.NextValidators.GetByAddress(val2PubKey.Address())
  441. // adding a validator should not lead to a ProposerPriority equal to zero (unless the combination of averaging and
  442. // incrementing would cause so; which is not the case here)
  443. // Steps from adding new validator:
  444. // 0 - val1 prio is 0, TVP after add:
  445. wantVal1Prio := int64(0)
  446. totalPowerAfter := val1VotingPower + val2VotingPower
  447. // 1. Add - Val2 should be initially added with (-123) =>
  448. wantVal2Prio := -(totalPowerAfter + (totalPowerAfter >> 3))
  449. // 2. Scale - noop
  450. // 3. Center - with avg, resulting val2:-61, val1:62
  451. avg := big.NewInt(0).Add(big.NewInt(wantVal1Prio), big.NewInt(wantVal2Prio))
  452. avg.Div(avg, big.NewInt(2))
  453. wantVal2Prio -= avg.Int64() // -61
  454. wantVal1Prio -= avg.Int64() // 62
  455. // 4. Steps from IncrementProposerPriority
  456. wantVal1Prio += val1VotingPower // 72
  457. wantVal2Prio += val2VotingPower // 39
  458. wantVal1Prio -= totalPowerAfter // -38 as val1 is proposer
  459. assert.Equal(t, wantVal1Prio, updatedVal1.ProposerPriority)
  460. assert.Equal(t, wantVal2Prio, addedVal2.ProposerPriority)
  461. // Updating a validator does not reset the ProposerPriority to zero:
  462. // 1. Add - Val2 VotingPower change to 1 =>
  463. updatedVotingPowVal2 := int64(1)
  464. updateVal := abci.ValidatorUpdate{PubKey: fvp, Power: updatedVotingPowVal2}
  465. validatorUpdates, err = types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{updateVal})
  466. assert.NoError(t, err)
  467. // this will cause the diff of priorities (77)
  468. // to be larger than threshold == 2*totalVotingPower (22):
  469. rs, err = abci.MarshalTxResults(fb.TxResults)
  470. require.NoError(t, err)
  471. h = merkle.HashFromByteSlices(rs)
  472. updatedState3, err := updatedState2.Update(blockID, &block.Header, h, fb.ConsensusParamUpdates, validatorUpdates)
  473. assert.NoError(t, err)
  474. require.Equal(t, len(updatedState3.NextValidators.Validators), 2)
  475. _, prevVal1 := updatedState3.Validators.GetByAddress(val1PubKey.Address())
  476. _, prevVal2 := updatedState3.Validators.GetByAddress(val2PubKey.Address())
  477. _, updatedVal1 = updatedState3.NextValidators.GetByAddress(val1PubKey.Address())
  478. _, updatedVal2 := updatedState3.NextValidators.GetByAddress(val2PubKey.Address())
  479. // 2. Scale
  480. // old prios: v1(10):-38, v2(1):39
  481. wantVal1Prio = prevVal1.ProposerPriority
  482. wantVal2Prio = prevVal2.ProposerPriority
  483. // scale to diffMax = 22 = 2 * tvp, diff=39-(-38)=77
  484. // new totalPower
  485. totalPower := updatedVal1.VotingPower + updatedVal2.VotingPower
  486. dist := wantVal2Prio - wantVal1Prio
  487. // ratio := (dist + 2*totalPower - 1) / 2*totalPower = 98/22 = 4
  488. ratio := (dist + 2*totalPower - 1) / (2 * totalPower)
  489. // v1(10):-38/4, v2(1):39/4
  490. wantVal1Prio /= ratio // -9
  491. wantVal2Prio /= ratio // 9
  492. // 3. Center - noop
  493. // 4. IncrementProposerPriority() ->
  494. // v1(10):-9+10, v2(1):9+1 -> v2 proposer so subsract tvp(11)
  495. // v1(10):1, v2(1):-1
  496. wantVal2Prio += updatedVal2.VotingPower // 10 -> prop
  497. wantVal1Prio += updatedVal1.VotingPower // 1
  498. wantVal2Prio -= totalPower // -1
  499. assert.Equal(t, wantVal2Prio, updatedVal2.ProposerPriority)
  500. assert.Equal(t, wantVal1Prio, updatedVal1.ProposerPriority)
  501. }
  502. func TestProposerPriorityProposerAlternates(t *testing.T) {
  503. // Regression test that would fail if the inner workings of
  504. // IncrementProposerPriority change.
  505. // Additionally, make sure that same power validators alternate if both
  506. // have the same voting power (and the 2nd was added later).
  507. tearDown, _, state := setupTestCase(t)
  508. defer tearDown(t)
  509. val1VotingPower := int64(10)
  510. val1PubKey := ed25519.GenPrivKey().PubKey()
  511. val1 := &types.Validator{Address: val1PubKey.Address(), PubKey: val1PubKey, VotingPower: val1VotingPower}
  512. // reset state validators to above validator
  513. state.Validators = types.NewValidatorSet([]*types.Validator{val1})
  514. state.NextValidators = state.Validators
  515. // we only have one validator:
  516. assert.Equal(t, val1PubKey.Address(), state.Validators.Proposer.Address)
  517. block := statefactory.MakeBlock(state, state.LastBlockHeight+1, new(types.Commit))
  518. bps, err := block.MakePartSet(testPartSize)
  519. require.NoError(t, err)
  520. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  521. // no updates:
  522. fb := &abci.ResponseFinalizeBlock{
  523. ValidatorUpdates: nil,
  524. }
  525. validatorUpdates, err := types.PB2TM.ValidatorUpdates(fb.ValidatorUpdates)
  526. require.NoError(t, err)
  527. rs, err := abci.MarshalTxResults(fb.TxResults)
  528. require.NoError(t, err)
  529. h := merkle.HashFromByteSlices(rs)
  530. updatedState, err := state.Update(blockID, &block.Header, h, fb.ConsensusParamUpdates, validatorUpdates)
  531. assert.NoError(t, err)
  532. // 0 + 10 (initial prio) - 10 (avg) - 10 (mostest - total) = -10
  533. totalPower := val1VotingPower
  534. wantVal1Prio := 0 + val1VotingPower - totalPower
  535. assert.Equal(t, wantVal1Prio, updatedState.NextValidators.Validators[0].ProposerPriority)
  536. assert.Equal(t, val1PubKey.Address(), updatedState.NextValidators.Proposer.Address)
  537. // add a validator with the same voting power as the first
  538. val2PubKey := ed25519.GenPrivKey().PubKey()
  539. fvp, err := encoding.PubKeyToProto(val2PubKey)
  540. require.NoError(t, err)
  541. updateAddVal := abci.ValidatorUpdate{PubKey: fvp, Power: val1VotingPower}
  542. validatorUpdates, err = types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{updateAddVal})
  543. assert.NoError(t, err)
  544. rs, err = abci.MarshalTxResults(fb.TxResults)
  545. require.NoError(t, err)
  546. h = merkle.HashFromByteSlices(rs)
  547. updatedState2, err := updatedState.Update(blockID, &block.Header, h, fb.ConsensusParamUpdates, validatorUpdates)
  548. assert.NoError(t, err)
  549. require.Equal(t, len(updatedState2.NextValidators.Validators), 2)
  550. assert.Equal(t, updatedState2.Validators, updatedState.NextValidators)
  551. // val1 will still be proposer as val2 just got added:
  552. assert.Equal(t, val1PubKey.Address(), updatedState.NextValidators.Proposer.Address)
  553. assert.Equal(t, updatedState2.Validators.Proposer.Address, updatedState2.NextValidators.Proposer.Address)
  554. assert.Equal(t, updatedState2.Validators.Proposer.Address, val1PubKey.Address())
  555. assert.Equal(t, updatedState2.NextValidators.Proposer.Address, val1PubKey.Address())
  556. _, updatedVal1 := updatedState2.NextValidators.GetByAddress(val1PubKey.Address())
  557. _, oldVal1 := updatedState2.Validators.GetByAddress(val1PubKey.Address())
  558. _, updatedVal2 := updatedState2.NextValidators.GetByAddress(val2PubKey.Address())
  559. // 1. Add
  560. val2VotingPower := val1VotingPower
  561. totalPower = val1VotingPower + val2VotingPower // 20
  562. v2PrioWhenAddedVal2 := -(totalPower + (totalPower >> 3)) // -22
  563. // 2. Scale - noop
  564. // 3. Center
  565. avgSum := big.NewInt(0).Add(big.NewInt(v2PrioWhenAddedVal2), big.NewInt(oldVal1.ProposerPriority))
  566. avg := avgSum.Div(avgSum, big.NewInt(2)) // -11
  567. expectedVal2Prio := v2PrioWhenAddedVal2 - avg.Int64() // -11
  568. expectedVal1Prio := oldVal1.ProposerPriority - avg.Int64() // 11
  569. // 4. Increment
  570. expectedVal2Prio += val2VotingPower // -11 + 10 = -1
  571. expectedVal1Prio += val1VotingPower // 11 + 10 == 21
  572. expectedVal1Prio -= totalPower // 1, val1 proposer
  573. assert.EqualValues(t, expectedVal1Prio, updatedVal1.ProposerPriority)
  574. assert.EqualValues(
  575. t,
  576. expectedVal2Prio,
  577. updatedVal2.ProposerPriority,
  578. "unexpected proposer priority for validator: %v",
  579. updatedVal2,
  580. )
  581. validatorUpdates, err = types.PB2TM.ValidatorUpdates(fb.ValidatorUpdates)
  582. require.NoError(t, err)
  583. rs, err = abci.MarshalTxResults(fb.TxResults)
  584. require.NoError(t, err)
  585. h = merkle.HashFromByteSlices(rs)
  586. updatedState3, err := updatedState2.Update(blockID, &block.Header, h, fb.ConsensusParamUpdates, validatorUpdates)
  587. assert.NoError(t, err)
  588. assert.Equal(t, updatedState3.Validators.Proposer.Address, updatedState3.NextValidators.Proposer.Address)
  589. assert.Equal(t, updatedState3.Validators, updatedState2.NextValidators)
  590. _, updatedVal1 = updatedState3.NextValidators.GetByAddress(val1PubKey.Address())
  591. _, updatedVal2 = updatedState3.NextValidators.GetByAddress(val2PubKey.Address())
  592. // val1 will still be proposer:
  593. assert.Equal(t, val1PubKey.Address(), updatedState3.NextValidators.Proposer.Address)
  594. // check if expected proposer prio is matched:
  595. // Increment
  596. expectedVal2Prio2 := expectedVal2Prio + val2VotingPower // -1 + 10 = 9
  597. expectedVal1Prio2 := expectedVal1Prio + val1VotingPower // 1 + 10 == 11
  598. expectedVal1Prio2 -= totalPower // -9, val1 proposer
  599. assert.EqualValues(
  600. t,
  601. expectedVal1Prio2,
  602. updatedVal1.ProposerPriority,
  603. "unexpected proposer priority for validator: %v",
  604. updatedVal2,
  605. )
  606. assert.EqualValues(
  607. t,
  608. expectedVal2Prio2,
  609. updatedVal2.ProposerPriority,
  610. "unexpected proposer priority for validator: %v",
  611. updatedVal2,
  612. )
  613. // no changes in voting power and both validators have same voting power
  614. // -> proposers should alternate:
  615. oldState := updatedState3
  616. fb = &abci.ResponseFinalizeBlock{
  617. ValidatorUpdates: nil,
  618. }
  619. validatorUpdates, err = types.PB2TM.ValidatorUpdates(fb.ValidatorUpdates)
  620. require.NoError(t, err)
  621. rs, err = abci.MarshalTxResults(fb.TxResults)
  622. require.NoError(t, err)
  623. h = merkle.HashFromByteSlices(rs)
  624. oldState, err = oldState.Update(blockID, &block.Header, h, fb.ConsensusParamUpdates, validatorUpdates)
  625. assert.NoError(t, err)
  626. expectedVal1Prio2 = 1
  627. expectedVal2Prio2 = -1
  628. expectedVal1Prio = -9
  629. expectedVal2Prio = 9
  630. for i := 0; i < 1000; i++ {
  631. // no validator updates:
  632. fb := &abci.ResponseFinalizeBlock{
  633. ValidatorUpdates: nil,
  634. }
  635. validatorUpdates, err = types.PB2TM.ValidatorUpdates(fb.ValidatorUpdates)
  636. require.NoError(t, err)
  637. rs, err := abci.MarshalTxResults(fb.TxResults)
  638. require.NoError(t, err)
  639. h := merkle.HashFromByteSlices(rs)
  640. updatedState, err := oldState.Update(blockID, &block.Header, h, fb.ConsensusParamUpdates, validatorUpdates)
  641. assert.NoError(t, err)
  642. // alternate (and cyclic priorities):
  643. assert.NotEqual(
  644. t,
  645. updatedState.Validators.Proposer.Address,
  646. updatedState.NextValidators.Proposer.Address,
  647. "iter: %v",
  648. i,
  649. )
  650. assert.Equal(t, oldState.Validators.Proposer.Address, updatedState.NextValidators.Proposer.Address, "iter: %v", i)
  651. _, updatedVal1 = updatedState.NextValidators.GetByAddress(val1PubKey.Address())
  652. _, updatedVal2 = updatedState.NextValidators.GetByAddress(val2PubKey.Address())
  653. if i%2 == 0 {
  654. assert.Equal(t, updatedState.Validators.Proposer.Address, val2PubKey.Address())
  655. assert.Equal(t, expectedVal1Prio, updatedVal1.ProposerPriority) // -19
  656. assert.Equal(t, expectedVal2Prio, updatedVal2.ProposerPriority) // 0
  657. } else {
  658. assert.Equal(t, updatedState.Validators.Proposer.Address, val1PubKey.Address())
  659. assert.Equal(t, expectedVal1Prio2, updatedVal1.ProposerPriority) // -9
  660. assert.Equal(t, expectedVal2Prio2, updatedVal2.ProposerPriority) // -10
  661. }
  662. // update for next iteration:
  663. oldState = updatedState
  664. }
  665. }
  666. func TestLargeGenesisValidator(t *testing.T) {
  667. tearDown, _, state := setupTestCase(t)
  668. defer tearDown(t)
  669. genesisVotingPower := types.MaxTotalVotingPower / 1000
  670. genesisPubKey := ed25519.GenPrivKey().PubKey()
  671. // fmt.Println("genesis addr: ", genesisPubKey.Address())
  672. genesisVal := &types.Validator{
  673. Address: genesisPubKey.Address(),
  674. PubKey: genesisPubKey,
  675. VotingPower: genesisVotingPower,
  676. }
  677. // reset state validators to above validator
  678. state.Validators = types.NewValidatorSet([]*types.Validator{genesisVal})
  679. state.NextValidators = state.Validators
  680. require.True(t, len(state.Validators.Validators) == 1)
  681. // update state a few times with no validator updates
  682. // asserts that the single validator's ProposerPrio stays the same
  683. oldState := state
  684. for i := 0; i < 10; i++ {
  685. // no updates:
  686. fb := &abci.ResponseFinalizeBlock{
  687. ValidatorUpdates: nil,
  688. }
  689. validatorUpdates, err := types.PB2TM.ValidatorUpdates(fb.ValidatorUpdates)
  690. require.NoError(t, err)
  691. block := statefactory.MakeBlock(oldState, oldState.LastBlockHeight+1, new(types.Commit))
  692. bps, err := block.MakePartSet(testPartSize)
  693. require.NoError(t, err)
  694. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  695. rs, err := abci.MarshalTxResults(fb.TxResults)
  696. require.NoError(t, err)
  697. h := merkle.HashFromByteSlices(rs)
  698. updatedState, err := oldState.Update(blockID, &block.Header, h, fb.ConsensusParamUpdates, validatorUpdates)
  699. require.NoError(t, err)
  700. // no changes in voting power (ProposerPrio += VotingPower == Voting in 1st round; than shiftByAvg == 0,
  701. // than -Total == -Voting)
  702. // -> no change in ProposerPrio (stays zero):
  703. assert.EqualValues(t, oldState.NextValidators, updatedState.NextValidators)
  704. assert.EqualValues(t, 0, updatedState.NextValidators.Proposer.ProposerPriority)
  705. oldState = updatedState
  706. }
  707. // add another validator, do a few iterations (create blocks),
  708. // add more validators with same voting power as the 2nd
  709. // let the genesis validator "unbond",
  710. // see how long it takes until the effect wears off and both begin to alternate
  711. // see: https://github.com/tendermint/tendermint/issues/2960
  712. firstAddedValPubKey := ed25519.GenPrivKey().PubKey()
  713. firstAddedValVotingPower := int64(10)
  714. fvp, err := encoding.PubKeyToProto(firstAddedValPubKey)
  715. require.NoError(t, err)
  716. firstAddedVal := abci.ValidatorUpdate{PubKey: fvp, Power: firstAddedValVotingPower}
  717. validatorUpdates, err := types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{firstAddedVal})
  718. assert.NoError(t, err)
  719. fb := &abci.ResponseFinalizeBlock{
  720. ValidatorUpdates: []abci.ValidatorUpdate{firstAddedVal},
  721. }
  722. block := statefactory.MakeBlock(oldState, oldState.LastBlockHeight+1, new(types.Commit))
  723. bps, err := block.MakePartSet(testPartSize)
  724. require.NoError(t, err)
  725. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  726. rs, err := abci.MarshalTxResults(fb.TxResults)
  727. require.NoError(t, err)
  728. h := merkle.HashFromByteSlices(rs)
  729. updatedState, err := oldState.Update(blockID, &block.Header, h, fb.ConsensusParamUpdates, validatorUpdates)
  730. require.NoError(t, err)
  731. lastState := updatedState
  732. for i := 0; i < 200; i++ {
  733. // no updates:
  734. fb := &abci.ResponseFinalizeBlock{
  735. ValidatorUpdates: nil,
  736. }
  737. validatorUpdates, err := types.PB2TM.ValidatorUpdates(fb.ValidatorUpdates)
  738. require.NoError(t, err)
  739. block := statefactory.MakeBlock(lastState, lastState.LastBlockHeight+1, new(types.Commit))
  740. bps, err = block.MakePartSet(testPartSize)
  741. require.NoError(t, err)
  742. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  743. rs, err := abci.MarshalTxResults(fb.TxResults)
  744. require.NoError(t, err)
  745. h := merkle.HashFromByteSlices(rs)
  746. updatedStateInner, err := lastState.Update(blockID, &block.Header, h, fb.ConsensusParamUpdates, validatorUpdates)
  747. require.NoError(t, err)
  748. lastState = updatedStateInner
  749. }
  750. // set state to last state of above iteration
  751. state = lastState
  752. // set oldState to state before above iteration
  753. oldState = updatedState
  754. _, oldGenesisVal := oldState.NextValidators.GetByAddress(genesisVal.Address)
  755. _, newGenesisVal := state.NextValidators.GetByAddress(genesisVal.Address)
  756. _, addedOldVal := oldState.NextValidators.GetByAddress(firstAddedValPubKey.Address())
  757. _, addedNewVal := state.NextValidators.GetByAddress(firstAddedValPubKey.Address())
  758. // expect large negative proposer priority for both (genesis validator decreased, 2nd validator increased):
  759. assert.True(t, oldGenesisVal.ProposerPriority > newGenesisVal.ProposerPriority)
  760. assert.True(t, addedOldVal.ProposerPriority < addedNewVal.ProposerPriority)
  761. // add 10 validators with the same voting power as the one added directly after genesis:
  762. for i := 0; i < 10; i++ {
  763. addedPubKey := ed25519.GenPrivKey().PubKey()
  764. ap, err := encoding.PubKeyToProto(addedPubKey)
  765. require.NoError(t, err)
  766. addedVal := abci.ValidatorUpdate{PubKey: ap, Power: firstAddedValVotingPower}
  767. validatorUpdates, err := types.PB2TM.ValidatorUpdates([]abci.ValidatorUpdate{addedVal})
  768. assert.NoError(t, err)
  769. fb := &abci.ResponseFinalizeBlock{
  770. ValidatorUpdates: []abci.ValidatorUpdate{addedVal},
  771. }
  772. block := statefactory.MakeBlock(oldState, oldState.LastBlockHeight+1, new(types.Commit))
  773. bps, err := block.MakePartSet(testPartSize)
  774. require.NoError(t, err)
  775. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  776. rs, err := abci.MarshalTxResults(fb.TxResults)
  777. require.NoError(t, err)
  778. h := merkle.HashFromByteSlices(rs)
  779. state, err = state.Update(blockID, &block.Header, h, fb.ConsensusParamUpdates, validatorUpdates)
  780. require.NoError(t, err)
  781. }
  782. require.Equal(t, 10+2, len(state.NextValidators.Validators))
  783. // remove genesis validator:
  784. gp, err := encoding.PubKeyToProto(genesisPubKey)
  785. require.NoError(t, err)
  786. removeGenesisVal := abci.ValidatorUpdate{PubKey: gp, Power: 0}
  787. fb = &abci.ResponseFinalizeBlock{
  788. ValidatorUpdates: []abci.ValidatorUpdate{removeGenesisVal},
  789. }
  790. block = statefactory.MakeBlock(oldState, oldState.LastBlockHeight+1, new(types.Commit))
  791. require.NoError(t, err)
  792. bps, err = block.MakePartSet(testPartSize)
  793. require.NoError(t, err)
  794. blockID = types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  795. validatorUpdates, err = types.PB2TM.ValidatorUpdates(fb.ValidatorUpdates)
  796. require.NoError(t, err)
  797. rs, err = abci.MarshalTxResults(fb.TxResults)
  798. require.NoError(t, err)
  799. h = merkle.HashFromByteSlices(rs)
  800. updatedState, err = state.Update(blockID, &block.Header, h, fb.ConsensusParamUpdates, validatorUpdates)
  801. require.NoError(t, err)
  802. // only the first added val (not the genesis val) should be left
  803. assert.Equal(t, 11, len(updatedState.NextValidators.Validators))
  804. // call update state until the effect for the 3rd added validator
  805. // being proposer for a long time after the genesis validator left wears off:
  806. curState := updatedState
  807. count := 0
  808. isProposerUnchanged := true
  809. for isProposerUnchanged {
  810. fb = &abci.ResponseFinalizeBlock{
  811. ValidatorUpdates: nil,
  812. }
  813. validatorUpdates, err = types.PB2TM.ValidatorUpdates(fb.ValidatorUpdates)
  814. require.NoError(t, err)
  815. block = statefactory.MakeBlock(curState, curState.LastBlockHeight+1, new(types.Commit))
  816. bps, err := block.MakePartSet(testPartSize)
  817. require.NoError(t, err)
  818. blockID = types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  819. rs, err := abci.MarshalTxResults(fb.TxResults)
  820. require.NoError(t, err)
  821. h := merkle.HashFromByteSlices(rs)
  822. curState, err = curState.Update(blockID, &block.Header, h, fb.ConsensusParamUpdates, validatorUpdates)
  823. require.NoError(t, err)
  824. if !bytes.Equal(curState.Validators.Proposer.Address, curState.NextValidators.Proposer.Address) {
  825. isProposerUnchanged = false
  826. }
  827. count++
  828. }
  829. updatedState = curState
  830. // the proposer changes after this number of blocks
  831. firstProposerChangeExpectedAfter := 1
  832. assert.Equal(t, firstProposerChangeExpectedAfter, count)
  833. // store proposers here to see if we see them again in the same order:
  834. numVals := len(updatedState.Validators.Validators)
  835. proposers := make([]*types.Validator, numVals)
  836. for i := 0; i < 100; i++ {
  837. // no updates:
  838. fb := &abci.ResponseFinalizeBlock{
  839. ValidatorUpdates: nil,
  840. }
  841. validatorUpdates, err := types.PB2TM.ValidatorUpdates(fb.ValidatorUpdates)
  842. require.NoError(t, err)
  843. block := statefactory.MakeBlock(updatedState, updatedState.LastBlockHeight+1, new(types.Commit))
  844. bps, err := block.MakePartSet(testPartSize)
  845. require.NoError(t, err)
  846. blockID := types.BlockID{Hash: block.Hash(), PartSetHeader: bps.Header()}
  847. rs, err := abci.MarshalTxResults(fb.TxResults)
  848. require.NoError(t, err)
  849. h := merkle.HashFromByteSlices(rs)
  850. updatedState, err = updatedState.Update(blockID, &block.Header, h, fb.ConsensusParamUpdates, validatorUpdates)
  851. require.NoError(t, err)
  852. if i > numVals { // expect proposers to cycle through after the first iteration (of numVals blocks):
  853. if proposers[i%numVals] == nil {
  854. proposers[i%numVals] = updatedState.NextValidators.Proposer
  855. } else {
  856. assert.Equal(t, proposers[i%numVals], updatedState.NextValidators.Proposer)
  857. }
  858. }
  859. }
  860. }
  861. func TestStoreLoadValidatorsIncrementsProposerPriority(t *testing.T) {
  862. const valSetSize = 2
  863. tearDown, stateDB, state := setupTestCase(t)
  864. t.Cleanup(func() { tearDown(t) })
  865. stateStore := sm.NewStore(stateDB)
  866. state.Validators = genValSet(valSetSize)
  867. state.NextValidators = state.Validators.CopyIncrementProposerPriority(1)
  868. err := stateStore.Save(state)
  869. require.NoError(t, err)
  870. nextHeight := state.LastBlockHeight + 1
  871. v0, err := stateStore.LoadValidators(nextHeight)
  872. assert.NoError(t, err)
  873. acc0 := v0.Validators[0].ProposerPriority
  874. v1, err := stateStore.LoadValidators(nextHeight + 1)
  875. assert.NoError(t, err)
  876. acc1 := v1.Validators[0].ProposerPriority
  877. assert.NotEqual(t, acc1, acc0, "expected ProposerPriority value to change between heights")
  878. }
  879. // TestValidatorChangesSaveLoad tests saving and loading a validator set with
  880. // changes.
  881. func TestManyValidatorChangesSaveLoad(t *testing.T) {
  882. const valSetSize = 7
  883. tearDown, stateDB, state := setupTestCase(t)
  884. defer tearDown(t)
  885. stateStore := sm.NewStore(stateDB)
  886. require.Equal(t, int64(0), state.LastBlockHeight)
  887. state.Validators = genValSet(valSetSize)
  888. state.NextValidators = state.Validators.CopyIncrementProposerPriority(1)
  889. err := stateStore.Save(state)
  890. require.NoError(t, err)
  891. _, valOld := state.Validators.GetByIndex(0)
  892. var pubkeyOld = valOld.PubKey
  893. pubkey := ed25519.GenPrivKey().PubKey()
  894. // Swap the first validator with a new one (validator set size stays the same).
  895. header, blockID, responses := makeHeaderPartsResponsesValPubKeyChange(t, state, pubkey)
  896. // Save state etc.
  897. var validatorUpdates []*types.Validator
  898. validatorUpdates, err = types.PB2TM.ValidatorUpdates(responses.FinalizeBlock.ValidatorUpdates)
  899. require.NoError(t, err)
  900. rs, err := abci.MarshalTxResults(responses.FinalizeBlock.TxResults)
  901. require.NoError(t, err)
  902. h := merkle.HashFromByteSlices(rs)
  903. state, err = state.Update(blockID, &header, h, responses.FinalizeBlock.ConsensusParamUpdates, validatorUpdates)
  904. require.NoError(t, err)
  905. nextHeight := state.LastBlockHeight + 1
  906. err = stateStore.Save(state)
  907. require.NoError(t, err)
  908. // Load nextheight, it should be the oldpubkey.
  909. v0, err := stateStore.LoadValidators(nextHeight)
  910. assert.NoError(t, err)
  911. assert.Equal(t, valSetSize, v0.Size())
  912. index, val := v0.GetByAddress(pubkeyOld.Address())
  913. assert.NotNil(t, val)
  914. if index < 0 {
  915. t.Fatal("expected to find old validator")
  916. }
  917. // Load nextheight+1, it should be the new pubkey.
  918. v1, err := stateStore.LoadValidators(nextHeight + 1)
  919. assert.NoError(t, err)
  920. assert.Equal(t, valSetSize, v1.Size())
  921. index, val = v1.GetByAddress(pubkey.Address())
  922. assert.NotNil(t, val)
  923. if index < 0 {
  924. t.Fatal("expected to find newly added validator")
  925. }
  926. }
  927. func TestStateMakeBlock(t *testing.T) {
  928. tearDown, _, state := setupTestCase(t)
  929. defer tearDown(t)
  930. proposerAddress := state.Validators.GetProposer().Address
  931. stateVersion := state.Version.Consensus
  932. block := statefactory.MakeBlock(state, 2, new(types.Commit))
  933. // test we set some fields
  934. assert.Equal(t, stateVersion, block.Version)
  935. assert.Equal(t, proposerAddress, block.ProposerAddress)
  936. }
  937. // TestConsensusParamsChangesSaveLoad tests saving and loading consensus params
  938. // with changes.
  939. func TestConsensusParamsChangesSaveLoad(t *testing.T) {
  940. tearDown, stateDB, state := setupTestCase(t)
  941. defer tearDown(t)
  942. stateStore := sm.NewStore(stateDB)
  943. // Change vals at these heights.
  944. changeHeights := []int64{1, 2, 4, 5, 10, 15, 16, 17, 20}
  945. N := len(changeHeights)
  946. // Each valset is just one validator.
  947. // create list of them.
  948. params := make([]types.ConsensusParams, N+1)
  949. params[0] = state.ConsensusParams
  950. for i := 1; i < N+1; i++ {
  951. params[i] = *types.DefaultConsensusParams()
  952. params[i].Block.MaxBytes += int64(i)
  953. }
  954. // Build the params history by running updateState
  955. // with the right params set for each height.
  956. highestHeight := changeHeights[N-1] + 5
  957. changeIndex := 0
  958. cp := params[changeIndex]
  959. var err error
  960. var validatorUpdates []*types.Validator
  961. for i := int64(1); i < highestHeight; i++ {
  962. // When we get to a change height, use the next params.
  963. if changeIndex < len(changeHeights) && i == changeHeights[changeIndex] {
  964. changeIndex++
  965. cp = params[changeIndex]
  966. }
  967. header, blockID, responses := makeHeaderPartsResponsesParams(t, state, &cp)
  968. validatorUpdates, err = types.PB2TM.ValidatorUpdates(responses.FinalizeBlock.ValidatorUpdates)
  969. require.NoError(t, err)
  970. rs, err := abci.MarshalTxResults(responses.FinalizeBlock.TxResults)
  971. require.NoError(t, err)
  972. h := merkle.HashFromByteSlices(rs)
  973. state, err = state.Update(blockID, &header, h, responses.FinalizeBlock.ConsensusParamUpdates, validatorUpdates)
  974. require.NoError(t, err)
  975. err = stateStore.Save(state)
  976. require.NoError(t, err)
  977. }
  978. // Make all the test cases by using the same params until after the change.
  979. testCases := make([]paramsChangeTestCase, highestHeight)
  980. changeIndex = 0
  981. cp = params[changeIndex]
  982. for i := int64(1); i < highestHeight+1; i++ {
  983. // We get to the height after a change height use the next pubkey (note
  984. // our counter starts at 0 this time).
  985. if changeIndex < len(changeHeights) && i == changeHeights[changeIndex]+1 {
  986. changeIndex++
  987. cp = params[changeIndex]
  988. }
  989. testCases[i-1] = paramsChangeTestCase{i, cp}
  990. }
  991. for _, testCase := range testCases {
  992. p, err := stateStore.LoadConsensusParams(testCase.height)
  993. assert.NoError(t, err, fmt.Sprintf("expected no err at height %d", testCase.height))
  994. assert.EqualValues(t, testCase.params, p, fmt.Sprintf(`unexpected consensus params at
  995. height %d`, testCase.height))
  996. }
  997. }
  998. func TestStateProto(t *testing.T) {
  999. tearDown, _, state := setupTestCase(t)
  1000. defer tearDown(t)
  1001. tc := []struct {
  1002. testName string
  1003. state *sm.State
  1004. expPass1 bool
  1005. expPass2 bool
  1006. }{
  1007. {"empty state", &sm.State{}, true, false},
  1008. {"nil failure state", nil, false, false},
  1009. {"success state", &state, true, true},
  1010. }
  1011. for _, tt := range tc {
  1012. tt := tt
  1013. pbs, err := tt.state.ToProto()
  1014. if !tt.expPass1 {
  1015. assert.Error(t, err)
  1016. } else {
  1017. assert.NoError(t, err, tt.testName)
  1018. }
  1019. smt, err := sm.FromProto(pbs)
  1020. if tt.expPass2 {
  1021. require.NoError(t, err, tt.testName)
  1022. require.Equal(t, tt.state, smt, tt.testName)
  1023. } else {
  1024. require.Error(t, err, tt.testName)
  1025. }
  1026. }
  1027. }