Struct pallet_election_provider_multi_phase::pallet::Pallet [−][src]
pub struct Pallet<T>(_);
Expand description
The pallet implementing the on-chain logic.
Implementations
Self
accessor for SignedSubmission<T>
.
Finish the signed phase. Process the signed submissions from best to worse until a valid one is found, rewarding the best one and slashing the invalid ones along the way.
Returns true if we have a good solution in the signed phase.
This drains the SignedSubmissions
, potentially storing the best valid one in
QueuedSolution
.
pub fn finalize_signed_phase_accept_solution(
ready_solution: ReadySolution<T::AccountId>,
who: &T::AccountId,
deposit: BalanceOf<T>,
reward: BalanceOf<T>
)
pub fn finalize_signed_phase_accept_solution(
ready_solution: ReadySolution<T::AccountId>,
who: &T::AccountId,
deposit: BalanceOf<T>,
reward: BalanceOf<T>
)
Helper function for the case where a solution is accepted in the signed phase.
Extracted to facilitate with weight calculation.
Infallible
Helper function for the case where a solution is accepted in the rejected phase.
Extracted to facilitate with weight calculation.
Infallible
pub fn feasibility_weight_of(
raw_solution: &RawSolution<SolutionOf<T>>,
size: SolutionOrSnapshotSize
) -> Weight
pub fn feasibility_weight_of(
raw_solution: &RawSolution<SolutionOf<T>>,
size: SolutionOrSnapshotSize
) -> Weight
The feasibility weight of the given raw solution.
pub fn deposit_for(
raw_solution: &RawSolution<SolutionOf<T>>,
size: SolutionOrSnapshotSize
) -> BalanceOf<T>
pub fn deposit_for(
raw_solution: &RawSolution<SolutionOf<T>>,
size: SolutionOrSnapshotSize
) -> BalanceOf<T>
Collect a sufficient deposit to store this solution.
The deposit is composed of 3 main elements:
- base deposit, fixed for all submissions.
- a per-byte deposit, for renting the state usage.
- a per-weight deposit, for the potential weight usage in an upcoming on_initialize
Attempt to restore a solution from cache. Otherwise, compute it fresh. Either way, submit if our call’s score is greater than that of the cached solution.
Mine a new solution, cache it, and submit it back to the chain as an unsigned transaction.
Mine a new solution as a call. Performs all checks.
pub fn basic_checks(
raw_solution: &RawSolution<SolutionOf<T>>,
solution_type: &str
) -> Result<(), MinerError>
pub fn mine_and_check(
iters: usize
) -> Result<(RawSolution<SolutionOf<T>>, SolutionOrSnapshotSize), MinerError>
pub fn mine_and_check(
iters: usize
) -> Result<(RawSolution<SolutionOf<T>>, SolutionOrSnapshotSize), MinerError>
Mine a new npos solution, with all the relevant checks to make sure that it will be accepted to the chain.
If you want an unchecked solution, use Pallet::mine_solution
.
If you want a checked solution and submit it at the same time, use
Pallet::mine_check_save_submit
.
pub fn mine_solution(
iters: usize
) -> Result<(RawSolution<SolutionOf<T>>, SolutionOrSnapshotSize), MinerError>
pub fn mine_solution(
iters: usize
) -> Result<(RawSolution<SolutionOf<T>>, SolutionOrSnapshotSize), MinerError>
Mine a new npos solution.
pub fn prepare_election_result(
election_result: ElectionResult<T::AccountId, SolutionAccuracyOf<T>>
) -> Result<(RawSolution<SolutionOf<T>>, SolutionOrSnapshotSize), MinerError>
pub fn prepare_election_result(
election_result: ElectionResult<T::AccountId, SolutionAccuracyOf<T>>
) -> Result<(RawSolution<SolutionOf<T>>, SolutionOrSnapshotSize), MinerError>
Convert a raw solution from sp_npos_elections::ElectionResult
to RawSolution
, which
is ready to be submitted to the chain.
Will always reduce the solution as well.
Get a random number of iterations to run the balancing in the OCW.
Uses the offchain seed to generate a random number, maxed with
Config::MinerMaxIterations
.
pub fn trim_assignments_weight(
desired_targets: u32,
size: SolutionOrSnapshotSize,
max_weight: Weight,
assignments: &mut Vec<IndexAssignmentOf<T>>
)
pub fn trim_assignments_weight(
desired_targets: u32,
size: SolutionOrSnapshotSize,
max_weight: Weight,
assignments: &mut Vec<IndexAssignmentOf<T>>
)
Greedily reduce the size of the solution to fit into the block w.r.t. weight.
The weight of the solution is foremost a function of the number of voters (i.e.
assignments.len()
). Aside from this, the other components of the weight are invariant. The
number of winners shall not be changed (otherwise the solution is invalid) and the
ElectionSize
is merely a representation of the total number of stakers.
Thus, we reside to stripping away some voters from the assignments
.
Note that the solution is already computed, and the winners are elected based on the merit of the entire stake in the system. Nonetheless, some of the voters will be removed further down the line.
Indeed, the score must be computed after this step. If this step reduces the score too much or remove a winner, then the solution must be discarded after this step.
pub fn trim_assignments_length(
max_allowed_length: u32,
assignments: &mut Vec<IndexAssignmentOf<T>>,
encoded_size_of: impl Fn(&[IndexAssignmentOf<T>]) -> Result<usize, Error>
) -> Result<(), MinerError>
pub fn trim_assignments_length(
max_allowed_length: u32,
assignments: &mut Vec<IndexAssignmentOf<T>>,
encoded_size_of: impl Fn(&[IndexAssignmentOf<T>]) -> Result<usize, Error>
) -> Result<(), MinerError>
Greedily reduce the size of the solution to fit into the block w.r.t length.
The length of the solution is largely a function of the number of voters. The number of winners cannot be changed. Thus, to reduce the solution size, we need to strip voters.
Note that this solution is already computed, and winners are elected based on the merit of the total stake in the system. Nevertheless, some of the voters may be removed here.
Sometimes, removing a voter can cause a validator to also be implicitly removed, if that voter was the only backer of that winner. In such cases, this solution is invalid, which will be caught prior to submission.
The score must be computed after this step. If this step reduces the score too much, then the solution must be discarded.
pub fn maximum_voter_for_weight<W: WeightInfo>(
desired_winners: u32,
size: SolutionOrSnapshotSize,
max_weight: Weight
) -> u32
pub fn maximum_voter_for_weight<W: WeightInfo>(
desired_winners: u32,
size: SolutionOrSnapshotSize,
max_weight: Weight
) -> u32
Find the maximum len
that a solution can have in order to fit into the block weight.
This only returns a value between zero and size.nominators
.
Checks if an execution of the offchain worker is permitted at the given block number, or not.
This makes sure that
- we don’t run on previous blocks in case of a re-org
- we don’t run twice within a window of length
T::OffchainRepeat
.
Returns Ok(())
if offchain worker limit is respected, Err(reason)
otherwise. If Ok()
is returned, now
is written in storage and will be used in further calls as the baseline.
pub fn unsigned_pre_dispatch_checks(
raw_solution: &RawSolution<SolutionOf<T>>
) -> DispatchResult
pub fn unsigned_pre_dispatch_checks(
raw_solution: &RawSolution<SolutionOf<T>>
) -> DispatchResult
Do the basics checks that MUST happen during the validation and pre-dispatch of an unsigned transaction.
Can optionally also be called during dispatch, if needed.
NOTE: Ideally, these tests should move more and more outside of this and more to the miner’s code, so that we do less and less storage reads here.
pub fn submit_unsigned(
origin: OriginFor<T>,
raw_solution: Box<RawSolution<SolutionOf<T>>>,
witness: SolutionOrSnapshotSize
) -> DispatchResultWithPostInfo
pub fn submit_unsigned(
origin: OriginFor<T>,
raw_solution: Box<RawSolution<SolutionOf<T>>>,
witness: SolutionOrSnapshotSize
) -> DispatchResultWithPostInfo
Submit a solution for the unsigned phase.
The dispatch origin fo this call must be none.
This submission is checked on the fly. Moreover, this unsigned solution is only validated when submitted to the pool from the local node. Effectively, this means that only active validators can submit this transaction when authoring a block (similar to an inherent).
To prevent any incorrect solution (and thus wasted time/weight), this transaction will panic if the solution submitted by the validator is invalid in any way, effectively putting their authoring reward at risk.
No deposit or reward is associated with this submission.
pub fn set_minimum_untrusted_score(
origin: OriginFor<T>,
maybe_next_score: Option<ElectionScore>
) -> DispatchResult
pub fn set_minimum_untrusted_score(
origin: OriginFor<T>,
maybe_next_score: Option<ElectionScore>
) -> DispatchResult
Set a new value for MinimumUntrustedScore
.
Dispatch origin must be aligned with T::ForceOrigin
.
This check can be turned off by setting the value to None
.
pub fn set_emergency_election_result(
origin: OriginFor<T>,
supports: Supports<T::AccountId>
) -> DispatchResult
pub fn set_emergency_election_result(
origin: OriginFor<T>,
supports: Supports<T::AccountId>
) -> DispatchResult
Set a solution in the queue, to be handed out to the client of this pallet in the next
call to ElectionProvider::elect
.
This can only be set by T::ForceOrigin
, and only when the phase is Emergency
.
The solution is not checked for any feasibility and is assumed to be trustworthy, as any feasibility check itself can in principle cause the election process to fail (due to memory/weight constrains).
pub fn submit(
origin: OriginFor<T>,
raw_solution: Box<RawSolution<SolutionOf<T>>>,
num_signed_submissions: u32
) -> DispatchResult
pub fn submit(
origin: OriginFor<T>,
raw_solution: Box<RawSolution<SolutionOf<T>>>,
num_signed_submissions: u32
) -> DispatchResult
Submit a solution for the signed phase.
The dispatch origin fo this call must be signed.
The solution is potentially queued, based on the claimed score and processed at the end of the signed phase.
A deposit is reserved and recorded for the solution. Based on the outcome, the solution might be rewarded, slashed, or get all or a part of the deposit back.
Queue size must be provided as witness data.
Current phase.
Current best solution, signed or unsigned, queued to be returned upon elect
.
Snapshot data of the round.
This is created at the beginning of the signed phase and cleared upon calling elect
.
Desired number of targets to elect for this round.
Only exists when Snapshot
is present.
The metadata of the RoundSnapshot
Only exists when Snapshot
is present.
The minimum score that each ‘untrusted’ solution must attain in order to be considered feasible.
Can be set via set_minimum_untrusted_score
.
Logic for [<Pallet as Hooks>::on_initialize
] when signed phase is being opened.
This is decoupled for easy weight calculation.
Returns Ok(snapshot_weight)
if success, where snapshot_weight
is the weight that
needs to recorded for the creation of snapshot.
pub fn on_initialize_open_unsigned(
need_snapshot: bool,
enabled: bool,
now: T::BlockNumber
) -> Result<Weight, ElectionError>
pub fn on_initialize_open_unsigned(
need_snapshot: bool,
enabled: bool,
now: T::BlockNumber
) -> Result<Weight, ElectionError>
Logic for [<Pallet as Hooks<T>>::on_initialize
] when unsigned phase is being opened.
This is decoupled for easy weight calculation.
Returns Ok(snapshot_weight)
if success, where snapshot_weight
is the weight that
needs to recorded for the creation of snapshot.
Creates the snapshot. Writes new data to:
Returns Ok(consumed_weight)
if operation is okay.
Kill everything created by Pallet::create_snapshot
.
pub fn feasibility_check(
raw_solution: RawSolution<SolutionOf<T>>,
compute: ElectionCompute
) -> Result<ReadySolution<T::AccountId>, FeasibilityError>
pub fn feasibility_check(
raw_solution: RawSolution<SolutionOf<T>>,
compute: ElectionCompute
) -> Result<ReadySolution<T::AccountId>, FeasibilityError>
Checks the feasibility of a solution.
Trait Implementations
Get the benchmarks available for this pallet. Generally there is one benchmark per extrinsic, so these are sometimes just called “extrinsics”. Read more
fn run_benchmark(
extrinsic: &[u8],
c: &[(BenchmarkParameter, u32)],
whitelist: &[TrackedStorageKey],
verify: bool,
internal_repeats: u32
) -> Result<Vec<BenchmarkResults>, &'static str>
fn run_benchmark(
extrinsic: &[u8],
c: &[(BenchmarkParameter, u32)],
whitelist: &[TrackedStorageKey],
verify: bool,
internal_repeats: u32
) -> Result<Vec<BenchmarkResults>, &'static str>
Run the benchmarks for this pallet.
impl<T: Config> ElectionProvider<<T as Config>::AccountId, <T as Config>::BlockNumber> for Pallet<T>
impl<T: Config> ElectionProvider<<T as Config>::AccountId, <T as Config>::BlockNumber> for Pallet<T>
type Error = ElectionError
type Error = ElectionError
The error type that is returned by the provider.
type DataProvider = T::DataProvider
type DataProvider = T::DataProvider
The data provider of the election.
Returns the current storage version as supported by the pallet.
Returns the on-chain storage version of the pallet as stored in the storage.
The block is being initialized. Implement to have something happen. Read more
Implementing this function on a module allows you to perform long-running tasks that make (by default) validators generate transactions that feed results of those long-running computations back on chain. Read more
Run integrity test. Read more
The block is being finalized. Implement to have something happen.
This will be run when the block is being finalized (before on_finalize
).
Implement to have something happen using the remaining weight.
Will not fire if the remaining weight is 0.
Return the weight used, the hook will subtract it from current weight used
and pass the result to the next on_idle
hook if it exists. Read more
Perform a module upgrade. Read more
Execute some pre-checks prior to a runtime upgrade. Read more
Run integrity test. Read more
This function is being called after every block import (when fully synced). Read more
The block is being finalized. Implement to have something happen. Read more
Something that should happen at genesis.
The block is being finalized.
Implement to have something happen in case there is leftover weight.
Check the passed remaining_weight
to make sure it is high enough to allow for
your pallet’s extra computation. Read more
The block is being initialized. Implement to have something happen. Read more
Auto Trait Implementations
impl<T> RefUnwindSafe for Pallet<T> where
T: RefUnwindSafe,
impl<T> UnwindSafe for Pallet<T> where
T: UnwindSafe,
Blanket Implementations
Mutably borrows from an owned value. Read more
impl<T> Downcast for T where
T: Any,
impl<T> Downcast for T where
T: Any,
Convert Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
. Read more
pub fn into_any_rc(self: Rc<T>) -> Rc<dyn Any + 'static>
pub fn into_any_rc(self: Rc<T>) -> Rc<dyn Any + 'static>
Convert Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
. Read more
Convert &Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s. Read more
pub fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
pub fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
Convert &mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s. Read more
Instruments this type with the provided Span
, returning an
Instrumented
wrapper. Read more
Generate a storage key unique to this runtime upgrade. Read more
Get temporary storage data written by Self::set_temp_storage
. Read more
Write some temporary data to a specific storage that can be read (potentially in
post-upgrade hook) via Self::get_temp_storage
. Read more
impl<T> PalletVersionToStorageVersionHelper for T where
T: GetStorageVersion + PalletInfoAccess,
impl<T> PalletVersionToStorageVersionHelper for T where
T: GetStorageVersion + PalletInfoAccess,
type Output = T
type Output = T
Should always be Self
The inverse inclusion map: attempts to construct self
from the equivalent element of its
superset. Read more
pub fn is_in_subset(&self) -> bool
pub fn is_in_subset(&self) -> bool
Checks if self
is actually part of its subset T
(and can be converted to it).
pub fn to_subset_unchecked(&self) -> SS
pub fn to_subset_unchecked(&self) -> SS
Use with care! Same as self.to_subset
but without any property checks. Always succeeds.
pub fn from_subset(element: &SS) -> SP
pub fn from_subset(element: &SS) -> SP
The inclusion map: converts self
to the equivalent element of its superset.
The counterpart to unchecked_from
.
Consume self to return an equivalent value of T
.
pub fn vzip(self) -> V
impl<T> MaybeDebug for T where
T: Debug,
impl<T> MaybeDebug for T where
T: Debug,