More renaming to move away from phragmen. (#6886)

This commit is contained in:
Kian Paimani
2020-08-13 23:30:22 +02:00
committed by GitHub
parent 0777a93532
commit 775e84cc04
8 changed files with 166 additions and 166 deletions
+2 -2
View File
@@ -8624,8 +8624,8 @@ name = "substrate-test-utils-derive"
version = "0.8.0-rc5"
dependencies = [
"proc-macro-crate",
"quote 1.0.6",
"syn 1.0.33",
"quote",
"syn",
]
[[package]]
+28 -28
View File
@@ -1300,34 +1300,34 @@ decl_error! {
/// Rewards for this era have already been claimed for this validator.
AlreadyClaimed,
/// The submitted result is received out of the open window.
PhragmenEarlySubmission,
OffchainElectionEarlySubmission,
/// The submitted result is not as good as the one stored on chain.
PhragmenWeakSubmission,
OffchainElectionWeakSubmission,
/// The snapshot data of the current window is missing.
SnapshotUnavailable,
/// Incorrect number of winners were presented.
PhragmenBogusWinnerCount,
OffchainElectionBogusWinnerCount,
/// One of the submitted winners is not an active candidate on chain (index is out of range
/// in snapshot).
PhragmenBogusWinner,
OffchainElectionBogusWinner,
/// Error while building the assignment type from the compact. This can happen if an index
/// is invalid, or if the weights _overflow_.
PhragmenBogusCompact,
OffchainElectionBogusCompact,
/// One of the submitted nominators is not an active nominator on chain.
PhragmenBogusNominator,
OffchainElectionBogusNominator,
/// One of the submitted nominators has an edge to which they have not voted on chain.
PhragmenBogusNomination,
OffchainElectionBogusNomination,
/// One of the submitted nominators has an edge which is submitted before the last non-zero
/// slash of the target.
PhragmenSlashedNomination,
OffchainElectionSlashedNomination,
/// A self vote must only be originated from a validator to ONLY themselves.
PhragmenBogusSelfVote,
OffchainElectionBogusSelfVote,
/// The submitted result has unknown edges that are not among the presented winners.
PhragmenBogusEdge,
OffchainElectionBogusEdge,
/// The claimed score does not match with the one computed from the data.
PhragmenBogusScore,
OffchainElectionBogusScore,
/// The election size is invalid.
PhragmenBogusElectionSize,
OffchainElectionBogusElectionSize,
/// The call is not allowed at the given time due to restrictions of election period.
CallNotAllowed,
/// Incorrect previous history depth input provided.
@@ -2542,14 +2542,14 @@ impl<T: Trait> Module<T> {
// check window open
ensure!(
Self::era_election_status().is_open(),
Error::<T>::PhragmenEarlySubmission.with_weight(T::DbWeight::get().reads(1)),
Error::<T>::OffchainElectionEarlySubmission.with_weight(T::DbWeight::get().reads(1)),
);
// check current era.
if let Some(current_era) = Self::current_era() {
ensure!(
current_era == era,
Error::<T>::PhragmenEarlySubmission.with_weight(T::DbWeight::get().reads(2)),
Error::<T>::OffchainElectionEarlySubmission.with_weight(T::DbWeight::get().reads(2)),
)
}
@@ -2557,7 +2557,7 @@ impl<T: Trait> Module<T> {
if let Some(queued_score) = Self::queued_score() {
ensure!(
is_score_better(score, queued_score, T::MinSolutionScoreBump::get()),
Error::<T>::PhragmenWeakSubmission.with_weight(T::DbWeight::get().reads(3)),
Error::<T>::OffchainElectionWeakSubmission.with_weight(T::DbWeight::get().reads(3)),
)
}
@@ -2594,13 +2594,13 @@ impl<T: Trait> Module<T> {
// size of the solution must be correct.
ensure!(
snapshot_validators_length == u32::from(election_size.validators),
Error::<T>::PhragmenBogusElectionSize,
Error::<T>::OffchainElectionBogusElectionSize,
);
// check the winner length only here and when we know the length of the snapshot validators
// length.
let desired_winners = Self::validator_count().min(snapshot_validators_length);
ensure!(winners.len() as u32 == desired_winners, Error::<T>::PhragmenBogusWinnerCount);
ensure!(winners.len() as u32 == desired_winners, Error::<T>::OffchainElectionBogusWinnerCount);
let snapshot_nominators_len = <SnapshotNominators<T>>::decode_len()
.map(|l| l as u32)
@@ -2609,7 +2609,7 @@ impl<T: Trait> Module<T> {
// rest of the size of the solution must be correct.
ensure!(
snapshot_nominators_len == election_size.nominators,
Error::<T>::PhragmenBogusElectionSize,
Error::<T>::OffchainElectionBogusElectionSize,
);
// decode snapshot validators.
@@ -2621,7 +2621,7 @@ impl<T: Trait> Module<T> {
// NOTE: at the moment, since staking is explicitly blocking any offence until election
// is closed, we don't check here if the account id at `snapshot_validators[widx]` is
// actually a validator. If this ever changes, this loop needs to also check this.
snapshot_validators.get(widx as usize).cloned().ok_or(Error::<T>::PhragmenBogusWinner)
snapshot_validators.get(widx as usize).cloned().ok_or(Error::<T>::OffchainElectionBogusWinner)
}).collect::<Result<Vec<T::AccountId>, Error<T>>>()?;
// decode the rest of the snapshot.
@@ -2643,7 +2643,7 @@ impl<T: Trait> Module<T> {
).map_err(|e| {
// log the error since it is not propagated into the runtime error.
log!(warn, "💸 un-compacting solution failed due to {:?}", e);
Error::<T>::PhragmenBogusCompact
Error::<T>::OffchainElectionBogusCompact
})?;
// check all nominators actually including the claimed vote. Also check correct self votes.
@@ -2659,7 +2659,7 @@ impl<T: Trait> Module<T> {
// have bigger problems.
log!(error, "💸 detected an error in the staking locking and snapshot.");
// abort.
return Err(Error::<T>::PhragmenBogusNominator.into());
return Err(Error::<T>::OffchainElectionBogusNominator.into());
}
if !is_validator {
@@ -2676,25 +2676,25 @@ impl<T: Trait> Module<T> {
// each target in the provided distribution must be actually nominated by the
// nominator after the last non-zero slash.
if nomination.targets.iter().find(|&tt| tt == t).is_none() {
return Err(Error::<T>::PhragmenBogusNomination.into());
return Err(Error::<T>::OffchainElectionBogusNomination.into());
}
if <Self as Store>::SlashingSpans::get(&t).map_or(
false,
|spans| nomination.submitted_in < spans.last_nonzero_slash(),
) {
return Err(Error::<T>::PhragmenSlashedNomination.into());
return Err(Error::<T>::OffchainElectionSlashedNomination.into());
}
}
} else {
// a self vote
ensure!(distribution.len() == 1, Error::<T>::PhragmenBogusSelfVote);
ensure!(distribution[0].0 == *who, Error::<T>::PhragmenBogusSelfVote);
ensure!(distribution.len() == 1, Error::<T>::OffchainElectionBogusSelfVote);
ensure!(distribution[0].0 == *who, Error::<T>::OffchainElectionBogusSelfVote);
// defensive only. A compact assignment of length one does NOT encode the weight and
// it is always created to be 100%.
ensure!(
distribution[0].1 == OffchainAccuracy::one(),
Error::<T>::PhragmenBogusSelfVote,
Error::<T>::OffchainElectionBogusSelfVote,
);
}
}
@@ -2713,11 +2713,11 @@ impl<T: Trait> Module<T> {
&staked_assignments,
);
// This technically checks that all targets in all nominators were among the winners.
ensure!(num_error == 0, Error::<T>::PhragmenBogusEdge);
ensure!(num_error == 0, Error::<T>::OffchainElectionBogusEdge);
// Check if the score is the same as the claimed one.
let submitted_score = evaluate_support(&supports);
ensure!(submitted_score == claimed_score, Error::<T>::PhragmenBogusScore);
ensure!(submitted_score == claimed_score, Error::<T>::OffchainElectionBogusScore);
// At last, alles Ok. Exposures and store the result.
let exposures = Self::collect_exposure(supports);
+2 -2
View File
@@ -437,7 +437,7 @@ impl ExtBuilder {
self.max_offchain_iterations = iterations;
self
}
pub fn offchain_phragmen_ext(self) -> Self {
pub fn offchain_election_ext(self) -> Self {
self.session_per_era(4)
.session_length(5)
.election_lookahead(3)
@@ -787,7 +787,7 @@ pub(crate) fn add_slash(who: &AccountId) {
// winners will be chosen by simply their unweighted total backing stake. Nominator stake is
// distributed evenly.
pub(crate) fn horrible_phragmen_with_post_processing(
pub(crate) fn horrible_npos_solution(
do_reduce: bool,
) -> (CompactAssignments, Vec<ValidatorIndex>, ElectionScore) {
let mut backing_stake_of: BTreeMap<AccountId, Balance> = BTreeMap::new();
+79 -79
View File
@@ -2810,7 +2810,7 @@ fn remove_multi_deferred() {
})
}
mod offchain_phragmen {
mod offchain_election {
use crate::*;
use codec::Encode;
use frame_support::{
@@ -2836,7 +2836,7 @@ mod offchain_phragmen {
/// setup a new set of validators and nominator storage items independent of the parent mock
/// file. This produces a edge graph that can be reduced.
pub fn build_offchain_phragmen_test_ext() {
pub fn build_offchain_election_test_ext() {
for i in (10..=40).step_by(10) {
// Note: we respect the convention of the mock (10, 11 pairs etc.) since these accounts
// have corresponding keys in session which makes everything more ergonomic and
@@ -3104,7 +3104,7 @@ mod offchain_phragmen {
#[ignore] // This takes a few mins
fn offchain_wont_work_if_snapshot_fails() {
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.build()
.execute_with(|| {
run_to_block(12);
@@ -3128,7 +3128,7 @@ mod offchain_phragmen {
#[test]
fn staking_is_locked_when_election_window_open() {
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.election_lookahead(3)
.build()
.execute_with(|| {
@@ -3150,7 +3150,7 @@ mod offchain_phragmen {
// should check that we have a new validator set normally, event says that it comes from
// offchain.
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.build()
.execute_with(|| {
run_to_block(12);
@@ -3208,7 +3208,7 @@ mod offchain_phragmen {
fn signed_result_can_be_submitted_later() {
// same as `signed_result_can_be_submitted` but at a later block.
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.build()
.execute_with(|| {
run_to_block(14);
@@ -3246,7 +3246,7 @@ mod offchain_phragmen {
// should check that we have a new validator set normally, event says that it comes from
// offchain.
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.build()
.execute_with(|| {
run_to_block(11);
@@ -3267,7 +3267,7 @@ mod offchain_phragmen {
current_era(),
ElectionSize::default(),
),
Error::<Test>::PhragmenEarlySubmission,
Error::<Test>::OffchainElectionEarlySubmission,
Some(<Test as frame_system::Trait>::DbWeight::get().reads(1)),
);
})
@@ -3277,12 +3277,12 @@ mod offchain_phragmen {
fn weak_solution_is_rejected() {
// A solution which is weaker than what we currently have on-chain is rejected.
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.has_stakers(false)
.validator_count(4)
.build()
.execute_with(|| {
build_offchain_phragmen_test_ext();
build_offchain_election_test_ext();
run_to_block(12);
// a good solution
@@ -3295,7 +3295,7 @@ mod offchain_phragmen {
));
// a bad solution
let (compact, winners, score) = horrible_phragmen_with_post_processing(false);
let (compact, winners, score) = horrible_npos_solution(false);
assert_err_with_weight!(
submit_solution(
Origin::signed(10),
@@ -3303,7 +3303,7 @@ mod offchain_phragmen {
compact.clone(),
score,
),
Error::<Test>::PhragmenWeakSubmission,
Error::<Test>::OffchainElectionWeakSubmission,
Some(<Test as frame_system::Trait>::DbWeight::get().reads(3))
);
})
@@ -3313,16 +3313,16 @@ mod offchain_phragmen {
fn better_solution_is_accepted() {
// A solution which is better than what we currently have on-chain is accepted.
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(4)
.has_stakers(false)
.build()
.execute_with(|| {
build_offchain_phragmen_test_ext();
build_offchain_election_test_ext();
run_to_block(12);
// a meeeeh solution
let (compact, winners, score) = horrible_phragmen_with_post_processing(false);
let (compact, winners, score) = horrible_npos_solution(false);
assert_ok!(submit_solution(
Origin::signed(10),
winners,
@@ -3345,7 +3345,7 @@ mod offchain_phragmen {
fn offchain_worker_runs_when_window_open() {
// at the end of the first finalized block with ElectionStatus::open(_), it should execute.
let mut ext = ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(2)
.build();
let state = offchainify(&mut ext, 0);
@@ -3387,7 +3387,7 @@ mod offchain_phragmen {
// Offchain worker equalises based on the number provided by randomness. See the difference
// in the priority, which comes from the computed score.
let mut ext = ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(2)
.max_offchain_iterations(2)
.build();
@@ -3429,7 +3429,7 @@ mod offchain_phragmen {
#[test]
fn mediocre_submission_from_authority_is_early_rejected() {
let mut ext = ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(4)
.build();
let state = offchainify(&mut ext, 0);
@@ -3463,21 +3463,21 @@ mod offchain_phragmen {
&inner,
),
TransactionValidity::Err(
InvalidTransaction::Custom(<Error<Test>>::PhragmenWeakSubmission.as_u8()).into(),
InvalidTransaction::Custom(<Error<Test>>::OffchainElectionWeakSubmission.as_u8()).into(),
),
)
})
}
#[test]
fn invalid_phragmen_result_correct_number_of_winners() {
fn invalid_election_correct_number_of_winners() {
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(4)
.has_stakers(false)
.build()
.execute_with(|| {
build_offchain_phragmen_test_ext();
build_offchain_election_test_ext();
run_to_block(12);
ValidatorCount::put(3);
@@ -3493,15 +3493,15 @@ mod offchain_phragmen {
compact,
score,
),
Error::<Test>::PhragmenBogusWinnerCount,
Error::<Test>::OffchainElectionBogusWinnerCount,
);
})
}
#[test]
fn invalid_phragmen_result_solution_size() {
fn invalid_election_solution_size() {
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.build()
.execute_with(|| {
run_to_block(12);
@@ -3517,21 +3517,21 @@ mod offchain_phragmen {
current_era(),
ElectionSize::default(),
),
Error::<Test>::PhragmenBogusElectionSize,
Error::<Test>::OffchainElectionBogusElectionSize,
);
})
}
#[test]
fn invalid_phragmen_result_correct_number_of_winners_1() {
fn invalid_election_correct_number_of_winners_1() {
// if we have too little validators, then the number of candidates is the bound.
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(8) // we simply cannot elect 8
.has_stakers(false)
.build()
.execute_with(|| {
build_offchain_phragmen_test_ext();
build_offchain_election_test_ext();
run_to_block(12);
ValidatorCount::put(3);
@@ -3547,21 +3547,21 @@ mod offchain_phragmen {
compact,
score,
),
Error::<Test>::PhragmenBogusWinnerCount,
Error::<Test>::OffchainElectionBogusWinnerCount,
);
})
}
#[test]
fn invalid_phragmen_result_correct_number_of_winners_2() {
fn invalid_election_correct_number_of_winners_2() {
// if we have too little validators, then the number of candidates is the bound.
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(8) // we simply cannot elect 8
.has_stakers(false)
.build()
.execute_with(|| {
build_offchain_phragmen_test_ext();
build_offchain_election_test_ext();
run_to_block(12);
let (compact, winners, score) = prepare_submission_with(true, 2, |_| {});
@@ -3579,15 +3579,15 @@ mod offchain_phragmen {
}
#[test]
fn invalid_phragmen_result_out_of_bound_nominator_index() {
fn invalid_election_out_of_bound_nominator_index() {
// A nominator index which is simply invalid
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(4)
.has_stakers(false)
.build()
.execute_with(|| {
build_offchain_phragmen_test_ext();
build_offchain_election_test_ext();
run_to_block(12);
assert_eq!(Staking::snapshot_nominators().unwrap().len(), 5 + 4);
@@ -3605,21 +3605,21 @@ mod offchain_phragmen {
compact,
score,
),
Error::<Test>::PhragmenBogusCompact,
Error::<Test>::OffchainElectionBogusCompact,
);
})
}
#[test]
fn invalid_phragmen_result_out_of_bound_validator_index() {
fn invalid_election_out_of_bound_validator_index() {
// A validator index which is out of bound
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(4)
.has_stakers(false)
.build()
.execute_with(|| {
build_offchain_phragmen_test_ext();
build_offchain_election_test_ext();
run_to_block(12);
assert_eq!(Staking::snapshot_nominators().unwrap().len(), 5 + 4);
@@ -3637,21 +3637,21 @@ mod offchain_phragmen {
compact,
score,
),
Error::<Test>::PhragmenBogusCompact,
Error::<Test>::OffchainElectionBogusCompact,
);
})
}
#[test]
fn invalid_phragmen_result_out_of_bound_winner_index() {
fn invalid_election_out_of_bound_winner_index() {
// A winner index which is simply invalid
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(4)
.has_stakers(false)
.build()
.execute_with(|| {
build_offchain_phragmen_test_ext();
build_offchain_election_test_ext();
run_to_block(12);
assert_eq!(Staking::snapshot_nominators().unwrap().len(), 5 + 4);
@@ -3668,22 +3668,22 @@ mod offchain_phragmen {
compact,
score,
),
Error::<Test>::PhragmenBogusWinner,
Error::<Test>::OffchainElectionBogusWinner,
);
})
}
#[test]
fn invalid_phragmen_result_non_winner_validator_index() {
fn invalid_election_non_winner_validator_index() {
// An edge that points to a correct validator index who is NOT a winner. This is very
// similar to the test that raises `PhragmenBogusNomination`.
// similar to the test that raises `OffchainElectionBogusNomination`.
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(2) // we select only 2.
.has_stakers(false)
.build()
.execute_with(|| {
build_offchain_phragmen_test_ext();
build_offchain_election_test_ext();
run_to_block(12);
assert_eq!(Staking::snapshot_nominators().unwrap().len(), 5 + 4);
@@ -3703,21 +3703,21 @@ mod offchain_phragmen {
compact,
score,
),
Error::<Test>::PhragmenBogusEdge,
Error::<Test>::OffchainElectionBogusEdge,
);
})
}
#[test]
fn invalid_phragmen_result_wrong_self_vote() {
fn invalid_election_wrong_self_vote() {
// A self vote for someone else.
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(4)
.has_stakers(false)
.build()
.execute_with(|| {
build_offchain_phragmen_test_ext();
build_offchain_election_test_ext();
run_to_block(12);
let (compact, winners, score) = prepare_submission_with(true, 2, |a| {
@@ -3738,21 +3738,21 @@ mod offchain_phragmen {
compact,
score,
),
Error::<Test>::PhragmenBogusSelfVote,
Error::<Test>::OffchainElectionBogusSelfVote,
);
})
}
#[test]
fn invalid_phragmen_result_wrong_self_vote_2() {
fn invalid_election_wrong_self_vote_2() {
// A self validator voting for someone else next to self vote.
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(4)
.has_stakers(false)
.build()
.execute_with(|| {
build_offchain_phragmen_test_ext();
build_offchain_election_test_ext();
run_to_block(12);
let (compact, winners, score) = prepare_submission_with(true, 2, |a| {
@@ -3773,21 +3773,21 @@ mod offchain_phragmen {
compact,
score,
),
Error::<Test>::PhragmenBogusSelfVote,
Error::<Test>::OffchainElectionBogusSelfVote,
);
})
}
#[test]
fn invalid_phragmen_result_over_stake() {
fn invalid_election_over_stake() {
// Someone's edge ratios sums to more than 100%.
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(4)
.has_stakers(false)
.build()
.execute_with(|| {
build_offchain_phragmen_test_ext();
build_offchain_election_test_ext();
run_to_block(12);
// Note: we don't reduce here to be able to tweak votes3. votes3 will vanish if you
@@ -3807,13 +3807,13 @@ mod offchain_phragmen {
compact,
score,
),
Error::<Test>::PhragmenBogusCompact,
Error::<Test>::OffchainElectionBogusCompact,
);
})
}
#[test]
fn invalid_phragmen_result_under_stake() {
fn invalid_election_under_stake() {
// at the time of this writing, we cannot under stake someone. The compact assignment works
// in a way that some of the stakes are presented by the submitter, and the last one is read
// from chain by subtracting the rest from total. Hence, the sum is always correct.
@@ -3821,16 +3821,16 @@ mod offchain_phragmen {
}
#[test]
fn invalid_phragmen_result_invalid_target_stealing() {
fn invalid_election_invalid_target_stealing() {
// A valid voter who voted for someone who is a candidate, and is a correct winner, but is
// actually NOT nominated by this nominator.
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(4)
.has_stakers(false)
.build()
.execute_with(|| {
build_offchain_phragmen_test_ext();
build_offchain_election_test_ext();
run_to_block(12);
let (compact, winners, score) = prepare_submission_with(false, 0, |a| {
@@ -3848,7 +3848,7 @@ mod offchain_phragmen {
compact,
score,
),
Error::<Test>::PhragmenBogusNomination,
Error::<Test>::OffchainElectionBogusNomination,
);
})
}
@@ -3859,12 +3859,12 @@ mod offchain_phragmen {
// nomination should be disabled for the upcoming election. A solution must respect this
// rule.
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(4)
.has_stakers(false)
.build()
.execute_with(|| {
build_offchain_phragmen_test_ext();
build_offchain_election_test_ext();
// finalize the round with fallback. This is needed since all nominator submission
// are in era zero and we want this one to pass with no problems.
@@ -3928,21 +3928,21 @@ mod offchain_phragmen {
compact,
score,
),
Error::<Test>::PhragmenSlashedNomination,
Error::<Test>::OffchainElectionSlashedNomination,
);
})
}
#[test]
fn invalid_phragmen_result_wrong_score() {
fn invalid_election_wrong_score() {
// A valid voter who's total distributed stake is more than what they bond
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(4)
.has_stakers(false)
.build()
.execute_with(|| {
build_offchain_phragmen_test_ext();
build_offchain_election_test_ext();
run_to_block(12);
let (compact, winners, mut score) = prepare_submission_with(true, 2, |_| {});
@@ -3955,7 +3955,7 @@ mod offchain_phragmen {
compact,
score,
),
Error::<Test>::PhragmenBogusScore,
Error::<Test>::OffchainElectionBogusScore,
);
})
}
@@ -3963,7 +3963,7 @@ mod offchain_phragmen {
#[test]
fn offchain_storage_is_set() {
let mut ext = ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(4)
.build();
let state = offchainify(&mut ext, 0);
@@ -3987,7 +3987,7 @@ mod offchain_phragmen {
#[test]
fn offchain_storage_prevents_duplicate() {
let mut ext = ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(4)
.build();
let _ = offchainify(&mut ext, 0);
@@ -4032,7 +4032,7 @@ mod offchain_phragmen {
#[should_panic]
fn offence_is_blocked_when_window_open() {
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(4)
.has_stakers(false)
.build()
@@ -4575,12 +4575,12 @@ fn on_initialize_weight_is_correct() {
});
ExtBuilder::default()
.offchain_phragmen_ext()
.offchain_election_ext()
.validator_count(4)
.has_stakers(false)
.build()
.execute_with(|| {
crate::tests::offchain_phragmen::build_offchain_phragmen_test_ext();
crate::tests::offchain_election::build_offchain_election_test_ext();
run_to_block(11);
Staking::on_finalize(System::block_number());
System::set_block_number((System::block_number() + 1).into());
@@ -78,7 +78,7 @@ fn into_impl(count: usize, per_thing: syn::Type) -> TokenStream2 {
let name = field_name_for(1);
quote!(
for (voter_index, target_index) in self.#name {
assignments.push(_phragmen::Assignment {
assignments.push(_npos::Assignment {
who: voter_at(voter_index).or_invalid_index()?,
distribution: vec![
(target_at(target_index).or_invalid_index()?, #per_thing::one())
@@ -93,16 +93,16 @@ fn into_impl(count: usize, per_thing: syn::Type) -> TokenStream2 {
quote!(
for (voter_index, (t1_idx, p1), t2_idx) in self.#name {
if p1 >= #per_thing::one() {
return Err(_phragmen::Error::CompactStakeOverflow);
return Err(_npos::Error::CompactStakeOverflow);
}
// defensive only. Since Percent doesn't have `Sub`.
let p2 = _phragmen::sp_arithmetic::traits::Saturating::saturating_sub(
let p2 = _npos::sp_arithmetic::traits::Saturating::saturating_sub(
#per_thing::one(),
p1,
);
assignments.push( _phragmen::Assignment {
assignments.push( _npos::Assignment {
who: voter_at(voter_index).or_invalid_index()?,
distribution: vec![
(target_at(t1_idx).or_invalid_index()?, p1),
@@ -121,25 +121,25 @@ fn into_impl(count: usize, per_thing: syn::Type) -> TokenStream2 {
let mut inners_parsed = inners
.iter()
.map(|(ref t_idx, p)| {
sum = _phragmen::sp_arithmetic::traits::Saturating::saturating_add(sum, *p);
sum = _npos::sp_arithmetic::traits::Saturating::saturating_add(sum, *p);
let target = target_at(*t_idx).or_invalid_index()?;
Ok((target, *p))
})
.collect::<Result<Vec<(A, #per_thing)>, _phragmen::Error>>()?;
.collect::<Result<Vec<(A, #per_thing)>, _npos::Error>>()?;
if sum >= #per_thing::one() {
return Err(_phragmen::Error::CompactStakeOverflow);
return Err(_npos::Error::CompactStakeOverflow);
}
// defensive only. Since Percent doesn't have `Sub`.
let p_last = _phragmen::sp_arithmetic::traits::Saturating::saturating_sub(
let p_last = _npos::sp_arithmetic::traits::Saturating::saturating_sub(
#per_thing::one(),
sum,
);
inners_parsed.push((target_at(t_last_idx).or_invalid_index()?, p_last));
assignments.push(_phragmen::Assignment {
assignments.push(_npos::Assignment {
who: voter_at(voter_index).or_invalid_index()?,
distribution: inners_parsed,
});
@@ -165,38 +165,38 @@ pub(crate) fn assignment(
let into_impl = into_impl(count, weight_type.clone());
quote!(
use _phragmen::__OrInvalidIndex;
use _npos::__OrInvalidIndex;
impl #ident {
pub fn from_assignment<FV, FT, A>(
assignments: Vec<_phragmen::Assignment<A, #weight_type>>,
assignments: Vec<_npos::Assignment<A, #weight_type>>,
index_of_voter: FV,
index_of_target: FT,
) -> Result<Self, _phragmen::Error>
) -> Result<Self, _npos::Error>
where
A: _phragmen::IdentifierT,
A: _npos::IdentifierT,
for<'r> FV: Fn(&'r A) -> Option<#voter_type>,
for<'r> FT: Fn(&'r A) -> Option<#target_type>,
{
let mut compact: #ident = Default::default();
for _phragmen::Assignment { who, distribution } in assignments {
for _npos::Assignment { who, distribution } in assignments {
match distribution.len() {
0 => continue,
#from_impl
_ => {
return Err(_phragmen::Error::CompactTargetOverflow);
return Err(_npos::Error::CompactTargetOverflow);
}
}
};
Ok(compact)
}
pub fn into_assignment<A: _phragmen::IdentifierT>(
pub fn into_assignment<A: _npos::IdentifierT>(
self,
voter_at: impl Fn(#voter_type) -> Option<A>,
target_at: impl Fn(#target_type) -> Option<A>,
) -> Result<Vec<_phragmen::Assignment<A, #weight_type>>, _phragmen::Error> {
let mut assignments: Vec<_phragmen::Assignment<A, #weight_type>> = Default::default();
) -> Result<Vec<_npos::Assignment<A, #weight_type>>, _npos::Error> {
let mut assignments: Vec<_npos::Assignment<A, #weight_type>> = Default::default();
#into_impl
Ok(assignments)
}
@@ -49,9 +49,9 @@ fn decode_impl(
quote! {
let #name =
<
Vec<(_phragmen::codec::Compact<#voter_type>, _phragmen::codec::Compact<#target_type>)>
Vec<(_npos::codec::Compact<#voter_type>, _npos::codec::Compact<#target_type>)>
as
_phragmen::codec::Decode
_npos::codec::Decode
>::decode(value)?;
let #name = #name
.into_iter()
@@ -66,12 +66,12 @@ fn decode_impl(
let #name =
<
Vec<(
_phragmen::codec::Compact<#voter_type>,
(_phragmen::codec::Compact<#target_type>, _phragmen::codec::Compact<#weight_type>),
_phragmen::codec::Compact<#target_type>,
_npos::codec::Compact<#voter_type>,
(_npos::codec::Compact<#target_type>, _npos::codec::Compact<#weight_type>),
_npos::codec::Compact<#target_type>,
)>
as
_phragmen::codec::Decode
_npos::codec::Decode
>::decode(value)?;
let #name = #name
.into_iter()
@@ -91,11 +91,11 @@ fn decode_impl(
let #name =
<
Vec<(
_phragmen::codec::Compact<#voter_type>,
[(_phragmen::codec::Compact<#target_type>, _phragmen::codec::Compact<#weight_type>); #c-1],
_phragmen::codec::Compact<#target_type>,
_npos::codec::Compact<#voter_type>,
[(_npos::codec::Compact<#target_type>, _npos::codec::Compact<#weight_type>); #c-1],
_npos::codec::Compact<#target_type>,
)>
as _phragmen::codec::Decode
as _npos::codec::Decode
>::decode(value)?;
let #name = #name
.into_iter()
@@ -115,8 +115,8 @@ fn decode_impl(
}).collect::<TokenStream2>();
quote!(
impl _phragmen::codec::Decode for #ident {
fn decode<I: _phragmen::codec::Input>(value: &mut I) -> Result<Self, _phragmen::codec::Error> {
impl _npos::codec::Decode for #ident {
fn decode<I: _npos::codec::Input>(value: &mut I) -> Result<Self, _npos::codec::Error> {
#decode_impl_single
#decode_impl_double
#decode_impl_rest
@@ -139,8 +139,8 @@ fn encode_impl(ident: syn::Ident, count: usize) -> TokenStream2 {
let #name = self.#name
.iter()
.map(|(v, t)| (
_phragmen::codec::Compact(v.clone()),
_phragmen::codec::Compact(t.clone()),
_npos::codec::Compact(v.clone()),
_npos::codec::Compact(t.clone()),
))
.collect::<Vec<_>>();
#name.encode_to(&mut r);
@@ -153,12 +153,12 @@ fn encode_impl(ident: syn::Ident, count: usize) -> TokenStream2 {
let #name = self.#name
.iter()
.map(|(v, (t1, w), t2)| (
_phragmen::codec::Compact(v.clone()),
_npos::codec::Compact(v.clone()),
(
_phragmen::codec::Compact(t1.clone()),
_phragmen::codec::Compact(w.clone())
_npos::codec::Compact(t1.clone()),
_npos::codec::Compact(w.clone())
),
_phragmen::codec::Compact(t2.clone()),
_npos::codec::Compact(t2.clone()),
))
.collect::<Vec<_>>();
#name.encode_to(&mut r);
@@ -171,8 +171,8 @@ fn encode_impl(ident: syn::Ident, count: usize) -> TokenStream2 {
// we use the knowledge of the length to avoid copy_from_slice.
let inners_compact_array = (0..c-1).map(|i|
quote!{(
_phragmen::codec::Compact(inner[#i].0.clone()),
_phragmen::codec::Compact(inner[#i].1.clone()),
_npos::codec::Compact(inner[#i].0.clone()),
_npos::codec::Compact(inner[#i].1.clone()),
),}
).collect::<TokenStream2>();
@@ -180,9 +180,9 @@ fn encode_impl(ident: syn::Ident, count: usize) -> TokenStream2 {
let #name = self.#name
.iter()
.map(|(v, inner, t_last)| (
_phragmen::codec::Compact(v.clone()),
_npos::codec::Compact(v.clone()),
[ #inners_compact_array ],
_phragmen::codec::Compact(t_last.clone()),
_npos::codec::Compact(t_last.clone()),
))
.collect::<Vec<_>>();
#name.encode_to(&mut r);
@@ -190,7 +190,7 @@ fn encode_impl(ident: syn::Ident, count: usize) -> TokenStream2 {
}).collect::<TokenStream2>();
quote!(
impl _phragmen::codec::Encode for #ident {
impl _npos::codec::Encode for #ident {
fn encode(&self) -> Vec<u8> {
let mut r = vec![];
#encode_impl_single
@@ -181,7 +181,7 @@ fn struct_def(
}
} else {
// automatically derived.
quote!(#[derive(Default, PartialEq, Eq, Clone, Debug, _phragmen::codec::Encode, _phragmen::codec::Decode)])
quote!(#[derive(Default, PartialEq, Eq, Clone, Debug, _npos::codec::Encode, _npos::codec::Decode)])
};
Ok(quote! (
@@ -189,7 +189,7 @@ fn struct_def(
#derives_and_maybe_compact_encoding
#vis struct #ident { #singles #doubles #rest }
impl _phragmen::VotingLimit for #ident {
impl _npos::VotingLimit for #ident {
const LIMIT: usize = #count;
}
@@ -220,13 +220,13 @@ fn struct_def(
fn imports() -> Result<TokenStream2> {
if std::env::var("CARGO_PKG_NAME").unwrap() == "sp-npos-elections" {
Ok(quote! {
use crate as _phragmen;
use crate as _npos;
})
} else {
match crate_name("sp-npos-elections") {
Ok(sp_npos_elections) => {
let ident = syn::Ident::new(&sp_npos_elections, Span::call_site());
Ok(quote!( extern crate #ident as _phragmen; ))
Ok(quote!( extern crate #ident as _npos; ))
},
Err(e) => Err(syn::Error::new(Span::call_site(), &e)),
}
+10 -10
View File
@@ -51,18 +51,18 @@ pub(crate) struct _Edge<A> {
pub(crate) struct _Support<A> {
pub own: f64,
pub total: f64,
pub others: Vec<_PhragmenAssignment<A>>,
pub others: Vec<_Assignment<A>>,
}
pub(crate) type _PhragmenAssignment<A> = (A, f64);
pub(crate) type _Assignment<A> = (A, f64);
pub(crate) type _SupportMap<A> = BTreeMap<A, _Support<A>>;
pub(crate) type AccountId = u64;
#[derive(Debug, Clone)]
pub(crate) struct _PhragmenResult<A: Clone> {
pub(crate) struct _ElectionResult<A: Clone> {
pub winners: Vec<(A, ExtendedBalance)>,
pub assignments: Vec<(A, Vec<_PhragmenAssignment<A>>)>
pub assignments: Vec<(A, Vec<_Assignment<A>>)>
}
pub(crate) fn auto_generate_self_voters<A: Clone>(candidates: &[A]) -> Vec<(A, Vec<A>)> {
@@ -75,12 +75,12 @@ pub(crate) fn elect_float<A, FS>(
initial_candidates: Vec<A>,
initial_voters: Vec<(A, Vec<A>)>,
stake_of: FS,
) -> Option<_PhragmenResult<A>> where
) -> Option<_ElectionResult<A>> where
A: Default + Ord + Copy,
for<'r> FS: Fn(&'r A) -> VoteWeight,
{
let mut elected_candidates: Vec<(A, ExtendedBalance)>;
let mut assigned: Vec<(A, Vec<_PhragmenAssignment<A>>)>;
let mut assigned: Vec<(A, Vec<_Assignment<A>>)>;
let mut c_idx_cache = BTreeMap::<A, usize>::new();
let num_voters = initial_candidates.len() + initial_voters.len();
let mut voters: Vec<_Voter<A>> = Vec::with_capacity(num_voters);
@@ -172,14 +172,14 @@ pub(crate) fn elect_float<A, FS>(
}
}
Some(_PhragmenResult {
Some(_ElectionResult {
winners: elected_candidates,
assignments: assigned,
})
}
pub(crate) fn equalize_float<A, FS>(
mut assignments: Vec<(A, Vec<_PhragmenAssignment<A>>)>,
mut assignments: Vec<(A, Vec<_Assignment<A>>)>,
supports: &mut _SupportMap<A>,
tolerance: f64,
iterations: usize,
@@ -211,7 +211,7 @@ pub(crate) fn equalize_float<A, FS>(
pub(crate) fn do_equalize_float<A>(
voter: &A,
budget_balance: VoteWeight,
elected_edges: &mut Vec<_PhragmenAssignment<A>>,
elected_edges: &mut Vec<_Assignment<A>>,
support_map: &mut _SupportMap<A>,
tolerance: f64
) -> f64 where
@@ -366,7 +366,7 @@ pub(crate) fn run_and_compare<Output: PerThing>(
}
pub(crate) fn build_support_map_float<FS>(
result: &mut _PhragmenResult<AccountId>,
result: &mut _ElectionResult<AccountId>,
stake_of: FS,
) -> _SupportMap<AccountId>
where for<'r> FS: Fn(&'r AccountId) -> VoteWeight