Switch elections to Phragmen, enable them in PoA (#492)

* Switch elections to Phragmen, enable them in PoA

* Remove superfluous code.

* Build fixes

* Update to substrate master

* Build fixes

* Add warning

* Disable authority discovery for now

* Remove commented code

* Fix warning
This commit is contained in:
Gavin Wood
2019-10-24 18:55:02 +02:00
committed by GitHub
parent dd2b43cd10
commit 425b884931
7 changed files with 181 additions and 229 deletions
+13 -20
View File
@@ -19,10 +19,9 @@
use primitives::Balance;
use sr_primitives::weights::Weight;
use sr_primitives::traits::{Convert, Saturating};
use sr_primitives::Fixed64;
use srml_support::traits::{OnUnbalanced, Currency};
use crate::{Balances, Authorship, MaximumBlockWeight, NegativeImbalance};
use crate::constants::fee::TARGET_BLOCK_FULLNESS;
use sr_primitives::{Fixed64, Perbill};
use srml_support::traits::{OnUnbalanced, Currency, Get};
use crate::{Balances, System, Authorship, MaximumBlockWeight, NegativeImbalance};
/// Logic for the author to get a portion of fees.
pub struct ToAuthor;
@@ -67,27 +66,21 @@ impl Convert<Weight, Balance> for WeightToFee {
}
}
/// A struct that updates the weight multiplier based on the saturation level of the previous block.
/// This should typically be called once per-block.
/// Update the given multiplier based on the following formula
///
/// This assumes that weight is a numeric value in the u32 range.
///
/// Given `TARGET_BLOCK_FULLNESS = 1/2`, a block saturation greater than 1/2 will cause the system
/// fees to slightly grow and the opposite for block saturations less than 1/2.
///
/// Formula:
/// diff = (target_weight - current_block_weight)
/// diff = (target_weight - previous_block_weight)
/// v = 0.00004
/// next_weight = weight * (1 + (v . diff) + (v . diff)^2 / 2)
///
/// Where `target_weight` must be given as the `Get` implementation of the `T` generic type.
/// https://research.web3.foundation/en/latest/polkadot/Token%20Economics/#relay-chain-transaction-fees
pub struct FeeMultiplierUpdateHandler;
pub struct TargetedFeeAdjustment<T>(rstd::marker::PhantomData<T>);
impl Convert<(Weight, Fixed64), Fixed64> for FeeMultiplierUpdateHandler {
fn convert(previous_state: (Weight, Fixed64)) -> Fixed64 {
let (block_weight, multiplier) = previous_state;
impl<T: Get<Perbill>> Convert<Fixed64, Fixed64> for TargetedFeeAdjustment<T> {
fn convert(multiplier: Fixed64) -> Fixed64 {
let block_weight = System::all_extrinsics_weight();
let max_weight = MaximumBlockWeight::get();
let target_weight = (TARGET_BLOCK_FULLNESS * max_weight) as u128;
let target_weight = (T::get() * max_weight) as u128;
let block_weight = block_weight as u128;
// determines if the first_term is positive
@@ -99,8 +92,8 @@ impl Convert<(Weight, Fixed64), Fixed64> for FeeMultiplierUpdateHandler {
// 0.00004 = 4/100_000 = 40_000/10^9
let v = Fixed64::from_rational(4, 100_000);
// 0.00004^2 = 16/10^10 ~= 2/10^9. Taking the future /2 into account, then it is just 1 parts
// from a billionth.
// 0.00004^2 = 16/10^10 ~= 2/10^9. Taking the future /2 into account, then it is just 1
// parts from a billionth.
let v_squared_2 = Fixed64::from_rational(1, 1_000_000_000);
let first_term = v.saturating_mul(diff);
+20 -66
View File
@@ -48,8 +48,7 @@ use sr_primitives::{
};
use version::RuntimeVersion;
use grandpa::{AuthorityId as GrandpaId, fg_primitives};
use babe_primitives::{AuthorityId as BabeId, AuthoritySignature as BabeSignature};
use elections::VoteIndex;
use babe_primitives::{AuthorityId as BabeId};
#[cfg(any(feature = "std", test))]
use version::NativeVersion;
use substrate_primitives::OpaqueMetadata;
@@ -57,7 +56,6 @@ use sr_staking_primitives::SessionIndex;
use srml_support::{
parameter_types, construct_runtime, traits::{SplitTwoWays, Currency, Randomness}
};
use authority_discovery_primitives::{AuthorityId as EncodedAuthorityId, Signature as EncodedSignature};
use im_online::sr25519::AuthorityId as ImOnlineId;
use system::offchain::TransactionSubmitter;
@@ -72,7 +70,7 @@ pub use parachains::{Call as ParachainsCall, NEW_HEADS_IDENTIFIER};
/// Implementations of some helper traits passed into runtime modules as associated types.
pub mod impls;
use impls::{CurrencyToVoteHandler, FeeMultiplierUpdateHandler, ToAuthor, WeightToFee};
use impls::{CurrencyToVoteHandler, TargetedFeeAdjustment, ToAuthor, WeightToFee};
/// Constant values used within the runtime.
pub mod constants;
@@ -131,7 +129,9 @@ impl SignedExtension for OnlyStakingAndClaims {
-> TransactionValidity
{
match call {
Call::Staking(_) | Call::Claims(_) | Call::Sudo(_) | Call::Session(_) =>
Call::Staking(_) | Call::Claims(_) | Call::Sudo(_) | Call::Session(_)
| Call::ElectionsPhragmen(_)
=>
Ok(Default::default()),
_ => Err(InvalidTransaction::Custom(ValidityError::NoPermission.into()).into()),
}
@@ -215,6 +215,8 @@ impl balances::Trait for Runtime {
parameter_types! {
pub const TransactionBaseFee: Balance = 1 * CENTS;
pub const TransactionByteFee: Balance = 10 * MILLICENTS;
// for a sane configuration, this should always be less than `AvailableBlockRatio`.
pub const TargetBlockFullness: Perbill = Perbill::from_percent(25);
}
impl transaction_payment::Trait for Runtime {
@@ -223,7 +225,7 @@ impl transaction_payment::Trait for Runtime {
type TransactionBaseFee = TransactionBaseFee;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = WeightToFee;
type FeeMultiplierUpdate = FeeMultiplierUpdateHandler;
type FeeMultiplierUpdate = TargetedFeeAdjustment<TargetBlockFullness>;
}
parameter_types! {
@@ -252,7 +254,10 @@ parameter_types! {
pub const Offset: BlockNumber = 0;
}
type SessionHandlers = (Grandpa, Babe, ImOnline, AuthorityDiscovery, Parachains);
// !!!!!!!!!!!!!
// WARNING!!!!!! SEE NOTE BELOW BEFORE TOUCHING THIS CODE
// !!!!!!!!!!!!!
type SessionHandlers = (Grandpa, Babe, ImOnline, Parachains);
impl_opaque_keys! {
pub struct SessionKeys {
#[id(key_types::GRANDPA)]
@@ -265,7 +270,6 @@ impl_opaque_keys! {
pub parachain_validator: parachain::ValidatorId,
}
}
// NOTE: `SessionHandler` and `SessionKeys` are co-dependent: One key will be used for each handler.
// The number and order of items in `SessionHandler` *MUST* be the same number and order of keys in
// `SessionKeys`.
@@ -370,35 +374,20 @@ impl collective::Trait<CouncilCollective> for Runtime {
}
parameter_types! {
pub const CandidacyBond: Balance = 10 * DOLLARS;
pub const VotingBond: Balance = 1 * DOLLARS;
pub const VotingFee: Balance = 2 * DOLLARS;
pub const MinimumVotingLock: Balance = 1 * DOLLARS;
pub const PresentSlashPerVoter: Balance = 1 * CENTS;
pub const CarryCount: u32 = 6;
// one additional vote should go by before an inactive voter can be reaped.
pub const InactiveGracePeriod: VoteIndex = 1;
pub const ElectionsVotingPeriod: BlockNumber = 2 * DAYS;
pub const DecayRatio: u32 = 0;
pub const CandidacyBond: Balance = 100 * DOLLARS;
pub const VotingBond: Balance = 5 * DOLLARS;
}
impl elections::Trait for Runtime {
impl elections_phragmen::Trait for Runtime {
type Event = Event;
type Currency = Balances;
type BadPresentation = ();
type BadReaper = ();
type BadVoterIndex = ();
type LoserCandidate = ();
type ChangeMembers = Council;
type CurrencyToVote = CurrencyToVoteHandler;
type CandidacyBond = CandidacyBond;
type VotingBond = VotingBond;
type VotingFee = VotingFee;
type MinimumVotingLock = MinimumVotingLock;
type PresentSlashPerVoter = PresentSlashPerVoter;
type CarryCount = CarryCount;
type InactiveGracePeriod = InactiveGracePeriod;
type VotingPeriod = ElectionsVotingPeriod;
type DecayRatio = DecayRatio;
type LoserCandidate = Treasury;
type BadReport = Treasury;
type KickedMember = Treasury;
}
type TechnicalCollective = collective::Instance2;
@@ -454,10 +443,6 @@ impl im_online::Trait for Runtime {
type ReportUnresponsiveness = ();
}
impl authority_discovery::Trait for Runtime {
type AuthorityId = BabeId;
}
impl grandpa::Trait for Runtime {
type Event = Event;
}
@@ -566,13 +551,12 @@ construct_runtime!(
FinalityTracker: finality_tracker::{Module, Call, Inherent},
Grandpa: grandpa::{Module, Call, Storage, Config, Event},
ImOnline: im_online::{Module, Call, Storage, Event<T>, ValidateUnsigned, Config<T>},
AuthorityDiscovery: authority_discovery::{Module, Call, Config<T>},
// Governance stuff; uncallable initially.
Democracy: democracy::{Module, Call, Storage, Config, Event<T>},
Council: collective::<Instance1>::{Module, Call, Storage, Origin<T>, Event<T>, Config<T>},
TechnicalCommittee: collective::<Instance2>::{Module, Call, Storage, Origin<T>, Event<T>, Config<T>},
Elections: elections::{Module, Call, Storage, Event<T>, Config<T>},
ElectionsPhragmen: elections_phragmen::{Module, Call, Storage, Event<T>, Config<T>},
TechnicalMembership: membership::<Instance1>::{Module, Call, Storage, Event<T>, Config<T>},
Treasury: treasury::{Module, Call, Storage, Event<T>},
@@ -723,36 +707,6 @@ impl_runtime_apis! {
}
}
impl authority_discovery_primitives::AuthorityDiscoveryApi<Block> for Runtime {
fn authorities() -> Vec<EncodedAuthorityId> {
AuthorityDiscovery::authorities().into_iter()
.map(|id| id.encode())
.map(EncodedAuthorityId)
.collect()
}
fn sign(payload: &Vec<u8>) -> Option<(EncodedSignature, EncodedAuthorityId)> {
AuthorityDiscovery::sign(payload).map(|(sig, id)| {
(EncodedSignature(sig.encode()), EncodedAuthorityId(id.encode()))
})
}
fn verify(payload: &Vec<u8>, signature: &EncodedSignature, authority_id: &EncodedAuthorityId) -> bool {
let signature = match BabeSignature::decode(&mut &signature.0[..]) {
Ok(s) => s,
_ => return false,
};
let authority_id = match BabeId::decode(&mut &authority_id.0[..]) {
Ok(id) => id,
_ => return false,
};
AuthorityDiscovery::verify(payload, signature, authority_id)
}
}
impl substrate_session::SessionKeys<Block> for Runtime {
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
let seed = seed.as_ref().map(|s| rstd::str::from_utf8(&s).expect("Seed is an utf8 string"));