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, 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::{bounded::BoundedVec, 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(Eq, PartialEq, RuntimeDebug)]
114pub enum Error {
115	/// While going from solution indices to ratio, the weight of all the edges has gone above the
116	/// total.
117	SolutionWeightOverflow,
118	/// The solution type has a voter who's number of targets is out of bound.
119	SolutionTargetOverflow,
120	/// One of the index functions returned none.
121	SolutionInvalidIndex,
122	/// One of the page indices was invalid.
123	SolutionInvalidPageIndex,
124	/// An error occurred in some arithmetic operation.
125	ArithmeticError(&'static str),
126	/// The data provided to create support map was invalid.
127	InvalidSupportEdge,
128	/// The number of voters is bigger than the `MaxVoters` bound.
129	TooManyVoters,
130	/// A duplicate voter was detected.
131	DuplicateVoter,
132	/// A duplicate target was detected.
133	DuplicateTarget,
134}
135
136/// A type which is used in the API of this crate as a numeric weight of a vote, most often the
137/// stake of the voter. It is always converted to [`ExtendedBalance`] for computation.
138pub type VoteWeight = u64;
139
140/// A type in which performing operations on vote weights are safe.
141pub type ExtendedBalance = u128;
142
143/// The score of an election. This is the main measure of an election's quality.
144///
145/// By definition, the order of significance in [`ElectionScore`] is:
146///
147/// 1. `minimal_stake`.
148/// 2. `sum_stake`.
149/// 3. `sum_stake_squared`.
150#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, MaxEncodedLen, TypeInfo, Debug, Default)]
151#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
152pub struct ElectionScore {
153	/// The minimal winner, in terms of total backing stake.
154	///
155	/// This parameter should be maximized.
156	pub minimal_stake: ExtendedBalance,
157	/// The sum of the total backing of all winners.
158	///
159	/// This parameter should maximized
160	pub sum_stake: ExtendedBalance,
161	/// The sum squared of the total backing of all winners, aka. the variance.
162	///
163	/// Ths parameter should be minimized.
164	pub sum_stake_squared: ExtendedBalance,
165}
166
167impl ElectionScore {
168	/// Iterate over the inner items, first visiting the most significant one.
169	fn iter_by_significance(self) -> impl Iterator<Item = ExtendedBalance> {
170		[self.minimal_stake, self.sum_stake, self.sum_stake_squared].into_iter()
171	}
172
173	/// Compares two sets of election scores based on desirability, returning true if `self` is
174	/// strictly `threshold` better than `other`. In other words, each element of `self` must be
175	/// `self * threshold` better than `other`.
176	///
177	/// Evaluation is done based on the order of significance of the fields of [`ElectionScore`].
178	pub fn strict_threshold_better(self, other: Self, threshold: impl PerThing) -> bool {
179		match self
180			.iter_by_significance()
181			.zip(other.iter_by_significance())
182			.map(|(this, that)| (this.ge(&that), this.tcmp(&that, threshold.mul_ceil(that))))
183			.collect::<Vec<(bool, Ordering)>>()
184			.as_slice()
185		{
186			// threshold better in the `score.minimal_stake`, accept.
187			[(x, Ordering::Greater), _, _] => {
188				debug_assert!(x);
189				true
190			},
191
192			// less than threshold better in `score.minimal_stake`, but more than threshold better
193			// in `score.sum_stake`.
194			[(true, Ordering::Equal), (_, Ordering::Greater), _] => true,
195
196			// less than threshold better in `score.minimal_stake` and `score.sum_stake`, but more
197			// than threshold better in `score.sum_stake_squared`.
198			[(true, Ordering::Equal), (true, Ordering::Equal), (_, Ordering::Less)] => true,
199
200			// anything else is not a good score.
201			_ => false,
202		}
203	}
204}
205
206impl core::cmp::Ord for ElectionScore {
207	fn cmp(&self, other: &Self) -> Ordering {
208		// we delegate this to the lexicographic cmp of slices`, and to incorporate that we want the
209		// third element to be minimized, we swap them.
210		[self.minimal_stake, self.sum_stake, other.sum_stake_squared].cmp(&[
211			other.minimal_stake,
212			other.sum_stake,
213			self.sum_stake_squared,
214		])
215	}
216}
217
218impl core::cmp::PartialOrd for ElectionScore {
219	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
220		Some(self.cmp(other))
221	}
222}
223
224/// Utility struct to group parameters for the balancing algorithm.
225#[derive(Clone, Copy)]
226pub struct BalancingConfig {
227	pub iterations: usize,
228	pub tolerance: ExtendedBalance,
229}
230
231/// A pointer to a candidate struct with interior mutability.
232pub type CandidatePtr<A> = Rc<RefCell<Candidate<A>>>;
233
234/// A candidate entity for the election.
235#[derive(RuntimeDebug, Clone, Default)]
236pub struct Candidate<AccountId> {
237	/// Identifier.
238	who: AccountId,
239	/// Score of the candidate.
240	///
241	/// Used differently in seq-phragmen and max-score.
242	score: Rational128,
243	/// Approval stake of the candidate. Merely the sum of all the voter's stake who approve this
244	/// candidate.
245	approval_stake: ExtendedBalance,
246	/// The final stake of this candidate. Will be equal to a subset of approval stake.
247	backed_stake: ExtendedBalance,
248	/// True if this candidate is already elected in the current election.
249	elected: bool,
250	/// The round index at which this candidate was elected.
251	round: usize,
252}
253
254impl<AccountId> Candidate<AccountId> {
255	pub fn to_ptr(self) -> CandidatePtr<AccountId> {
256		Rc::new(RefCell::new(self))
257	}
258}
259
260/// A vote being casted by a [`Voter`] to a [`Candidate`] is an `Edge`.
261#[derive(Clone)]
262pub struct Edge<AccountId> {
263	/// Identifier of the target.
264	///
265	/// This is equivalent of `self.candidate.borrow().who`, yet it helps to avoid double borrow
266	/// errors of the candidate pointer.
267	who: AccountId,
268	/// Load of this edge.
269	load: Rational128,
270	/// Pointer to the candidate.
271	candidate: CandidatePtr<AccountId>,
272	/// The weight (i.e. stake given to `who`) of this edge.
273	weight: ExtendedBalance,
274}
275
276#[cfg(test)]
277impl<AccountId: Clone> Edge<AccountId> {
278	fn new(candidate: Candidate<AccountId>, weight: ExtendedBalance) -> Self {
279		let who = candidate.who.clone();
280		let candidate = Rc::new(RefCell::new(candidate));
281		Self { weight, who, candidate, load: Default::default() }
282	}
283}
284
285#[cfg(feature = "std")]
286impl<A: IdentifierT> core::fmt::Debug for Edge<A> {
287	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
288		write!(f, "Edge({:?}, weight = {:?})", self.who, self.weight)
289	}
290}
291
292/// A voter entity.
293#[derive(Clone, Default)]
294pub struct Voter<AccountId> {
295	/// Identifier.
296	who: AccountId,
297	/// List of candidates approved by this voter.
298	edges: Vec<Edge<AccountId>>,
299	/// The stake of this voter.
300	budget: ExtendedBalance,
301	/// Load of the voter.
302	load: Rational128,
303}
304
305#[cfg(feature = "std")]
306impl<A: IdentifierT> std::fmt::Debug for Voter<A> {
307	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
308		write!(f, "Voter({:?}, budget = {}, edges = {:?})", self.who, self.budget, self.edges)
309	}
310}
311
312impl<AccountId: IdentifierT> Voter<AccountId> {
313	/// Create a new `Voter`.
314	pub fn new(who: AccountId) -> Self {
315		Self {
316			who,
317			edges: Default::default(),
318			budget: Default::default(),
319			load: Default::default(),
320		}
321	}
322
323	/// Returns `true` if `self` votes for `target`.
324	///
325	/// Note that this does not take into account if `target` is elected (i.e. is *active*) or not.
326	pub fn votes_for(&self, target: &AccountId) -> bool {
327		self.edges.iter().any(|e| &e.who == target)
328	}
329
330	/// Returns none if this voter does not have any non-zero distributions.
331	///
332	/// Note that this might create _un-normalized_ assignments, due to accuracy loss of `P`. Call
333	/// site might compensate by calling `normalize()` on the returned `Assignment` as a
334	/// post-processing.
335	pub fn into_assignment<P: PerThing>(self) -> Option<Assignment<AccountId, P>> {
336		let who = self.who;
337		let budget = self.budget;
338		let distribution = self
339			.edges
340			.into_iter()
341			.filter_map(|e| {
342				let per_thing = P::from_rational(e.weight, budget);
343				// trim zero edges.
344				if per_thing.is_zero() {
345					None
346				} else {
347					Some((e.who, per_thing))
348				}
349			})
350			.collect::<Vec<_>>();
351
352		if distribution.len() > 0 {
353			Some(Assignment { who, distribution })
354		} else {
355			None
356		}
357	}
358
359	/// Try and normalize the votes of self.
360	///
361	/// If the normalization is successful then `Ok(())` is returned.
362	///
363	/// Note that this will not distinguish between elected and unelected edges. Thus, it should
364	/// only be called on a voter who has already been reduced to only elected edges.
365	///
366	/// ### Errors
367	///
368	/// This will return only if the internal `normalize` fails. This can happen if the sum of the
369	/// weights exceeds `ExtendedBalance::max_value()`.
370	pub fn try_normalize(&mut self) -> Result<(), &'static str> {
371		let edge_weights = self.edges.iter().map(|e| e.weight).collect::<Vec<_>>();
372		edge_weights.normalize(self.budget).map(|normalized| {
373			// here we count on the fact that normalize does not change the order.
374			for (edge, corrected) in self.edges.iter_mut().zip(normalized.into_iter()) {
375				let mut candidate = edge.candidate.borrow_mut();
376				// first, subtract the incorrect weight
377				candidate.backed_stake = candidate.backed_stake.saturating_sub(edge.weight);
378				edge.weight = corrected;
379				// Then add the correct one again.
380				candidate.backed_stake = candidate.backed_stake.saturating_add(edge.weight);
381			}
382		})
383	}
384
385	/// Same as [`Self::try_normalize`] but the normalization is only limited between elected edges.
386	pub fn try_normalize_elected(&mut self) -> Result<(), &'static str> {
387		let elected_edge_weights = self
388			.edges
389			.iter()
390			.filter_map(|e| if e.candidate.borrow().elected { Some(e.weight) } else { None })
391			.collect::<Vec<_>>();
392		elected_edge_weights.normalize(self.budget).map(|normalized| {
393			// here we count on the fact that normalize does not change the order, and that vector
394			// iteration is deterministic.
395			for (edge, corrected) in self
396				.edges
397				.iter_mut()
398				.filter(|e| e.candidate.borrow().elected)
399				.zip(normalized.into_iter())
400			{
401				let mut candidate = edge.candidate.borrow_mut();
402				// first, subtract the incorrect weight
403				candidate.backed_stake = candidate.backed_stake.saturating_sub(edge.weight);
404				edge.weight = corrected;
405				// Then add the correct one again.
406				candidate.backed_stake = candidate.backed_stake.saturating_add(edge.weight);
407			}
408		})
409	}
410
411	/// This voter's budget.
412	#[inline]
413	pub fn budget(&self) -> ExtendedBalance {
414		self.budget
415	}
416}
417
418/// Final result of the election.
419#[derive(RuntimeDebug)]
420pub struct ElectionResult<AccountId, P: PerThing> {
421	/// Just winners zipped with their approval stake. Note that the approval stake is merely the
422	/// sub of their received stake and could be used for very basic sorting and approval voting.
423	pub winners: Vec<(AccountId, ExtendedBalance)>,
424	/// Individual assignments. for each tuple, the first elements is a voter and the second is the
425	/// list of candidates that it supports.
426	pub assignments: Vec<Assignment<AccountId, P>>,
427}
428
429/// A structure to demonstrate the election result from the perspective of the candidate, i.e. how
430/// much support each candidate is receiving.
431///
432/// This complements the [`ElectionResult`] and is needed to run the balancing post-processing.
433///
434/// This, at the current version, resembles the `Exposure` defined in the Staking pallet, yet they
435/// do not necessarily have to be the same.
436#[derive(RuntimeDebug, Encode, Decode, Clone, Eq, PartialEq, TypeInfo)]
437#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
438pub struct Support<AccountId> {
439	/// Total support.
440	pub total: ExtendedBalance,
441	/// Support from voters.
442	pub voters: Vec<(AccountId, ExtendedBalance)>,
443}
444
445impl<AccountId> Default for Support<AccountId> {
446	fn default() -> Self {
447		Self { total: Default::default(), voters: vec![] }
448	}
449}
450
451/// A target-major representation of the the election outcome.
452///
453/// Essentially a flat variant of [`SupportMap`].
454///
455/// The main advantage of this is that it is encodable.
456pub type Supports<A> = Vec<(A, Support<A>)>;
457
458/// Same as `Supports` but bounded by `B`.
459///
460/// To note, the inner `Support` is still unbounded.
461pub type BoundedSupports<A, B> = BoundedVec<(A, Support<A>), B>;
462
463/// Linkage from a winner to their [`Support`].
464///
465/// This is more helpful than a normal [`Supports`] as it allows faster error checking.
466pub type SupportMap<A> = BTreeMap<A, Support<A>>;
467
468/// Build the support map from the assignments.
469pub fn to_support_map<AccountId: IdentifierT>(
470	assignments: &[StakedAssignment<AccountId>],
471) -> SupportMap<AccountId> {
472	let mut supports = <BTreeMap<AccountId, Support<AccountId>>>::new();
473
474	// build support struct.
475	for StakedAssignment { who, distribution } in assignments.iter() {
476		for (c, weight_extended) in distribution.iter() {
477			let support = supports.entry(c.clone()).or_default();
478			support.total = support.total.saturating_add(*weight_extended);
479			support.voters.push((who.clone(), *weight_extended));
480		}
481	}
482
483	supports
484}
485
486/// Same as [`to_support_map`] except it returns a
487/// flat vector.
488pub fn to_supports<AccountId: IdentifierT>(
489	assignments: &[StakedAssignment<AccountId>],
490) -> Supports<AccountId> {
491	to_support_map(assignments).into_iter().collect()
492}
493
494/// Extension trait for evaluating a support map or vector.
495pub trait EvaluateSupport {
496	/// Evaluate a support map. The returned tuple contains:
497	///
498	/// - Minimum support. This value must be **maximized**.
499	/// - Sum of all supports. This value must be **maximized**.
500	/// - Sum of all supports squared. This value must be **minimized**.
501	fn evaluate(&self) -> ElectionScore;
502}
503
504impl<AccountId: IdentifierT> EvaluateSupport for Supports<AccountId> {
505	fn evaluate(&self) -> ElectionScore {
506		let mut minimal_stake = ExtendedBalance::max_value();
507		let mut sum_stake: ExtendedBalance = Zero::zero();
508		// NOTE: The third element might saturate but fine for now since this will run on-chain and
509		// need to be fast.
510		let mut sum_stake_squared: ExtendedBalance = Zero::zero();
511
512		for (_, support) in self {
513			sum_stake = sum_stake.saturating_add(support.total);
514			let squared = support.total.saturating_mul(support.total);
515			sum_stake_squared = sum_stake_squared.saturating_add(squared);
516			if support.total < minimal_stake {
517				minimal_stake = support.total;
518			}
519		}
520
521		ElectionScore { minimal_stake, sum_stake, sum_stake_squared }
522	}
523}
524
525/// Converts raw inputs to types used in this crate.
526///
527/// This will perform some cleanup that are most often important:
528/// - It drops any votes that are pointing to non-candidates.
529/// - It drops duplicate targets within a voter.
530pub fn setup_inputs<AccountId: IdentifierT>(
531	initial_candidates: Vec<AccountId>,
532	initial_voters: Vec<(AccountId, VoteWeight, impl IntoIterator<Item = AccountId>)>,
533) -> (Vec<CandidatePtr<AccountId>>, Vec<Voter<AccountId>>) {
534	// used to cache and access candidates index.
535	let mut c_idx_cache = BTreeMap::<AccountId, usize>::new();
536
537	let candidates = initial_candidates
538		.into_iter()
539		.enumerate()
540		.map(|(idx, who)| {
541			c_idx_cache.insert(who.clone(), idx);
542			Candidate {
543				who,
544				score: Default::default(),
545				approval_stake: Default::default(),
546				backed_stake: Default::default(),
547				elected: Default::default(),
548				round: Default::default(),
549			}
550			.to_ptr()
551		})
552		.collect::<Vec<CandidatePtr<AccountId>>>();
553
554	let voters = initial_voters
555		.into_iter()
556		.filter_map(|(who, voter_stake, votes)| {
557			let mut edges: Vec<Edge<AccountId>> = Vec::new();
558			for v in votes {
559				if edges.iter().any(|e| e.who == v) {
560					// duplicate edge.
561					continue
562				}
563				if let Some(idx) = c_idx_cache.get(&v) {
564					// This candidate is valid + already cached.
565					let mut candidate = candidates[*idx].borrow_mut();
566					candidate.approval_stake =
567						candidate.approval_stake.saturating_add(voter_stake.into());
568					edges.push(Edge {
569						who: v.clone(),
570						candidate: Rc::clone(&candidates[*idx]),
571						load: Default::default(),
572						weight: Default::default(),
573					});
574				} // else {} would be wrong votes. We don't really care about it.
575			}
576			if edges.is_empty() {
577				None
578			} else {
579				Some(Voter { who, edges, budget: voter_stake.into(), load: Rational128::zero() })
580			}
581		})
582		.collect::<Vec<_>>();
583
584	(candidates, voters)
585}