Remove Default bound for AccountId (#10403)

* Remove Default for AccountId

* More removals of default

* Update frame/authorship/src/lib.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update frame/authorship/src/lib.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update frame/authorship/src/lib.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update frame/authorship/src/lib.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* More work

* More work

* Remove old code

* More work

* pallet-asset-tx-payment

* tips

* sc-consensus-babe

* sc-finality-grandpa

* sc-consensus-babe-rpc

* sc-cli

* make npos crates accept non-default account (#10420)

* minimal changes to make npos pallets all work

* make this pesky reduce.rs a bit cleaner

* more work

* more work

* Tests build

* Fix imonline tests

* Formatting

* Fixes

* Fixes

* Fix bench

* Fixes

* Fixes

* Fixes

* Fixes

* Fixes

* Formatting

* Fixes

* Formatting

* Fixes

* Formatting

* Fixes

* Formatting

* Fixes

* Formatting

* Update client/keystore/src/local.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/finality-grandpa/src/lib.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/keystore/src/local.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update client/keystore/src/local.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update frame/staking/src/lib.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update frame/staking/src/lib.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update primitives/runtime/src/traits.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Formatting

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
Co-authored-by: kianenigma <kian@parity.io>
This commit is contained in:
Gavin Wood
2021-12-13 15:03:59 +01:00
committed by GitHub
parent a4ccc26e33
commit 1e24e45ea1
118 changed files with 998 additions and 4181 deletions
+34 -5
View File
@@ -178,7 +178,7 @@ impl<AccountId> Candidate<AccountId> {
}
/// A vote being casted by a [`Voter`] to a [`Candidate`] is an `Edge`.
#[derive(Clone, Default)]
#[derive(Clone)]
pub struct Edge<AccountId> {
/// Identifier of the target.
///
@@ -193,6 +193,15 @@ pub struct Edge<AccountId> {
weight: ExtendedBalance,
}
#[cfg(test)]
impl<AccountId: Clone> Edge<AccountId> {
fn new(candidate: Candidate<AccountId>, weight: ExtendedBalance) -> Self {
let who = candidate.who.clone();
let candidate = Rc::new(RefCell::new(candidate));
Self { weight, who, candidate, load: Default::default() }
}
}
#[cfg(feature = "std")]
impl<A: IdentifierT> sp_std::fmt::Debug for Edge<A> {
fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result {
@@ -223,7 +232,12 @@ impl<A: IdentifierT> std::fmt::Debug for Voter<A> {
impl<AccountId: IdentifierT> Voter<AccountId> {
/// Create a new `Voter`.
pub fn new(who: AccountId) -> Self {
Self { who, ..Default::default() }
Self {
who,
edges: Default::default(),
budget: Default::default(),
load: Default::default(),
}
}
/// Returns `true` if `self` votes for `target`.
@@ -339,7 +353,7 @@ pub struct ElectionResult<AccountId, P: PerThing> {
///
/// This, at the current version, resembles the `Exposure` defined in the Staking pallet, yet they
/// do not necessarily have to be the same.
#[derive(Default, RuntimeDebug, Encode, Decode, Clone, Eq, PartialEq, scale_info::TypeInfo)]
#[derive(RuntimeDebug, Encode, Decode, Clone, Eq, PartialEq, scale_info::TypeInfo)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct Support<AccountId> {
/// Total support.
@@ -348,6 +362,12 @@ pub struct Support<AccountId> {
pub voters: Vec<(AccountId, ExtendedBalance)>,
}
impl<AccountId> Default for Support<AccountId> {
fn default() -> Self {
Self { total: Default::default(), voters: vec![] }
}
}
/// A target-major representation of the the election outcome.
///
/// Essentially a flat variant of [`SupportMap`].
@@ -461,7 +481,15 @@ pub fn setup_inputs<AccountId: IdentifierT>(
.enumerate()
.map(|(idx, who)| {
c_idx_cache.insert(who.clone(), idx);
Candidate { who, ..Default::default() }.to_ptr()
Candidate {
who,
score: Default::default(),
approval_stake: Default::default(),
backed_stake: Default::default(),
elected: Default::default(),
round: Default::default(),
}
.to_ptr()
})
.collect::<Vec<CandidatePtr<AccountId>>>();
@@ -482,7 +510,8 @@ pub fn setup_inputs<AccountId: IdentifierT>(
edges.push(Edge {
who: v.clone(),
candidate: Rc::clone(&candidates[*idx]),
..Default::default()
load: Default::default(),
weight: Default::default(),
});
} // else {} would be wrong votes. We don't really care about it.
}
+29 -6
View File
@@ -287,7 +287,15 @@ fn prepare_pjr_input<AccountId: IdentifierT>(
let elected = maybe_support.is_some();
let backed_stake = maybe_support.map(|support| support.total).unwrap_or_default();
Candidate { who, elected, backed_stake, ..Default::default() }.to_ptr()
Candidate {
who,
elected,
backed_stake,
score: Default::default(),
approval_stake: Default::default(),
round: Default::default(),
}
.to_ptr()
})
.collect::<Vec<_>>();
@@ -315,14 +323,14 @@ fn prepare_pjr_input<AccountId: IdentifierT>(
who: t,
candidate: Rc::clone(&candidates[*idx]),
weight,
..Default::default()
load: Default::default(),
});
}
}
let who = v;
let budget: ExtendedBalance = w.into();
Voter { who, budget, edges, ..Default::default() }
Voter { who, budget, edges, load: Default::default() }
})
.collect::<Vec<_>>();
@@ -387,7 +395,14 @@ mod tests {
.into_iter()
.map(|(t, w, e)| {
budget += w;
Candidate { who: t, elected: e, backed_stake: w, ..Default::default() }
Candidate {
who: t,
elected: e,
backed_stake: w,
score: Default::default(),
approval_stake: Default::default(),
round: Default::default(),
}
})
.collect::<Vec<_>>();
let edges = candidates
@@ -396,7 +411,7 @@ mod tests {
who: c.who,
weight: c.backed_stake,
candidate: c.to_ptr(),
..Default::default()
load: Default::default(),
})
.collect::<Vec<_>>();
voter.edges = edges;
@@ -432,7 +447,15 @@ mod tests {
// will give 10 slack.
let v3 = setup_voter(30, vec![(1, 20, true), (2, 20, true), (3, 0, false)]);
let unelected = Candidate { who: 3u32, elected: false, ..Default::default() }.to_ptr();
let unelected = Candidate {
who: 3u32,
elected: false,
score: Default::default(),
approval_stake: Default::default(),
backed_stake: Default::default(),
round: Default::default(),
}
.to_ptr();
let score = pre_score(unelected, &vec![v1, v2, v3], 15);
assert_eq!(score, 15);
@@ -55,7 +55,6 @@ use sp_arithmetic::traits::{Bounded, Zero};
use sp_std::{
collections::btree_map::{BTreeMap, Entry::*},
prelude::*,
vec,
};
/// Map type used for reduce_4. Can be easily swapped with HashMap.
@@ -356,7 +355,7 @@ fn reduce_all<A: IdentifierT>(assignments: &mut Vec<StakedAssignment<A>>) -> u32
.or_insert_with(|| Node::new(target_id).into_ref())
.clone();
// If one exists but the other one doesn't, or if both does not, then set the existing
// If one exists but the other one doesn't, or if both do not, then set the existing
// one as the parent of the non-existing one and move on. Else, continue with the rest
// of the code.
match (voter_exists, target_exists) {
@@ -390,39 +389,44 @@ fn reduce_all<A: IdentifierT>(assignments: &mut Vec<StakedAssignment<A>>) -> u32
let common_count = trailing_common(&voter_root_path, &target_root_path);
// because roots are the same.
#[cfg(feature = "std")]
debug_assert_eq!(target_root_path.last().unwrap(), voter_root_path.last().unwrap());
//debug_assert_eq!(target_root_path.last().unwrap(),
// voter_root_path.last().unwrap()); TODO: @kian
// the common path must be non-void..
debug_assert!(common_count > 0);
// and smaller than btoh
debug_assert!(common_count <= voter_root_path.len());
debug_assert!(common_count <= target_root_path.len());
// cycle part of each path will be `path[path.len() - common_count - 1 : 0]`
// NOTE: the order of chaining is important! it is always build from [target, ...,
// voter]
let cycle = target_root_path
.iter()
.take(target_root_path.len() - common_count + 1)
.take(target_root_path.len().saturating_sub(common_count).saturating_add(1))
.cloned()
.chain(
voter_root_path
.iter()
.take(voter_root_path.len() - common_count)
.take(voter_root_path.len().saturating_sub(common_count))
.rev()
.cloned(),
)
.collect::<Vec<NodeRef<A>>>();
// a cycle's length shall always be multiple of two.
#[cfg(feature = "std")]
debug_assert_eq!(cycle.len() % 2, 0);
// find minimum of cycle.
let mut min_value: ExtendedBalance = Bounded::max_value();
// The voter and the target pair that create the min edge.
let mut min_target: A = Default::default();
let mut min_voter: A = Default::default();
// The voter and the target pair that create the min edge. These MUST be set by the
// end of this code block, otherwise we skip.
let mut maybe_min_target: Option<A> = None;
let mut maybe_min_voter: Option<A> = None;
// The index of the min in opaque cycle list.
let mut min_index = 0usize;
let mut maybe_min_index: Option<usize> = None;
// 1 -> next // 0 -> prev
let mut min_direction = 0u32;
let mut maybe_min_direction: Option<u32> = None;
// helpers
let next_index = |i| {
if i < (cycle.len() - 1) {
@@ -438,6 +442,7 @@ fn reduce_all<A: IdentifierT>(assignments: &mut Vec<StakedAssignment<A>>) -> u32
cycle.len() - 1
}
};
for i in 0..cycle.len() {
if cycle[i].borrow().id.role == NodeRole::Voter {
// NOTE: sadly way too many clones since I don't want to make A: Copy
@@ -448,10 +453,10 @@ fn reduce_all<A: IdentifierT>(assignments: &mut Vec<StakedAssignment<A>>) -> u32
ass.distribution.iter().find(|d| d.0 == next).map(|(_, w)| {
if *w < min_value {
min_value = *w;
min_target = next.clone();
min_voter = current.clone();
min_index = i;
min_direction = 1;
maybe_min_target = Some(next.clone());
maybe_min_voter = Some(current.clone());
maybe_min_index = Some(i);
maybe_min_direction = Some(1);
}
})
});
@@ -459,16 +464,39 @@ fn reduce_all<A: IdentifierT>(assignments: &mut Vec<StakedAssignment<A>>) -> u32
ass.distribution.iter().find(|d| d.0 == prev).map(|(_, w)| {
if *w < min_value {
min_value = *w;
min_target = prev.clone();
min_voter = current.clone();
min_index = i;
min_direction = 0;
maybe_min_target = Some(prev.clone());
maybe_min_voter = Some(current.clone());
maybe_min_index = Some(i);
maybe_min_direction = Some(0);
}
})
});
}
}
// all of these values must be set by now, we assign them to un-mut values, no
// longer being optional either.
let (min_value, min_target, min_voter, min_index, min_direction) =
match (
min_value,
maybe_min_target,
maybe_min_voter,
maybe_min_index,
maybe_min_direction,
) {
(
min_value,
Some(min_target),
Some(min_voter),
Some(min_index),
Some(min_direction),
) => (min_value, min_target, min_voter, min_index, min_direction),
_ => {
sp_runtime::print("UNREACHABLE code reached in `reduce` algorithm. This must be a bug.");
break
},
};
// if the min edge is in the voter's sub-chain.
// [target, ..., X, Y, ... voter]
let target_chunk = target_root_path.len() - common_count;
@@ -624,8 +652,8 @@ fn reduce_all<A: IdentifierT>(assignments: &mut Vec<StakedAssignment<A>>) -> u32
num_changed
}
/// Reduce the given [`Vec<StakedAssignment<IdentifierT>>`]. This removes redundant edges from
/// without changing the overall backing of any of the elected candidates.
/// Reduce the given [`Vec<StakedAssignment<IdentifierT>>`]. This removes redundant edges without
/// changing the overall backing of any of the elected candidates.
///
/// Returns the number of edges removed.
///
@@ -192,16 +192,15 @@ fn balancing_core_works() {
#[test]
fn voter_normalize_ops_works() {
use crate::{Candidate, Edge};
use sp_std::{cell::RefCell, rc::Rc};
// normalize
{
let c1 = Candidate { who: 10, elected: false, ..Default::default() };
let c2 = Candidate { who: 20, elected: false, ..Default::default() };
let c3 = Candidate { who: 30, elected: false, ..Default::default() };
let e1 = Edge { candidate: Rc::new(RefCell::new(c1)), weight: 30, ..Default::default() };
let e2 = Edge { candidate: Rc::new(RefCell::new(c2)), weight: 33, ..Default::default() };
let e3 = Edge { candidate: Rc::new(RefCell::new(c3)), weight: 30, ..Default::default() };
let e1 = Edge::new(c1, 30);
let e2 = Edge::new(c2, 33);
let e3 = Edge::new(c3, 30);
let mut v = Voter { who: 1, budget: 100, edges: vec![e1, e2, e3], ..Default::default() };
@@ -214,9 +213,9 @@ fn voter_normalize_ops_works() {
let c2 = Candidate { who: 20, elected: true, ..Default::default() };
let c3 = Candidate { who: 30, elected: true, ..Default::default() };
let e1 = Edge { candidate: Rc::new(RefCell::new(c1)), weight: 30, ..Default::default() };
let e2 = Edge { candidate: Rc::new(RefCell::new(c2)), weight: 33, ..Default::default() };
let e3 = Edge { candidate: Rc::new(RefCell::new(c3)), weight: 30, ..Default::default() };
let e1 = Edge::new(c1, 30);
let e2 = Edge::new(c2, 33);
let e3 = Edge::new(c3, 30);
let mut v = Voter { who: 1, budget: 100, edges: vec![e1, e2, e3], ..Default::default() };
@@ -36,8 +36,8 @@ use sp_std::{
/// an aggregator trait for a generic type of a voter/target identifier. This usually maps to
/// substrate's account id.
pub trait IdentifierT: Clone + Eq + Default + Ord + Debug + codec::Codec {}
impl<T: Clone + Eq + Default + Ord + Debug + codec::Codec> IdentifierT for T {}
pub trait IdentifierT: Clone + Eq + Ord + Debug + codec::Codec {}
impl<T: Clone + Eq + Ord + Debug + codec::Codec> IdentifierT for T {}
/// Aggregator trait for a PerThing that can be multiplied by u128 (ExtendedBalance).
pub trait PerThing128: PerThing + Mul<ExtendedBalance, Output = ExtendedBalance> {}