sp_npos_elections/lib.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
7// in compliance with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software distributed under the License
12// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
13// or implied. See the License for the specific language governing permissions and limitations under
14// the License.
15
16//! A set of election algorithms to be used with a substrate runtime, typically within the staking
17//! sub-system. Notable implementation include:
18//!
19//! - [`seq_phragmen`]: Implements the Phragmén Sequential Method. An un-ranked, relatively fast
20//! election method that ensures PJR, but does not provide a constant factor approximation of the
21//! maximin problem.
22//! - [`ghragmms`](phragmms::phragmms()): Implements a hybrid approach inspired by Phragmén which is
23//! executed faster but it can achieve a constant factor approximation of the maximin problem,
24//! similar to that of the MMS algorithm.
25//! - [`balance`]: Implements the star balancing algorithm. This iterative process can push a
26//! solution toward being more "balanced", which in turn can increase its score.
27//!
28//! ### Terminology
29//!
30//! This crate uses context-independent words, not to be confused with staking. This is because the
31//! election algorithms of this crate, while designed for staking, can be used in other contexts as
32//! well.
33//!
34//! `Voter`: The entity casting some votes to a number of `Targets`. This is the same as `Nominator`
35//! in the context of staking. `Target`: The entities eligible to be voted upon. This is the same as
36//! `Validator` in the context of staking. `Edge`: A mapping from a `Voter` to a `Target`.
37//!
38//! The goal of an election algorithm is to provide an `ElectionResult`. A data composed of:
39//! - `winners`: A flat list of identifiers belonging to those who have won the election, usually
40//! ordered in some meaningful way. They are zipped with their total backing stake.
41//! - `assignment`: A mapping from each voter to their winner-only targets, zipped with a ration
42//! denoting the amount of support given to that particular target.
43//!
44//! ```rust
45//! # use sp_npos_elections::*;
46//! # use sp_runtime::Perbill;
47//! // the winners.
48//! let winners = vec![(1, 100), (2, 50)];
49//! let assignments = vec![
50//! // A voter, giving equal backing to both 1 and 2.
51//! Assignment {
52//! who: 10,
53//! distribution: vec![(1, Perbill::from_percent(50)), (2, Perbill::from_percent(50))],
54//! },
55//! // A voter, Only backing 1.
56//! Assignment { who: 20, distribution: vec![(1, Perbill::from_percent(100))] },
57//! ];
58//!
59//! // the combination of the two makes the election result.
60//! let election_result = ElectionResult { winners, assignments };
61//! ```
62//!
63//! The `Assignment` field of the election result is voter-major, i.e. it is from the perspective of
64//! the voter. The struct that represents the opposite is called a `Support`. This struct is usually
65//! accessed in a map-like manner, i.e. keyed by voters, therefore it is stored as a mapping called
66//! `SupportMap`.
67//!
68//! Moreover, the support is built from absolute backing values, not ratios like the example above.
69//! A struct similar to `Assignment` that has stake value instead of ratios is called an
70//! `StakedAssignment`.
71//!
72//!
73//! More information can be found at: <https://arxiv.org/abs/2004.12990>
74
75#![cfg_attr(not(feature = "std"), no_std)]
76
77extern crate alloc;
78
79use alloc::{collections::btree_map::BTreeMap, rc::Rc, vec, vec::Vec};
80use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
81use core::{cell::RefCell, cmp::Ordering};
82use scale_info::TypeInfo;
83#[cfg(feature = "serde")]
84use serde::{Deserialize, Serialize};
85use sp_arithmetic::{traits::Zero, Normalizable, PerThing, Rational128, ThresholdOrd};
86use sp_core::RuntimeDebug;
87
88#[cfg(test)]
89mod mock;
90#[cfg(test)]
91mod tests;
92
93mod assignments;
94pub mod balancing;
95pub mod helpers;
96pub mod node;
97pub mod phragmen;
98pub mod phragmms;
99pub mod pjr;
100pub mod reduce;
101pub mod traits;
102
103pub use assignments::{Assignment, StakedAssignment};
104pub use balancing::*;
105pub use helpers::*;
106pub use phragmen::*;
107pub use phragmms::*;
108pub use pjr::*;
109pub use reduce::reduce;
110pub use traits::{IdentifierT, PerThing128};
111
112/// The errors that might occur in this crate and `frame-election-provider-solution-type`.
113#[derive(
114 Eq,
115 PartialEq,
116 RuntimeDebug,
117 Clone,
118 codec::Encode,
119 codec::Decode,
120 codec::DecodeWithMemTracking,
121 scale_info::TypeInfo,
122)]
123pub enum Error {
124 /// While going from solution indices to ratio, the weight of all the edges has gone above the
125 /// total.
126 SolutionWeightOverflow,
127 /// The solution type has a voter who's number of targets is out of bound.
128 SolutionTargetOverflow,
129 /// One of the index functions returned none.
130 SolutionInvalidIndex,
131 /// One of the page indices was invalid.
132 SolutionInvalidPageIndex,
133 /// An error occurred in some arithmetic operation.
134 ArithmeticError,
135 /// The data provided to create support map was invalid.
136 InvalidSupportEdge,
137 /// The number of voters is bigger than the `MaxVoters` bound.
138 TooManyVoters,
139 /// Some bounds were exceeded when converting election types.
140 BoundsExceeded,
141 /// A duplicate voter was detected.
142 DuplicateVoter,
143 /// A duplicate target was detected.
144 DuplicateTarget,
145}
146
147/// A type which is used in the API of this crate as a numeric weight of a vote, most often the
148/// stake of the voter. It is always converted to [`ExtendedBalance`] for computation.
149pub type VoteWeight = u64;
150
151/// A type in which performing operations on vote weights are safe.
152pub type ExtendedBalance = u128;
153
154/// The score of an election. This is the main measure of an election's quality.
155///
156/// By definition, the order of significance in [`ElectionScore`] is:
157///
158/// 1. `minimal_stake`.
159/// 2. `sum_stake`.
160/// 3. `sum_stake_squared`.
161#[derive(
162 Clone,
163 Copy,
164 PartialEq,
165 Eq,
166 Encode,
167 Decode,
168 DecodeWithMemTracking,
169 MaxEncodedLen,
170 TypeInfo,
171 Debug,
172 Default,
173)]
174#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
175pub struct ElectionScore {
176 /// The minimal winner, in terms of total backing stake.
177 ///
178 /// This parameter should be maximized.
179 pub minimal_stake: ExtendedBalance,
180 /// The sum of the total backing of all winners.
181 ///
182 /// This parameter should maximized
183 pub sum_stake: ExtendedBalance,
184 /// The sum squared of the total backing of all winners, aka. the variance.
185 ///
186 /// Ths parameter should be minimized.
187 pub sum_stake_squared: ExtendedBalance,
188}
189
190#[cfg(feature = "std")]
191impl ElectionScore {
192 /// format the election score in a pretty way with the given `token` symbol and `decimals`.
193 pub fn pretty(&self, token: &str, decimals: u32) -> String {
194 format!(
195 "ElectionScore (minimal_stake: {}, sum_stake: {}, sum_stake_squared: {})",
196 pretty_balance(self.minimal_stake, token, decimals),
197 pretty_balance(self.sum_stake, token, decimals),
198 pretty_balance(self.sum_stake_squared, token, decimals),
199 )
200 }
201}
202
203/// Format a single [`ExtendedBalance`] into a pretty string with the given `token` symbol and
204/// `decimals`.
205#[cfg(feature = "std")]
206pub fn pretty_balance<B: Into<u128>>(b: B, token: &str, decimals: u32) -> String {
207 let b: u128 = b.into();
208 format!("{} {}", b / 10u128.pow(decimals), token)
209}
210
211impl ElectionScore {
212 /// Iterate over the inner items, first visiting the most significant one.
213 fn iter_by_significance(self) -> impl Iterator<Item = ExtendedBalance> {
214 [self.minimal_stake, self.sum_stake, self.sum_stake_squared].into_iter()
215 }
216
217 /// Compares two sets of election scores based on desirability, returning true if `self` is
218 /// strictly `threshold` better than `other`. In other words, each element of `self` must be
219 /// `self * threshold` better than `other`.
220 ///
221 /// Evaluation is done based on the order of significance of the fields of [`ElectionScore`].
222 pub fn strict_threshold_better(self, other: Self, threshold: impl PerThing) -> bool {
223 match self
224 .iter_by_significance()
225 .zip(other.iter_by_significance())
226 .map(|(this, that)| (this.ge(&that), this.tcmp(&that, threshold.mul_ceil(that))))
227 .collect::<Vec<(bool, Ordering)>>()
228 .as_slice()
229 {
230 // threshold better in the `score.minimal_stake`, accept.
231 [(x, Ordering::Greater), _, _] => {
232 debug_assert!(x);
233 true
234 },
235
236 // less than threshold better in `score.minimal_stake`, but more than threshold better
237 // in `score.sum_stake`.
238 [(true, Ordering::Equal), (_, Ordering::Greater), _] => true,
239
240 // less than threshold better in `score.minimal_stake` and `score.sum_stake`, but more
241 // than threshold better in `score.sum_stake_squared`.
242 [(true, Ordering::Equal), (true, Ordering::Equal), (_, Ordering::Less)] => true,
243
244 // anything else is not a good score.
245 _ => false,
246 }
247 }
248}
249
250impl core::cmp::Ord for ElectionScore {
251 fn cmp(&self, other: &Self) -> Ordering {
252 // we delegate this to the lexicographic cmp of slices`, and to incorporate that we want the
253 // third element to be minimized, we swap them.
254 [self.minimal_stake, self.sum_stake, other.sum_stake_squared].cmp(&[
255 other.minimal_stake,
256 other.sum_stake,
257 self.sum_stake_squared,
258 ])
259 }
260}
261
262impl core::cmp::PartialOrd for ElectionScore {
263 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
264 Some(self.cmp(other))
265 }
266}
267
268/// Utility struct to group parameters for the balancing algorithm.
269#[derive(Clone, Copy)]
270pub struct BalancingConfig {
271 pub iterations: usize,
272 pub tolerance: ExtendedBalance,
273}
274
275/// A pointer to a candidate struct with interior mutability.
276pub type CandidatePtr<A> = Rc<RefCell<Candidate<A>>>;
277
278/// A candidate entity for the election.
279#[derive(RuntimeDebug, Clone, Default)]
280pub struct Candidate<AccountId> {
281 /// Identifier.
282 who: AccountId,
283 /// Score of the candidate.
284 ///
285 /// Used differently in seq-phragmen and max-score.
286 score: Rational128,
287 /// Approval stake of the candidate. Merely the sum of all the voter's stake who approve this
288 /// candidate.
289 approval_stake: ExtendedBalance,
290 /// The final stake of this candidate. Will be equal to a subset of approval stake.
291 backed_stake: ExtendedBalance,
292 /// True if this candidate is already elected in the current election.
293 elected: bool,
294 /// The round index at which this candidate was elected.
295 round: usize,
296}
297
298impl<AccountId> Candidate<AccountId> {
299 pub fn to_ptr(self) -> CandidatePtr<AccountId> {
300 Rc::new(RefCell::new(self))
301 }
302}
303
304/// A vote being casted by a [`Voter`] to a [`Candidate`] is an `Edge`.
305#[derive(Clone)]
306pub struct Edge<AccountId> {
307 /// Identifier of the target.
308 ///
309 /// This is equivalent of `self.candidate.borrow().who`, yet it helps to avoid double borrow
310 /// errors of the candidate pointer.
311 who: AccountId,
312 /// Load of this edge.
313 load: Rational128,
314 /// Pointer to the candidate.
315 candidate: CandidatePtr<AccountId>,
316 /// The weight (i.e. stake given to `who`) of this edge.
317 weight: ExtendedBalance,
318}
319
320#[cfg(test)]
321impl<AccountId: Clone> Edge<AccountId> {
322 fn new(candidate: Candidate<AccountId>, weight: ExtendedBalance) -> Self {
323 let who = candidate.who.clone();
324 let candidate = Rc::new(RefCell::new(candidate));
325 Self { weight, who, candidate, load: Default::default() }
326 }
327}
328
329#[cfg(feature = "std")]
330impl<A: IdentifierT> core::fmt::Debug for Edge<A> {
331 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
332 write!(f, "Edge({:?}, weight = {:?})", self.who, self.weight)
333 }
334}
335
336/// A voter entity.
337#[derive(Clone, Default)]
338pub struct Voter<AccountId> {
339 /// Identifier.
340 who: AccountId,
341 /// List of candidates approved by this voter.
342 edges: Vec<Edge<AccountId>>,
343 /// The stake of this voter.
344 budget: ExtendedBalance,
345 /// Load of the voter.
346 load: Rational128,
347}
348
349#[cfg(feature = "std")]
350impl<A: IdentifierT> std::fmt::Debug for Voter<A> {
351 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352 write!(f, "Voter({:?}, budget = {}, edges = {:?})", self.who, self.budget, self.edges)
353 }
354}
355
356impl<AccountId: IdentifierT> Voter<AccountId> {
357 /// Create a new `Voter`.
358 pub fn new(who: AccountId) -> Self {
359 Self {
360 who,
361 edges: Default::default(),
362 budget: Default::default(),
363 load: Default::default(),
364 }
365 }
366
367 /// Returns `true` if `self` votes for `target`.
368 ///
369 /// Note that this does not take into account if `target` is elected (i.e. is *active*) or not.
370 pub fn votes_for(&self, target: &AccountId) -> bool {
371 self.edges.iter().any(|e| &e.who == target)
372 }
373
374 /// Returns none if this voter does not have any non-zero distributions.
375 ///
376 /// Note that this might create _un-normalized_ assignments, due to accuracy loss of `P`. Call
377 /// site might compensate by calling `normalize()` on the returned `Assignment` as a
378 /// post-processing.
379 pub fn into_assignment<P: PerThing>(self) -> Option<Assignment<AccountId, P>> {
380 let who = self.who;
381 let budget = self.budget;
382 let distribution = self
383 .edges
384 .into_iter()
385 .filter_map(|e| {
386 let per_thing = P::from_rational(e.weight, budget);
387 // trim zero edges.
388 if per_thing.is_zero() {
389 None
390 } else {
391 Some((e.who, per_thing))
392 }
393 })
394 .collect::<Vec<_>>();
395
396 if distribution.len() > 0 {
397 Some(Assignment { who, distribution })
398 } else {
399 None
400 }
401 }
402
403 /// Try and normalize the votes of self.
404 ///
405 /// If the normalization is successful then `Ok(())` is returned.
406 ///
407 /// Note that this will not distinguish between elected and unelected edges. Thus, it should
408 /// only be called on a voter who has already been reduced to only elected edges.
409 ///
410 /// ### Errors
411 ///
412 /// This will return only if the internal `normalize` fails. This can happen if the sum of the
413 /// weights exceeds `ExtendedBalance::max_value()`.
414 pub fn try_normalize(&mut self) -> Result<(), &'static str> {
415 let edge_weights = self.edges.iter().map(|e| e.weight).collect::<Vec<_>>();
416 edge_weights.normalize(self.budget).map(|normalized| {
417 // here we count on the fact that normalize does not change the order.
418 for (edge, corrected) in self.edges.iter_mut().zip(normalized.into_iter()) {
419 let mut candidate = edge.candidate.borrow_mut();
420 // first, subtract the incorrect weight
421 candidate.backed_stake = candidate.backed_stake.saturating_sub(edge.weight);
422 edge.weight = corrected;
423 // Then add the correct one again.
424 candidate.backed_stake = candidate.backed_stake.saturating_add(edge.weight);
425 }
426 })
427 }
428
429 /// Same as [`Self::try_normalize`] but the normalization is only limited between elected edges.
430 pub fn try_normalize_elected(&mut self) -> Result<(), &'static str> {
431 let elected_edge_weights = self
432 .edges
433 .iter()
434 .filter_map(|e| if e.candidate.borrow().elected { Some(e.weight) } else { None })
435 .collect::<Vec<_>>();
436 elected_edge_weights.normalize(self.budget).map(|normalized| {
437 // here we count on the fact that normalize does not change the order, and that vector
438 // iteration is deterministic.
439 for (edge, corrected) in self
440 .edges
441 .iter_mut()
442 .filter(|e| e.candidate.borrow().elected)
443 .zip(normalized.into_iter())
444 {
445 let mut candidate = edge.candidate.borrow_mut();
446 // first, subtract the incorrect weight
447 candidate.backed_stake = candidate.backed_stake.saturating_sub(edge.weight);
448 edge.weight = corrected;
449 // Then add the correct one again.
450 candidate.backed_stake = candidate.backed_stake.saturating_add(edge.weight);
451 }
452 })
453 }
454
455 /// This voter's budget.
456 #[inline]
457 pub fn budget(&self) -> ExtendedBalance {
458 self.budget
459 }
460}
461
462/// Final result of the election.
463#[derive(RuntimeDebug)]
464pub struct ElectionResult<AccountId, P: PerThing> {
465 /// Just winners zipped with their approval stake. Note that the approval stake is merely the
466 /// sub of their received stake and could be used for very basic sorting and approval voting.
467 pub winners: Vec<(AccountId, ExtendedBalance)>,
468 /// Individual assignments. for each tuple, the first elements is a voter and the second is the
469 /// list of candidates that it supports.
470 pub assignments: Vec<Assignment<AccountId, P>>,
471}
472
473/// A structure to demonstrate the election result from the perspective of the candidate, i.e. how
474/// much support each candidate is receiving.
475///
476/// This complements the [`ElectionResult`] and is needed to run the balancing post-processing.
477///
478/// This, at the current version, resembles the `Exposure` defined in the Staking pallet, yet they
479/// do not necessarily have to be the same.
480#[derive(RuntimeDebug, Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, TypeInfo)]
481#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
482pub struct Support<AccountId> {
483 /// Total support.
484 pub total: ExtendedBalance,
485 /// Support from voters.
486 pub voters: Vec<(AccountId, ExtendedBalance)>,
487}
488
489impl<AccountId> Default for Support<AccountId> {
490 fn default() -> Self {
491 Self { total: Default::default(), voters: vec![] }
492 }
493}
494
495impl<AccountId> Backings for &Support<AccountId> {
496 fn total(&self) -> ExtendedBalance {
497 self.total
498 }
499}
500
501/// A target-major representation of the the election outcome.
502///
503/// Essentially a flat variant of [`SupportMap`].
504///
505/// The main advantage of this is that it is encodable.
506pub type Supports<A> = Vec<(A, Support<A>)>;
507
508/// Linkage from a winner to their [`Support`].
509///
510/// This is more helpful than a normal [`Supports`] as it allows faster error checking.
511pub type SupportMap<A> = BTreeMap<A, Support<A>>;
512
513/// Build the support map from the assignments.
514pub fn to_support_map<AccountId: IdentifierT>(
515 assignments: &[StakedAssignment<AccountId>],
516) -> SupportMap<AccountId> {
517 let mut supports = <BTreeMap<AccountId, Support<AccountId>>>::new();
518
519 // build support struct.
520 for StakedAssignment { who, distribution } in assignments.iter() {
521 for (c, weight_extended) in distribution.iter() {
522 let support = supports.entry(c.clone()).or_default();
523 support.total = support.total.saturating_add(*weight_extended);
524 support.voters.push((who.clone(), *weight_extended));
525 }
526 }
527
528 supports
529}
530
531/// Same as [`to_support_map`] except it returns a flat vector.
532pub fn to_supports<AccountId: IdentifierT>(
533 assignments: &[StakedAssignment<AccountId>],
534) -> Supports<AccountId> {
535 to_support_map(assignments).into_iter().collect()
536}
537
538/// Extension trait for evaluating a support map or vector.
539pub trait EvaluateSupport {
540 /// Evaluate a support map. The returned tuple contains:
541 ///
542 /// - Minimum support. This value must be **maximized**.
543 /// - Sum of all supports. This value must be **maximized**.
544 /// - Sum of all supports squared. This value must be **minimized**.
545 fn evaluate(&self) -> ElectionScore;
546}
547
548impl<AccountId: IdentifierT> EvaluateSupport for Supports<AccountId> {
549 fn evaluate(&self) -> ElectionScore {
550 evaluate_support(self.iter().map(|(_, s)| s))
551 }
552}
553
554/// Generic representation of a support.
555pub trait Backings {
556 /// The total backing of an individual target.
557 fn total(&self) -> ExtendedBalance;
558}
559
560/// General evaluation of a list of backings that returns an election score.
561pub fn evaluate_support(backings: impl Iterator<Item = impl Backings>) -> ElectionScore {
562 let mut minimal_stake = ExtendedBalance::max_value();
563 let mut sum_stake: ExtendedBalance = Zero::zero();
564 // NOTE: The third element might saturate but fine for now since this will run on-chain and
565 // need to be fast.
566 let mut sum_stake_squared: ExtendedBalance = Zero::zero();
567
568 for support in backings {
569 sum_stake = sum_stake.saturating_add(support.total());
570 let squared = support.total().saturating_mul(support.total());
571 sum_stake_squared = sum_stake_squared.saturating_add(squared);
572 if support.total() < minimal_stake {
573 minimal_stake = support.total();
574 }
575 }
576
577 ElectionScore { minimal_stake, sum_stake, sum_stake_squared }
578}
579
580/// Converts raw inputs to types used in this crate.
581///
582/// This will perform some cleanup that are most often important:
583/// - It drops any votes that are pointing to non-candidates.
584/// - It drops duplicate targets within a voter.
585pub fn setup_inputs<AccountId: IdentifierT>(
586 initial_candidates: Vec<AccountId>,
587 initial_voters: Vec<(AccountId, VoteWeight, impl IntoIterator<Item = AccountId>)>,
588) -> (Vec<CandidatePtr<AccountId>>, Vec<Voter<AccountId>>) {
589 // used to cache and access candidates index.
590 let mut c_idx_cache = BTreeMap::<AccountId, usize>::new();
591
592 let candidates = initial_candidates
593 .into_iter()
594 .enumerate()
595 .map(|(idx, who)| {
596 c_idx_cache.insert(who.clone(), idx);
597 Candidate {
598 who,
599 score: Default::default(),
600 approval_stake: Default::default(),
601 backed_stake: Default::default(),
602 elected: Default::default(),
603 round: Default::default(),
604 }
605 .to_ptr()
606 })
607 .collect::<Vec<CandidatePtr<AccountId>>>();
608
609 let voters = initial_voters
610 .into_iter()
611 .filter_map(|(who, voter_stake, votes)| {
612 let mut edges: Vec<Edge<AccountId>> = Vec::new();
613 for v in votes {
614 if edges.iter().any(|e| e.who == v) {
615 // duplicate edge.
616 continue
617 }
618 if let Some(idx) = c_idx_cache.get(&v) {
619 // This candidate is valid + already cached.
620 let mut candidate = candidates[*idx].borrow_mut();
621 candidate.approval_stake =
622 candidate.approval_stake.saturating_add(voter_stake.into());
623 edges.push(Edge {
624 who: v.clone(),
625 candidate: Rc::clone(&candidates[*idx]),
626 load: Default::default(),
627 weight: Default::default(),
628 });
629 } // else {} would be wrong votes. We don't really care about it.
630 }
631 if edges.is_empty() {
632 None
633 } else {
634 Some(Voter { who, edges, budget: voter_stake.into(), load: Rational128::zero() })
635 }
636 })
637 .collect::<Vec<_>>();
638
639 (candidates, voters)
640}