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