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.

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