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.

1632 lines
48 KiB

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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
5 years ago
types: prevent spurious validator power overflow warnings when changing the validator set (#4183) Fix for #4164 The general problem is that in certain conditions an overflow warning is issued when attempting to update a validator set even if the final set's total voting power is not over the maximum allowed. Root cause is that in verifyUpdates(), updates are verified wrt to total voting power in the order of validator address. It is then possible that a low address validator may increase its power such that the temporary total voting power count goes over MaxTotalVotingPower. Scenarios where removing and adding/ updating validators with high voting power, in the same update operation, cause the same false warning and the updates are not applied. Main changes to fix this are in verifyUpdate() that now does the verification starting with the decreases in power. It also takes into account the removals that are part of the update. ## Commits: * tests for overflow detection and prevention * test fix * more tests * fix the false overflow warnings and golint * scopelint warning fix * review comments * variant with using sort by amount of change in power * compute separately number new validators in update * types: use a switch in processChanges * more review comments * types: use HasAddress in numNewValidators * types: refactor verifyUpdates copy updates, sort them by delta and use resulting slice to calculate tvpAfterUpdatesBeforeRemovals. * remove unused structs * review comments * update changelog
5 years ago
types: prevent spurious validator power overflow warnings when changing the validator set (#4183) Fix for #4164 The general problem is that in certain conditions an overflow warning is issued when attempting to update a validator set even if the final set's total voting power is not over the maximum allowed. Root cause is that in verifyUpdates(), updates are verified wrt to total voting power in the order of validator address. It is then possible that a low address validator may increase its power such that the temporary total voting power count goes over MaxTotalVotingPower. Scenarios where removing and adding/ updating validators with high voting power, in the same update operation, cause the same false warning and the updates are not applied. Main changes to fix this are in verifyUpdate() that now does the verification starting with the decreases in power. It also takes into account the removals that are part of the update. ## Commits: * tests for overflow detection and prevention * test fix * more tests * fix the false overflow warnings and golint * scopelint warning fix * review comments * variant with using sort by amount of change in power * compute separately number new validators in update * types: use a switch in processChanges * more review comments * types: use HasAddress in numNewValidators * types: refactor verifyUpdates copy updates, sort them by delta and use resulting slice to calculate tvpAfterUpdatesBeforeRemovals. * remove unused structs * review comments * update changelog
5 years ago
types: prevent spurious validator power overflow warnings when changing the validator set (#4183) Fix for #4164 The general problem is that in certain conditions an overflow warning is issued when attempting to update a validator set even if the final set's total voting power is not over the maximum allowed. Root cause is that in verifyUpdates(), updates are verified wrt to total voting power in the order of validator address. It is then possible that a low address validator may increase its power such that the temporary total voting power count goes over MaxTotalVotingPower. Scenarios where removing and adding/ updating validators with high voting power, in the same update operation, cause the same false warning and the updates are not applied. Main changes to fix this are in verifyUpdate() that now does the verification starting with the decreases in power. It also takes into account the removals that are part of the update. ## Commits: * tests for overflow detection and prevention * test fix * more tests * fix the false overflow warnings and golint * scopelint warning fix * review comments * variant with using sort by amount of change in power * compute separately number new validators in update * types: use a switch in processChanges * more review comments * types: use HasAddress in numNewValidators * types: refactor verifyUpdates copy updates, sort them by delta and use resulting slice to calculate tvpAfterUpdatesBeforeRemovals. * remove unused structs * review comments * update changelog
5 years ago
types: prevent spurious validator power overflow warnings when changing the validator set (#4183) Fix for #4164 The general problem is that in certain conditions an overflow warning is issued when attempting to update a validator set even if the final set's total voting power is not over the maximum allowed. Root cause is that in verifyUpdates(), updates are verified wrt to total voting power in the order of validator address. It is then possible that a low address validator may increase its power such that the temporary total voting power count goes over MaxTotalVotingPower. Scenarios where removing and adding/ updating validators with high voting power, in the same update operation, cause the same false warning and the updates are not applied. Main changes to fix this are in verifyUpdate() that now does the verification starting with the decreases in power. It also takes into account the removals that are part of the update. ## Commits: * tests for overflow detection and prevention * test fix * more tests * fix the false overflow warnings and golint * scopelint warning fix * review comments * variant with using sort by amount of change in power * compute separately number new validators in update * types: use a switch in processChanges * more review comments * types: use HasAddress in numNewValidators * types: refactor verifyUpdates copy updates, sort them by delta and use resulting slice to calculate tvpAfterUpdatesBeforeRemovals. * remove unused structs * review comments * update changelog
5 years ago
types: prevent spurious validator power overflow warnings when changing the validator set (#4183) Fix for #4164 The general problem is that in certain conditions an overflow warning is issued when attempting to update a validator set even if the final set's total voting power is not over the maximum allowed. Root cause is that in verifyUpdates(), updates are verified wrt to total voting power in the order of validator address. It is then possible that a low address validator may increase its power such that the temporary total voting power count goes over MaxTotalVotingPower. Scenarios where removing and adding/ updating validators with high voting power, in the same update operation, cause the same false warning and the updates are not applied. Main changes to fix this are in verifyUpdate() that now does the verification starting with the decreases in power. It also takes into account the removals that are part of the update. ## Commits: * tests for overflow detection and prevention * test fix * more tests * fix the false overflow warnings and golint * scopelint warning fix * review comments * variant with using sort by amount of change in power * compute separately number new validators in update * types: use a switch in processChanges * more review comments * types: use HasAddress in numNewValidators * types: refactor verifyUpdates copy updates, sort them by delta and use resulting slice to calculate tvpAfterUpdatesBeforeRemovals. * remove unused structs * review comments * update changelog
5 years ago
types: prevent spurious validator power overflow warnings when changing the validator set (#4183) Fix for #4164 The general problem is that in certain conditions an overflow warning is issued when attempting to update a validator set even if the final set's total voting power is not over the maximum allowed. Root cause is that in verifyUpdates(), updates are verified wrt to total voting power in the order of validator address. It is then possible that a low address validator may increase its power such that the temporary total voting power count goes over MaxTotalVotingPower. Scenarios where removing and adding/ updating validators with high voting power, in the same update operation, cause the same false warning and the updates are not applied. Main changes to fix this are in verifyUpdate() that now does the verification starting with the decreases in power. It also takes into account the removals that are part of the update. ## Commits: * tests for overflow detection and prevention * test fix * more tests * fix the false overflow warnings and golint * scopelint warning fix * review comments * variant with using sort by amount of change in power * compute separately number new validators in update * types: use a switch in processChanges * more review comments * types: use HasAddress in numNewValidators * types: refactor verifyUpdates copy updates, sort them by delta and use resulting slice to calculate tvpAfterUpdatesBeforeRemovals. * remove unused structs * review comments * update changelog
5 years ago
types: prevent spurious validator power overflow warnings when changing the validator set (#4183) Fix for #4164 The general problem is that in certain conditions an overflow warning is issued when attempting to update a validator set even if the final set's total voting power is not over the maximum allowed. Root cause is that in verifyUpdates(), updates are verified wrt to total voting power in the order of validator address. It is then possible that a low address validator may increase its power such that the temporary total voting power count goes over MaxTotalVotingPower. Scenarios where removing and adding/ updating validators with high voting power, in the same update operation, cause the same false warning and the updates are not applied. Main changes to fix this are in verifyUpdate() that now does the verification starting with the decreases in power. It also takes into account the removals that are part of the update. ## Commits: * tests for overflow detection and prevention * test fix * more tests * fix the false overflow warnings and golint * scopelint warning fix * review comments * variant with using sort by amount of change in power * compute separately number new validators in update * types: use a switch in processChanges * more review comments * types: use HasAddress in numNewValidators * types: refactor verifyUpdates copy updates, sort them by delta and use resulting slice to calculate tvpAfterUpdatesBeforeRemovals. * remove unused structs * review comments * update changelog
5 years ago
types: prevent spurious validator power overflow warnings when changing the validator set (#4183) Fix for #4164 The general problem is that in certain conditions an overflow warning is issued when attempting to update a validator set even if the final set's total voting power is not over the maximum allowed. Root cause is that in verifyUpdates(), updates are verified wrt to total voting power in the order of validator address. It is then possible that a low address validator may increase its power such that the temporary total voting power count goes over MaxTotalVotingPower. Scenarios where removing and adding/ updating validators with high voting power, in the same update operation, cause the same false warning and the updates are not applied. Main changes to fix this are in verifyUpdate() that now does the verification starting with the decreases in power. It also takes into account the removals that are part of the update. ## Commits: * tests for overflow detection and prevention * test fix * more tests * fix the false overflow warnings and golint * scopelint warning fix * review comments * variant with using sort by amount of change in power * compute separately number new validators in update * types: use a switch in processChanges * more review comments * types: use HasAddress in numNewValidators * types: refactor verifyUpdates copy updates, sort them by delta and use resulting slice to calculate tvpAfterUpdatesBeforeRemovals. * remove unused structs * review comments * update changelog
5 years ago
types: prevent spurious validator power overflow warnings when changing the validator set (#4183) Fix for #4164 The general problem is that in certain conditions an overflow warning is issued when attempting to update a validator set even if the final set's total voting power is not over the maximum allowed. Root cause is that in verifyUpdates(), updates are verified wrt to total voting power in the order of validator address. It is then possible that a low address validator may increase its power such that the temporary total voting power count goes over MaxTotalVotingPower. Scenarios where removing and adding/ updating validators with high voting power, in the same update operation, cause the same false warning and the updates are not applied. Main changes to fix this are in verifyUpdate() that now does the verification starting with the decreases in power. It also takes into account the removals that are part of the update. ## Commits: * tests for overflow detection and prevention * test fix * more tests * fix the false overflow warnings and golint * scopelint warning fix * review comments * variant with using sort by amount of change in power * compute separately number new validators in update * types: use a switch in processChanges * more review comments * types: use HasAddress in numNewValidators * types: refactor verifyUpdates copy updates, sort them by delta and use resulting slice to calculate tvpAfterUpdatesBeforeRemovals. * remove unused structs * review comments * update changelog
5 years ago
types: prevent spurious validator power overflow warnings when changing the validator set (#4183) Fix for #4164 The general problem is that in certain conditions an overflow warning is issued when attempting to update a validator set even if the final set's total voting power is not over the maximum allowed. Root cause is that in verifyUpdates(), updates are verified wrt to total voting power in the order of validator address. It is then possible that a low address validator may increase its power such that the temporary total voting power count goes over MaxTotalVotingPower. Scenarios where removing and adding/ updating validators with high voting power, in the same update operation, cause the same false warning and the updates are not applied. Main changes to fix this are in verifyUpdate() that now does the verification starting with the decreases in power. It also takes into account the removals that are part of the update. ## Commits: * tests for overflow detection and prevention * test fix * more tests * fix the false overflow warnings and golint * scopelint warning fix * review comments * variant with using sort by amount of change in power * compute separately number new validators in update * types: use a switch in processChanges * more review comments * types: use HasAddress in numNewValidators * types: refactor verifyUpdates copy updates, sort them by delta and use resulting slice to calculate tvpAfterUpdatesBeforeRemovals. * remove unused structs * review comments * update changelog
5 years ago
types: prevent spurious validator power overflow warnings when changing the validator set (#4183) Fix for #4164 The general problem is that in certain conditions an overflow warning is issued when attempting to update a validator set even if the final set's total voting power is not over the maximum allowed. Root cause is that in verifyUpdates(), updates are verified wrt to total voting power in the order of validator address. It is then possible that a low address validator may increase its power such that the temporary total voting power count goes over MaxTotalVotingPower. Scenarios where removing and adding/ updating validators with high voting power, in the same update operation, cause the same false warning and the updates are not applied. Main changes to fix this are in verifyUpdate() that now does the verification starting with the decreases in power. It also takes into account the removals that are part of the update. ## Commits: * tests for overflow detection and prevention * test fix * more tests * fix the false overflow warnings and golint * scopelint warning fix * review comments * variant with using sort by amount of change in power * compute separately number new validators in update * types: use a switch in processChanges * more review comments * types: use HasAddress in numNewValidators * types: refactor verifyUpdates copy updates, sort them by delta and use resulting slice to calculate tvpAfterUpdatesBeforeRemovals. * remove unused structs * review comments * update changelog
5 years ago
  1. package types
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "math"
  7. "math/rand"
  8. "sort"
  9. "strings"
  10. "testing"
  11. "testing/quick"
  12. "time"
  13. "github.com/stretchr/testify/assert"
  14. "github.com/stretchr/testify/require"
  15. "github.com/tendermint/tendermint/crypto"
  16. "github.com/tendermint/tendermint/crypto/ed25519"
  17. tmmath "github.com/tendermint/tendermint/libs/math"
  18. tmrand "github.com/tendermint/tendermint/libs/rand"
  19. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  20. )
  21. func TestValidatorSetBasic(t *testing.T) {
  22. // empty or nil validator lists are allowed,
  23. // but attempting to IncrementProposerPriority on them will panic.
  24. vset := NewValidatorSet([]*Validator{})
  25. assert.Panics(t, func() { vset.IncrementProposerPriority(1) })
  26. vset = NewValidatorSet(nil)
  27. assert.Panics(t, func() { vset.IncrementProposerPriority(1) })
  28. assert.EqualValues(t, vset, vset.Copy())
  29. assert.False(t, vset.HasAddress([]byte("some val")))
  30. idx, val := vset.GetByAddress([]byte("some val"))
  31. assert.EqualValues(t, -1, idx)
  32. assert.Nil(t, val)
  33. addr, val := vset.GetByIndex(-100)
  34. assert.Nil(t, addr)
  35. assert.Nil(t, val)
  36. addr, val = vset.GetByIndex(0)
  37. assert.Nil(t, addr)
  38. assert.Nil(t, val)
  39. addr, val = vset.GetByIndex(100)
  40. assert.Nil(t, addr)
  41. assert.Nil(t, val)
  42. assert.Zero(t, vset.Size())
  43. assert.Equal(t, int64(0), vset.TotalVotingPower())
  44. assert.Nil(t, vset.GetProposer())
  45. assert.Equal(t, []byte{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4,
  46. 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95,
  47. 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}, vset.Hash())
  48. // add
  49. val = randModuloValidator(vset.TotalVotingPower())
  50. assert.NoError(t, vset.UpdateWithChangeSet([]*Validator{val}))
  51. assert.True(t, vset.HasAddress(val.Address))
  52. idx, _ = vset.GetByAddress(val.Address)
  53. assert.EqualValues(t, 0, idx)
  54. addr, _ = vset.GetByIndex(0)
  55. assert.Equal(t, []byte(val.Address), addr)
  56. assert.Equal(t, 1, vset.Size())
  57. assert.Equal(t, val.VotingPower, vset.TotalVotingPower())
  58. assert.NotNil(t, vset.Hash())
  59. assert.NotPanics(t, func() { vset.IncrementProposerPriority(1) })
  60. assert.Equal(t, val.Address, vset.GetProposer().Address)
  61. // update
  62. val = randModuloValidator(vset.TotalVotingPower())
  63. assert.NoError(t, vset.UpdateWithChangeSet([]*Validator{val}))
  64. _, val = vset.GetByAddress(val.Address)
  65. val.VotingPower += 100
  66. proposerPriority := val.ProposerPriority
  67. val.ProposerPriority = 0
  68. assert.NoError(t, vset.UpdateWithChangeSet([]*Validator{val}))
  69. _, val = vset.GetByAddress(val.Address)
  70. assert.Equal(t, proposerPriority, val.ProposerPriority)
  71. }
  72. func TestValidatorSetValidateBasic(t *testing.T) {
  73. ctx, cancel := context.WithCancel(context.Background())
  74. defer cancel()
  75. val, _, err := randValidator(ctx, false, 1)
  76. require.NoError(t, err)
  77. badVal := &Validator{}
  78. testCases := []struct {
  79. vals ValidatorSet
  80. err bool
  81. msg string
  82. }{
  83. {
  84. vals: ValidatorSet{},
  85. err: true,
  86. msg: "validator set is nil or empty",
  87. },
  88. {
  89. vals: ValidatorSet{
  90. Validators: []*Validator{},
  91. },
  92. err: true,
  93. msg: "validator set is nil or empty",
  94. },
  95. {
  96. vals: ValidatorSet{
  97. Validators: []*Validator{val},
  98. },
  99. err: true,
  100. msg: "proposer failed validate basic, error: nil validator",
  101. },
  102. {
  103. vals: ValidatorSet{
  104. Validators: []*Validator{badVal},
  105. },
  106. err: true,
  107. msg: "invalid validator #0: validator does not have a public key",
  108. },
  109. {
  110. vals: ValidatorSet{
  111. Validators: []*Validator{val},
  112. Proposer: val,
  113. },
  114. err: false,
  115. msg: "",
  116. },
  117. }
  118. for _, tc := range testCases {
  119. err := tc.vals.ValidateBasic()
  120. if tc.err {
  121. if assert.Error(t, err) {
  122. assert.Equal(t, tc.msg, err.Error())
  123. }
  124. } else {
  125. assert.NoError(t, err)
  126. }
  127. }
  128. }
  129. func TestCopy(t *testing.T) {
  130. vset := randModuloValidatorSet(10)
  131. vsetHash := vset.Hash()
  132. if len(vsetHash) == 0 {
  133. t.Fatalf("ValidatorSet had unexpected zero hash")
  134. }
  135. vsetCopy := vset.Copy()
  136. vsetCopyHash := vsetCopy.Hash()
  137. if !bytes.Equal(vsetHash, vsetCopyHash) {
  138. t.Fatalf("ValidatorSet copy had wrong hash. Orig: %X, Copy: %X", vsetHash, vsetCopyHash)
  139. }
  140. }
  141. // Test that IncrementProposerPriority requires positive times.
  142. func TestIncrementProposerPriorityPositiveTimes(t *testing.T) {
  143. vset := NewValidatorSet([]*Validator{
  144. newValidator([]byte("foo"), 1000),
  145. newValidator([]byte("bar"), 300),
  146. newValidator([]byte("baz"), 330),
  147. })
  148. assert.Panics(t, func() { vset.IncrementProposerPriority(-1) })
  149. assert.Panics(t, func() { vset.IncrementProposerPriority(0) })
  150. vset.IncrementProposerPriority(1)
  151. }
  152. func BenchmarkValidatorSetCopy(b *testing.B) {
  153. b.StopTimer()
  154. vset := NewValidatorSet([]*Validator{})
  155. for i := 0; i < 1000; i++ {
  156. privKey := ed25519.GenPrivKey()
  157. pubKey := privKey.PubKey()
  158. val := NewValidator(pubKey, 10)
  159. err := vset.UpdateWithChangeSet([]*Validator{val})
  160. require.NoError(b, err)
  161. }
  162. b.StartTimer()
  163. for i := 0; i < b.N; i++ {
  164. vset.Copy()
  165. }
  166. }
  167. //-------------------------------------------------------------------
  168. func TestProposerSelection1(t *testing.T) {
  169. vset := NewValidatorSet([]*Validator{
  170. newValidator([]byte("foo"), 1000),
  171. newValidator([]byte("bar"), 300),
  172. newValidator([]byte("baz"), 330),
  173. })
  174. var proposers []string
  175. for i := 0; i < 99; i++ {
  176. val := vset.GetProposer()
  177. proposers = append(proposers, string(val.Address))
  178. vset.IncrementProposerPriority(1)
  179. }
  180. expected := `foo baz foo bar foo foo baz foo bar foo foo baz foo foo bar foo baz foo foo bar` +
  181. ` foo foo baz foo bar foo foo baz foo bar foo foo baz foo foo bar foo baz foo foo bar` +
  182. ` foo baz foo foo bar foo baz foo foo bar foo baz foo foo foo baz bar foo foo foo baz` +
  183. ` foo bar foo foo baz foo bar foo foo baz foo bar foo foo baz foo bar foo foo baz foo` +
  184. ` foo bar foo baz foo foo bar foo baz foo foo bar foo baz foo foo`
  185. if expected != strings.Join(proposers, " ") {
  186. t.Errorf("expected sequence of proposers was\n%v\nbut got \n%v", expected, strings.Join(proposers, " "))
  187. }
  188. }
  189. func TestProposerSelection2(t *testing.T) {
  190. addr0 := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
  191. addr1 := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
  192. addr2 := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}
  193. // when all voting power is same, we go in order of addresses
  194. val0, val1, val2 := newValidator(addr0, 100), newValidator(addr1, 100), newValidator(addr2, 100)
  195. valList := []*Validator{val0, val1, val2}
  196. vals := NewValidatorSet(valList)
  197. for i := 0; i < len(valList)*5; i++ {
  198. ii := (i) % len(valList)
  199. prop := vals.GetProposer()
  200. if !bytes.Equal(prop.Address, valList[ii].Address) {
  201. t.Fatalf("(%d): Expected %X. Got %X", i, valList[ii].Address, prop.Address)
  202. }
  203. vals.IncrementProposerPriority(1)
  204. }
  205. // One validator has more than the others, but not enough to propose twice in a row
  206. *val2 = *newValidator(addr2, 400)
  207. vals = NewValidatorSet(valList)
  208. // vals.IncrementProposerPriority(1)
  209. prop := vals.GetProposer()
  210. if !bytes.Equal(prop.Address, addr2) {
  211. t.Fatalf("Expected address with highest voting power to be first proposer. Got %X", prop.Address)
  212. }
  213. vals.IncrementProposerPriority(1)
  214. prop = vals.GetProposer()
  215. if !bytes.Equal(prop.Address, addr0) {
  216. t.Fatalf("Expected smallest address to be validator. Got %X", prop.Address)
  217. }
  218. // One validator has more than the others, and enough to be proposer twice in a row
  219. *val2 = *newValidator(addr2, 401)
  220. vals = NewValidatorSet(valList)
  221. prop = vals.GetProposer()
  222. if !bytes.Equal(prop.Address, addr2) {
  223. t.Fatalf("Expected address with highest voting power to be first proposer. Got %X", prop.Address)
  224. }
  225. vals.IncrementProposerPriority(1)
  226. prop = vals.GetProposer()
  227. if !bytes.Equal(prop.Address, addr2) {
  228. t.Fatalf("Expected address with highest voting power to be second proposer. Got %X", prop.Address)
  229. }
  230. vals.IncrementProposerPriority(1)
  231. prop = vals.GetProposer()
  232. if !bytes.Equal(prop.Address, addr0) {
  233. t.Fatalf("Expected smallest address to be validator. Got %X", prop.Address)
  234. }
  235. // each validator should be the proposer a proportional number of times
  236. val0, val1, val2 = newValidator(addr0, 4), newValidator(addr1, 5), newValidator(addr2, 3)
  237. valList = []*Validator{val0, val1, val2}
  238. propCount := make([]int, 3)
  239. vals = NewValidatorSet(valList)
  240. N := 1
  241. for i := 0; i < 120*N; i++ {
  242. prop := vals.GetProposer()
  243. ii := prop.Address[19]
  244. propCount[ii]++
  245. vals.IncrementProposerPriority(1)
  246. }
  247. if propCount[0] != 40*N {
  248. t.Fatalf(
  249. "Expected prop count for validator with 4/12 of voting power to be %d/%d. Got %d/%d",
  250. 40*N,
  251. 120*N,
  252. propCount[0],
  253. 120*N,
  254. )
  255. }
  256. if propCount[1] != 50*N {
  257. t.Fatalf(
  258. "Expected prop count for validator with 5/12 of voting power to be %d/%d. Got %d/%d",
  259. 50*N,
  260. 120*N,
  261. propCount[1],
  262. 120*N,
  263. )
  264. }
  265. if propCount[2] != 30*N {
  266. t.Fatalf(
  267. "Expected prop count for validator with 3/12 of voting power to be %d/%d. Got %d/%d",
  268. 30*N,
  269. 120*N,
  270. propCount[2],
  271. 120*N,
  272. )
  273. }
  274. }
  275. func TestProposerSelection3(t *testing.T) {
  276. vset := NewValidatorSet([]*Validator{
  277. newValidator([]byte("avalidator_address12"), 1),
  278. newValidator([]byte("bvalidator_address12"), 1),
  279. newValidator([]byte("cvalidator_address12"), 1),
  280. newValidator([]byte("dvalidator_address12"), 1),
  281. })
  282. proposerOrder := make([]*Validator, 4)
  283. for i := 0; i < 4; i++ {
  284. // need to give all validators to have keys
  285. pk := ed25519.GenPrivKey().PubKey()
  286. vset.Validators[i].PubKey = pk
  287. proposerOrder[i] = vset.GetProposer()
  288. vset.IncrementProposerPriority(1)
  289. }
  290. // i for the loop
  291. // j for the times
  292. // we should go in order for ever, despite some IncrementProposerPriority with times > 1
  293. var (
  294. i int
  295. j int32
  296. )
  297. for ; i < 10000; i++ {
  298. got := vset.GetProposer().Address
  299. expected := proposerOrder[j%4].Address
  300. if !bytes.Equal(got, expected) {
  301. t.Fatalf(fmt.Sprintf("vset.Proposer (%X) does not match expected proposer (%X) for (%d, %d)", got, expected, i, j))
  302. }
  303. // serialize, deserialize, check proposer
  304. b := vset.toBytes(t)
  305. vset = vset.fromBytes(t, b)
  306. computed := vset.GetProposer() // findGetProposer()
  307. if i != 0 {
  308. if !bytes.Equal(got, computed.Address) {
  309. t.Fatalf(
  310. fmt.Sprintf(
  311. "vset.Proposer (%X) does not match computed proposer (%X) for (%d, %d)",
  312. got,
  313. computed.Address,
  314. i,
  315. j,
  316. ),
  317. )
  318. }
  319. }
  320. // times is usually 1
  321. times := int32(1)
  322. mod := (rand.Int() % 5) + 1
  323. if rand.Int()%mod > 0 {
  324. // sometimes its up to 5
  325. times = (rand.Int31() % 4) + 1
  326. }
  327. vset.IncrementProposerPriority(times)
  328. j += times
  329. }
  330. }
  331. func newValidator(address []byte, power int64) *Validator {
  332. return &Validator{Address: address, VotingPower: power}
  333. }
  334. func randPubKey() crypto.PubKey {
  335. pubKey := make(ed25519.PubKey, ed25519.PubKeySize)
  336. copy(pubKey, tmrand.Bytes(32))
  337. return ed25519.PubKey(tmrand.Bytes(32))
  338. }
  339. func randModuloValidator(totalVotingPower int64) *Validator {
  340. // this modulo limits the ProposerPriority/VotingPower to stay in the
  341. // bounds of MaxTotalVotingPower minus the already existing voting power:
  342. val := NewValidator(randPubKey(), int64(rand.Uint64()%uint64(MaxTotalVotingPower-totalVotingPower)))
  343. val.ProposerPriority = rand.Int63() % (MaxTotalVotingPower - totalVotingPower)
  344. return val
  345. }
  346. func randValidator(ctx context.Context, randPower bool, minPower int64) (*Validator, PrivValidator, error) {
  347. privVal := NewMockPV()
  348. votePower := minPower
  349. if randPower {
  350. votePower += int64(rand.Uint32())
  351. }
  352. pubKey, err := privVal.GetPubKey(ctx)
  353. if err != nil {
  354. return nil, nil, err
  355. }
  356. val := NewValidator(pubKey, votePower)
  357. return val, privVal, nil
  358. }
  359. func randModuloValidatorSet(numValidators int) *ValidatorSet {
  360. validators := make([]*Validator, numValidators)
  361. totalVotingPower := int64(0)
  362. for i := 0; i < numValidators; i++ {
  363. validators[i] = randModuloValidator(totalVotingPower)
  364. totalVotingPower += validators[i].VotingPower
  365. }
  366. return NewValidatorSet(validators)
  367. }
  368. func (vals *ValidatorSet) toBytes(t *testing.T) []byte {
  369. pbvs, err := vals.ToProto()
  370. require.NoError(t, err)
  371. bz, err := pbvs.Marshal()
  372. require.NoError(t, err)
  373. return bz
  374. }
  375. func (vals *ValidatorSet) fromBytes(t *testing.T, b []byte) *ValidatorSet {
  376. pbvs := new(tmproto.ValidatorSet)
  377. err := pbvs.Unmarshal(b)
  378. require.NoError(t, err)
  379. vs, err := ValidatorSetFromProto(pbvs)
  380. require.NoError(t, err)
  381. return vs
  382. }
  383. //-------------------------------------------------------------------
  384. func TestValidatorSetTotalVotingPowerPanicsOnOverflow(t *testing.T) {
  385. // NewValidatorSet calls IncrementProposerPriority which calls TotalVotingPower()
  386. // which should panic on overflows:
  387. shouldPanic := func() {
  388. NewValidatorSet([]*Validator{
  389. {Address: []byte("a"), VotingPower: math.MaxInt64, ProposerPriority: 0},
  390. {Address: []byte("b"), VotingPower: math.MaxInt64, ProposerPriority: 0},
  391. {Address: []byte("c"), VotingPower: math.MaxInt64, ProposerPriority: 0},
  392. })
  393. }
  394. assert.Panics(t, shouldPanic)
  395. }
  396. func TestAvgProposerPriority(t *testing.T) {
  397. // Create Validator set without calling IncrementProposerPriority:
  398. tcs := []struct {
  399. vs ValidatorSet
  400. want int64
  401. }{
  402. 0: {ValidatorSet{Validators: []*Validator{{ProposerPriority: 0}, {ProposerPriority: 0}, {ProposerPriority: 0}}}, 0},
  403. 1: {
  404. ValidatorSet{
  405. Validators: []*Validator{{ProposerPriority: math.MaxInt64}, {ProposerPriority: 0}, {ProposerPriority: 0}},
  406. }, math.MaxInt64 / 3,
  407. },
  408. 2: {
  409. ValidatorSet{
  410. Validators: []*Validator{{ProposerPriority: math.MaxInt64}, {ProposerPriority: 0}},
  411. }, math.MaxInt64 / 2,
  412. },
  413. 3: {
  414. ValidatorSet{
  415. Validators: []*Validator{{ProposerPriority: math.MaxInt64}, {ProposerPriority: math.MaxInt64}},
  416. }, math.MaxInt64,
  417. },
  418. 4: {
  419. ValidatorSet{
  420. Validators: []*Validator{{ProposerPriority: math.MinInt64}, {ProposerPriority: math.MinInt64}},
  421. }, math.MinInt64,
  422. },
  423. }
  424. for i, tc := range tcs {
  425. got := tc.vs.computeAvgProposerPriority()
  426. assert.Equal(t, tc.want, got, "test case: %v", i)
  427. }
  428. }
  429. func TestAveragingInIncrementProposerPriority(t *testing.T) {
  430. // Test that the averaging works as expected inside of IncrementProposerPriority.
  431. // Each validator comes with zero voting power which simplifies reasoning about
  432. // the expected ProposerPriority.
  433. tcs := []struct {
  434. vs ValidatorSet
  435. times int32
  436. avg int64
  437. }{
  438. 0: {ValidatorSet{
  439. Validators: []*Validator{
  440. {Address: []byte("a"), ProposerPriority: 1},
  441. {Address: []byte("b"), ProposerPriority: 2},
  442. {Address: []byte("c"), ProposerPriority: 3}}},
  443. 1, 2},
  444. 1: {ValidatorSet{
  445. Validators: []*Validator{
  446. {Address: []byte("a"), ProposerPriority: 10},
  447. {Address: []byte("b"), ProposerPriority: -10},
  448. {Address: []byte("c"), ProposerPriority: 1}}},
  449. // this should average twice but the average should be 0 after the first iteration
  450. // (voting power is 0 -> no changes)
  451. 11, 0},
  452. 2: {ValidatorSet{
  453. Validators: []*Validator{
  454. {Address: []byte("a"), ProposerPriority: 100},
  455. {Address: []byte("b"), ProposerPriority: -10},
  456. {Address: []byte("c"), ProposerPriority: 1}}},
  457. 1, 91 / 3},
  458. }
  459. for i, tc := range tcs {
  460. // work on copy to have the old ProposerPriorities:
  461. newVset := tc.vs.CopyIncrementProposerPriority(tc.times)
  462. for _, val := range tc.vs.Validators {
  463. _, updatedVal := newVset.GetByAddress(val.Address)
  464. assert.Equal(t, updatedVal.ProposerPriority, val.ProposerPriority-tc.avg, "test case: %v", i)
  465. }
  466. }
  467. }
  468. func TestAveragingInIncrementProposerPriorityWithVotingPower(t *testing.T) {
  469. // Other than TestAveragingInIncrementProposerPriority this is a more complete test showing
  470. // how each ProposerPriority changes in relation to the validator's voting power respectively.
  471. // average is zero in each round:
  472. vp0 := int64(10)
  473. vp1 := int64(1)
  474. vp2 := int64(1)
  475. total := vp0 + vp1 + vp2
  476. avg := (vp0 + vp1 + vp2 - total) / 3
  477. vals := ValidatorSet{Validators: []*Validator{
  478. {Address: []byte{0}, ProposerPriority: 0, VotingPower: vp0},
  479. {Address: []byte{1}, ProposerPriority: 0, VotingPower: vp1},
  480. {Address: []byte{2}, ProposerPriority: 0, VotingPower: vp2}}}
  481. tcs := []struct {
  482. vals *ValidatorSet
  483. wantProposerPrioritys []int64
  484. times int32
  485. wantProposer *Validator
  486. }{
  487. 0: {
  488. vals.Copy(),
  489. []int64{
  490. // Acumm+VotingPower-Avg:
  491. 0 + vp0 - total - avg, // mostest will be subtracted by total voting power (12)
  492. 0 + vp1,
  493. 0 + vp2},
  494. 1,
  495. vals.Validators[0]},
  496. 1: {
  497. vals.Copy(),
  498. []int64{
  499. (0 + vp0 - total) + vp0 - total - avg, // this will be mostest on 2nd iter, too
  500. (0 + vp1) + vp1,
  501. (0 + vp2) + vp2},
  502. 2,
  503. vals.Validators[0]}, // increment twice -> expect average to be subtracted twice
  504. 2: {
  505. vals.Copy(),
  506. []int64{
  507. 0 + 3*(vp0-total) - avg, // still mostest
  508. 0 + 3*vp1,
  509. 0 + 3*vp2},
  510. 3,
  511. vals.Validators[0]},
  512. 3: {
  513. vals.Copy(),
  514. []int64{
  515. 0 + 4*(vp0-total), // still mostest
  516. 0 + 4*vp1,
  517. 0 + 4*vp2},
  518. 4,
  519. vals.Validators[0]},
  520. 4: {
  521. vals.Copy(),
  522. []int64{
  523. 0 + 4*(vp0-total) + vp0, // 4 iters was mostest
  524. 0 + 5*vp1 - total, // now this val is mostest for the 1st time (hence -12==totalVotingPower)
  525. 0 + 5*vp2},
  526. 5,
  527. vals.Validators[1]},
  528. 5: {
  529. vals.Copy(),
  530. []int64{
  531. 0 + 6*vp0 - 5*total, // mostest again
  532. 0 + 6*vp1 - total, // mostest once up to here
  533. 0 + 6*vp2},
  534. 6,
  535. vals.Validators[0]},
  536. 6: {
  537. vals.Copy(),
  538. []int64{
  539. 0 + 7*vp0 - 6*total, // in 7 iters this val is mostest 6 times
  540. 0 + 7*vp1 - total, // in 7 iters this val is mostest 1 time
  541. 0 + 7*vp2},
  542. 7,
  543. vals.Validators[0]},
  544. 7: {
  545. vals.Copy(),
  546. []int64{
  547. 0 + 8*vp0 - 7*total, // mostest again
  548. 0 + 8*vp1 - total,
  549. 0 + 8*vp2},
  550. 8,
  551. vals.Validators[0]},
  552. 8: {
  553. vals.Copy(),
  554. []int64{
  555. 0 + 9*vp0 - 7*total,
  556. 0 + 9*vp1 - total,
  557. 0 + 9*vp2 - total}, // mostest
  558. 9,
  559. vals.Validators[2]},
  560. 9: {
  561. vals.Copy(),
  562. []int64{
  563. 0 + 10*vp0 - 8*total, // after 10 iters this is mostest again
  564. 0 + 10*vp1 - total, // after 6 iters this val is "mostest" once and not in between
  565. 0 + 10*vp2 - total}, // in between 10 iters this val is "mostest" once
  566. 10,
  567. vals.Validators[0]},
  568. 10: {
  569. vals.Copy(),
  570. []int64{
  571. 0 + 11*vp0 - 9*total,
  572. 0 + 11*vp1 - total, // after 6 iters this val is "mostest" once and not in between
  573. 0 + 11*vp2 - total}, // after 10 iters this val is "mostest" once
  574. 11,
  575. vals.Validators[0]},
  576. }
  577. for i, tc := range tcs {
  578. tc.vals.IncrementProposerPriority(tc.times)
  579. assert.Equal(t, tc.wantProposer.Address, tc.vals.GetProposer().Address,
  580. "test case: %v",
  581. i)
  582. for valIdx, val := range tc.vals.Validators {
  583. assert.Equal(t,
  584. tc.wantProposerPrioritys[valIdx],
  585. val.ProposerPriority,
  586. "test case: %v, validator: %v",
  587. i,
  588. valIdx)
  589. }
  590. }
  591. }
  592. func TestSafeAdd(t *testing.T) {
  593. f := func(a, b int64) bool {
  594. c, overflow := safeAdd(a, b)
  595. return overflow || (!overflow && c == a+b)
  596. }
  597. if err := quick.Check(f, nil); err != nil {
  598. t.Error(err)
  599. }
  600. }
  601. func TestSafeAddClip(t *testing.T) {
  602. assert.EqualValues(t, math.MaxInt64, safeAddClip(math.MaxInt64, 10))
  603. assert.EqualValues(t, math.MaxInt64, safeAddClip(math.MaxInt64, math.MaxInt64))
  604. assert.EqualValues(t, math.MinInt64, safeAddClip(math.MinInt64, -10))
  605. }
  606. func TestSafeSubClip(t *testing.T) {
  607. assert.EqualValues(t, math.MinInt64, safeSubClip(math.MinInt64, 10))
  608. assert.EqualValues(t, 0, safeSubClip(math.MinInt64, math.MinInt64))
  609. assert.EqualValues(t, math.MinInt64, safeSubClip(math.MinInt64, math.MaxInt64))
  610. assert.EqualValues(t, math.MaxInt64, safeSubClip(math.MaxInt64, -10))
  611. }
  612. //-------------------------------------------------------------------
  613. func TestEmptySet(t *testing.T) {
  614. var valList []*Validator
  615. valSet := NewValidatorSet(valList)
  616. assert.Panics(t, func() { valSet.IncrementProposerPriority(1) })
  617. assert.Panics(t, func() { valSet.RescalePriorities(100) })
  618. assert.Panics(t, func() { valSet.shiftByAvgProposerPriority() })
  619. assert.Panics(t, func() { assert.Zero(t, computeMaxMinPriorityDiff(valSet)) })
  620. valSet.GetProposer()
  621. // Add to empty set
  622. v1 := newValidator([]byte("v1"), 100)
  623. v2 := newValidator([]byte("v2"), 100)
  624. valList = []*Validator{v1, v2}
  625. assert.NoError(t, valSet.UpdateWithChangeSet(valList))
  626. verifyValidatorSet(t, valSet)
  627. // Delete all validators from set
  628. v1 = newValidator([]byte("v1"), 0)
  629. v2 = newValidator([]byte("v2"), 0)
  630. delList := []*Validator{v1, v2}
  631. assert.Error(t, valSet.UpdateWithChangeSet(delList))
  632. // Attempt delete from empty set
  633. assert.Error(t, valSet.UpdateWithChangeSet(delList))
  634. }
  635. func TestUpdatesForNewValidatorSet(t *testing.T) {
  636. v1 := newValidator([]byte("v1"), 100)
  637. v2 := newValidator([]byte("v2"), 100)
  638. valList := []*Validator{v1, v2}
  639. valSet := NewValidatorSet(valList)
  640. verifyValidatorSet(t, valSet)
  641. // Verify duplicates are caught in NewValidatorSet() and it panics
  642. v111 := newValidator([]byte("v1"), 100)
  643. v112 := newValidator([]byte("v1"), 123)
  644. v113 := newValidator([]byte("v1"), 234)
  645. valList = []*Validator{v111, v112, v113}
  646. assert.Panics(t, func() { NewValidatorSet(valList) })
  647. // Verify set including validator with voting power 0 cannot be created
  648. v1 = newValidator([]byte("v1"), 0)
  649. v2 = newValidator([]byte("v2"), 22)
  650. v3 := newValidator([]byte("v3"), 33)
  651. valList = []*Validator{v1, v2, v3}
  652. assert.Panics(t, func() { NewValidatorSet(valList) })
  653. // Verify set including validator with negative voting power cannot be created
  654. v1 = newValidator([]byte("v1"), 10)
  655. v2 = newValidator([]byte("v2"), -20)
  656. v3 = newValidator([]byte("v3"), 30)
  657. valList = []*Validator{v1, v2, v3}
  658. assert.Panics(t, func() { NewValidatorSet(valList) })
  659. }
  660. type testVal struct {
  661. name string
  662. power int64
  663. }
  664. func permutation(valList []testVal) []testVal {
  665. if len(valList) == 0 {
  666. return nil
  667. }
  668. permList := make([]testVal, len(valList))
  669. perm := rand.Perm(len(valList))
  670. for i, v := range perm {
  671. permList[v] = valList[i]
  672. }
  673. return permList
  674. }
  675. func createNewValidatorList(testValList []testVal) []*Validator {
  676. valList := make([]*Validator, 0, len(testValList))
  677. for _, val := range testValList {
  678. valList = append(valList, newValidator([]byte(val.name), val.power))
  679. }
  680. return valList
  681. }
  682. func createNewValidatorSet(testValList []testVal) *ValidatorSet {
  683. return NewValidatorSet(createNewValidatorList(testValList))
  684. }
  685. func valSetTotalProposerPriority(valSet *ValidatorSet) int64 {
  686. sum := int64(0)
  687. for _, val := range valSet.Validators {
  688. // mind overflow
  689. sum = safeAddClip(sum, val.ProposerPriority)
  690. }
  691. return sum
  692. }
  693. func verifyValidatorSet(t *testing.T, valSet *ValidatorSet) {
  694. // verify that the capacity and length of validators is the same
  695. assert.Equal(t, len(valSet.Validators), cap(valSet.Validators))
  696. // verify that the set's total voting power has been updated
  697. tvp := valSet.totalVotingPower
  698. valSet.updateTotalVotingPower()
  699. expectedTvp := valSet.TotalVotingPower()
  700. assert.Equal(t, expectedTvp, tvp,
  701. "expected TVP %d. Got %d, valSet=%s", expectedTvp, tvp, valSet)
  702. // verify that validator priorities are centered
  703. valsCount := int64(len(valSet.Validators))
  704. tpp := valSetTotalProposerPriority(valSet)
  705. assert.True(t, tpp < valsCount && tpp > -valsCount,
  706. "expected total priority in (-%d, %d). Got %d", valsCount, valsCount, tpp)
  707. // verify that priorities are scaled
  708. dist := computeMaxMinPriorityDiff(valSet)
  709. assert.True(t, dist <= PriorityWindowSizeFactor*tvp,
  710. "expected priority distance < %d. Got %d", PriorityWindowSizeFactor*tvp, dist)
  711. }
  712. func toTestValList(valList []*Validator) []testVal {
  713. testList := make([]testVal, len(valList))
  714. for i, val := range valList {
  715. testList[i].name = string(val.Address)
  716. testList[i].power = val.VotingPower
  717. }
  718. return testList
  719. }
  720. func testValSet(nVals int, power int64) []testVal {
  721. vals := make([]testVal, nVals)
  722. for i := 0; i < nVals; i++ {
  723. vals[i] = testVal{fmt.Sprintf("v%d", i+1), power}
  724. }
  725. return vals
  726. }
  727. type valSetErrTestCase struct {
  728. startVals []testVal
  729. updateVals []testVal
  730. }
  731. func executeValSetErrTestCase(t *testing.T, idx int, tt valSetErrTestCase) {
  732. // create a new set and apply updates, keeping copies for the checks
  733. valSet := createNewValidatorSet(tt.startVals)
  734. valSetCopy := valSet.Copy()
  735. valList := createNewValidatorList(tt.updateVals)
  736. valListCopy := validatorListCopy(valList)
  737. err := valSet.UpdateWithChangeSet(valList)
  738. // for errors check the validator set has not been changed
  739. assert.Error(t, err, "test %d", idx)
  740. assert.Equal(t, valSet, valSetCopy, "test %v", idx)
  741. // check the parameter list has not changed
  742. assert.Equal(t, valList, valListCopy, "test %v", idx)
  743. }
  744. func TestValSetUpdatesDuplicateEntries(t *testing.T) {
  745. testCases := []valSetErrTestCase{
  746. // Duplicate entries in changes
  747. { // first entry is duplicated change
  748. testValSet(2, 10),
  749. []testVal{{"v1", 11}, {"v1", 22}},
  750. },
  751. { // second entry is duplicated change
  752. testValSet(2, 10),
  753. []testVal{{"v2", 11}, {"v2", 22}},
  754. },
  755. { // change duplicates are separated by a valid change
  756. testValSet(2, 10),
  757. []testVal{{"v1", 11}, {"v2", 22}, {"v1", 12}},
  758. },
  759. { // change duplicates are separated by a valid change
  760. testValSet(3, 10),
  761. []testVal{{"v1", 11}, {"v3", 22}, {"v1", 12}},
  762. },
  763. // Duplicate entries in remove
  764. { // first entry is duplicated remove
  765. testValSet(2, 10),
  766. []testVal{{"v1", 0}, {"v1", 0}},
  767. },
  768. { // second entry is duplicated remove
  769. testValSet(2, 10),
  770. []testVal{{"v2", 0}, {"v2", 0}},
  771. },
  772. { // remove duplicates are separated by a valid remove
  773. testValSet(2, 10),
  774. []testVal{{"v1", 0}, {"v2", 0}, {"v1", 0}},
  775. },
  776. { // remove duplicates are separated by a valid remove
  777. testValSet(3, 10),
  778. []testVal{{"v1", 0}, {"v3", 0}, {"v1", 0}},
  779. },
  780. { // remove and update same val
  781. testValSet(2, 10),
  782. []testVal{{"v1", 0}, {"v2", 20}, {"v1", 30}},
  783. },
  784. { // duplicate entries in removes + changes
  785. testValSet(2, 10),
  786. []testVal{{"v1", 0}, {"v2", 20}, {"v2", 30}, {"v1", 0}},
  787. },
  788. { // duplicate entries in removes + changes
  789. testValSet(3, 10),
  790. []testVal{{"v1", 0}, {"v3", 5}, {"v2", 20}, {"v2", 30}, {"v1", 0}},
  791. },
  792. }
  793. for i, tt := range testCases {
  794. executeValSetErrTestCase(t, i, tt)
  795. }
  796. }
  797. func TestValSetUpdatesOverflows(t *testing.T) {
  798. maxVP := MaxTotalVotingPower
  799. testCases := []valSetErrTestCase{
  800. { // single update leading to overflow
  801. testValSet(2, 10),
  802. []testVal{{"v1", math.MaxInt64}},
  803. },
  804. { // single update leading to overflow
  805. testValSet(2, 10),
  806. []testVal{{"v2", math.MaxInt64}},
  807. },
  808. { // add validator leading to overflow
  809. testValSet(1, maxVP),
  810. []testVal{{"v2", math.MaxInt64}},
  811. },
  812. { // add validator leading to exceed Max
  813. testValSet(1, maxVP-1),
  814. []testVal{{"v2", 5}},
  815. },
  816. { // add validator leading to exceed Max
  817. testValSet(2, maxVP/3),
  818. []testVal{{"v3", maxVP / 2}},
  819. },
  820. { // add validator leading to exceed Max
  821. testValSet(1, maxVP),
  822. []testVal{{"v2", maxVP}},
  823. },
  824. }
  825. for i, tt := range testCases {
  826. executeValSetErrTestCase(t, i, tt)
  827. }
  828. }
  829. func TestValSetUpdatesOtherErrors(t *testing.T) {
  830. testCases := []valSetErrTestCase{
  831. { // update with negative voting power
  832. testValSet(2, 10),
  833. []testVal{{"v1", -123}},
  834. },
  835. { // update with negative voting power
  836. testValSet(2, 10),
  837. []testVal{{"v2", -123}},
  838. },
  839. { // remove non-existing validator
  840. testValSet(2, 10),
  841. []testVal{{"v3", 0}},
  842. },
  843. { // delete all validators
  844. []testVal{{"v1", 10}, {"v2", 20}, {"v3", 30}},
  845. []testVal{{"v1", 0}, {"v2", 0}, {"v3", 0}},
  846. },
  847. }
  848. for i, tt := range testCases {
  849. executeValSetErrTestCase(t, i, tt)
  850. }
  851. }
  852. func TestValSetUpdatesBasicTestsExecute(t *testing.T) {
  853. valSetUpdatesBasicTests := []struct {
  854. startVals []testVal
  855. updateVals []testVal
  856. expectedVals []testVal
  857. }{
  858. { // no changes
  859. testValSet(2, 10),
  860. []testVal{},
  861. testValSet(2, 10),
  862. },
  863. { // voting power changes
  864. testValSet(2, 10),
  865. []testVal{{"v2", 22}, {"v1", 11}},
  866. []testVal{{"v2", 22}, {"v1", 11}},
  867. },
  868. { // add new validators
  869. []testVal{{"v2", 20}, {"v1", 10}},
  870. []testVal{{"v4", 40}, {"v3", 30}},
  871. []testVal{{"v4", 40}, {"v3", 30}, {"v2", 20}, {"v1", 10}},
  872. },
  873. { // add new validator to middle
  874. []testVal{{"v3", 20}, {"v1", 10}},
  875. []testVal{{"v2", 30}},
  876. []testVal{{"v2", 30}, {"v3", 20}, {"v1", 10}},
  877. },
  878. { // add new validator to beginning
  879. []testVal{{"v3", 20}, {"v2", 10}},
  880. []testVal{{"v1", 30}},
  881. []testVal{{"v1", 30}, {"v3", 20}, {"v2", 10}},
  882. },
  883. { // delete validators
  884. []testVal{{"v3", 30}, {"v2", 20}, {"v1", 10}},
  885. []testVal{{"v2", 0}},
  886. []testVal{{"v3", 30}, {"v1", 10}},
  887. },
  888. }
  889. for i, tt := range valSetUpdatesBasicTests {
  890. // create a new set and apply updates, keeping copies for the checks
  891. valSet := createNewValidatorSet(tt.startVals)
  892. valList := createNewValidatorList(tt.updateVals)
  893. err := valSet.UpdateWithChangeSet(valList)
  894. assert.NoError(t, err, "test %d", i)
  895. valListCopy := validatorListCopy(valSet.Validators)
  896. // check that the voting power in the set's validators is not changing if the voting power
  897. // is changed in the list of validators previously passed as parameter to UpdateWithChangeSet.
  898. // this is to make sure copies of the validators are made by UpdateWithChangeSet.
  899. if len(valList) > 0 {
  900. valList[0].VotingPower++
  901. assert.Equal(t, toTestValList(valListCopy), toTestValList(valSet.Validators), "test %v", i)
  902. }
  903. // check the final validator list is as expected and the set is properly scaled and centered.
  904. assert.Equal(t, tt.expectedVals, toTestValList(valSet.Validators), "test %v", i)
  905. verifyValidatorSet(t, valSet)
  906. }
  907. }
  908. // Test that different permutations of an update give the same result.
  909. func TestValSetUpdatesOrderIndependenceTestsExecute(t *testing.T) {
  910. // startVals - initial validators to create the set with
  911. // updateVals - a sequence of updates to be applied to the set.
  912. // updateVals is shuffled a number of times during testing to check for same resulting validator set.
  913. valSetUpdatesOrderTests := []struct {
  914. startVals []testVal
  915. updateVals []testVal
  916. }{
  917. 0: { // order of changes should not matter, the final validator sets should be the same
  918. []testVal{{"v4", 40}, {"v3", 30}, {"v2", 10}, {"v1", 10}},
  919. []testVal{{"v4", 44}, {"v3", 33}, {"v2", 22}, {"v1", 11}}},
  920. 1: { // order of additions should not matter
  921. []testVal{{"v2", 20}, {"v1", 10}},
  922. []testVal{{"v3", 30}, {"v4", 40}, {"v5", 50}, {"v6", 60}}},
  923. 2: { // order of removals should not matter
  924. []testVal{{"v4", 40}, {"v3", 30}, {"v2", 20}, {"v1", 10}},
  925. []testVal{{"v1", 0}, {"v3", 0}, {"v4", 0}}},
  926. 3: { // order of mixed operations should not matter
  927. []testVal{{"v4", 40}, {"v3", 30}, {"v2", 20}, {"v1", 10}},
  928. []testVal{{"v1", 0}, {"v3", 0}, {"v2", 22}, {"v5", 50}, {"v4", 44}}},
  929. }
  930. for i, tt := range valSetUpdatesOrderTests {
  931. // create a new set and apply updates
  932. valSet := createNewValidatorSet(tt.startVals)
  933. valSetCopy := valSet.Copy()
  934. valList := createNewValidatorList(tt.updateVals)
  935. assert.NoError(t, valSetCopy.UpdateWithChangeSet(valList))
  936. // save the result as expected for next updates
  937. valSetExp := valSetCopy.Copy()
  938. // perform at most 20 permutations on the updates and call UpdateWithChangeSet()
  939. n := len(tt.updateVals)
  940. maxNumPerms := tmmath.MinInt(20, n*n)
  941. for j := 0; j < maxNumPerms; j++ {
  942. // create a copy of original set and apply a random permutation of updates
  943. valSetCopy := valSet.Copy()
  944. valList := createNewValidatorList(permutation(tt.updateVals))
  945. // check there was no error and the set is properly scaled and centered.
  946. assert.NoError(t, valSetCopy.UpdateWithChangeSet(valList),
  947. "test %v failed for permutation %v", i, valList)
  948. verifyValidatorSet(t, valSetCopy)
  949. // verify the resulting test is same as the expected
  950. assert.Equal(t, valSetCopy, valSetExp,
  951. "test %v failed for permutation %v", i, valList)
  952. }
  953. }
  954. }
  955. // This tests the private function validator_set.go:applyUpdates() function, used only for additions and changes.
  956. // Should perform a proper merge of updatedVals and startVals
  957. func TestValSetApplyUpdatesTestsExecute(t *testing.T) {
  958. valSetUpdatesBasicTests := []struct {
  959. startVals []testVal
  960. updateVals []testVal
  961. expectedVals []testVal
  962. }{
  963. // additions
  964. 0: { // prepend
  965. []testVal{{"v4", 44}, {"v5", 55}},
  966. []testVal{{"v1", 11}},
  967. []testVal{{"v1", 11}, {"v4", 44}, {"v5", 55}}},
  968. 1: { // append
  969. []testVal{{"v4", 44}, {"v5", 55}},
  970. []testVal{{"v6", 66}},
  971. []testVal{{"v4", 44}, {"v5", 55}, {"v6", 66}}},
  972. 2: { // insert
  973. []testVal{{"v4", 44}, {"v6", 66}},
  974. []testVal{{"v5", 55}},
  975. []testVal{{"v4", 44}, {"v5", 55}, {"v6", 66}}},
  976. 3: { // insert multi
  977. []testVal{{"v4", 44}, {"v6", 66}, {"v9", 99}},
  978. []testVal{{"v5", 55}, {"v7", 77}, {"v8", 88}},
  979. []testVal{{"v4", 44}, {"v5", 55}, {"v6", 66}, {"v7", 77}, {"v8", 88}, {"v9", 99}}},
  980. // changes
  981. 4: { // head
  982. []testVal{{"v1", 111}, {"v2", 22}},
  983. []testVal{{"v1", 11}},
  984. []testVal{{"v1", 11}, {"v2", 22}}},
  985. 5: { // tail
  986. []testVal{{"v1", 11}, {"v2", 222}},
  987. []testVal{{"v2", 22}},
  988. []testVal{{"v1", 11}, {"v2", 22}}},
  989. 6: { // middle
  990. []testVal{{"v1", 11}, {"v2", 222}, {"v3", 33}},
  991. []testVal{{"v2", 22}},
  992. []testVal{{"v1", 11}, {"v2", 22}, {"v3", 33}}},
  993. 7: { // multi
  994. []testVal{{"v1", 111}, {"v2", 222}, {"v3", 333}},
  995. []testVal{{"v1", 11}, {"v2", 22}, {"v3", 33}},
  996. []testVal{{"v1", 11}, {"v2", 22}, {"v3", 33}}},
  997. // additions and changes
  998. 8: {
  999. []testVal{{"v1", 111}, {"v2", 22}},
  1000. []testVal{{"v1", 11}, {"v3", 33}, {"v4", 44}},
  1001. []testVal{{"v1", 11}, {"v2", 22}, {"v3", 33}, {"v4", 44}}},
  1002. }
  1003. for i, tt := range valSetUpdatesBasicTests {
  1004. // create a new validator set with the start values
  1005. valSet := createNewValidatorSet(tt.startVals)
  1006. // applyUpdates() with the update values
  1007. valList := createNewValidatorList(tt.updateVals)
  1008. valSet.applyUpdates(valList)
  1009. // check the new list of validators for proper merge
  1010. assert.Equal(t, toTestValList(valSet.Validators), tt.expectedVals, "test %v", i)
  1011. }
  1012. }
  1013. type testVSetCfg struct {
  1014. name string
  1015. startVals []testVal
  1016. deletedVals []testVal
  1017. updatedVals []testVal
  1018. addedVals []testVal
  1019. expectedVals []testVal
  1020. expErr error
  1021. }
  1022. func randTestVSetCfg(t *testing.T, nBase, nAddMax int) testVSetCfg {
  1023. if nBase <= 0 || nAddMax < 0 {
  1024. t.Fatalf("bad parameters %v %v", nBase, nAddMax)
  1025. }
  1026. const maxPower = 1000
  1027. var nOld, nDel, nChanged, nAdd int
  1028. nOld = int(uint(rand.Int())%uint(nBase)) + 1
  1029. if nBase-nOld > 0 {
  1030. nDel = int(uint(rand.Int()) % uint(nBase-nOld))
  1031. }
  1032. nChanged = nBase - nOld - nDel
  1033. if nAddMax > 0 {
  1034. nAdd = rand.Int()%nAddMax + 1
  1035. }
  1036. cfg := testVSetCfg{}
  1037. cfg.startVals = make([]testVal, nBase)
  1038. cfg.deletedVals = make([]testVal, nDel)
  1039. cfg.addedVals = make([]testVal, nAdd)
  1040. cfg.updatedVals = make([]testVal, nChanged)
  1041. cfg.expectedVals = make([]testVal, nBase-nDel+nAdd)
  1042. for i := 0; i < nBase; i++ {
  1043. cfg.startVals[i] = testVal{fmt.Sprintf("v%d", i), int64(uint(rand.Int())%maxPower + 1)}
  1044. if i < nOld {
  1045. cfg.expectedVals[i] = cfg.startVals[i]
  1046. }
  1047. if i >= nOld && i < nOld+nChanged {
  1048. cfg.updatedVals[i-nOld] = testVal{fmt.Sprintf("v%d", i), int64(uint(rand.Int())%maxPower + 1)}
  1049. cfg.expectedVals[i] = cfg.updatedVals[i-nOld]
  1050. }
  1051. if i >= nOld+nChanged {
  1052. cfg.deletedVals[i-nOld-nChanged] = testVal{fmt.Sprintf("v%d", i), 0}
  1053. }
  1054. }
  1055. for i := nBase; i < nBase+nAdd; i++ {
  1056. cfg.addedVals[i-nBase] = testVal{fmt.Sprintf("v%d", i), int64(uint(rand.Int())%maxPower + 1)}
  1057. cfg.expectedVals[i-nDel] = cfg.addedVals[i-nBase]
  1058. }
  1059. sort.Sort(testValsByVotingPower(cfg.startVals))
  1060. sort.Sort(testValsByVotingPower(cfg.deletedVals))
  1061. sort.Sort(testValsByVotingPower(cfg.updatedVals))
  1062. sort.Sort(testValsByVotingPower(cfg.addedVals))
  1063. sort.Sort(testValsByVotingPower(cfg.expectedVals))
  1064. return cfg
  1065. }
  1066. func applyChangesToValSet(t *testing.T, expErr error, valSet *ValidatorSet, valsLists ...[]testVal) {
  1067. changes := make([]testVal, 0)
  1068. for _, valsList := range valsLists {
  1069. changes = append(changes, valsList...)
  1070. }
  1071. valList := createNewValidatorList(changes)
  1072. err := valSet.UpdateWithChangeSet(valList)
  1073. if expErr != nil {
  1074. assert.Equal(t, expErr, err)
  1075. } else {
  1076. assert.NoError(t, err)
  1077. }
  1078. }
  1079. func TestValSetUpdatePriorityOrderTests(t *testing.T) {
  1080. const nMaxElections int32 = 5000
  1081. testCases := []testVSetCfg{
  1082. 0: { // remove high power validator, keep old equal lower power validators
  1083. startVals: []testVal{{"v3", 1000}, {"v1", 1}, {"v2", 1}},
  1084. deletedVals: []testVal{{"v3", 0}},
  1085. updatedVals: []testVal{},
  1086. addedVals: []testVal{},
  1087. expectedVals: []testVal{{"v1", 1}, {"v2", 1}},
  1088. },
  1089. 1: { // remove high power validator, keep old different power validators
  1090. startVals: []testVal{{"v3", 1000}, {"v2", 10}, {"v1", 1}},
  1091. deletedVals: []testVal{{"v3", 0}},
  1092. updatedVals: []testVal{},
  1093. addedVals: []testVal{},
  1094. expectedVals: []testVal{{"v2", 10}, {"v1", 1}},
  1095. },
  1096. 2: { // remove high power validator, add new low power validators, keep old lower power
  1097. startVals: []testVal{{"v3", 1000}, {"v2", 2}, {"v1", 1}},
  1098. deletedVals: []testVal{{"v3", 0}},
  1099. updatedVals: []testVal{{"v2", 1}},
  1100. addedVals: []testVal{{"v5", 50}, {"v4", 40}},
  1101. expectedVals: []testVal{{"v5", 50}, {"v4", 40}, {"v1", 1}, {"v2", 1}},
  1102. },
  1103. // generate a configuration with 100 validators,
  1104. // randomly select validators for updates and deletes, and
  1105. // generate 10 new validators to be added
  1106. 3: randTestVSetCfg(t, 100, 10),
  1107. 4: randTestVSetCfg(t, 1000, 100),
  1108. 5: randTestVSetCfg(t, 10, 100),
  1109. 6: randTestVSetCfg(t, 100, 1000),
  1110. 7: randTestVSetCfg(t, 1000, 1000),
  1111. }
  1112. for _, cfg := range testCases {
  1113. // create a new validator set
  1114. valSet := createNewValidatorSet(cfg.startVals)
  1115. verifyValidatorSet(t, valSet)
  1116. // run election up to nMaxElections times, apply changes and verify that the priority order is correct
  1117. verifyValSetUpdatePriorityOrder(t, valSet, cfg, nMaxElections)
  1118. }
  1119. }
  1120. func verifyValSetUpdatePriorityOrder(t *testing.T, valSet *ValidatorSet, cfg testVSetCfg, nMaxElections int32) {
  1121. // Run election up to nMaxElections times, sort validators by priorities
  1122. valSet.IncrementProposerPriority(rand.Int31()%nMaxElections + 1)
  1123. // apply the changes, get the updated validators, sort by priorities
  1124. applyChangesToValSet(t, nil, valSet, cfg.addedVals, cfg.updatedVals, cfg.deletedVals)
  1125. // basic checks
  1126. assert.Equal(t, cfg.expectedVals, toTestValList(valSet.Validators))
  1127. verifyValidatorSet(t, valSet)
  1128. // verify that the added validators have the smallest priority:
  1129. // - they should be at the beginning of updatedValsPriSorted since it is
  1130. // sorted by priority
  1131. if len(cfg.addedVals) > 0 {
  1132. updatedValsPriSorted := validatorListCopy(valSet.Validators)
  1133. sort.Sort(validatorsByPriority(updatedValsPriSorted))
  1134. addedValsPriSlice := updatedValsPriSorted[:len(cfg.addedVals)]
  1135. sort.Sort(ValidatorsByVotingPower(addedValsPriSlice))
  1136. assert.Equal(t, cfg.addedVals, toTestValList(addedValsPriSlice))
  1137. // - and should all have the same priority
  1138. expectedPri := addedValsPriSlice[0].ProposerPriority
  1139. for _, val := range addedValsPriSlice[1:] {
  1140. assert.Equal(t, expectedPri, val.ProposerPriority)
  1141. }
  1142. }
  1143. }
  1144. func TestNewValidatorSetFromExistingValidators(t *testing.T) {
  1145. ctx, cancel := context.WithCancel(context.Background())
  1146. defer cancel()
  1147. size := 5
  1148. vals := make([]*Validator, size)
  1149. for i := 0; i < size; i++ {
  1150. pv := NewMockPV()
  1151. vals[i] = pv.ExtractIntoValidator(ctx, int64(i+1))
  1152. }
  1153. valSet := NewValidatorSet(vals)
  1154. valSet.IncrementProposerPriority(5)
  1155. newValSet := NewValidatorSet(valSet.Validators)
  1156. assert.NotEqual(t, valSet, newValSet)
  1157. existingValSet, err := ValidatorSetFromExistingValidators(valSet.Validators)
  1158. assert.NoError(t, err)
  1159. assert.Equal(t, valSet, existingValSet)
  1160. assert.Equal(t, valSet.CopyIncrementProposerPriority(3), existingValSet.CopyIncrementProposerPriority(3))
  1161. }
  1162. func TestValSetUpdateOverflowRelated(t *testing.T) {
  1163. testCases := []testVSetCfg{
  1164. {
  1165. name: "1 no false overflow error messages for updates",
  1166. startVals: []testVal{{"v2", MaxTotalVotingPower - 1}, {"v1", 1}},
  1167. updatedVals: []testVal{{"v1", MaxTotalVotingPower - 1}, {"v2", 1}},
  1168. expectedVals: []testVal{{"v1", MaxTotalVotingPower - 1}, {"v2", 1}},
  1169. expErr: nil,
  1170. },
  1171. {
  1172. // this test shows that it is important to apply the updates in the order of the change in power
  1173. // i.e. apply first updates with decreases in power, v2 change in this case.
  1174. name: "2 no false overflow error messages for updates",
  1175. startVals: []testVal{{"v2", MaxTotalVotingPower - 1}, {"v1", 1}},
  1176. updatedVals: []testVal{{"v1", MaxTotalVotingPower/2 - 1}, {"v2", MaxTotalVotingPower / 2}},
  1177. expectedVals: []testVal{{"v2", MaxTotalVotingPower / 2}, {"v1", MaxTotalVotingPower/2 - 1}},
  1178. expErr: nil,
  1179. },
  1180. {
  1181. name: "3 no false overflow error messages for deletes",
  1182. startVals: []testVal{{"v1", MaxTotalVotingPower - 2}, {"v2", 1}, {"v3", 1}},
  1183. deletedVals: []testVal{{"v1", 0}},
  1184. addedVals: []testVal{{"v4", MaxTotalVotingPower - 2}},
  1185. expectedVals: []testVal{{"v4", MaxTotalVotingPower - 2}, {"v2", 1}, {"v3", 1}},
  1186. expErr: nil,
  1187. },
  1188. {
  1189. name: "4 no false overflow error messages for adds, updates and deletes",
  1190. startVals: []testVal{
  1191. {"v1", MaxTotalVotingPower / 4}, {"v2", MaxTotalVotingPower / 4},
  1192. {"v3", MaxTotalVotingPower / 4}, {"v4", MaxTotalVotingPower / 4}},
  1193. deletedVals: []testVal{{"v2", 0}},
  1194. updatedVals: []testVal{
  1195. {"v1", MaxTotalVotingPower/2 - 2}, {"v3", MaxTotalVotingPower/2 - 3}, {"v4", 2}},
  1196. addedVals: []testVal{{"v5", 3}},
  1197. expectedVals: []testVal{
  1198. {"v1", MaxTotalVotingPower/2 - 2}, {"v3", MaxTotalVotingPower/2 - 3}, {"v5", 3}, {"v4", 2}},
  1199. expErr: nil,
  1200. },
  1201. {
  1202. name: "5 check panic on overflow is prevented: update 8 validators with power int64(math.MaxInt64)/8",
  1203. startVals: []testVal{
  1204. {"v1", 1}, {"v2", 1}, {"v3", 1}, {"v4", 1}, {"v5", 1},
  1205. {"v6", 1}, {"v7", 1}, {"v8", 1}, {"v9", 1}},
  1206. updatedVals: []testVal{
  1207. {"v1", MaxTotalVotingPower}, {"v2", MaxTotalVotingPower}, {"v3", MaxTotalVotingPower},
  1208. {"v4", MaxTotalVotingPower}, {"v5", MaxTotalVotingPower}, {"v6", MaxTotalVotingPower},
  1209. {"v7", MaxTotalVotingPower}, {"v8", MaxTotalVotingPower}, {"v9", 8}},
  1210. expectedVals: []testVal{
  1211. {"v1", 1}, {"v2", 1}, {"v3", 1}, {"v4", 1}, {"v5", 1},
  1212. {"v6", 1}, {"v7", 1}, {"v8", 1}, {"v9", 1}},
  1213. expErr: ErrTotalVotingPowerOverflow,
  1214. },
  1215. }
  1216. for _, tt := range testCases {
  1217. tt := tt
  1218. t.Run(tt.name, func(t *testing.T) {
  1219. valSet := createNewValidatorSet(tt.startVals)
  1220. verifyValidatorSet(t, valSet)
  1221. // execute update and verify returned error is as expected
  1222. applyChangesToValSet(t, tt.expErr, valSet, tt.addedVals, tt.updatedVals, tt.deletedVals)
  1223. // verify updated validator set is as expected
  1224. assert.Equal(t, tt.expectedVals, toTestValList(valSet.Validators))
  1225. verifyValidatorSet(t, valSet)
  1226. })
  1227. }
  1228. }
  1229. func TestSafeMul(t *testing.T) {
  1230. testCases := []struct {
  1231. a int64
  1232. b int64
  1233. c int64
  1234. overflow bool
  1235. }{
  1236. 0: {0, 0, 0, false},
  1237. 1: {1, 0, 0, false},
  1238. 2: {2, 3, 6, false},
  1239. 3: {2, -3, -6, false},
  1240. 4: {-2, -3, 6, false},
  1241. 5: {-2, 3, -6, false},
  1242. 6: {math.MaxInt64, 1, math.MaxInt64, false},
  1243. 7: {math.MaxInt64 / 2, 2, math.MaxInt64 - 1, false},
  1244. 8: {math.MaxInt64 / 2, 3, 0, true},
  1245. 9: {math.MaxInt64, 2, 0, true},
  1246. }
  1247. for i, tc := range testCases {
  1248. c, overflow := safeMul(tc.a, tc.b)
  1249. assert.Equal(t, tc.c, c, "#%d", i)
  1250. assert.Equal(t, tc.overflow, overflow, "#%d", i)
  1251. }
  1252. }
  1253. func TestValidatorSetProtoBuf(t *testing.T) {
  1254. ctx, cancel := context.WithCancel(context.Background())
  1255. defer cancel()
  1256. valset, _ := randValidatorPrivValSet(ctx, t, 10, 100)
  1257. valset2, _ := randValidatorPrivValSet(ctx, t, 10, 100)
  1258. valset2.Validators[0] = &Validator{}
  1259. valset3, _ := randValidatorPrivValSet(ctx, t, 10, 100)
  1260. valset3.Proposer = nil
  1261. valset4, _ := randValidatorPrivValSet(ctx, t, 10, 100)
  1262. valset4.Proposer = &Validator{}
  1263. testCases := []struct {
  1264. msg string
  1265. v1 *ValidatorSet
  1266. expPass1 bool
  1267. expPass2 bool
  1268. }{
  1269. {"success", valset, true, true},
  1270. {"fail valSet2, pubkey empty", valset2, false, false},
  1271. {"fail nil Proposer", valset3, false, false},
  1272. {"fail empty Proposer", valset4, false, false},
  1273. {"fail empty valSet", &ValidatorSet{}, true, false},
  1274. {"false nil", nil, true, false},
  1275. }
  1276. for _, tc := range testCases {
  1277. protoValSet, err := tc.v1.ToProto()
  1278. if tc.expPass1 {
  1279. require.NoError(t, err, tc.msg)
  1280. } else {
  1281. require.Error(t, err, tc.msg)
  1282. }
  1283. valSet, err := ValidatorSetFromProto(protoValSet)
  1284. if tc.expPass2 {
  1285. require.NoError(t, err, tc.msg)
  1286. require.EqualValues(t, tc.v1, valSet, tc.msg)
  1287. } else {
  1288. require.Error(t, err, tc.msg)
  1289. }
  1290. }
  1291. }
  1292. //---------------------
  1293. // Sort validators by priority and address
  1294. type validatorsByPriority []*Validator
  1295. func (valz validatorsByPriority) Len() int {
  1296. return len(valz)
  1297. }
  1298. func (valz validatorsByPriority) Less(i, j int) bool {
  1299. if valz[i].ProposerPriority < valz[j].ProposerPriority {
  1300. return true
  1301. }
  1302. if valz[i].ProposerPriority > valz[j].ProposerPriority {
  1303. return false
  1304. }
  1305. return bytes.Compare(valz[i].Address, valz[j].Address) < 0
  1306. }
  1307. func (valz validatorsByPriority) Swap(i, j int) {
  1308. valz[i], valz[j] = valz[j], valz[i]
  1309. }
  1310. //-------------------------------------
  1311. type testValsByVotingPower []testVal
  1312. func (tvals testValsByVotingPower) Len() int {
  1313. return len(tvals)
  1314. }
  1315. func (tvals testValsByVotingPower) Less(i, j int) bool {
  1316. if tvals[i].power == tvals[j].power {
  1317. return bytes.Compare([]byte(tvals[i].name), []byte(tvals[j].name)) == -1
  1318. }
  1319. return tvals[i].power > tvals[j].power
  1320. }
  1321. func (tvals testValsByVotingPower) Swap(i, j int) {
  1322. tvals[i], tvals[j] = tvals[j], tvals[i]
  1323. }
  1324. //-------------------------------------
  1325. // Benchmark tests
  1326. //
  1327. func BenchmarkUpdates(b *testing.B) {
  1328. const (
  1329. n = 100
  1330. m = 2000
  1331. )
  1332. // Init with n validators
  1333. vs := make([]*Validator, n)
  1334. for j := 0; j < n; j++ {
  1335. vs[j] = newValidator([]byte(fmt.Sprintf("v%d", j)), 100)
  1336. }
  1337. valSet := NewValidatorSet(vs)
  1338. l := len(valSet.Validators)
  1339. // Make m new validators
  1340. newValList := make([]*Validator, m)
  1341. for j := 0; j < m; j++ {
  1342. newValList[j] = newValidator([]byte(fmt.Sprintf("v%d", j+l)), 1000)
  1343. }
  1344. b.ResetTimer()
  1345. for i := 0; i < b.N; i++ {
  1346. // Add m validators to valSetCopy
  1347. valSetCopy := valSet.Copy()
  1348. assert.NoError(b, valSetCopy.UpdateWithChangeSet(newValList))
  1349. }
  1350. }
  1351. func BenchmarkValidatorSet_VerifyCommit_Ed25519(b *testing.B) { // nolint
  1352. ctx, cancel := context.WithCancel(context.Background())
  1353. defer cancel()
  1354. for _, n := range []int{1, 8, 64, 1024} {
  1355. n := n
  1356. var (
  1357. chainID = "test_chain_id"
  1358. h = int64(3)
  1359. blockID = makeBlockIDRandom()
  1360. )
  1361. b.Run(fmt.Sprintf("valset size %d", n), func(b *testing.B) {
  1362. b.ReportAllocs()
  1363. // generate n validators
  1364. voteSet, valSet, vals := randVoteSet(ctx, b, h, 0, tmproto.PrecommitType, n, int64(n*5))
  1365. // create a commit with n validators
  1366. commit, err := makeCommit(ctx, blockID, h, 0, voteSet, vals, time.Now())
  1367. require.NoError(b, err)
  1368. for i := 0; i < b.N/n; i++ {
  1369. err = valSet.VerifyCommit(chainID, blockID, h, commit)
  1370. assert.NoError(b, err)
  1371. }
  1372. })
  1373. }
  1374. }
  1375. func BenchmarkValidatorSet_VerifyCommitLight_Ed25519(b *testing.B) { // nolint
  1376. ctx, cancel := context.WithCancel(context.Background())
  1377. defer cancel()
  1378. for _, n := range []int{1, 8, 64, 1024} {
  1379. n := n
  1380. var (
  1381. chainID = "test_chain_id"
  1382. h = int64(3)
  1383. blockID = makeBlockIDRandom()
  1384. )
  1385. b.Run(fmt.Sprintf("valset size %d", n), func(b *testing.B) {
  1386. b.ReportAllocs()
  1387. // generate n validators
  1388. voteSet, valSet, vals := randVoteSet(ctx, b, h, 0, tmproto.PrecommitType, n, int64(n*5))
  1389. // create a commit with n validators
  1390. commit, err := makeCommit(ctx, blockID, h, 0, voteSet, vals, time.Now())
  1391. require.NoError(b, err)
  1392. for i := 0; i < b.N/n; i++ {
  1393. err = valSet.VerifyCommitLight(chainID, blockID, h, commit)
  1394. assert.NoError(b, err)
  1395. }
  1396. })
  1397. }
  1398. }
  1399. func BenchmarkValidatorSet_VerifyCommitLightTrusting_Ed25519(b *testing.B) {
  1400. ctx, cancel := context.WithCancel(context.Background())
  1401. defer cancel()
  1402. for _, n := range []int{1, 8, 64, 1024} {
  1403. n := n
  1404. var (
  1405. chainID = "test_chain_id"
  1406. h = int64(3)
  1407. blockID = makeBlockIDRandom()
  1408. )
  1409. b.Run(fmt.Sprintf("valset size %d", n), func(b *testing.B) {
  1410. b.ReportAllocs()
  1411. // generate n validators
  1412. voteSet, valSet, vals := randVoteSet(ctx, b, h, 0, tmproto.PrecommitType, n, int64(n*5))
  1413. // create a commit with n validators
  1414. commit, err := makeCommit(ctx, blockID, h, 0, voteSet, vals, time.Now())
  1415. require.NoError(b, err)
  1416. for i := 0; i < b.N/n; i++ {
  1417. err = valSet.VerifyCommitLightTrusting(chainID, commit, tmmath.Fraction{Numerator: 1, Denominator: 3})
  1418. assert.NoError(b, err)
  1419. }
  1420. })
  1421. }
  1422. }
  1423. // Testing Utils
  1424. // deterministicValidatorSet returns a deterministic validator set (size: +numValidators+),
  1425. // where each validator has a power of 50
  1426. //
  1427. // EXPOSED FOR TESTING.
  1428. func deterministicValidatorSet(ctx context.Context, t *testing.T) (*ValidatorSet, []PrivValidator) {
  1429. var (
  1430. valz = make([]*Validator, 10)
  1431. privValidators = make([]PrivValidator, 10)
  1432. )
  1433. t.Helper()
  1434. for i := 0; i < 10; i++ {
  1435. // val, privValidator := DeterministicValidator(ed25519.PrivKey([]byte(deterministicKeys[i])))
  1436. val, privValidator := deterministicValidator(ctx, t, ed25519.GenPrivKeyFromSecret([]byte(fmt.Sprintf("key: %x", i))))
  1437. valz[i] = val
  1438. privValidators[i] = privValidator
  1439. }
  1440. sort.Sort(PrivValidatorsByAddress(privValidators))
  1441. return NewValidatorSet(valz), privValidators
  1442. }